Version Control System-GIT

Overview of version control system

Actual scene in development

Scenario 1: Code backup

Scenario 2: Code restoration [version control]

Scenario 3: Collaborative development

Scenario 4: Tracing the problem code

Version control system

The version control system can track the entire process of the project from start to finish. For programmers, version control technology is a bridge for team development, helping multiple people to collaborate and develop large projects simultaneously.

The core task of the software version control system: check the historical operation records of the project and realize collaborative development.

Two common types of version control

  • Centralized version control tool: Centralized version control tool. The version repository is centrally stored on the central server. Everyone in the team downloads code from the central server when working. After everyone makes changes, they are submitted to the central version warehouse. The commit code needs to be connected to the Internet. Such as SVN.
  • Distributed version control tool: The distributed version control system can have no "central server". Everyone's computer is a complete version warehouse, so that when working, there is no need to network. Because the version repository is on your own computer. Multi-person collaboration only needs to modify individually, and the development is complete, and then push to the other party. When pushing, the entire version warehouse is pushed over the network. Such as GIT.

Introduction to Git

Git is an open source distributed version control system that can effectively and quickly handle the version management of small to very large projects.

  • Speed, simple design
  • Strong support for non-linear development mode (allowing thousands of parallel development branches)
  • Fully distributed
  • Ability to efficiently manage super-large-scale projects like the Linux kernel (speed and data volume)

Git workflow

Clone: ​​clone, clone code from remote warehouse to local warehouse, the first operation

Push: After the code is completed, when you need to share the code with team members, push the code to the remote warehouse

Pull: Pull, from the remote library code to the local library, automatically merge (merge), and finally put it in the workspace

checkout: Check out the contents of the local warehouse to the workspace

add: Submit the code to the staging area before submitting

commit: Submit to the local warehouse

basic concepts

Local warehouse: a code base on the local host, which can exist independently or be associated with a remote warehouse

  • Work area: Any file revisions (additions, deletions and changes) are placed in the work area first, and the work area is not associated with any warehouse branch
  • Temporary storage area: After the revised file is added from the work area, it is associated with a certain warehouse branch. Only the files that enter the temporary storage area can be committed to the local warehouse.

Remote warehouse: a host on a local area network or the Internet, a host or platform for storing code libraries, such as GitHub,Gitee

Branch: The code is stored in the warehouse. The default is the master branch. You can create many sub-branches on the basis of the master branch, such as develop, BugFixetc.

Folder contains a .githidden directory (Git working directory), use the file directory using the Git version management.

.gitA lot of configuration information, log information, file version information, temporary storage area information, etc. are stored in the hidden directory. .gitThere are many files in the folder, and one of the index files is the temporary storage area, which can also be called stage. The temporary storage area is a place to temporarily save modified files.

summary

Git is a distributed version control system.

Problems solved by Git: code backup and restoration; collaborative development; simultaneous development of multiple versions and tracing of problem codes.

Local warehouse: store all version codes

Work area: Edit code area

Staging area: put all the codes to be submitted here

Remote warehouse: for sharing code between teams

Branch: simultaneous development of multiple versions, master master branch, develop development branch, test branch

Remote warehouse operations:

  • clone Clone: ​​Download code from remote warehouse for the first time

  • pull Pull: get other members of the team to submit changes

  • push Push: upload the completed code to the remote warehouse

Local warehouse operations:

  • checkout Check out: check out the contents of the local warehouse to the workspace
  1. add Add: Add code to the staging area, ready to submit
  2. commit Submit: Submit the code in the temporary storage area to the local warehouse

Git download and installation

Download address: https://git-scm.com/download

Git GUI: Graphical interface tools provided by Git

Git Bash: Command line tool provided by Git

Git basic configuration

basic configuration

Make global settings, such as user name, email:

# 设置全局用户名
git config --global user.name "YOUR_NAME"    
# 设置邮箱
git config --global user.email "YOUR_EMAIL" 

Information will be provided by the above command to save the .gitconfigfile

Among them, --globalspecify the global configuration. If this parameter is not used, it is the current warehouse configuration.

Above default configuration information stored in the user directory, if set incorrectly, you can delete .gitconfigthe file and repeat the process over command.

View configuration information:

# 查看配置信息
git config --list 

Build a local warehouse

To use Git to version control the code, you first need to build a local warehouse

There are usually two ways:

  1. Initialize a Git repository locally
  2. Clone a warehouse from a remote warehouse (remote warehouse demo)

Initialize the local Git repository

1) Create an empty directory (such as local_repo1) anywhere on the computer as a local Git repository

2) Enter this directory, right-click to open the Git bash window

3) Run Git initIf you see in the current directory .gitfolder (this folder is hidden folder) then the Git repository successfully created

Operation of local warehouse

Create Git repository

Create a Git repository locally, you need to use the git initcommand.

Create a new directory to store the version library, enter the path where the directory is located, and execute:

git init

Check the directory structure, you can see that contains .gitsubdirectories, which indicates the success of the repository creation

View current file status

# 命令形式:
git status
# 更简洁的信息命令形式:
git status -s

Add (modify) files to the repository

To include a file in the repository management, first add it to the staging area, and then submit it to the warehouse.

To add files to the staging area, use git add:

# 添加单个文件到暂存区
git add Readme.txt
# 将当前目录下所有修改添加到暂存区,除按照规则忽略的之外
git add .

Note: Empty folders will not be added to the staging area.

Submit the files in the temporary storage area to the warehouse. Need to use git commit:

# 如果暂存区有文件,则将其中的文件提交到仓库
git commit  
# 带评论提交,用于说明提交内容、变更、作用等
git commit -m 'YOUR_COMMENTS' 

Note: directly git commitsubmit a page will pop up to add a comment.

View submission history

You need to check which commits you have made to review what you have completed; or you need to find a specific commit to check the code at that time:

# 显示所有提交的历史记录
git log
# 单行显示提交历史记录的内容
git log --pretty=oneline

The git logoutput of the content, the ID can be seen that each submission is a 40-bit string.

Version rollback

With git logto view the history of submission, you can git reset --hardretreat to require a specific version of back and forth, and then use the code to perform various operations.

 # 回退到 commit_id 指定的提交版本
git reset --hard 'COMMIT_ID'   

When returning to a version submitted later, by then git logit is unable to submit the information displayed in this later. However, the git refloghistory can get to operational command.

Therefore, we want to return to a future submission, first by git reflogsubmitting ID found in the version of the history back to the command you want, and then git reset --hardto switch.

git reflog
git reset --hard 'COMMIT_ID'

Delete Files

Before the file is added to the temporary storage area, you can directly delete the file physically. If the file has been submitted, you will need git rmto delete:

# 删除已经被提交过的 Readme.md
git rm Readme.md

Note: You git rmcan only delete files that have been submitted to the version library. It is an error to directly use this command to operate files in other states.

Add file to ignore list

Generally in the workspace, not all files need to be under version control

Such files that do not require version control are usually automatically generated files. For example: IDEA project files ( springmvc.iml), compiled files target, pictures uploaded by the system img.

You can create a working directory named in this case .gitignorefile (file name fixed), list the files to be ignored.

Generally, when the project is initialized, a list of files to be ignored is prepared in advance.

Branch management

Almost all version control systems support branches in some form. Using branches means that work can be separated from the main line of development to make major bug modifications and develop new features so as not to affect the main line of development.

In development, there are generally the following principles and procedures for branch use

  • master Production branch: online branch, main branch, small and medium-sized projects as the branch corresponding to the application running online.

  • test Test branch: The branch created from the master is generally used as the test branch of the test department for pre-release testing; after the test is completed, it needs to be merged into the master branch to go online. Small and medium-sized projects can omit this branch.

  • develop Development branch: create a branch from test. If the development does not have a test branch, it is a branch created from master, which is generally used as the main development branch of the development department; if there are no other parallel development requirements for different periods to go online, you can develop in this version; phase development After completion, you need to merge to the test branch to continue testing. If there is no test branch, you can merge directly to the master branch.

  • hotfix(bugfix) Branch: The branch derived from master is generally used for online bug repair. After the repair is completed, it needs to be merged into the master, test, and develop branches.

View branch

View branch usage git branch:

# 查看本地分支信息
git branch
# 查看相对详细的本地分支信息
git branch -v
# 查看包括远程仓库在内的分支信息
git branch -av

Note: git branchFrom the output, in front of a branch with *, which identify the current location of the branch

Create branch

When you want to fix a bug or develop a new feature, or even if you are afraid of disrupting the original code, you can create a new branch to avoid the impact on the original code.

#  新建一个名称为 dev 的分支
git branch dev

Switch branch

After creating the branch, you need to switch to the newly created branch, otherwise, all the changes will still be on the original branch. All changes can only affect the current branch.

#  新建完 dev 分支以后,通过该命令切换到 dev 分支
git checkout dev 

Create and switch branches

# 新建 dev 分支,并切换到该分支上
git checkout -b dev 

This command merges the first two independent commands, and is generally used in normal use.

Merge branch

When the repair is complete a Bug, or developed a new feature, you will put on the relevant characteristics of the Bug or merge the changes back to the original primary branch, this time you need git mergeto do the merge branches.

First, you need to switch back to the branch you want to merge into, such as master:

# 切换回 master 分支
git checkout master
# 将 dev 分钟中的修改合并回 master 分支
git merge dev

When merging back to the main branch, you may face conflicts git add ./

Delete branch

When the previously created branch has completed its mission, if the bug is fixed, after the branch is merged, the branch is no longer needed, and you can delete it.

#  删除 dev 分支
git branch -d dev 

Git remote warehouse

Add remote library

Now that a Git warehouse has been created locally, and I want to let other people develop collaboratively, you can synchronize the local warehouse to the remote warehouse at this time, and at the same time add a backup of the local warehouse.

So how to build a Git remote warehouse? It can be achieved with the help of some code hosting service platforms provided on the Internet, among which GitHub and Code Cloud are more commonly used.

GitHub (https://github.com/) is a hosting platform for open source and private software projects. Because it only supports Git as the only version repository format for hosting, it is named GitHub.

Code Cloud (https://gitee.com/) is a domestic code hosting platform. Since the server is in China, Code Cloud will be faster than GitHub.

Sign up for GitHub

The first step: login URL, click on the sign upregistered account

Step 2: Fill in the information and pay attention to the fact that the email address is true

Step 3: Click directly join a free plan

Step 4: Draw directly to the bottom and click complete setup

Step 5: The email needs to be verified. After verification, log in to GitHub

Verify email: After entering the email, click the button to jump to the page

After jumping to the page: click skip this for now

Step 6: Login

Create remote warehouse

Click the create repositorybutton warehouse to create success.

Synchronize remote warehouse

GitHub supports both synchronous mode httpsand ssh. If you are using httpsneed to enter a user name and password you do not need very simple basic configuration can be used, but each time you submit the code and download the code. And if the company private Git server configuration generally do not provide httpsaccess to, so to demonstrate to focus on sshthe way.

SSH protocol

What is SSH?

SSH-short form of Secure Shell. By using SSH, all transmitted data can be encrypted, so that the "man in the middle" attack method is impossible to achieve, and it can also prevent DNS spoofing and IP spoofing. Using SSH, there is an additional advantage that the transmitted data is compressed, so the transmission speed can be accelerated.

Note: To use the SSH synchronization method, you need to generate a key and configure the public key in GitHub

SSH key generation

In the windows we can use Git Bash.exeto generate a key, right-click menu to open Git Bash

git bash Execute commands to generate public and private keys:

ssh-keygen -t rsa

After completion of the command execution, window in the local user .sshdirectory C:\Users\用户名.sshgenerated public key and private key file as the file name of the following:

id_rsa
id_rsa.pub

SSH key configuration

After the key is generated, you need to configure the key on GitHub so that you can access it locally.

In the key part of the contents of the file id_rsa.pub added to it, and then click the Add SSH keybutton to complete the configuration.

Operation of remote warehouse

View remote warehouse

If you want to view the remote warehouse server has been configured, you can run git remotethe command. It will list the abbreviations of each remote server specified. If you have cloned the remote repository, you should at least see origin, which is the default name of the repository server cloned by Git.

# 命令形式:
git remote -v
# origin ——仓库服务器的默认名称

Add remote warehouse

If you already have a local warehouse, then plan to publish it remotely for others to collaborate. Then use:

#  为本地仓库添加远程仓库
git remote add origin your_remote_git_repo 

Push local content to remote warehouse

When the code is submitted in the local warehouse, it needs to be pushed to the remote warehouse so that other collaborators can synchronize content from the remote warehouse.

# 第一次推送时使用,可以简化后面的推送或者拉取命令使用
git push -u origin master 
# 将本地 master 分支推送到 origin 远程分支
git push origin master 

note:

  • git push -u origin masterWhen the first time, to bring -uthe parameters, while the master branch push new remote master branch, but also to correlate the master branch of local and remote master branch.
  • Before pushing, you need to pull the remote warehouse first. If the submitted version is found to be inconsistent, an error will occur

Get the latest content from a remote warehouse

In the process of multi-person collaboration, when you have completed the submission in the local warehouse and want to push to the remote warehouse, you need to get the latest content of the remote warehouse.

Can git fetchand git pullto get the contents of the remote repository.

git fetch origin master    
git pull origin master

git fetchAnd git pullthe difference between:

  • git fetch It only gets the updated content of the remote warehouse, and does not automatically merge.
  • git pullAfter obtaining the contents of the remote repository, it will automatically do merge, it can be seen git fetchlater git merge.

Remove invalid remote warehouse

If you want to remove a remote warehouse for some reason

# 命令形式
git remote rm <shortname>

Note: This command only removes the records of the remote warehouse from the local, and will not really affect the remote warehouse

Clone from remote warehouse

If you want to get a copy of an existing Git repository, then you should use git clonethe command. Git clones almost all data (including log information, historical records, etc.) on the Git warehouse server, not just the files needed for the copy work. When the execution git clonetime command, the default configuration remote Git repository under every version of every file will get pulled down.

If there is no local warehouse and you want to copy a copy of code from an existing remote warehouse, then you need it git clone.

#  通过 https 协议,克隆 Github 上 git 仓库的源码
git clone https://github.com/lagou-zimu/repo1.git
#  通过 ssh 协议,克隆 Github 上 git 仓库的源码
git clone [email protected]:lagou-zimu/repo1.git

Note: The git clonefollowing warehouse address can support multiple protocols, such as https, sshetc.

Pull from remote warehouse

Pull

# 命令形式
git pull [远程仓库名称] [分支名称]  

Resolve merge conflicts

In a period of time, users A and B modify the same file and modify the code at the same line position. At this time, a merge conflict will occur.

User A modifies the code locally and pushes it to the remote warehouse first. At this time, user B revises the code locally. After submitting it to the local warehouse, it also needs to be pushed to the remote warehouse. At this time, user B pushes later than user A, so it needs to be pulled first. The remote warehouse code can only be pushed after being merged. When user B pulls the code, because users A and B modify the same location code of the same file at the same time, a merge conflict will occur.

User A: Modify a.java code and push it to the remote warehouse

User B: modify the same line of code in a.java, after submission, the merge code conflicts

Solution:

1. 先拉取代码
2. 然后打开代码解决冲突
3. 再提交

summary

Common commands for remote warehouse operations:

# 查看所有远程仓库名称
git remote
# 查看远程仓库缩略信息
git remote -v
# 将本地仓库代码推送到远程仓库
git push origin master
# 克隆远程仓库代码到本地
git clone https://github.com/lagou-zimu/repo1.git
# 拉取远程仓库代码到本地(fetch+merge)
git pull origin master

Use Git in IDEA

Configure Git in IDEA

After installing IntelliJ IDEA, if Git is installed in the default path, idea will automatically find the location of Git. If you change the installation location of Git, you need to manually configure the path of Git. Select File → SettingsSettings window opens, find Version ControlGit option under the input git.exepath, click the Test button to execute successfully now configured.

Common Git operations of IDEA in development

Initialize and submit the project to the remote warehouse [Project Leader operation]

Steps:

  1. Create a remote warehouse in GitHub / Code Cloud
  2. Hand over the maven project to Git management
  3. Configure ignore files
  4. Submit to local warehouse
  5. Push to remote warehouse

Clone remote warehouse to local 【Developer】

Start IDEA, clone project from remote warehouse

Push Push from local warehouse to remote warehouse

Steps:

  1. Be sure to pull the corresponding branch of the remote warehouse before pushing
  2. If there is a conflict, resolve the conflict first and submit to the local warehouse
  3. Push the current branch to the remote warehouse

Branch operation

Steps:

  1. Create branch
  2. Switch branch execution operation
  3. Perform merge operation, master merge dev and push to remote warehouse

Fool Tracker: Version Comparison

After the code changes, you can click the Show Historybutton to compare differences

Want to know more, welcome to follow my WeChat public account: Renda_Zhang

Guess you like

Origin blog.csdn.net/qq_40286307/article/details/108738262