15
头图

Hello everyone! I am a migrant worker.

For Git, I believe that most programmers will not be unfamiliar with it.

As the most advanced distributed version control system in the world (there is none), Git is an open source distributed version control software for efficient and high-speed processing of project version management from small to very large. Git was originally designed and developed by Linus Torvalds to manage Linux kernel development. Over time, Git has developed to today and has become a must-have development tool for many developers.

If you usually feel boring when learning Git, you might as well try this fun little game, and learn through entertainment in another way.

Here's a demo of it:
image.png
Readers who need this game can click on the official account below to reply to the keyword Git game to get it

Introduction to Git

Git is an open source distributed version control system.

What is version control?

Version control is a system of recording changes to the content of one or several files for future reference to revisions to a particular version.

What is a distributed version control system?

Before introducing distributed version control systems, it is necessary to first understand the traditional centralized version control system.

Centralized version control systems, such as CVS, Subversion, etc., have a single centrally managed server that saves revisions of all files, and people working together connect to this server through clients to retrieve the latest files or Submit an update.

The most obvious disadvantage of doing this is the single point of failure of the central server. If there is an hour of downtime, no one will be able to submit updates and work together during that hour. If the disk on the central server fails, and the backups happen not to be made, or the backups are not timely enough, there is a risk of data loss. The worst case scenario is complete loss of all historical change records for the entire project.

The client of the distributed version control system does not only extract the latest version of the file snapshot, but completely mirrors the code repository. In this way, any server used for collaborative work fails, and it can be recovered with any mirrored local warehouse afterwards. Because each extraction operation is actually a complete backup of the code repository.

Reference: Git from entry to proficient

Git vs SVN

Git and SVN are better, everyone has a different experience.

Git is distributed, SVN is centralized

This is the biggest difference between Git and SVN. If you can grasp this concept, the difference between the two is basically understood. Because Git is distributed, Git supports offline work, and many operations can be performed locally, including the branch function that will be launched next. And SVN must be connected to the Internet to work properly.

  • Git has many complex concepts, and SVN is simple and easy to use

All developers who master both Git and SVN must admit that there are too many commands in Git, and daily work needs to master add, commit, status, fetch, push, rebase, etc. If you want to master it, you must master rebase and merge. The difference, the difference between fetch and pull, etc., in addition, there are cherry-pick, submodule, stash and other functions, but these terms sound very confusing.

In terms of ease of use, SVN is better for novices. But on the other hand, Git commands mean more functions. If we can master most of the functions of Git and understand the mystery, we will find that we can never go back to the era of SVN.

  • Git branches are cheap, SVN branches are expensive

Branching is a very common feature in version management. Before releasing a version, a branch needs to be released for large demand development, a feature branch is required, and a large team will also have a development branch, a stable branch, and so on. In the development process of large teams, there is often a need to create branches and switch branches.

A Git branch is a pointer to a commit, and an SVN branch is a copied directory. This feature makes Git branch switching very fast and very cheap to create.

And Git has local branches, SVN has no local branches. In the actual development process, it is often encountered that some codes are not finished, but other problems need to be urgently dealt with. If we use Git, we can create a local branch to store the code that has not been written, and return to the local after the problem is solved. Branches continue to complete the code.

For more attention to the comparison between Git and Svn, please refer to: understand | Make good use of Git and SVN to easily manage version management

How Git works

The text is not understand, please see 161ee8dc725217 Detailed explanation of how Git works

Git installation

  • Debian/Ubuntu environment installation

If your system is Debian/Ubuntu, the installation command is:

$ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \
> libz-dev libssl-dev
$ apt-get install git-core
$ git --version
git version 1.8.1.2
  • Centos/RedHat environment installation

If you are using Centos/RedHat, the installation command is:

$ yum install curl-devel expat-devel gettext-devel \
> openssl-devel zlib-devel
$ yum -y install git-core
$ git --version
git version 1.7.1
  • Windows environment installation

Download the exe installation package from the official Git download address. Follow the installation wizard to install.

It is recommended to install Git Bash, a command-line tool for git.

  • Mac environment installation

Download the mac installation package from the official Git download address. Follow the installation wizard to install.

Git configuration

Git comes with a git config tool to help set configuration variables that control Git's appearance and behavior. These variables are stored in three different locations:

/etc/gitconfig 文件: 包含系统上每一个用户及他们仓库的通用配置。如果使用带有 --system 选项的 git config 时,它会从此文件读写配置变量。

\~/.gitconfig 或 \~/.config/git/config 文件:只针对当前用户。可以传递 --global 选项让 Git 读写此文件。

The config file in the Git directory of the current repository (that is, .git/config): for this repository.

Each level overrides the previous level's configuration, so configuration variables in .git/config override those in /etc/gitconfig.

On Windows systems, Git will look for a .gitconfig file in the $HOME directory (usually C:\Users\$USER). Git will also look for the /etc/gitconfig file, but only in the root directory of MSys, which is the target location chosen when Git was installed.

Git basic concepts

  • repository

When you move a project locally or create a git project, there will be a hidden .git subdirectory in the project directory. This directory is used by git to track and manage the repository. Do not modify it manually.

  • hash value

All data in Git is checksummed before being stored, and then referenced with the checksum. This means that it is impossible to change any file contents or directory contents without Git's knowledge. This functionality is built on top of Git and is an integral part of the Git philosophy. If you lose information or corrupt files in the transfer process, Git will find out.

The mechanism Git uses to calculate checksums is called a SHA-1 hash. This is a string of 40 hexadecimal characters (0-9 and af) calculated based on the contents of a file or directory structure in Git. The SHA-1 hash looks like this:

24b9da6552252987aa493b52f8696cd6d3b00373
There are many uses of this hash in Git, and you'll see it quite often. In fact, the information stored in the Git database is indexed by the hash value of the file content, not the file name.

  • file status

In GIt, your files can be in one of three states:

  • has been modified (modified) - Modified means that the file has been modified, but has not been saved to the database.
  • staged - Staged means that the current version of a modified file is marked for inclusion in the next commit's snapshot.
  • has been committed (committed) - committed means that the data has been safely stored in the local database.
  • Work area

Corresponding to the file status, files with different statuses are in different working areas in Git.

  • workspace (working ) - When you git clone a project locally, it is equivalent to cloning a copy of the project locally. A workspace is an independent extraction of a version of a project. These files are extracted from the compressed database of the Git repository and placed on disk for you to use or modify.
  • staging area (staging) - The staging area is a file that saves the list of files to be submitted next, usually in the Git repository directory. It is sometimes called an ''index'', but is generally referred to as a scratch area.
  • Local Repository (local) - Commit the update, find the files in the staging area, and permanently store the snapshot to the Git local repository.
  • Remote warehouse (remote) - The above workspaces are all local. In order for others to see your changes, you need to push your updates to the remote repository. Similarly, if you want to sync other people's changes, you need to pull the updates from the remote repository.

  • Branch

Branching is to store the entire process of modifying records separately, so that separate branches are not affected by other branches, so multiple different modifications can be made in the same database at the same time.

The master branch (Master) mentioned earlier that master is the first branch that Git automatically creates for us, also called the master branch. After the development of other branches is completed, they must be merged into master.

  • Tag (Tag)

Tags are used to mark specific points or the history of commits, usually the name or version number of the release version (eg: publish/0.0.1), although tags look a bit like branches, but tagged commits are fixed Yes, it cannot be changed arbitrarily, see 1.0 / 2.0 / 3.0 in the above picture

  • HEAD

HEAD points to the latest commit image of the current branch

The above concepts are almost the same, so you can continue to look down.

Git commands

  • Create repository

Clone an already created repository:

# 通过 SSH
$ git clone ssh://user@domain.com/repo.git

#通过 HTTP
$ git clone http://domain.com/user/repo.git

Create a new local repository:

$ git init
  • add modification
    Add changes to the staging area:

    # 把指定文件添加到暂存区
    $ git add xxx
    
    # 把当前所有修改添加到暂存区
    $ git add .
    
    # 把所有修改添加到暂存区
    $ git add -A

    Submit the changes to the local repository:

    # 提交本地的所有修改
    $ git commit -a
    
    # 提交之前已标记的变化
    $ git commit
    
    # 附加消息提交
    $ git commit -m 'commit message'
  • storage

Sometimes, we need to work on different branches of the same project. When it is necessary to switch branches, the local work has not been completed. At this time, it is not rigorous to submit changes, but it is impossible to switch branches without submitting code. At this point, you can use git stash to stash your local changes as drafts.

Officially it's called storage, but I personally prefer to call it drafts.

# 1. 将修改作为当前分支的草稿保存
$ git stash

# 2. 查看草稿列表
$ git stash list
stash@{0}: WIP on master: 6fae349 :memo: Writing docs.

# 3.1 删除草稿
$ git stash drop stash@{0}

# 3.2 读取草稿
$ git stash apply stash@{0}
  • Undo changes

Undo local changes:

# 移除缓存区的所有文件(i.e. 撤销上次git add)
$ git reset HEAD

# 将HEAD重置到上一次提交的版本,并将之后的修改标记为未添加到缓存区的修改
$ git reset <commit>

# 将HEAD重置到上一次提交的版本,并保留未提交的本地修改
$ git reset --keep <commit>

# 放弃工作目录下的所有修改
$ git reset --hard HEAD

# 将HEAD重置到指定的版本,并抛弃该版本之后的所有修改
$ git reset --hard <commit-hash>

# 用远端分支强制覆盖本地分支
$ git reset --hard <remote/branch> e.g., upstream/master, origin/my-feature

# 放弃某个文件的所有本地修改
$ git checkout HEAD <file>

Remove the wrongly committed file before adding the .gitignore file:

$ git rm -r --cached .
$ git add .
$ git commit -m "remove xyz file"

Undo remote changes (create a new commit and roll back to the specified version):

$ git revert <commit-hash>

To completely remove the specified version:

# 执行下面命令后,commit-hash 提交后的记录都会被彻底删除,使用需谨慎
$ git reset --hard <commit-hash>
$ git push -f
  • Update and push

renew:

# 下载远程端版本,但不合并到HEAD中
$ git fetch <remote>

# 将远程端版本合并到本地版本中
$ git pull origin master

# 以rebase方式将远端分支与本地合并
$ git pull --rebase <remote> <branch>

Push:

# 将本地版本推送到远程端
$ git push remote <remote> <branch>

# 删除远程端分支
$ git push <remote> :<branch> (since Git v1.5.0)
$ git push <remote> --delete <branch> (since Git v1.7.0)

# 发布标签
$ git push --tags
  • View information

Display the modified files in the working path:

$ git status

Show the difference from the last commit version file:

$ git diff

Show commit history:

# 从最新提交开始,显示所有的提交记录(显示hash, 作者信息,提交的标题和时间)
$ git log

# 显示某个用户的所有提交
$ git log --author="username"

# 显示某个文件的所有修改
$ git log -p <file>
  • Show search content:

    # 从当前目录的所有文件中查找文本内容
    $ git grep "Hello"
    
    # 在某一版本中搜索文本
    $ git grep "Hello" v2.5
  • branch

Add, delete and check branches:

# 列出所有的分支
$ git branch

# 列出所有的远端分支
$ git branch -r

# 基于当前分支创建新分支
$ git branch <new-branch>

# 基于远程分支创建新的可追溯的分支
$ git branch --track <new-branch> <remote-branch>

# 删除本地分支
$ git branch -d <branch>

# 强制删除本地分支,将会丢失未合并的修改
$ git branch -D <branch>

Switch branches:

# 切换分支
$ git checkout <branch>

# 创建并切换到新分支
$ git checkout -b <branch>

Label

# 给当前版本打标签
$ git tag <tag-name>

# 给当前版本打标签并附加消息
$ git tag -a <tag-name>

Merge and reset

Although merge and rebase are common functions of git, it is strongly recommended not to use git commands to complete this work.

Because if there is a code conflict, it is too difficult without a code comparison tool.

You can consider using various Git GUI tools.

merge:

# 将分支合并到当前HEAD中
$ git merge <branch>

reset:

# 将当前HEAD版本重置到分支中,请勿重置已发布的提交
$ git rebase <branch>

For more command reference: Three-year Git experience & FAQ finishing

Git branch development

Git is the most popular source code management tool out there. In order to standardize development, keep code submission records and git branch structure clear, and facilitate subsequent maintenance, git related operations are now standardized.

branch naming

1. master branch

master is the main branch and is also the branch used to deploy the production environment to ensure the stability of the master branch. The master branch is generally merged by the develop and hotfix branches, and the code cannot be directly modified at any time

2. develop branch

develop is the development branch, always keeping the latest completed and bug-fixed code. Generally, when developing new functions, the feature branch is created based on the develop branch.

  • feature branch

When developing new features, create a feature branch based on develop.
Branch naming: feature branches starting with feature/, naming rules: feature/user_module, feature/cart_module

  • release branch

release is a pre-launch branch, and in the release test phase, the release branch code will be used as a benchmark test. When a set of features is developed, it will be merged into the develop branch first, and a release branch will be created when entering the test. If there are bugs that need to be fixed during the testing process, the developers will directly fix and submit them in the release branch. When the test is completed, merge the release branch into the master and develop branches. At this time, the master is the latest code and is used for online.

  • hotfix branch

Branch naming: Hotfix/ starts with a repair branch, and its naming rules are similar to feature branches. When an urgent problem occurs online, it needs to be repaired in time. Using the master branch as the baseline, create a hotfix branch. After the repair is completed, it needs to be merged into the master branch and the develop branch.

For more development specifications, please refer to: The most complete Git branch development specification manual on the entire network | Master these 10 specifications and easily handle Git!

Git these advanced usage, like to use it!

Git commit specification

Why do you need specifications?

There are no rules and no circles, and so is programming.

If you have a project that you write yourself from start to finish, you can write whatever you want, no one can interfere with you. But if in teamwork, everyone shows their individuality, then the code will be a mess, and a good project will be ruined. Whether it is development or future maintenance, it will be a disaster.

At this time, someone proposed why not to unify the standard, and everyone should follow this standard. As a result, code tools such as ESLint and JSHint have sprung up like mushrooms after a rain, and they have become a must-have for project construction.

The Git Commit specification may not be that exaggerated, but if you see a lot of bad commits during a version rollback, I'm afraid you'll be annoyed. Therefore, strictly abide by the norms, benefit others and benefit yourself.

For details, see: Git commit specification you might ignore

Git usage tips

Only when you have a problem do you realize the benefits of your skills!

Common Enterprise Workflows

Mainly introduce, the Git workflow commonly used in enterprises!

  • Git Flow
  • trunk branch
  • stable branch
  • development branch
  • patch branch
  • modify branch

Github Flow
  • create branch
  • add commit
  • Submit a PR request
  • Discuss and evaluate code
  • Deployment detection
  • Merge code

Gitlab Flow
  • with production branch
  • with environment branch
  • with release branch

Best Practices for Everyday Use

Git usage methods and methods that should be followed in daily work!

  • Use the command line instead of the GUI
  • Use the command line to operate, concise and efficient
  • The submission should express the submitted revisions as much as possible
  • Separate subject and body content with blank lines
  • subject generally no more than 50 characters
  • The length of each line of body is controlled at 72 characters
  • Subject does not need to end with a period or a period
  • body is used to explain in detail what the commit did.
  • Use .gitignore file to exclude useless files
  • Template files can be used and then modified according to the actual project
  • Branch or fork-based development mode
  • Do not develop directly on the main branch
  • Feature development and bug fixes on newly created branches
  • Version management with release branches and tags
  • Use the release branch to release code and version maintenance (release/1.32)
  • Use tag to mark the version (A-big feature function.B-small feature function.C-bug fix only)

Summary of common commands

Just remember 6 commands for daily use.

Whether it is development, operation and maintenance, or testing, everyone knows the place of Git in daily work. Therefore, it is also one of the necessary skills for everyone.

However, brother migrant workers, I often see readers in the background saying that there are too many orders to remember, and it is not necessary to forget them after a long time. Yes, it is really difficult to learn a technology, not to mention that the technology is updated and iterated so fast...

Therefore, for the technology of learning Git, if there is an introductory material that you can understand at a glance, it will be good. Not long ago, a young lady from abroad wrote such an article "CS Visualized: Useful Git Commands". The author is Miss Lydia Hallie from British Columbia. In this article, she shows developers the merge, rebase, reset, revert, cherry-pick in Git commands in a more intuitive way through vivid animations. The specific principles of commonly used Sao operation. uses animation to illustrate Git commands, you can understand it at a glance!

# 工作区 -> 暂存区
$ git add <file/dir>

# 暂存区 -> 本地仓库
$ git commit -m "some info"

# 本地仓库 -> 远程仓库
$ git push origin master  # 本地master分支推送到远程origin仓库 
# 工作区 <- 暂存区
$ git checkout -- <file>  # 暂存区文件内容覆盖工作区文件内容

# 暂存区 <- 本地仓库
$ git reset HEAD <file>   # 本地仓库文件内容覆盖暂存区文件内容

# 本地仓库 <- 远程仓库
$ git clone <git_url>        # 克隆远程仓库
$ git fetch upstream master  # 拉取远程代码到本地但不应用在当前分支
$ git pull upstream master   # 拉取远程代码到本地但应用在当前分支
$ git pull --rebase upstream master  # 如果平时使用rebase合并代码则加上
# 工作区 <- 本地仓库
$ git reset <commit>          # 本地仓库覆盖到工作区(保存回退文件内容修改)
$ git reset --mixed <commit>  # 本地仓库覆盖到工作区(保存回退文件内容修改)
$ git reset --soft <commit>   # 本地仓库覆盖到工作区(保留修改并加到暂存区)
$ git reset --hard <commit>   # 本地仓库覆盖到工作区(不保留修改直接删除掉)

For more introduction to Git usage skills, please refer to: Learn these 11 items, and you are not far from the Git god!

See here for the dynamic update of the Git knowledge system: Git technical learning


民工哥
26.4k 声望56.7k 粉丝

10多年IT职场老司机的经验分享,坚持自学一路从技术小白成长为互联网企业信息技术部门的负责人。2019/2020/2021年度 思否Top Writer