webdev-resources

Git Cheatsheet

Last Updated: 2024-06-06

General Notes

In Git branching nomenclature, main and master are synonymous. This guide will use main to refer to the main/master branch (or trunk) of the development chain.

⚠️ Note: assume that codeblocks in this guide show an ordered sequence of steps to follow unless otherwise specified.

Best Practices

Comment Styles

WordPress Usage

Whether you are using Git or SFTP to deploy changes, the last step is to refresh your database. Settings or content that you add/modify are stored in your database. (E.g., custom post types, custom fields, references to images, etc.)


Git Installation Or Upgrading

You may already have Apple Git running on your machine. If you run git --version and are returned something like “git version 2.24.3 (Apple Git-128)” and then install Git with Homebrew, your machine will have two different versions of Git at the following locations:

  1. Apple version: /usr/bin/git
  2. Open source (Homebrew installation): /usr/local/bin/git

Updating the PATH variable and overwriting any symlinks as shown below will make your machine use the git command default to the open source version of Git. Using Homebrew will make it easier to update (i.e. upgrade) Git in the future.

# Iterate through all Git executables and display locations/versions
for i in $(which -a git); do echo -n "${i}:  "; ${i} --version; done

# Install or upgrade git with Homebrew package manager
brew install git
brew upgrade git

# Update the PATH variable to the Homebrew install
export PATH=/usr/local/bin:$PATH

# Check that your git command is linked to the updated Homebrew version you installed
git --version

# If necessary, overwrite any existing symlinks to the installed version of git
brew link --overwrite git


Version Control Configuration

Initialize Local Git Repo

# Navigate to project directory
cd Sites/projectName

# Initialize repo
git init

# Confirm all files are present
git status

# Add all files and commit with comment
git add . && git commit -m "Initial commit"

# Ensure working tree is clean
git status

Connect Local Repo To GitHub (Or A Remote Server)

# Check for existing remote repos
git remote -v

# In a browser, go to your GitHub account and create new repository
# Make private if necessary
# Switch from HTTPS to SSH
# Copy this command block from GitHub:
git remote add origin git@github...git push -u origin main

# Back in terminal, paste the command in project directory where git was initialized

# Type your SSH password when prompted

# Check remote origin is now connected
git remote -v

# Refresh GitHub page in browser and confirm sync

The -u tag in git push -u origin main is used to set the origin as the upstream remote in your git config. It is only needed the first time you push.

View more about Remotes at Git Basics - Working with Remotes

Set An Upstream (Remote) Branch

# Checkout the branch you want to connect to remote
git checkout -b development # Option 1: create new branch
git checkout development # Option 2: use existing branch

# Set the upstream of the local branch (development) to the remote server (origin)
git push -u origin development

# View all remote branches
git branch -r
# You should see 'origin/development' listed


Version Control Removal

Remove Local Git Tracking

To remove Git from a project, you can simply delete the .git directory in the root of your project.

⛔️ Caution! This will permanently remove the version control history and configurations.

# Navigate to project directory
cd Sites/projectName

# View all files in the directory, including hidden files like .git
ls -a

# Remove all git directories and their contents recursively
# BE SURE BEFORE YOU PROCEED!
rm -rf .git

# Remove the .gitignore file
rm .gitignore

# Go to GitHub and delete your repository if you don't want a remote copy

Remove Remote Tracking

After cloning a remote repo, you may want to remove the tracking so that your local project is no longer synced to the remote.

# Navigate to project directory
cd Sites/projectName

# Remove remote tracking
git remove remote


View Branches

# View local branches
git branch

# View remote branches
git branch -r

# View all branches
git branch -a


Creating & Modifying Branches

Rename An Existing Local Branch

# Change the name of oldBranch to newBranch
git branch -m oldBranch newBranch

Create A New Branch

# View all branches
git branch

# Create a checkout a new branch called “staging”
git checkout -b staging

Clone A Repo

# Copy/paste repo from GitHub
git clone <repo>

# ??? NEEDS INSPECTION
git checkout -b feature/modal origin/deploy

# Push the feature/modal branch to remote origin
git push origin feature/modal

Rename a Remote Repo

# View existing remotes
git remote -v

# Rename origin to upstream
git remote rename origin upstream

Download Remote Files & Commits to Local

Fetch vs. Pull

git pull and fetch comparison

Source: TheServerSide

fetch: copies changes to you local git repo.

pull: copies changes directly into your working directory. A pull is equivalent to a fetch & merge.

# Synchronize branch list
git fetch -p

-p: prune.


Comparing Branches & Commits

Output Unique Commits

# Shows if commits are present in devBranch but NOT in main
git log main..devBranch

View Behind/Ahead Commit Count

# Local branches comparison
git rev-list --left-right --count main...devBranch

# Remote branches comparison
git rev-list --left-right --count origin/main...origin/devBranch

# Example Output:
# 1   3
# Compared to main, devBranch is 1 behind & 3 ahead

Compare Unique Commits

# Return list of unique commits on each branch
git rev-list --left-right --pretty=oneline main...devBranch

# Example Output:
# <abc123...unique commit 2 on main
# >def456...unique commit 1 on devBranch


Merges & Conflicts

Merging Branches

When merging, you checkout the trunk (e.g. main) and merge in the development branch (e.g. staging, feature/modal, bugfix, etc).

# Checkout the trunk
git checkout main

# Merge the branch you worked on
git merge development

# Make sure working tree is clean and resolve any conflicts if necessary before pushing.
git status

# Push your merged local (main) to remote (origin)
git push origin main

Merge Conflicts

Perform merge conflict housekeeping in your text editor.

# See what HEAD points to
cat .git/HEAD


# Stage changes (after conflicts are resolved)
git add filename.abc

# Commit changes with comment
git commit -m "Fix merge conflict in filename"

# Make sure working tree is clean
git status

# Push your merged local (main) to remote (origin)
git push origin main


Scratch That: Reversing Changes & Deleting Branches

Undo/Ignore Simple File Changes

# Discard uncommitted edits & revert a file to prior commit state
git checkout -- filename.abc

Undo/Ignore Changes To All Files

# Discard all file changes & revert everything to prior commit
git checkout .

Delete Local Branch

# Delete branch that has been already been pushed & merged with remote
git branch -d localBranchName
# Delete branch that has NOT been pushed & merged with remote
git branch -D localBranchName

Delete Remote Branch

# View remote branches
git branch -r

# Delete remote branch - Option 1
git push origin --delete remoteBranchName

# Delete remote branch - Option 2
git push origin :remoteBranchName

The remote may have already been deleted if you see this:


Rolling Back The Clock: Revert, Amend, Rebase, Clean

⚠️ Warning: Resetting is destructive. Make sure you’re ok with losing the data before you proceed!

Git Revert: undo changes made in a commit by creating a new commit that reverses the changes.

# Undo changes introduced by commit hash abc123
git revert abc123

Git Reset: reset the current HEAD to a specified state, which can be a previous commit or the staging area.

# This is a codeblock of options, not sequences
# Replace abc123 with the hash (ID) of the commit you want to keep
git reset abc123            # Reset to specified commit
git reset --soft abc123     # Reset & keep changes staged
git reset --mixed abc123    # (Default) Reset & unstage changes
git reset --hard abc123     # Reset & discard changes
git reset --hard HEAD^      # Undo last commit & all changes
git reset --hard HEAD^^     # Undo last 2 commits & all changes

Rollback & Reset Branches To Match One Another

# Checkout the branch that you want to rollback (i.e. development)
git checkout development

## Reset the checked out branch to match another branch (i.e. main)
git reset --hard main

# Force push the changes to your remote branch if desired
git push origin development --force


Hosting on GitHub Pages

# Create a branch for hosting
# You must name it 'gh-pages' for GitHub
git checkout -b gh-pages

# Push branch to GitHub
git push origin gh-pages

# In your browser, visit your GitHub repo
# Click the Settings button (gear icon in the top menu)
# Scroll down  to the Pages section to view/modify any settings

GitHub Pages & React

See the React For GitHub Pages guide to get static React applications running on GitHub.