Git & GitHub Tricks

·

3 min read

Branches

Check current branch:

git branch

Create new branch

git checkout -b feature-branch-name

Note: this command will also switch from current branch to the new branch

Synch a feature branch to the main branch

git checkout main-branch
git pull
git checkout feature-branch
git merge main-branch

Push local commits to remote repo

git push origin feature-branch-name

Pull request

Once pull request gets merged, delete feature branch:

  1. Make sure you are on the main branch:

    git checkout main-branch

  2. Sync fork to upstream branch on GitHub, then locally, run:

    git pull

  3. Delete your local feature branch:

    git branch -d feature-branch

  4. Delete remote feature branch:

    git push origin --delete feature-branch

Now you can move on to your next issue and create a new branch. (This ensures you don’t accidentally include the changes from your previous branch in your new branch)

From here, once your pull request is approved and merged you can pull the recent merge from the Hack For LA repository and delete your local branch:

git pull upstream main-branch
git branch -d feature-branch-to-be-deleted

Troubleshooting

Local changes are bad and ahead of remote origin branch

just remove them or reset your local branch to the state on remote git reset --hard origin/branchname or git pull --rebase

Backdating a commit

Made changes to a project yesterday but forgot to commit and push to GitHub?

  1. git add . (or a specific file that you made changes to)

  2. git commit --date="{date of the day you wish to backdate to in the format of YYYY-MM-DD}" -m "{your commit message}"

  3. git push

Check remote origin/remote

Want to make sure the branch is set up to track the right origin and upstream?

git remote show origin

git remote show upstream

Accidentally Pushed .env to GitHub? Here’s How to Fix It

This has happened too many times by now I don't even panic when I see my .env file in a GitHub repo and realize that it was not added to .gitignore before I pushed the code--I just shake my head, and do the following:

  1. change all secrets/passwords in .env
(If you skip this step, and just add .env to .gitignore, the repo will still have .env showing 
your updated content in .env)

3. add .env to .gitignore

4. commit and push

The history on GitHub will still show the old content from .env file, but the new .env file will not be in the repo so the new secrets/passwords are safe.


# Cloned a repo from GitHub but want to remove existing version control?

1. `ls -a` to check all files including hidden ones such as .git and .gitignore
2. `rm -rf .git` to remove .git file

# Revert changes to last commit:
`git reset HEAD --hard`