Git Basics

development

Change User Information

One of the first things to do when setting up Git is to set your name and email. This information is included in each commit and is important when working on your own open source project, or contributing to another, so others can contact you if there are any issues.

To set your name and email for all repositories:

git config --global user.name "Enter your name here"
git config --global user.email "Enter your email here"

To set your name and email only for the current repository (overrides global settings):

git config user.name "Enter your name here"
git config user.email "Enter your email here"

Change Editor

The default editor for writing commit messages varies by operating system but it can be explicitly configured.

To change the editor for all repositories:

git config --global core.editor "vi"

To change the editor only for the current repository (overrides global setting):

git config core.editor "vi"

Work With Upstream Repository

When working on another project it's useful to fetch and merge new commits from the original repository into your fork.

To add an upstream repository:

git remote add upstream https://github.com/example/example.git

To fetch and merge updates from the master branch of the upstream repository to the master branch of your fork:

git checkout master
git fetch upstream
git merge upstream/master

Squash Commits

You can combine multiple commits into one commit by using the git reset command (also called squashing commits).

To squash the last 3 commits:

git reset --soft HEAD~3
git commit

This resets the repository to the third most recent commit and re-commits all changes since then as a single commit (allowing you to write a new commit message). The --soft switch ensures neither the repository's index nor working tree are touched, allowing you to re-commit immediately. The HEAD~3 syntax refers to the third most recent commit without having to reference its hash.

Rebase Branch

You can use the git rebase command to update new commits in a branch based on the commits in an existing branch. This allows for a cleaner project history than using git merge by eliminating merge commits and allowing for a linear history; however, because it re-writes the branch's history it should never be used on a public branch.

git checkout feature-1043
git rebase master

This incorporates missing commits from the master branch into the feature-1043 branch and moves all new commits in the feature-1043 branch after the commits from the master branch.

View other posts