A quick introduction to the distributed version control system Git

As a programmer, in addition to our own single-person development projects, more situations require multi-person collaborative development. If you use methods such as hard disk copy or sending compressed packages (although our company commonly uses them), it is definitely not 版本控制系统as safe and efficient as Lai. Regardless of unexpected situations such as hard disk loss or file corruption, the merge of copied code is very troublesome. This article will bring you a quick start 分布式版本控制系统Git.

1 Classification of version control systems

1.1 Centralized

The version library of the centralized version control system is stored in the "central server", and all operations need to be connected to the Internet, local area network or Internet. For example, if you modify a certain bug, but your computer cannot be connected to the Internet or the "central server" is down, you cannot submit it to the "central server" at this time, which will affect you 版本管理. Representative tool: SVN.

1.2 Distributed

There is no "central server" in distributed version control. Every computer has a complete version library. You can submit code, merge branches, resolve conflicts, and other operations on the local branch. When multiple people are collaborating, they only need to push their own modifications to the other party, and then they can see the other party's operation records. Representative tool: Git.

2 Introduction to Git

Git is a tool 开源的分布式版本控制系统that can effectively and quickly handle version management of small to very large projects. It is Linus Torvaldsalso Linuxan open source version control software developed to help manage kernel development. First look at the schematic diagram below:
insert image description here
Git has a local warehouse and a remote warehouse, both of which have a complete version library. The role of the remote warehouse is to facilitate the push and pull of code between developers.

3 Git workflow flow chart

insert image description here
Git command:

  1. clone (clone): clone the code from the remote warehouse to the local warehouse
  2. checkout: Check out a repository branch from the local repository and make revisions
  3. add (add): Save the code to the staging area before submitting
  4. commit (submit): Submit to the local warehouse
  5. fetch (fetching): update the version library from the remote warehouse to the local warehouse without merging
  6. pull (pull): update the version library from the remote warehouse to the local warehouse, and automatically merge
  7. push (push): Push the modified content of the local warehouse to the remote warehouse

4 Git installation and configuration

4.1 Git download and installation

Official website: Git official website
insert image description here
The current latest version is 2.37.3, run the program after downloading, all defaults are sufficient. After the installation is complete, right-click on the desktop or any folder, and if the following two appear, it means success:
insert image description here

Git GUI: a graphical interface tool provided by Git

insert image description here

Git Bash: A command-line tool provided by Git

insert image description here

This article only introduces the commands Git Bashin , and the interface tools are easy to use after understanding the commands.

4.2 Git basic configuration

After the installation is complete, the user information 必须must , because Git will use this user every time it submits a version

  1. Open Git Bash
  2. Set user information (the mailbox may not be the real mailbox)
git config --global user.name '你的用户名'
git config --global user.email '你的邮箱'
  1. View configuration information
git config --global user.name
git config --global user.email

5 Commonly used commands in Git local warehouse

5.1 Basic commands

5.1.1 Initialize the local warehouse

Command form:

git init

Create a new folder git_test, open it after entering the directory Git Bash, enter the above command, and if the following content appears, the initialization is successful.
insert image description here
At this time, a hidden .gitfolder , which contains your version library information. .gitThe directory containing the folder is called 工作目录.
insert image description here

5.1.2 View warehouse status

All files in the working directory have a status. New files are untracked, modified existing files are unstaged, added to the temporary storage area is staged, and submitted to the warehouse is submitted. (committed).

Command form:

git status

Enter the above command to view the current status of the warehouse.
insert image description here
The command line prompts that: there is nothing to submit on the master branch (create or copy files, and then use the "git add" command to track)

5.1.3 Add to the staging area

Command form:

git add 文件名|通配符

The above command can add one or more files in the workspace to the temporary storage area

To add a single file: git add filename or directoryname
To add all modified files: git add .

For example: create a new txt file called file01 in
our working directory (you can create it with the right mouse button, or use the command ), and then execute the command you will get another prompt: the command line prompts that: file01.txt is not Tracked files, use " " to include content to commit. Then we execute the command , and then execute the command again, and we can find that its status has changed: Command line prompt: file01.txt file is waiting to be submitted, use "git rm --cached" to return to the untemporary status.git_testtouch file01.txtgit status
insert image description here
git add 文件名
git add file01.txtgit status
insert image description here

The above operation is to add a new file. If the submitted file is modified, the status will be changed to unstaged. suppose youThe operation of 5.1.4 submission to the warehouse has been completed, then modify file01.txtthe content , add count=1, and then execute git statusthe command :
insert image description here
Command line prompt: Your modification has not been temporarily saved, and cannot be submitted! You can use "git add" to update what you want to commit, or "git restore" to discard changes in your working directory.
Then we can execute git add file01.txtthe or git add .command here, and then execute git statusthe command , and we can find that its status has changed:
insert image description here
we can see that the modified file01.txtfile has been successfully added

5.1.4 Submit to local warehouse

Command form:

git commit[ -m "注释内容"]

Through this command, you can submit the staged files to the local warehouse. []The part in means optional, 推荐必填. Because 注释内容itself is necessary, if you do not fill it here, the next step will open other editors (such as vim editor or others) for you to fill in.
insert image description here
At this time, execute git statusView
insert image description here
and you can see that it has been successfully submitted, and the previous has No commits yetalso disappeared. Note : The submission step is required 先添加到暂存区再提交, and the submission to the warehouse mentioned below refers to these two consecutive steps.

5.1.5 View logs

Command form:

git log[option]

options:

  • --all show all branches
  • --oneline display commit message as one line
  • --graph display as a graph

Through this command, you can view all the operation records of the warehouse. The long string of strings behind
insert image description here
here is the version number (commitID), and the brackets behind indicate that the meaning here iscommitHEAD当前所在分支The current branch is the master branch. Author indicates the author, Date indicates the submission time,add file01That's what we fill in 提交信息.

We can add all the above common options, and output the log without options for comparison:
insert image description here

The commitID is shortened, the user information and date are omitted, and only the key branches and comments are left, so that we can see the log more clearly. At the same time, the effect of using the abbreviated commitID is the same, because it is unique.

5.1.6 Version Reset

Command form:

git reset --hard commitID

For example, the above has been submitted twice, the first time to create a file01 file, and the second time to modify the content of file01 file, so there are two submission records, after executing the above command, the current version will be reset to the first submission record At this
insert image description here
time You can no longer see the record of the second submission in the log, so can we use this command to reset the current version to the second submission record? The answer is yes, we can execute the command through the commitID of the second submission above.
insert image description here
You can see that there is a record of the second commit in the log, but if we clear the content of the command line tool and cannot get the commitID, can we reset it back? The answer is yes, another command needs to be used here: git reflog. This command can be understood as that 显示所有引用日志it can view all version operation records, including submit and reset, and git logonly display the current version ( HEAD指针) and previous version information.
insert image description here
Here we compare the output of the two commands, there are only two submission records git logbelow , and git reflogthere are four records below, from top to bottom are the latest to oldest records, respectively: 1. Reset to the second submission , 2. Reset to the first submission, 3. Submit the updated file file01.txt, 4. Submit the new file file01.txt. So we can get the commitID we want here.

5.1.7 Ignore list

We added a new file02.txtfile , but we don't want to submit it, and at the same time want to use git add .to submit all with one click. At this time, we can create a new .gitignorefile and write file02.txtsave in it. Next, I will execute it before and after saving. git statusCheck the status of the file
insert image description here
and you can see Include file02.txtfiles , and ignore them after saving.

5.1.8 Configure aliases for common commands

Some commands will be very long with options, but they are often used. For example git log --oneline --graph, we can configure an alias for it at this time.

  1. Open the user directory and create .bashrca file
    Open [C drive] - [User], my user directory here is [Administrator], open the directory and create a new .bashrcfile. Some windows systems do not support the creation of files beginning with dots, which can be opened Git Bashand executed touch ~/.bashrc.
  2. .bashrcEnter the following in the file
alias git-log='git log --all --oneline --graph'

In this way, the alias is set successfully. We can execute git-logit to try the effect
insert image description here
and find that it git log --oneline --graphis . Note that .bashrcafter the content is modified, Git Bashit needs to be restarted to take effect.

5.2 Branch command

As the name suggests, a branch is a part that is separated from the main body. Branches can separate the development environment from the production environment, preventing development from affecting the production environment. There are two most commonly used branches: master(生产)分支and dev(开发)分支. For other more detailed branches, you can use Baidu. Here is an example. For example, if the leader asks you to develop a new function, you should create dev分支a new branch on . Merge to above, which can ensure the stability and security of the production environment while developing new functions.feature/xxxdev分支master分支

5.2.1 View local branch

Command form:

git branch

insert image description here
When the warehouse is initialized, masterthe branch . You can see that there is only one master分支, and 当前所在分支it is master分支(the color is green and preceded by an asterisk)

5.2.2 Create a local branch

Command form:

git branch 分支名

insert image description here
You can see that it has been successfully created dev分支, but 当前所在分支still master分支.

5.2.3 Switch branches

Command form:

git checkout[ -b] 分支名

No parameter -bcan only switch the created branch, and adding parameters -bcan create and switch when the branch does not exist.
insert image description here

5.2.4 Merging branches

Commits on one branch can be merged into another branch. For example, as mentioned earlier, as the master 生产分支, our new functional modules should not be developed on it. We can create a new dev branch, and merge it into the master branch after the development is completed.
Command form:

git merge 分支名

Example: Continue to use the previous example, we switch to dev分支and then create a file03.txt file, execute in order git add ., git commit -m 'add file03', git-log.
insert image description here
At this point, you can see the latest version record, the branch is dev (the HEAD pointer points to the current branch), and the content of the comment is add file03what we just submitted. Then switch back to the master branch, and
insert image description here
you can see that the version record of the master branch has only reached update count=1this step. At this time, we want to dev分支merge the changes of master分支to , and then we can execute it git merge dev. Note that if we want to merge into the master branch, we need to switch to the master branch. If we cannot execute it on the dev branch, it will have no effect.
insert image description here
As you can see, dev分支the changes from above have been successfully merged into master分支the above.

5.2.5 Delete branch

Command form:

git branch -d branch name//Usually use
git branch -D branch name//Forcibly delete, used when the deleted branch is newer than the current branch version, for example, dev has one more commit than master, if you want to delete dev, you must use the command

5.2.6 Resolving Conflicts

Conflicts arise when we change the same file on two branches. masterFor example, in the above example, there are devboth file01.txtfiles and content count=1, we switch to dev分支, change the content count=2to submit, then switch to master分支, change the content count=3to submit, and then we merge dev into master,
insert image description here
at this time the command line prompts : Failed to automatically merge file01.txt, you need to resolve the conflict and submit the result. We can use Notepad to open file01.txt:
insert image description here
both branches have modified the same line of the same file. Git does not know how to choose when merging, so it is simply handed over to the person who executes the merge command. From HEAD to the dotted line is the content of the current branch, and from the dotted line to dev is the content of the dev branch. Resolving conflicts is very simple and violent, that is to stay 你需要提交的内容, for example, if I want to stay here count=3, then delete other content,
insert image description here
and then submit it again

6 Git remote repository

We talked about the operation commands of the local warehouse before, only when the remote warehouse is associated 完整的Git工作流程. So how do we build a Git remote warehouse? In fact, it can be realized through some code hosting services provided on the Internet, such as Github, Gitee and so on. Github needs to access the Internet scientifically for some reasons, so we choose Code Cloud here.

6.1 Registration code cloud account

Code Cloud is a code hosting platform in China. If you want to use its services, you must first register an account, and the registration process is skipped directly.

6.2 Create a remote warehouse

There is a plus sign in the upper right corner of the code cloud. After expanding it, click [New Warehouse]
insert image description here
and fill in the name of the warehouse. The system will automatically fill in the path.
insert image description here
Others can be created without changing, and
insert image description here
the appearance after creation is shown in the figure above.

6.3 Configure SSH public key

Now that the remote warehouse has been created, we want to push the local warehouse to the remote warehouse. The remote warehouse needs to verify our identity. There are two ways, one is to enter the Git account and password, and the other is the SSH public key. Recommended Use the second.

First open Git Bashand execute the following command to generate the public key:

ssh-keygen -t rsa

Then just go back and forth,If the public key already exists, it will be overwritten automatically. The generated public key can be viewed by executing the following command:

cat ~/.ssh/id_rsa.pub

insert image description here
In this way, we get the public key we need, and then where should we fill it? Open Code Cloud, expand the avatar menu in the upper right corner,
insert image description here
click [Settings] according to the above picture, and then click [SSH Public Key] on the left menu bar, fill in the obtained public key in the public key column, and sometimes the title
insert image description here
column will be automatically filled. You can also change it as you like, and click OK to add it successfully. So how to verify that the public key is valid? Open and Git Bashexecute ssh -T [email protected], if the following content appears, it means success
insert image description here
Note : If you visit it for the first time, you will be asked whether to continue to visit, hereType yes and press Enter, and then you can see the content of the above picture.

6.4 Operating remote warehouses

6.4.1 Add remote warehouse

Command form:

git remote add 远端名称 仓库路径
  • Remote name, the default is origin
  • Warehouse path, obtained from the remote server

We open the new warehouse on the code cloud, get the SSH address of the warehouse from it
insert image description here
, and then execute the command Git Bashin
insert image description here

6.4.2 View remote warehouse

Command form:

git remote

insert image description here

6.4.3 Push to remote warehouse

Command form:

git push[ -u][ <远程主机名> <本地分支名>[:<远程分支名>]]

If executed directly git push, it will prompt that the current branch is not associated with the remote branch, and we need to push the current branch and bind the association.
insert image description here

There are two methods, the first is:

git push origin master

origin is a common remote host name, and can be omitted when the local branch name is the same as the remote branch name, so there can be only one master. This way of writing has a disadvantage, that is, it must be written in full every time. The second method is:

git push -u origin master

The parameter -uis --set-upstreamthe abbreviation of , which is used to associate the current local branch (ie master) with the remote branch (also called master), and subsequent pushes can be executed directly git push.
insert image description here
At this time, it was successfully pushed to the remote warehouse, and the master branch was created, origin/masterwhich is the remote branch. We open the warehouse on Code Cloud, and we can see that all the files have been pushed successfully, and the historically submitted versions can also be viewed.
insert image description here
We can also execute git branch -vvto view the association relationship between the local branch and the remote branch. If you see masterfollowed by in the figure below, origin/masterit means that the association is successful.
insert image description here

Others : There aregit push other parameters besides the command , which will not be expanded here, and those who are interested can execute it to view it for self-research.-ugit push -h
insert image description here

Roll back the remote warehouse : git pushto the remote warehouse, the normal push will be rejected, you need to use the mandatory command git push -fto the remote warehouse to complete the rollback.

6.4.4 Cloning from a remote repository

We have successfully pushed the local warehouse to the remote warehouse. If our colleagues want to develop together, he can clone from the remote warehouse.
Command form:

git clone[ 远程仓库路径][ 本地目录名称]

远程仓库路径It is the url of the warehouse, which can be SSH or other, as shown in the figure below,
insert image description here
insert image description here
and the warehouse is successfully cloned.
本地目录名称The effect is 修改本地项目名称that if not added, the directory name of the local project is the name of the remote warehouse. For example, if the remote warehouse name is above git_test, Cloning into 'git_test'it means that a git_testdirectory , and the content of the remote warehouse is cloned to this directory. We can add it git_testf_01, and the directory name will automatically change.
insert image description here
Here we can execute lsthe command , which
insert image description here
can view all files in the current directory. As you can see, git_test_01the directory

6.4.5 Fetching and Pulling

抓取Command form:

git fetch[ <远程仓库名> [ <分支名>]]

Tip: If you do not specify the remote warehouse name and branch name, the corresponding branch will be fetched.

Continue to use the above example git_test, add a new file04.txtfile in the directory and submit it to the warehouse, and then push it to the remote warehouse. Open git_test_01the directory and execute the grabbing command
insert image description here
Execute git-logYou can see that the latest version library is origin/masterthe remote branch, but the local masterbranch is not the latest version library, so you need to execute git merge origin/masterMerge Branch
insert image description here
At this time, the local masterbranch is also the latest version library

Pull command form:

git pull[ <远程仓库名> [ <分支名>]]

Tip: If you do not specify the remote warehouse name and branch name, the corresponding branch will be fetched.

The difference between fetching and fetching is that fetching does not automatically merge, whereas fetching performs a merge after fetching. We git_testcan add a new file05.txtfile in the directory and submit it to the warehouse, and then push it to the remote warehouse. Open git_test_01the directory and execute the pull command
insert image description here
. You can see that the local masterbranch .

6.4.6 Conflict resolution

** After the local warehouse is changed, before pushing to the remote warehouse, it should be fetched first, and then pushed. **If user A modifies the file01 file and pushes it to the remote warehouse, and user B also modifies the file01 file locally, then he will fail to push it to the remote warehouse.
insert image description here
The prompt says that the remote warehouse has work that you do not have locally. It is recommended that you first integrate the changes in the remote warehouse. That's why the fetch is performed first. After we execute the crawl (usually pull, here is for the purpose of crawling), output the log to view.
insert image description here
The count is changed to 8 remotely, and the count is changed to 9 locally. At this time, the execution 合并分支will conflict.
insert image description here
If you find it 抓取+合并too troublesome, you can also perform pull directly, and the effect is the same.
insert image description here
HEAD in the figure means local, and the last version number means remote.

Don’t be afraid of conflicts, conflict resolution is the same as the previous local warehouse, that is, 需要提交的内容留下delete the rest, then submit to the local, and then push to the remote. Here we will delete this content, leavingcount=10, and submit.
insert image description here
In this way, we have resolved the conflict, and the last step is to push the resolved file to the remote warehouse.
insert image description here
At this point, the introductory knowledge of Git is over. This is what I have sorted out after studying, thinking and practicing. After all, it is better to read more than to write more, and it is better to say (tell others) more than to write more. I hope this article can be of some help to those getting started.

Guess you like

Origin blog.csdn.net/sunddy_x/article/details/126822966