65
头图

This is the 103rd original without water. If you want to get more original good articles, please search the public account and follow us~ This article first appeared on the front-end blog of Zheng Caiyun: 160f65f67856ca How do I use git

image

Preface

Recently, there was a real case on the Internet that was quite popular. It was about a new employee who did not use Git to pull code and was fired the next day. From this, we can see the importance of Git to our work. Whether it is front-end or back-end, it is inseparable from Git. Let's find out below.

The above case raises a question. After you join a new company and your leader assigns you warehouse permissions, how do you configure the local Git environment and pull code? Don't panic, follow the four steps I talked about below to ensure that you can use Git to pull code smoothly!

  1. Download Git download address , select the version corresponding to your system to download.
  2. Generate the ssh key on your computer, open the terminal, execute ssh-keygen -t rsa -C "your company's internal email address", if the execution is successful, switch to the ~/.ssh directory, the directory should now look like the following. Copy the content of id_rsa.pub

    image-20210519163921819.png

  3. Here at Github, for example, as shown below, enter settings -> SSH and GPG keys by cat view the file command id_rsa.pub content and then copied, click add ssh key , this step mean that your public key to be hosted on Github.

    image-20210519164643069.png

  4. Configure Git username and email globally
git config --global user.name "xxx"
git config --global user.email "xxx@xx.com"

After completing the above four steps, you can happily develop the pull code. Unlike the https pull method, the https method requires you to manually enter the user name and password before each submission. After the ssh method is configured, Git will use your local private key and the public key of the remote warehouse to verify whether it is a pair of secrets. Key, which simplifies the operation process.

Introduction to Git

Before introducing the related operations of Git, I think it is very necessary to understand the origin of Git and what problems Git is used to solve. Git (pronounced /gɪt/) is an open source distributed version control system that can effectively and quickly handle the version management of projects from very small to very large. Linus Torvalds, I believe everyone knows this person, the inventor of the open source Linux system. Nowadays, most of the servers you see are actually running on Linux systems. What is amazing is that this great-level programmer not only created Linux systems. How is the Linux code managed? Before 2002, volunteers from all over the world sent the source code files to Linus via diff, and then Linus himself merged the code manually! You should know that the amount of Linux code at that time was already very large. Through manual management, one is prone to errors, and the other is low efficiency. So Linus chose a commercial version control system BitKeeper. BitMover, the owner of BitKeeper, authorized the Linux community to use this version control system free of charge out of humanitarian spirit. Finally, for some reason, BitMover took back the free use right of the Linux community, so Linus spent two weeks writing a distributed version control system in C language by himself. This is the origin of Git.

img

Git's work area and process

To understand how Git manages our code, the first thing to do is to understand how Git's work area is structured. Because, only by thoroughly understanding the composition of the Git work area, you can use the appropriate commands in the appropriate area. As shown in the figure below, this figure contains 4 workspaces of Git and some common operations.

git

Workspace: The workspace is the place where development and changes are usually made. It is the latest content that is currently seen. During the development process, it is the operation of the workspace.

Index: Temporary storage area. When the git add command is executed, the files in the work area will be moved to the temporary storage area. The temporary storage area marks the contents of the current work area that are managed by Git. When a certain requirement or function is completed Need to submit the code, the first step is to submit it to the temporary storage area git add

Repository: Local warehouse, located on your own computer, submit the contents of the temporary storage area git commit

Remote: A remote warehouse, a server used to host the code. The content of a remote warehouse can be modified by a local warehouse in a collaborative relationship distributed in multiple locations. After the local warehouse has modified the code, the code is synchronized to the remote warehouse git push

Generally speaking, the workflow of Git is divided into the following steps

1.在工作区开发,添加,修改文件。
2.将修改后的文件放入暂存区。
3.将暂存区域的文件提交到本地仓库。
4.将本地仓库的修改推送到远程仓库。

Git basic operation

git add

Add files to the staging area

# 添加某个文件到暂存区,后面可以跟多个文件,以空格区分
git add xxx
# 添加当前更改的所有文件到暂存区。
git add .

git commit

# 提交暂存的更改,会新开编辑器进行编辑
git commit 
# 提交暂存的更改,并记录下备注
git commit -m "you message"
# 等同于 git add . && git commit -m
git commit -am
# 对最近一次的提交的信息进行修改,此操作会修改commit的hash值
git commit --amend

git pull

# 从远程仓库拉取代码并合并到本地,可简写为 git pull 等同于 git fetch && git merge 
git pull <远程主机名> <远程分支名>:<本地分支名>
# 使用rebase的模式进行合并
git pull --rebase <远程主机名> <远程分支名>:<本地分支名>

git fetch

And git pull difference is git fetch operation will only pull remote changes will not perform merge operations automatically. No effect on your current code

# 获取远程仓库特定分支的更新
git fetch <远程主机名> <分支名>
# 获取远程仓库所有分支的更新
git fetch --all

git branch

# 新建本地分支,但不切换
git branch <branch-name> 
# 查看本地分支
git branch
# 查看远程分支
git branch -r
# 查看本地和远程分支
git branch -a
# 删除本地分支
git branch -D <branch-nane>
# 重新命名分支
git branch -m <old-branch-name> <new-branch-name>

Scenarios of using Git to solve problems at work

git rebase makes your commit record more clear and readable

Use of git rebase

Rebase translates to rebase. Its function is very similar to merge. It is used to merge the changes of a branch into the current branch.

As shown in the figure below, the figure below describes the changes in the submission history after rebase.

WechatIMG2.png

Now let's use an example to explain the above process.

Suppose we now have 2 branches, one is master and the other is feature/1. They are all checked out branches based on the initial submission of add readme. After that, the master branch adds 3.js and 4.js files, respectively. After two submissions, feature/1 also added files 1.js and 2.js, corresponding to the following two submission records.

At this time, the commit record of the corresponding branch is as follows.

The master branch is shown below:

image-20210531144909187.png

The feature/1 branch is as shown below

image-20210531145504071.png

It looks like this when combined

image-20210531145553107.png

At this point, switch to the feature/1 branch and execute git rebase master . After success, check the record git log

As shown in the figure below: you can see that the changes of the mater branch are applied one by one, and then the last commit of the master branch is used as the base point, and then each change of feature/1 is applied one by one.

image-20210531150719965.png

Therefore, our submission record will be very clear and there is no fork. The above demonstration is a relatively smooth situation, but in most cases, conflicts will occur during the rebase process. At this time, you need to manually resolve the conflicts and then use git add and git rebase --continue are used to deal with conflicts and complete the rebase process. If you do not want the result of a certain rebase, you need to use git rebase --skip to skip this rebase operation.

The difference between git merge and git rebase

Different from git rebase , git merge will generate an additional merge record when it is not fast-forward, similar to a submission message of Merge branch 'xxx' into 'xxx'

image-20210531151838328.png

In addition, when resolving conflicts, you only need to resolve the conflict once with merge, which is simple and rude, while when using rebase, you need to resolve each conflict in turn before submitting.

git rebase interactive mode

In development, we often encounter many invalid submissions on a branch. In this case, using the interactive mode of rebase can compress the multiple submissions that have occurred into one submission, and get a clean submission history. For example, the commit history of a branch is as follows:

image-20210518211345258.png

The way to enter interactive mode is to execute:

git rebase -i <base-commit>

The parameter base-commit is to specify the base point submission object of the operation, and the rebase operation is performed based on this base point. For the above submission history example, we need to compress the previous submission of the last submission object (ac18084) into one submission. The command format we need to execute Yes:

git rebase -i ac18084

At this point, you will enter a vim interactive page, and the editor will list information like the following.

image-20210518212036198.png

To merge this bunch of changes, we have to use the Squash strategy to merge, that is, to merge the current commit and its previous commit content, which can be expressed as the following. Under the rebase of the interactive mode, at least one pick is reserved, Otherwise, the command will fail to execute.

pick  ... ...
s     ... ... 
s     ... ... 
s     ... ... 

After modifying the file, press : and then wq save and exit. At this time, an editing page will pop up. This page is used to edit the submitted information. Modify it to feat: Correct, save it at last, and then use git branch view the submitted commit information. The submission record after rebase is shown in the figure below, is it much more refreshing? The rebase operation can make our submission history clearer.

image-20210518212812000.png

Pay special attention to the rebase operation only on the feature branch you use, and rebase on the integrated branch is not allowed, because this operation will modify the history of the integrated branch.

Use git cherry-pick to get the specified commit

git cherry-pick can be understood as a "picking" submission. Unlike merge, which merges all the submissions of a branch, it will get a single submission of a certain branch and introduce it to your current branch as a new submission. When we need to merge the commits of other branches locally, if we don't want to merge the entire branch, but only want to merge a certain commit into the local current branch, then we need to use git cherry-pick .

In the following scenario, there are three branches, feature/cherry-pick1 and feature/cherry-pick2 are based on the two functional branches checked out by the master, and the corresponding branch log records are as follows

image-20210518221001432.png

image-20210518221010458.png

The submission of the master branch is as follows
image-20210518221051734.png

Now the master only needs feature/cherry-pick1 and feature/cherry-pick2 for changes related to changes, and does not care about the modification of fix content. At this point, you can use the cherry-pick command.

Syntax: git cherry-pick [commit-hash]

commit-hash represents the hash value of a certain commit. Now, execute the following two instructions git cherry-pick e0bb7f3 and git cherry-pick c9a3101 . In the process, if there is a conflict, proceed to git add after resolving the conflict, and then execute git cherry-pick --continue . Finally, the submission on the master is as follows

image-20210518235707190.png

At this point, the required submission is applied on the master branch, and the desired effect is achieved. If multiple cherry-pick needs to be synchronized to the target branch, it can be abbreviated as git cherry-pick <first-commit-id>...<last-commit-id> , which is a left-open and right-closed interval. In other words first-commit-id submission will not be merged. If you need to merge the past , You can use git cherry-pick <first-commit-id>^...<last-commit-id> , which means that the first-commit-id including 060f65f678612b to last-commit-id will be merged.

Use git revert to roll back a certain commit

Imagine a scenario where you have two versions of your project to go online recently. These two versions are also accompanied by the fixes of the previous bugs. At the beginning, you fixed the bugs on the release branch of the first version. Suddenly one day before the release, the feedback from the testing side needs to change the content of the bug fixes in the first version to the second version. At this time, the submission of the integration branch of the first version should include the first version. Functional content, the submission of remaining bug fixes and the content submitted by other colleagues. It is definitely impossible to remove the previous commits about bug fixes through reset. At the same time, this approach is more dangerous. At this time, we don’t want to destroy it. What should I do if I want to withdraw the commit records of our remaining bugs from previous submission records? git revert comes in handy.

git revert operation. This operation will not modify the original submission record, but will add a new submission record to offset the operation.

Syntax: git revert <commit-id> for ordinary commit

git revert <commit-id> -m commit for merge

Let's use a case to understand this command. As shown in the figure below, suppose that the place framed by the red box is a submission that will cause a bug. After his submission, two more submissions were made, which included other colleagues' submit.

image-20210519142702752.png

At this time, if you want to get rid of the bug that caused the submission, execute git revert 1121932 , and then open to view the log. As shown in the figure below, you can see that a new commit record has been added. The msg generated by this commit is automatically generated. At the beginning of Revert, the commit record followed by the withdrawn commit-msg information did not disappear. At this time, the effect of code rollback was also achieved.

image-20210519142824836.png

In addition, git revert can also roll back multiple submissions

Syntax: git revert [commit-id1] [commit-id2] ... Note that this is a front opening and closing interval, that is, it does not include commit1, but includes commit2.

Rollback our submission there are two ways, one is the above-mentioned git revert command, you can also use git reset command, they both have what difference does it make?

git revert will create a new commit message to withdraw the previous modification.

git reset will directly return the submission record to the specified commit.

For individual feature branches, you can use git reset back the history records, and then use git push --force to push to the remote, but if you are on a multi-person collaboration integrated branch, it is not recommended to use the git reset command directly, but use the more secure git revert Order to withdraw the submission. In this way, the submitted historical records will not be erased and can be withdrawn safely.

Use git stash to stage files

There will be such a scenario, and now you are using your feature branch to develop new features. At this time, there is a bug in the production environment that needs to be fixed urgently, but this part of your code has not been developed yet and you don't want to submit it. What should you do? At this time, you can use the git stash command to temporarily store the modified files in the workspace, and then switch to the hotfix branch to fix the bug. After the repair is complete, switch back to the feature branch to restore the just saved content from the stack.

The basic commands are as follows

git stash //把本地的改动暂存起来
git stash save "message" 执行存储时,添加备注,方便查找。
git stash pop // 应用最近一次暂存的修改,并删除暂存的记录
git stash apply  // 应用某个存储,但不会把存储从存储列表中删除,默认使用第一个存储,即 stash@{0},如果要使用其他个,git stash apply stash@{$num} 。
git stash list // 查看 stash 有哪些存储
git stash clear // 删除所有缓存的 stash

Let's learn more about stash commands through a few pictures.

At this time, I am developing a new feature and amended the content in the 1.js file

image-20210519175036869.png

The development has not been completed yet. At this time, I want to switch to the hotfix branch to fix the bugs. I have to pause the development and switch to the hotfix branch, but now there is still content in the workspace. At this time, if I switch the branch, Git will report the following error

error: Your local changes to the following files would be overwritten by checkout:
        1.js
Please commit your changes or stash them before you switch branches.
Aborting

The above sentence means that there are file modifications in the workspace and cannot be submitted. You need to perform a commit or stash operation first, and execute git stash . The results are as follows

Saved working directory and index state WIP on stash: 22e561c feat: add 1.js

At this point, our work area is clean, and we can switch to the hotfix branch to fix the bug. Assuming that we have now completed the bug fix, we continue to switch back to the feature branch to develop the original function. At this time, we git stash pop The temporarily saved changes will be restored to the work area, as shown in the figure below.

image-20210519185011012.png

When we want to temporarily store files and switch branches to do something, we can use the mechanism of git stash

It is recommended that when using stash related commands, do not directly use the git stash command for temporary storage every time you temporarily save, but use git stash save "message..." to make a record of the information for this submission. In this way, when you want to apply the changes, first check all the temporary storage lists git stash list After that, it is recommended to use git stash apply stash@${num} to apply the corresponding stash, so that the existing stash list items will not be cleared, and can be applied to the current workspace. If this temporary storage is not needed, then manually clear it.

Undo changes in different work areas

During development, we often need to roll back code operations, and in different work areas, the way to roll back code is also different. As shown in the figure below, suppose you want to develop on the feature/revoke branch now,

First check the current status git status

image-20210520115802579.png

At present, our work area is very clean, without any modification operations. At this time, modify the code and check the status again. You can see that the 1.js file has been modified.

image-20210520115934693.png

Now we want to restore the 1.js file to the state before modification, that is, to withdraw the modification of the workspace, we can use git checkout -- <filename> . If we want to withdraw the modification of multiple files, separate the files with spaces, as shown in the following figure. As indicated, we withdrew the modification of the 1.js file, and the workspace was restored cleanly.

image-20210520120242475.png

If we have modified the file and submitted it to the temporary storage area. If we don’t want this part of the file, then we can use the git reset <filename> command to revoke a specific file. git reset will withdraw all existing temporary storage areas. As shown in the figure below, you can see that the file was successfully withdrawn to the working area after checking the status before and after.

image-20210520141538130.png

Configure git alias to improve work efficiency

Generally, we need to create a new branch for development in our work after receiving a development task. At this time, we need to use git branch , git checkout , git pull and other commands. After we have a meal, the development is completed, and when the code is submitted, we need to use git add such as 060f65f67864d4, git commit , git push are simple, but they are not concise enough to input. As a programmer, the purpose of developing programs is to improve our efficiency. Laziness is the source of human progress, so we can configure aliases. Simplify these commands.

Its basic usage is git config --global alias.<simplified character> original command

Such as the following example:

$ git config --global alias.co checkout
$ git config --global alias.ci commit
$ git config --global alias.br branch

Here, co stands for checkout, ci stands for commit, and br stands for branch. Subsequent submissions can be abbreviated as

image-20210519152804390.png

--global is a global parameter, that is, after one configuration, these commands can be applied to all warehouses under this computer. These commands actually update your global .gitconfig file, which is used to save the global git configuration, vim ~/.gitconfig . After executing this command, it will be displayed as follows. The following figure shows the git config --global alias just added by alias .

image-20210519153624712.png

In addition to the above-mentioned direct command method, you can also set the alias alias

Here is a common alias setting that I use. Replace the following configuration with [alias] in the .gitconfig file, and then you can use it happily~

[alias]
st = status -sb
co = checkout
br = branch
mg = merge
ci = commit
ds = diff --staged
dt = difftool
mt = mergetool
last = log -1 HEAD
latest = for-each-ref --sort=-committerdate --format=\"%(committername)@%(refname:short) [%(committerdate:short)] %(contents)\"
ls = log --pretty=format:\"%C(yellow)%h %C(blue)%ad %C(red)%d %C(reset)%s %C(green)[%cn]\" --decorate --date=short
hist = log --pretty=format:\"%C(yellow)%h %C(red)%d %C(reset)%s %C(green)[%an] %C(blue)%ad\" --topo-order --graph --date=short
type = cat-file -t
dump = cat-file -p
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

In this way, every time we want to view the history of Git, we don’t need to enter a long list of commands and use git lg directly. The following figure is the submission record in the axios source code, and the encapsulated git lg view the effect.

image-20210519162327693.png

The relationship between branches is clear at a glance, and the merge operation on which commit is performed is also very clear, which can help us trace the history of submissions and solve problems well.

to sum up

This article explains the Git environment construction, basic usage, and the usage of the more high-frequency Git commands in your work from the shallower to the deeper. Whether you are a front-end or back-end development or other end-of-development, the use of Git is indispensable in your daily work, we Not only need to be able to use it, but also to use it beautifully, flexibly, and steadily. In this way, you can be more comfortable when collaborating on projects with colleagues. After learning the Git usage skills in this article, practice more in your daily work, I believe it will bring you great gains!

references

Yifeng's git tutorial

The difference between Git merge and rebase branch merge commands

Open source works

  • Front-end tabloid of Zheng Caiyun

open source address www.zoo.team/openweekly/ (WeChat exchange group on the homepage of the tabloid official website)

Recruitment

ZooTeam, a young, passionate and creative front-end team, is affiliated to the product development department of Zheng Caiyun. The Base is located in picturesque Hangzhou. The team now has more than 40 front-end partners with an average age of 27 years old. Nearly 30% are full-stack engineers, a proper youth storm troupe. The membership consists of not only “veteran” soldiers from Ali and Netease, as well as newcomers from Zhejiang University, University of Science and Technology of China, Hangzhou Electric Power and other schools. In addition to the daily business docking, the team also conducts technical exploration and actual combat in the material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, and promotes and implements a series of internal technical products. Explore the new boundaries of the front-end technology system.

If you want to change that you have been tossed by things, hope to start to toss things; if you want to change and have been warned, you need more ideas, but you can’t break the game; if you want to change you have the ability to make that result, but you don’t need you; if If you want to change what you want to accomplish, you need a team to support it, but there is no position for you to lead people; if you want to change the established rhythm, it will be "5 years of work time and 3 years of work experience"; if you want to change the original The comprehension is good, but there is always the ambiguity of the window paper... If you believe in the power of belief, believe that ordinary people can achieve extraordinary things, believe that you can meet a better self. If you want to participate in the process of business take-off, and personally promote the growth of a front-end team with in-depth business understanding, complete technical system, technology to create value, and influence spillover, I think we should talk. Anytime, waiting for you to write something, send it to ZooTeam@cai-inc.com


政采云前端团队
3.8k 声望4k 粉丝

Z 是政采云拼音首字母,oo 是无穷的符号,结合 Zoo 有生物圈的含义。寄望我们的前端 ZooTeam 团队,不论是人才梯队,还是技术体系,都能各面兼备,成长为一个生态,卓越且持续卓越。