SpringBoot one-stop development (2)

Git version control

**Note:**Before starting to learn, make sure that your network can connect to Github smoothly: https://github.com, this is a foreign website, and it is very difficult to connect. As for how to achieve smooth access, everyone knows Understand.

In fact, version control is ubiquitous in our lives, such as your final or graduation thesis, because your writing is not standardized or the teacher is not satisfied, your teacher may ask you to change it again and again, so there will be The following situation:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-2D31q0qQ-1684911412343)(https://gimg2.baidu.com/image_search/src=http://5b0988e595225 .cdn.sohucs.com/images/20200417/1e63ac0f4d8442cb8c9ab1cb73f510c4.jpeg & amp; refer=http://5b0988e595225.cdn.sohucs.com & amp; app=2002 & amp; ;q=a80 &n=0 &g=0n &fmt=jpeg?sec=1644370473 &t=fa8742db0b4f8db635ec003e37bca76c)]

The papers in our hands may go through multiple version iterations, and finally we will select the best version as the final submitted paper. The use of version control is not only to record the version iteration history, but also to be able to roll back to the previous version at any time to realize time retrospective. At the same time, our thesis may be completed by multiple people, so how do multiple people achieve synchronization, how to ensure that the changes submitted by each person can be summarized normally, and how to resolve conflicts, these problems need an excellent version control system to solve.

Into Git

The projects we develop also need a suitable version control system to help us better manage version iterations, and Git was born for this reason (I won’t elaborate on the history of Git here, interested friends You can understand it by yourself, it was developed by a top boss in C language for only 2 weeks in a rage, and you will meet him in the following chapters)

First, let’s understand how Git works:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-HI64KyrI-1684911412344)(https://gimg2.baidu.com/image_search/src=http://img2020 .cnblogs.com/blog/932856/202004/932856-20200423143251346-796113044.jpg &refer=http://img2020.cnblogs.com &app=2002 &size=f9999,10000 &q =a80 & amp;n=0 & amp;g=0n & amp;fmt=jpeg?sec=1644374894 & amp;t=7c2044128f7851ecd92de3c01f0187ca)]

As you can see, it is roughly divided into 4 sections:

  • Working directory: store the code we are writing (when our new version is developed, we can submit the new version)
  • Temporary storage area: Temporarily save the content to be submitted (the new version will be stored in the local warehouse after submission)
  • Local warehouse: a version control warehouse located on our computer (which stores the addition and deletion information of each version code of the current project)
  • Remote warehouse: the version control warehouse located on the server (the version information on the server can be pushed up by the local warehouse, or fetched from the server to the local warehouse)

It is a distributed control system, so in general, each of us has a local warehouse on the computer, and everyone jointly pushes the version iteration information to the remote warehouse.

Through this series of operations, we can submit a new version every time a version or function is developed, so that we can control the version iteration of the project well, and we can roll back to the previous version at any time If you want to go back and check what code is added or deleted in the new version, you can check it at any time.

Install Git

First, please go to the Git official website to download the latest installation package: https://git-scm.com/download/win

This demonstrates how to install the Git environment step by step.

After the installation is complete, you need to set the user name and email address to distinguish different users:

git config --global user.name "Your Name"
git config --global user.email "[email protected]"

Introduction to basic commands

Create a local repository

We can use any folder as a local warehouse, enter:

git init

After input, a .git directory will be automatically generated. Note that this directory is a hidden directory, and the current directory is our working directory.

After the creation is successful, we can check the current status, enter:

git status

If it has been successfully configured as a Git local warehouse, you can see after entering:

On branch master

No commits yet

This means we haven’t committed anything to the repository, which is an empty state.

Add and Submit

Then let’s take a look at how to use git to manage the version of our document. We create a text document, write a little content, and then enter:

git status

We will get the following prompt:

Untracked files:
  (use "git add <file>..." to include in what will be committed)
hello.txt

nothing added to commit but untracked files present (use "git add" to track)

Among them, Untracked files means untracked files, that is to say, if a file is in an untracked state, git will not record its changes, and always treat it as a newly created file, here we add it to the temporary storage area , then it will automatically become tracked:

git add hello.txt #You can also add . Add all the files in the directory at once

Check the current status again:

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
new file: hello.txt

Now the color of the file name has changed to green, and it is under Changes to be committed, so our hello.txt has now been added to the staging area.

Next, let’s try to submit it to the Git local warehouse. Note that you need to enter a description of the submission for subsequent viewing, such as what content has been modified or added in this submission:

git commit -m 'Hello World'

Then we can view our commit record:

git log
git log --graph

We can also view the details of the last change:

git show [You can also add commit ID to view the specified commit record]

Check the current status again, it is already cleared:

On branch master
nothing to commit, working tree clean

Then we can try to modify our text document. Since the current file is already being tracked, git will track its changes. If the file has been modified, we will get the following results when we check the status again:

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
modified: hello.txt

That is to say, this file is now in a modified state. If we modify it, we can submit our new version to the local warehouse:

git add .
git commit -m 'Modify Text'

Then let’s check the submission records, and we can see that there are two submission records.

We can create a .gitignore file to determine a file ignore list. If the file in the ignore list exists and is not tracked, then git will not check it:

# This will match all files ending with txt
*.txt
# Although the above excludes all files ending in txt, this does not exclude
!666.txt
# You can also specify a folder directly, all files under the folder will be ignored
test/
# All files ending in txt in the directory, but not including subdirectories
xxx/*.txt
# All files ending in txt in the directory, including subdirectories
xxx/**/*.txt

Once created, let’s see if the file we ignored is still detected.

Rollback

When we want to go back to the past version, we can perform a rollback operation. After execution, the content of the workspace can be restored to the state of the specified submission:

git reset --hard commitID

After execution, it will be directly reset to the state at that time. Looking at the commit log again, we found that all subsequent logs disappeared.

So what if I want to go back now? We can view all operation records of all branches by:

git reflog

In this way, you can find the previous commitID and reset it again.

branch

Branches are like a branch on our tree. They may start out as the same branch, but as they grow, they start to diverge. This is the branch. The same is true for our code. We may use a single branch when writing basic functions at the beginning, but one day we hope to make our project into two projects with different directions based on these basic functions, such as a web site in one direction , the other direction is the game server.

Therefore, we can separate N branches on a trunk, and maintain the codes of multiple branches separately.

Create a branch

We can view the branches existing in the current warehouse with the following command:

git branch

We found that there is a master branch by default, and we also use the master branch. Generally, the master branch is an official version update, while other branches are usually updated frequently during development. Let’s then create a new branch based on the current branch:

git branch test
# The corresponding delete branch is
git branch -d yyds

Now let’s modify the file, submit it, and check the submission log again:

git commit -a -m 'branch master commit'

By adding -a, the modified files that are not put into the temporary storage area are automatically put into the temporary storage area and the commit operation is performed. Looking at the log, we found that our commits are now only valid on the master branch, and the newly created branch has not been modified.

We switch the branch to another branch:

git checkout test

We will find that the file becomes the state when this branch was created, that is to say, our file content is isolated from each other under different branches.

Let’s submit the change again now, and we will find that it only takes effect on the yyds branch. We can look at the current branch state:

git log --all --graph

Merge branch

We can also finally merge the updated content of the two branches into the same branch, and we switch back to the main branch first:

git checkout master

Then use the branch merge command:

git merge test

You will get the following prompt:

Auto-merging hello.txt
CONFLICT (content): Merge conflict in hello.txt
Automatic merge failed; fix conflicts and then commit the result.

A conflict occurred during the merging process, because both branches have modified the hello.txt file, so now they are merging together, whose hello file should be kept?

We can see where the conflict occurred:

git diff

Therefore, now we roll back the version of the master branch to the content before modifying hello.txt or directly modify it to the latest version, so that there will be no conflicts, and then perform a merge operation again. Now the two branches are successfully merged into the same a branch.

Rebase branch

In addition to directly merging branches, we can also perform rebase operations, which are different from merging. Merging is the process of returning a branch to the trunk, while rebasing is the process of directly modifying the starting position of a branch. For example, we want to rebase yyds to master. Then yyds will move the branch starting point to the last commit position of master:

git rebase master

After the rebase, the yyds branch is equivalent to synchronizing all the commits of the previous master branch.

Preferred

We can also choose to apply the commits on other branches to the current branch. This operation is called cherrypick:

git cherry-pick <commit id>: Merge a commit separately

Here we create a new file on the master branch, submit the update, and then apply the update to the test branch through cherry-pick.

Use IDEA version control

Although we basically explained how to use the command line of git, but there is no graphical interface, it will always feel very abstract, so here we use IDEA to demonstrate, IDEA integrates the git module, which allows us to manage the git version Graphical display, of course, in addition to IDEA, there are also some independent software such as: SourceTree (very easy to use)

After opening IDEA, find the version control module, we directly click to create a local warehouse, it will automatically use the root directory of the current project as our local warehouse, and all the code we write and other files in the project directory can be version controlled.

We found that all the class files being written in all projects turned red, that is, they were in an untracked state, and then we made the first initial submission. After submission, we can see all the local warehouse submission records below.

Then let’s integrate the web environment. After creating a new class, IDEA will prompt us whether to add the file to Git, that is, whether to put it in the temporary storage area and enable tracking. We can directly compare the similarities and differences between the two codes .

Next, let’s demonstrate branch creation and branch management.

Remote repository

The remote warehouse is actually a warehouse located on the server. It can save our version history at the remote end, and can realize multiple people to collaborate on projects at the same time. Everyone can synchronize other people’s versions and see other people’s version submissions, which is quite to host our code on a server.

There are public and private remote warehouses. The public remote warehouses include GitHub, Code Cloud, Coding, etc. They are all open to the outside world. After we register an account, we can use remote warehouses for version control. The largest one is GitHub, but its server In foreign countries, our domestic connection may be a little stuck. Private ones are generally self-built remote warehouse private servers such as GitLab, which are more commonly used in companies. It is only open to the company, not to the outside world.

Here we use GitHub as an explanation, the official website: https://github.com, first complete the user registration.

Remote account authentication and push

Then we can create a custom remote warehouse.

After creating the warehouse, we can push the content in the local warehouse to the remote warehouse by pushing.

git remote add name remote warehouse address
git push remote warehouse name local branch name[:remote branch name]

Pay attention to the two parameters behind push, one is the remote name, and the other is the local branch name, but if the local branch name is the same as the remote branch name, then there is no need to specify the remote branch name, but if The branch we want to push does not have the same name at the remote end, so it needs to be specified additionally. You need to log in to your account before pushing. GitHub currently does not allow user name and password authentication, but only allows personal AccessToken to verify identity, so we need to generate a Token first.

After pushing, we found that the content in the remote warehouse has been consistent with the content in our local warehouse. Note that the remote warehouse can also have many branches.

But this is more troublesome. We need to enter the user name and password every time. Is there a way to do it once and for all? Of course, we can also use SSH to achieve one-time verification. We can generate an rsa public key locally:

ssh-keygen -t rsa
cat ~/.ssh/github.pub

Then we need to upload our public key on GitHub. When we visit GitHub again, it will be automatically verified and there is no need to log in. Later, in the Linux part, we will explain the principle of SSH in detail.

Then we modify the content of the workspace, submit it to the local warehouse, and then push it to the remote warehouse. During the submission process, we pay attention to the submission record:

git commit -a -m 'Modify files'
git log --all --oneline --graph
git push origin master
git log --all --oneline --graph

We can bind the remote and local branches, and there is no need to specify the branch name after binding:

git push --set-upstream origin master:master
git push origin

In the case of a local warehouse corresponding to a remote warehouse, the remote warehouse is basically pure code hosting (the feeling of cloud disk is purely for storing your code)

Clone project

If we already have a remote warehouse, we need to continue writing code on the code of the remote warehouse, what should we do at this time?

We can use the clone operation to copy all the contents of the remote warehouse to the local:

git clone remote warehouse address

In this way, the local can directly keep in sync with the remote.

Crawling, pulling and conflict resolution

Let’s look at it next. If at this time, multiple local warehouses correspond to a remote warehouse, for example, in a team, N people are using the same remote warehouse, but they are only responsible for writing and pushing the code of their own business part. , which is what we often call collaborative work, then at this time, we need coordination.

For example, programmer A has completed his module, then he can submit the code and push it to the remote warehouse. At this time, programmer B will also start writing code. Since the remote warehouse has other programmers’ submission records, programmer B’s The local warehouse is inconsistent with the remote warehouse. At this time, it is necessary to perform a pull operation first to obtain the latest submission in the remote warehouse:

git fetch remote warehouse #Crawl: only fetch but not merge remote branches, we need to manually merge later to submit
git pull remote warehouse #Pull: get + merge

After programmer B pulls the latest version, he writes his own code and submits it to realize multi-person cooperation to write the project, and during the pulling process, the content submitted by others can be synchronized to the local, which greatly improves the development efficiency .

If there are inconsistencies in the work, for example, we now have two local warehouses, one warehouse modifies hello.txt and submits it directly, and the other warehouse also modifies hello.txt and submits it directly, the following error will be obtained:

To https://github.com/xx/xxx.git
 ! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/xx/xxx.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Once a local warehouse pushes the code, the push of another local warehouse will be rejected because the current file has been modified by other pushes. Our side is equivalent to another version, which is the same as the previous two branch merges. There is no conflict, so we can only solve the conflict problem.

If the submission in the remote warehouse and the submission in the local warehouse do not write the same file, then you can pull it directly:

git pull remote warehouse

After the pull, it will be merged automatically, and we can submit it after the merge is completed.

But if the same file is modified in both commits, then you will encounter the same situation as multi-branch merge, and conflicts will occur during the merge, and we need to resolve the conflicts ourselves.

We can demonstrate in IDEA the problems that may be encountered in actual development scenarios.