← All writing

Pro Git

Git study notes covering the working tree, staging and commits, alongside everyday commands for history, remotes, tags and undoing changes. Includes branching, merging, rebasing, ignore rules and commit conventions.

Pro Git

Getting Started

Git Has Integrity

Everything in Git is checksummed before it is stored and is then referred to by that checksum. The mechanism that Git uses for this checksumming is called a SHA-1 hash. In fact, Git stores everything in its database not by file name but by the hash value of its contents.

The Three States

• Modified means that you have changed the file but have not committed it to your database yet.

• Staged means that you have marked a modified file in its current version to go into your next commit snapshot.

• Committed means that the data is safely stored in your local database.

This leads us to the three main sections of a Git project: the working tree, the staging area, and the Git directory.

First-Time Git Setup

Git comes with a tool called git config that lets you get and set configuration variables that control all aspects of how Git looks and operates.

You can view all of your settings and where they are coming from using:

shell
git config --list --show-origin

Your Identity

The first thing you should do when you install Git is to set your user name and email address. This is important because every Git commit uses this information, and it’s immutably baked into the commits you start creating:

shell
git config --global user.name "iSaber"
git config --global user.email 1346959878@qq.com

Your default branch name

By default Git will create a branch called master when you create a new repository with git init.

To set main as the default branch name do:

shell
git config --global init.defaultBranch main

Checking Your Settings

If you want to check your configuration settings, you can use the git config --list command to list all the settings Git can find at that point:

shell
git config --list
git config --global --lsit

Git Basics

Getting a Git Repository

Initializing a Repository in an Existing Directory

shell
git init

This creates a new subdirectory named .git that contains all of your necessary repository files — a Git repository skeleton.

shell
git add *
git commit -m "Initial project version"

Recording Changes to the Repository

Remember that each file in your working directory can be in one of two states: tracked or untracked.

Checking the Status of Your Files

shell
git status
git status -s

Tracking New Files

shell
git add README.md

Ignoring Files

You can create a file listing patterns to match them named .gitignore.

Viewing Your Staged and Unstaged Changes

You want to know exactly what you changed, not just which files were changed, you can use the git diff command.

shell
git diff
git diff --staged
git diff --cached

If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged.

(--staged and --cached are synonyms)

Skipping the Staging Area

Adding the -a option to the git commit command makes Git automatically stage every file that is already tracked (e.t. it is ever runned git add ) before doing the commit, letting you skip the git add part:

shell
git commit -a -m "commit message"
# or
git commit -am "commit message"

Removing Files

The git rm command will remove the file from your working directory and remove it from your staging area.

If you just delete the file in your working directory, you shuld git add that file to remove it from your staging area.

Both two ways need to git commit

shell
git rm

Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area.

shell
git rm --cached

Viewing the Commit History

You can view the commit history to use the git log command.

shell
git log

One of the more helpful options is -p or --patch, which shows the difference introduced in each commit.

shell
git log -p

If you want to see some abbreviated stats for each commit, you can use the --stat option:

shell
git log --stat

This option adds a nice little ASCII graph showing your branch and merge history:

shell
git log --graph

Show only the last 5 commits.

shell
git log -5

One line.

shell
git log --oneline

Working with Remotes

Showing Your Remotes

To see which remote servers you have configured, you can run the git remote command.You can also specify -v, which shows you the URLs that Git has stored for the shortname to be used when reading and writing to that remote.

shell
git remote -v

Adding Remote Repositories

To add a new remote Git repository as a shortname you can reference easily, run git remote add <shortname> <url>:

shell
git remote add origin git@github.com:IiCEight/SICP.git

Fetching and Pulling from Your Remotes

As you just saw, to get data from your remote projects, you can run:

shell
git fetch <remote>
git fetch origin

Note that the git fetch command doesn't automatically merge it with any of your work or modify what you’re currently working on.

If you clone a repository, the command automatically adds that remote repository under the name “origin”.

shell
git clone

By default, the git clone command automatically sets up your local master branch to track the remote master branch (or whatever the default branch is called) on the server you cloned from.

If your current branch is set up to track a remote branch, you can use the git pull command to automatically fetch and then merge that remote branch into your current branch.

shell
git pull
git pull <remote> <remotebranch>:<localbranch>

Pushing to Your Remotes

The command for this is simple: git push <remote> <branch>.

shell
git push origin master

Use -u to for --set-upstream

sh
git push -u origin master
git push --set-upstream origin master

Inspecting a Remote

It also shows you which remote branches on the server you don’t yet have, which remote branches you have that have been removed from the server.

shell
git remote show <remote>
git remote show origin

Renaming and Removing Remotes

You can run git remote rename to change a remote’s shortname.

shell
git remote rename origin saber

You can either use git remote remove or git remote rm to remove a remote.

shell
git remote remove
git remote rm

Once you delete the reference to a remote this way, all remote-tracking branches and configuration settings associated with that remote are also deleted.

Tagging

Typically, people use this functionality to mark release points (v1.0, v2.0 and so on)

Listing Your Tags

shell
git tag

Creating Tags

Git supports two types of tags: lightweight and annotated.

A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit.

Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG).

It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too.

Annotated Tags

The easiest way is to specify -a when you run the git tag command and -m specifies a tagging message which must be specified like commit messages.

shell
git tag -a v1.0 -m "my version 1.0"

You can see the tag data along with the commit that was tagged by using the git show command:

shell
git show v1.0

Lightweight Tags

To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name:

shell
git tag v2.0

This time, if you run git show on the tag, you don’t see the extra tag information.

Tagging Later

You can run git log to find the checksum of commit that you want to tag. Then run:

shell
git tag -a v3.0 <checksum>

Sharing Tags

By default, the git push command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server. This process is just like sharing remote branches — you can run git push origin <tagname>.

shell
git push origin v1.0

You can also use the --tags option to the git push command. This will transfer all of your tags to the remote server that are not already there.

shell
git push origin --tags

Deleting Tags

You can use git tag -d <tagname>:

shell
git tag -d v3.0

Note that this does not remove the tag from any remote servers. You can do that with:

shell
git push origin --delete <tagname>

Git Aliases

Code
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status

This means that, for example, instead of typing git commit, you just need to type git ci.

Undo

You modified some files but not stage, you can give up the modification:

sh
git checkout -- filepathname 
git checkout .

git restore file.txt

And for all modified files, you can run git checkout . or git restore .

But if you want to restore a staged file to unstaged, you can

sh
git restore --staged file.text

If some files I commite, I want to stop Git from tracking it and remove it from your Git history

sh
git rm --cached path/to/your/file

This unstages (untracks) the file in Git. But the actual file remains in your local folder.

However the history still exists.

If you want to change the latest commit message, use git commit --amend

sh
git commit --amend

Git Branching

Branches in a Nutshell

Because a branch in Git is actually a simple file that contains the 40 character SHA-1 checksum of the commit it points to, branches are cheap to create and destroy.

see more Git - Branches in a Nutshell (git-scm.com).

Creating a New Branch

This creates a new pointer to the same commit you’re currently on.

shell
git branch <branchname>
git branch main

How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. This is a pointer to the local branch you’re currently on.

The git branch command only created a new branch — it didn’t switch to that branch.

It’s typical to create a new branch and want to switch to that new branch at the same time:

sh
git checkout -b <newbranchname>.

You can create a new branch on a history by its checksum.

sh
git checkout -b <newbranchname> <commitchecksum>

Switching Branches

To switch to an existing branch, you run the git checkout command.

shell
git checkout main

This moves HEAD to point to the main branch.

If you do some commit on branch main. Now main branch has moved forward but master branch still stay original commit.

Basic Branching and Merging

Basic Merging

If you want to merge B branch into A branch, You can checkout main branch and run the git merge command:

shell
git checkout A
git merge B

If A is the ancestor of B, the pointer of A wil move to the position of B.

If B is the ancestor of A, then nothing will happen because A is new version of B.

If none of both, git does a simple three-way merge, using the two snapshots pointed to by the branch and the lowest common ancestor of the two. Git wil creates a new snapshot and automatically creates a new commit which is called merge commit. Then the pointer of A wil move to that new snapshot.

External image · git-scm.com

External image · git-scm.com

Basic Merge Conflicts

If you changed the same part of the same file differently in the two branches you’re merging, Git won’t be able to merge them cleanly (i,e, otherwise, it works well). Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run git status.

sh
$ git status
On branch main
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Unmerged paths:
  (use "git add <file>..." to mark resolution)
        both modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

Anything that has merge conflicts and hasn’t been resolved is listed as unmerged.

Open README.md you will see:

Code
<<<<<<< HEAD
This is main commit
=======
This is dev commit
>>>>>>> dev

In order to resolve the conflict, you have to either choose one side or the other or merge the contents yourself. And the <<<<<<<, =======, and >>>>>>> lines need to be completely removed like this:

Code
This is main commit

After you’ve resolved each of these sections in each conflicted file, run git add on each file to mark it as resolved. Then using git status you will see:

Code
$ git status
On branch main
All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

Changes to be committed:
        modified:   README.md

Finally, you can type git commit to finalize the merge commit.

Delete Branch

shell
git branch -d <branchname>

Rename Branch

If you are currently on the branch you want to rename:

sh
git branch -m <new-branch-name>

If you are on a different branch and want to rename another one:

sh
git branch -m <old-branch-name> <new-branch-name>

Branch Management

You will see local and remote branch:

sh
git branch --all
git branch -a

Remote Branch

Remote-tracking branches are references to the state of remote branches. They’re local references that you can’t move; Git moves them for you whenever you do any network communication, to make sure they accurately represent the state of the remote repository. Think of them as bookmarks, to remind you where the branches in your remote repositories were the last time you connected to them.

Remote-tracking branch names take the form <remote>/<branch>.

If you clone from git@github.com:IiCEight/SICP.git, git clone command automatically names it origin for you, pulls down all its data, creates a pointer to where its main branch is, and names it origin/main locally. Git also gives you your own local main branch starting at the same place as origin’s main branch, so you have something to work from.

If you do some work on your local main branch, and, in the meantime, someone else pushes remote main branch on server like Github. Then your histories move forward differently. Also, as long as you stay out of contact with your origin server, your origin/main pointer doesn’t move.

To synchronize your work with a given remote, you run a git fetch <remote> command. This command fetches any data from it that you don’t yet have, and updates your local database, moving your origin/main pointer to its new, more up-to-date position.

Pushing

sh
git push <remote> <localbranch>:<remotebranch>
git push <remote> <localbranch>
git push origin main

Tracking Branches

Checking out a local branch from a remote-tracking branch automatically creates what is called a “tracking branch” (and the branch it tracks is called an “upstream branch”).

If you’re on a tracking branch and type git pull, Git automatically knows which server to fetch from and which branch to merge in.

you can set up other tracking branches if you wish:

sh
git checkout -b <branch> <remote>/<branch>
git checkout -b <newbranch> <existingbranch>
git checkout -b main origin/main

This is a common enough operation that Git provides the --track shorthand:

sh
git checkout --track origin/main

If you already have a local branch and want to set it to a remote branch you just pulled down, or want to change the upstream branch you’re tracking, you can use the -u or --set-upstream-to option to git branch to explicitly set it at any time.

sh
git checkout main
git branch -u origin/main

If you want to see what tracking branches you have set up, you can use the -vv option to git branch.

sh
git branch -vv

Pulling

While the git fetch command will fetch all the changes on the server that you don’t have yet, it will not modify your working directory at all. It will modify your <remote>/<branch> and you need to merge it into your local branch.

However, there is a command called git pull which is essentially a git fetch immediately followed by a git merge in most cases.

If you have a tracking branch, git pull will look up what server and branch your current branch is tracking, fetch from that server and then try to merge in that remote branch.

Rebasing

To be learned

Git ignore

File name should be .gitignore

Ignore File Folder

Code
filename/
data/

Ignore File

Code
*.log
main.py

Authorization

Find The folder .ssh.

Generally, it's in ~/.ssh in Linux and C:\Users\<userFolder>\.ssh in windows.

If this folder is null or empty,

Then we need to generate

shell
ssh-keygen -t rsa -C "your git email"

Then save content of id_rsa.pub to your remote setting (like github).

Commit Message Convention

The commit message should be structured as follows:

Code
<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

For example:

Code
feat(auth): add JWT-based login authentication

Added support for user login using JWT tokens. This includes token generation,
validation middleware, and secure routes.

BREAKING CHANGE: old session-based login has been removed

TypeMeaning
featA new feature
fixA bug fix
docsDocumentation only changes
styleCode style changes (formatting, missing semi-colons)
refactorCode changes that neither fix a bug nor add a feature
testAdding or updating tests
choreChanges to the build process or auxiliary tools
← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.