GIT usage tutorial (fifteen steps to understand, the most detailed on the Internet)

1. Install GIT

Download GIT from the official website: https://git-scm.com/downloads
Insert image description here

2. Create a warehouse

Right-click on a blank area of ​​the folder where you want to create the repository,
Insert image description here
click "GIT Bash Here" in the pop-up menu, and then initialize the repository.

$ git init

Insert image description here
After success, there will be an additional ".git" hidden folder in the folder. This directory is used by GIT to track and manage versions. Do not manually modify the files in this directory, otherwise, the git warehouse will be destroyed. broken.
Insert image description here
.git is a hidden folder, which needs to be set to show hidden folders before it can be seen.

1. Open the folder options
Insert image description here
or
Insert image description here
2. Set the hidden files to
Insert image description here
be displayed. Remember, just make sure that the .git folder exists. Do not change the contents casually.

3. GIT partitioning and workflow

Insert image description here

  • Workspace: The workspace
    is where programmers edit code. It is the directory where .git (warehouse) is located (not inside .git). All changes are made in this area and will take effect directly in this area first.
  • Index / Stage:
    The place where changed files in the temporary storage area are temporarily stored. All changes to be submitted to the warehouse (addition, deletion, and modification of files in the workspace) must be added (add) here first, and then submitted (commit). . Of course, you can also checkout the workspace.

  • Repository: Each submission in the warehouse area (or local warehouse) is a version. The warehouse area saves each version submitted before. It can be pushed to the remote warehouse or restored (reset, revert, checkout) back to the workspace .
  • Remote: Remote warehouse
    The remote warehouse stores various versions and branches pushed by one or more authors from their local warehouse. Each author can pull the latest version of master (master branch) locally, merge his or her own changes, and then push it to the master branch of the remote warehouse for use by others. Everyone is responsible for their own part, and then merges their own results into the master branch, so that division of labor can be easily carried out.

4. Add files to the temporary storage area

4.1 First check the current status of the warehouse

$ git status

Insert image description here
The red ones are files that have not been added to the staging area. If it is a newly created warehouse, all files in the folder will be red after git status, because these files have not been added to the staging area and are all "untracked files" (Untracked files).
Insert image description here

4.2 Add a single file to the temporary storage area

$ git add source1.c

4.3 Add multiple files to the temporary storage area

$ git add source1.c source2.c source3.c

4.4 Add all files to the temporary storage area

$ git add .

After adding it to the staging area, check the warehouse status. The added file turns green.
Insert image description here

5. Clear files that have not been added to the temporary storage area

If you want to clear newly added files or files that have never been tracked (added to the temporary storage area), you can use the following command.
For example: source4.c and source5.c have been added, or the local warehouse has never been added to the staging area after creating it, and now I want to clear it out.

5.1 Check which files will be deleted by clean

$ git clean -n

Insert image description here

5.2 Delete all untracked files in the current directory. The folders and files specified in the .gitignore file will not be deleted.

$ git clean -f

Insert image description here
After execution, source4.c and source5.c in the folder will be deleted. If you run git status again (check the warehouse status), you will not see the reminder of these two files.

5.3 Delete files in the specified path that have not been tracked

$ git clean -f <路径>

5.4 Delete files and folders in the current directory that have not been tracked

$ git clean -df

5.5 Delete all untracked files in the current directory. Regardless of whether they are the folders and files specified in the .gitignore file.

$ git clean -xf

5.6 Add .gitignore file

Generally, we will always have some files that do not need to be managed by Git, do not need to be added and submitted, and we do not want them to always appear in the untracked file list. Usually these are automatically generated files, such as log files, or temporary files created during the compilation process.
For example, there is a temporary file called file1.txt, and there is an assembly file (*.o) generated during the compilation process, which we want to ignore.
Insert image description here
When there is no .gitignore file, this untracked file will be displayed when viewing the status.

5.6.1 Create a .gitignore file

Let’s first look at the situation created under window
Insert image description here
. After creating a new document, the following file appears.
Insert image description here
Change name.
Insert image description here
Something went wrong! Because we want to create a file with an empty name and a .gitignore suffix, and files created in window must have a name.
How to fix it?

There are still methods, we can create it in the black box of git base. Then use vim or vi editor to edit, or double-click in the directory to open editing.
Insert image description here
After creating and editing the .gitignore file (the editing process is placed at the end of this section), let's check the warehouse status.
Insert image description here
It can be seen that the files that were previously displayed as untracked have been ignored.
Next we can add .gitignore and submit it, so that we have a .gitignore file in the latest version.
Insert image description here
However, if the file is already in the repository, ignoring it has no effect.

For example, source1.c is already a file in the warehouse, and newfile.txt is a newly created file that has been added to the staging area. We want to ignore them now.
Insert image description here
It can be seen that ignoring is invalid. After source1.c is changed, there will still be a corresponding reminder. The newfile.txt in the temporary storage area is still there, and if you continue to make changes to newfile.txt, a corresponding reminder will appear.
Insert image description here
It can be seen that if you want to ignore a file, you must first ensure that it is not in the warehouse and staging area at this time.
If they are already in the warehouse and staging area, the only way is to clear them out.
As shown below:
Insert image description here

The following is the editing process with vim editor.
Insert image description here
After executing the $vim .gitignore command, the vim editor opens the .gitignore file (empty file). This is the normal mode of the vim editor. Click i to enter the insert mode (editable).
Insert image description here
Insert image description here

5.6.2 How to write gitignore files

1. All empty lines or lines starting with the comment symbol # will be ignored by Git.
2. Standard glob pattern matching can be used.
3. The matching pattern followed by a backslash (/) indicates that the directory is to be ignored.
4. To ignore files or directories outside the specified pattern, you can add an exclamation mark (!) before the pattern to negate it.

The so-called glob pattern refers to a simplified regular expression used by the shell.

  • The asterisk (*) matches zero or more arbitrary characters;
  • [abc] matches any character listed in square brackets (this example matches either an a, a b, or a c);
  • Question mark (?) matches only one arbitrary character;
  • If you use a dash to separate two characters in square brackets, it means that all characters within the range of these two characters can be matched (for example, [0-9] means that all numbers from 0 to 9 are matched).

For example:

# 此为注释 – 将被 Git 忽略
*.a       # 忽略所有 .a 结尾的文件
!lib.a    # 但 lib.a 除外
/TODO     # 仅仅忽略项目根目录下的 TODO 文件,不包括 subdir/TODO
build/    # 忽略 build/ 目录下的所有文件
doc/*.txt # 会忽略 doc/notes.txt 但不包括 doc/server/arch.txt

Insert image description here

/ , /* and !
/OBJ/
indicate that all files in the OBJ directory are ignored.
/OBJ/
!/OBJ/UWB.sct
*
indicates that files in the OBJ directory are ignored, except UWB.sct.
"!" is used to restore tracing, but if the directory where the file is located is ignored, the file cannot be traced again.

* and **
/a/*/b can only match b in the second-level subdirectory of a, such as a/x/b
/a/**/b can match b in any level subdirectory of a, such as a/b , a/x/b, a/x/y/b …

6. Delete files in the warehouse

6.1 Add a request to delete a file in the warehouse to the temporary storage area, and cancel the tracking of the file, but do not delete the source file

$ git rm --cached source1.c

Reminder: If you want to clear multiple files, just list them later.
Insert image description here
After execution:
The request to delete files in the warehouse is added to the temporary storage area and takes effect after submission.
Cancel tracking of the file, effective immediately
. The file and its changes in the workspace are still there, but the changes are not added to the staging area.

6.2 Add a request to delete a file in the warehouse to the temporary storage area and delete the source file

$ git rm source1.c

Reminder: If you want to clear multiple files, just list them later.
Insert image description here
After the command is executed:
the source file is deleted immediately, and the deletion of the files in the warehouse takes effect only after submission.

7. Undo the changes of tracked files in the workspace

7.1 First check the current status of the warehouse

$ git status

Insert image description here
Insert image description here
This is the tracking file that has changed in the workspace.

7.2 View specific changes to tracked files

$ git diff 

Insert image description here

7.3 Check what content has been modified in a tracked file

$ git diff  soure1.c   

Reminder: If you want to view multiple files, just list them later.
Insert image description here
Red is deleted content, green is added content.

7.4 Check what content has been modified by a certain type of tracked file

Sometimes only one or two files may be changed, but after compilation, git status finds that a large number of files have been changed (marked in red). If you use git diff directly, the following content will make you doubt your life. Therefore, we can also look at changes in a certain type or types of files.

Reminder: If you want to view multiple categories, just list them later.

$ git diff *.c *.h

Insert image description here
Of course, a better way is to use the .gitignore file to ignore those intermediate files and not trace them. Please see section 5.6.1 for specific operations.

7.5 Undo the changes of a tracked file in the workspace

$ git checkout -- source1.c   

Reminder: If you want to clear multiple files, just list them later.
Insert image description here
For example: "modified: source1.c" in the picture above indicates that the file source1.c in the temporary storage area has been modified. You can use $ git checkout – source1.c to discard this change.

7.6 Undo all changes to tracked files in the workspace

$ git checkout . 

7.7 Cancel all changes (addition, deletion, modification) to tracked files in the local workspace after the last git add, and delete untracked files

$ git checkout . && git clean -df

For example: the current directory includes source1.c, source2.c and source3.c, all of which were added to the temporary storage area last time.
Insert image description here
Later, source4.c was added, and the content of source3.c was changed to: 333.
Insert image description here
Check the warehouse status and you can see all the changes in the current directory compared to the last time it was added to the staging area (git add).
If you want to discard these changes, you can use: $ git checkout . && git clean -df
According to the above content:
$ git checkout . is to discard the changes in the tracked files in the workspace, such as the changes in source3.c above
$ git clean -df discards untracked files. For example,
after the two newly added source4.c commands above are executed, the tracked files can be restored to the state after the last git add.

8. Submit to local warehouse

8.1 Before submitting, check the warehouse status to ensure that the files in the temporary storage area have not changed.

$ git status

Insert image description here
In the picture above, "modified: source1.c" means that the file has been modified, and this prompt must be dealt with before submission.
Method 1 To update this change to the staging area, you can use:

$ git add source1.c "或 "$ git add .

Method 2 To discard this change, you can use:

$ git checkout -- source1.c 

8.2 If there are changed files in the temporary storage area, you must first update them to the temporary storage area using the add command.

$ git add sorce1.c		//把source1.c加到暂存区
或 
$ git add .					//把当前目录中所有文件加到暂存区

Insert image description here

8.3 Submit files (the following –m is a comment)

$ git commit –m “注释内容”

Insert image description here
This is only submitted to the local warehouse. To push it to the remote warehouse (github) and save it, the following conditions or operations must be met:
1. Have a github account
2. Create a github warehouse
3. Create an SSH KEY locally, and then add it to github's permission List
4. Establish an association between the local and github repositories

8.4 Modify the most recently submitted comments

$ git commit --amend

8.5 Modify comments submitted one or more times before

$ git rebase -i HEAD~2	//修改最近两次提交的注释

Insert image description here
The following is the window that pops up after executing the git rebase -i HEAD~2 command. The window that
Insert image description here
just popped up above cannot be edited yet. Click "i" to enter the editing mode.
Insert image description here
After editing the instructions, proceed to the step of modifying the comments.
Insert image description here

8.6 tap

After frequent commits, there will be a long list of dense commit records. Once there is a problem with the project and you need to check the code problem of a certain node, it will be a bit of a headache. Although there is a commit message, there are still problems such as difficulty in finding and unclear description.

Like most VCSs, Git can also tag versions at a certain point in time. People often do this when releasing a certain software version (such as v1.0, etc.).

The purpose of tagging is to add semantic names to the development nodes of the project, that is, aliases for functional versions. When adding a tag name and accompanying information, it can facilitate backtracking and review during the future maintenance of the project. In addition, you can also use tag records to roughly understand the backward compatibility, API modifications and iterations of the current project.

8.6.1 Tag the current version

Use the git tag command followed by the tag name to create a tag directly.

$ git tag v1.0

Insert image description here
You can also add the -a parameter to create a tag with comments. The comment information is specified by -m.

$ git tag -a v1.0 -m "备注信息"

Insert image description here

8.6.2 Label a specified commit number

The tag does not need to be on the head, it can also be on the previous version.
Insert image description here

8.6.3 List existing tags

$ git tag

Insert image description here

8.6.4 View tag details

$ git show v1.0	//查看v1.0标签的详细信息

Insert image description here

8.6.5 Switch to the version corresponding to a certain tag

$ git checkout v1.0	//切换到v1.0标签对应的版本

Insert image description here
If you want to make further changes to the v0.5 version, after entering the v0.5 version, it will be in a free state. In this state, you can create and switch to a new branch, and then you can save your changes and submissions.
Insert image description here

8.6.6 Synchronize tags to remote warehouse

$ git push origin v1.0	//将本地v1.0标签同步到远程仓库

Insert image description hereInsert image description here

8.6.7 Delete tags

8.6.7.1 Delete local tags

$ git tag -d v1.0	//删除本地的v1.0标签

Insert image description here

8.6.7.2 Delete the tag of the remote warehouse

If you want to delete the tag of the remote warehouse, you must first delete the corresponding local tag, and then delete the tag of the remote warehouse, otherwise it will be invalid.

$  git push origin :refs/tags/v1.0	//删除远程仓库的v1.0标签

Insert image description here
Tip: For information about remote warehouses, please see lectures 9 and 10 below.

9. Register an account, create a warehouse, and create an SSH KEY

9.1 First go to the official website to register a github account: https://github.com/

Insert image description here

9.2 Create a github repository

Insert image description here
Insert image description here

9.3 Create SSH KEY

Since the transfer between your local Git repository and github repository is encrypted through SSH, you need to create an SSH KEY locally and add it to the github allowed list.

9.3.1 Check if there is SSH. If it has never been created, it must not be there.

$ cd ~/.ssh
$ ls

Check whether the id_rsa.pub or id_dsa.pub file already exists. If so, there is already SSH.
Insert image description here

9.3.2 Create an SSH key

$ ssh-keygen -t rsa -C "注释文字"

Meaning of the command parameters:
-t specifies the key type. The default is rsa and can be omitted.
-C sets the comment text, such as email address.
-f specifies the key file storage file name.
The above code omits the -f parameter. Therefore, after running the above command, you will be asked to enter a file name to save the SSH key code just generated.

9.3.3 Copy the contents of the id_rsa.pub file

$ clip < ~/.ssh/id_rsa.pub

After executing this command, the public key of SSH KEY has been copied to the pasteboard and can be pasted on github.

9.3.4 Go to github to open the settings

Insert image description here
Insert image description here

9.3.5 Add SSH

Fill in any title and paste the contents of the id_rsa.pub file in the Key text box.
Insert image description here

9.3.6 Copy the address of the remote library

Click on github repositoryInsert image description here
Insert image description here

10. Associated with remote warehouse

10.1. View remote library information

$ git remote 
$ git remote –v	(-v显示对应的克隆地址)

Insert image description here
If the remote warehouse has not been associated, nothing will be displayed after execution.

10.2.Associate remote library

$ git remote add heater_mainboard [email protected]:wuzulie/Demo_hub.git 

The name of the remote library is origin, which is the default name of Git. It can also be changed to something else, but the name origin tells you that it is a remote library at a glance.
After the association, use git remote to check the remote warehouse information and you will have the content. fetch corresponds to the fetch address, and push is the push address.
Insert image description here

10.3 Delete remote library

$ git remote rm origin

Insert image description here
If you check the remote library after deletion, there will be no content.

11. Create and merge branches

Almost all version control systems support branching in some form. Using branches means that you can separate your work from the main development line so as not to affect the stable version of the main development line.

First of all, the master branch should be very stable, which is used to release new versions. Under normal circumstances, work on it is not allowed.
Under normal circumstances, work is done on the newly created dev (develop) branch. After the new functions added on the dev branch are debugged and stabilized, they can be merged into the main branch master for distribution.
If you suddenly find a BUG, ​​you can create a new branch from the master branch to specifically fix the BUG. After the patch is completed, merge it back to the master branch. Generally, BUGs are not patched on the dev branch or other new function development branches, because the code of these branches is generally not complete during the editing process, and there is a high probability that there will be new BUGs, and it may even be temporarily unable to run.

As of now, there is only one branch, the master branch. HEAD points to the latest version of the current branch.

11.1 Branch strategy

In the above example, we have only used the master branch and the dev branch. In actual development, it is impossible to have only two branches. What other branches should there be, and what are the differences between these branches?
Insert image description here

  • Two long-standing branches in the project

master : the main branch, responsible for recording the iteration of the online version. The code of this branch is completely consistent with the online code.
develop(dev) : development branch, which records a relatively stable version, and all feature branches and bugfix branches are created from this branch.

  • Other branches are short-term branches and need to be deleted after functional development is completed.

feature : feature (function) branch, used to develop new functions. Different functions create different function branches. After the function branch is developed and self-tested, it needs to be merged into the develop branch and then deleted.
bugfix : bug fix branch, used to fix non-urgent bugs. For ordinary bugs, you need to create a bugfix branch for development. After the development is completed and the self-test is no problem, merge it into the develop branch and delete the branch.
release : Release branch, used to prepare for code to go online. This branch is created from the develop branch. After creation, it is released to the test environment by test students for testing. Bugs found during the test require developers to fix bugs on the release branch. All bugs are fixed. After completion, before going online, you need to merge the release branch into the master branch and develop branch.
hotfix : emergency bug fix branch, this branch is only used in emergencies. It is created from the master branch and is used to urgently fix online bugs . After the repair is completed, the branch needs to be merged into the master branch to go online, and it needs to be merged into the develop branch. .

11.2 View all current branches

$ git branch  

Insert image description here

11.3 Create a branch

If you want to fix a bug or add new features, you often create a branch for modification and testing. After achieving the goal, you can merge it back to the main branch, and then the version of the main branch will be modified accordingly.

$ git branch dev	//创建分支dev 

After creation, the new branch is exactly the same as the main branch, including the warehouse area, staging area, work area and submission records.

11.4 Switch branches

$ git checkout dev 

Note: If the staging area and workspace are modified when switching branches, switching errors may occur or even files may be lost.

If you switch branches with modifications, there are five situations:

1. The files in the warehouse have not been changed, and the changed files in the staging area and workspace have not been committed.
In this case, you can switch to any branch, and the changes in the staging area and workspace will also be shared after the switch. The reason why we say sharing is that after you switch over, the contents of the temporary storage area and the workspace will be the same. Moreover, if you make changes to uncommitted files in the staging area or workspace of any branch, the changes will also take effect on other branches.

2. The files in the warehouse have been changed, but there is no conflict in the contents of the files between the branches before and after the switch. In
this case, you can also switch, and the changes in the temporary storage area and workspace after the switch will also be shared. This sharing is the same as mentioned above, so I won’t go into details.

3. The files in the warehouse have been changed, and the contents of the files in the branches before and after the switch conflict.
In this case, an error will occur during the switch, as shown below.

4. The new file of the current branch has the same name as the file in the branch warehouse to be switched, but the content is different or the file has not been added to the staging area.
In this case, the switch will go wrong, as shown below.
Insert image description here
Note: If the file with the same name has not been added to the temporary storage area, no matter whether the content is the same, the switch will cause an error.

5. The new file of the current branch has the same name as the file in the branch warehouse to be switched, and the content is the same (can be understood as the same file). It is also added to the temporary storage area. In this case, the file will be lost, as shown
below .
Insert image description here
Therefore, special attention should be paid before switching branches to ensure that the temporary storage area is clean. If there are files, one situation is that they cannot be switched and must be submitted first. In another case (the files in the temporary storage area also exist in the branch warehouse after switching, and the content is the same as before), the files will be lost.

Of course, if you use the create and switch command "$ git checkout –b dev", no matter whether the status of the staging area and work area is clean or not, there will be no error. Because there is no possibility of conflict, after creating and switching over, the contents of the new branch's warehouse area, staging area, and work area will be the same as the master branch when it was created.
See the next section (11.5) for details.

11.5 Create a new branch and switch to this branch

$ git checkout –b dev  

This is equivalent to executing the following two commands:

$ git branch dev	//创建新分支dev
$ git checkout dev	//切换到分支dev  

Insert image description here
When viewing branches, the branch with "*" indicates the current branch.
If the staging area and workspace were clean before the switch was created (no changes compared to the latest version), then the workspace before the switch was created is also clean.
But what will happen if the workspace before the switch is not in a clean state?
Insert image description here
It can be seen that the status of the new branch and the master branch workspace when the switch is created is the same.
We mentioned in Section 11.4 that when switching branches normally (different from creating and switching), if the files in the staging area are not the files tracked in the latest version, they will be deleted after the switch is made.
So, if it is created and switched, how to handle the same situation?
Insert image description here
It can be seen that if you create and switch, the contents of the new branch's warehouse, staging area and workspace are the same, which is safe and no files will be lost.

However, a special reminder here is that whether you are switching or creating and switching, try not to operate with modified content. Because the functions and tasks of different branches are different, the content you modify in this branch should be submitted in this branch. If you switch to another branch, the modifications in other branches will destroy the modifications in the previous branch. Even if it is submitted on another branch, the temporary storage area of ​​the previous branch will be empty, and the previous modifications will have no effect on this branch.

Therefore, it is recommended to develop the habit of dealing with all changes before switching branches, otherwise you may be in big trouble.

11.6 Storage

The following two situations may occur at work:
1. Sometimes, we are only halfway through the modification of a certain branch and do not want to submit it yet, lest the submission record be too messy. However, at this time there is a BUG that needs to be fixed urgently, or you want to write another part of the code in another branch.
2. The code that should have been written on the dev branch was written on the master branch. You don't want to go to the dev branch and rewrite, but move the changes written on the master branch to the dev branch.

Is there any way? It really does, let’s take a look at the magical storage function.

11.6.1 Storing the current worksite

$ git stash	//储藏当前工作现场,不加注释
$ git stash save "注释内容"	//储藏当前工作现场,带注释

Insert image description here

11.6.2 View existing storage

$ git stash list	//查看现有的储藏

Insert image description here

11.6.3 Check the difference between a certain storage item and the current content

$ git stash show	//查看最近的储藏与当前内容的改动概况
$ git stash show -p	//查看最近的储藏与当前内容的具体改动
$ git stash show stash@{0} -p	//查看编号为0的储藏与当前内容的具体改动

Insert image description here

11.6.4 Restored work site

$ git stash pop stash@{index}	//恢复储藏的工作现场,并删除该储藏记录
$ git stash apply stash@{index}	//恢复储藏的工作现场,但保留该储藏记录

Insert image description here
If you do not specify a number and use $ git stash pop directly, the most recent stash record will be restored.

Note: Do not use the storage number to determine which storage it is, because the number will change. It should be judged based on the stored branches and comments.

11.6.5 Delete a stored worksite

$ git stash drop stash@{index}	//删除储藏的工作现场

Insert image description here
If you do not specify a number and use $ git stash drop directly, the most recent stash record will be deleted.

11.6.6 Creating a new branch from the repository

$ git stash branch newbranch

Insert image description here
Note: Do not use the storage number to determine which storage it is, because the number will change. It should be judged based on the stored branches and comments.

11.7 Contents of different branches are independent

Modifications made on one branch are only effective on the current branch and have no effect on other branches.
Insert image description here
The changes of each branch are unique to that branch. If you want the changes to be applied to the master branch, or if you want to update the changes on the master branch to the current branch, you need to use branch merging. Please see the following two sections for details.
For the submission records of each branch, when it is first created, it will contain all the submission records of the master branch at that time. But before that, the commit records added by the master branch and each small branch will not be shared, unless they are merged into the changes of each branch.

11.8 Merge other branches on the current branch

$ git merge dev 

Merge the dev branch into the current branch. The current branch can be the master branch or other branches.
As we mentioned before, we create new branches for the purpose of division of labor and cooperation. Generally, different branches are responsible for different functional modules. Sometimes new branches are created to fix bugs or add functionality. In either case, the changes must be merged back into the master branch.
Insert image description here
Another situation is that during the modification process of a certain branch, the changes of other branches need to be updated to the current branch.
For example, during the modification process of a certain branch, if the changes on the main branch need to be updated to the current branch, the main branch must be merged into the current branch.
Insert image description here
Note: In the process of multi-person collaborative development, if you want to update the changes of other programmers on the master branch to the current branch, you must first obtain the latest version of the master branch in the remote warehouse to the local one, and then merge it.
If you want to push changes to the remote warehouse in multi-person collaboration, you must first obtain the latest master version, then merge the changes in the current branch, and finally push them to the remote warehouse. Otherwise, the local master branch version will be larger than the master branch version in the remote warehouse. Old and cannot be pushed.

The above mergers are all ideal and smooth, but sometimes they are not.
Because the previous merger was only performed when only one party made changes, what would happen if both parties made changes?

11.9 Resolving conflicts when merging branches

What happens if both parties change different parts of the same file?
Insert image description here
So the question is, what happens if both parties make changes in the same place in the same file?
Insert image description here
As you can see, the merge is indeed conflicting. But it should be noted that the merge has been completed, but there are conflicts that have not been submitted. In other words, the master branch has merged the contents of the dev branch, including the conflicting source1.c contents.
So, what does it look like when the conflicting source1.c is merged?
Insert image description here
It can be seen that the way to handle the conflict is to retain the modifications on both sides, and then use fixed identifiers to mark the modifications of different branches.

"<<<<<<< HEAD" represents the current branch, not necessarily the main branch.
"=======" is the separator
">>>>>>>> dev": represents the dev branch, which is relative to the current branch. branches are other branches

If you submit at this time, there will be no error at all, but the content will definitely not be what you want. Because the conflict part in the file contains the changes of the two branches, it also contains the branch identifier and separator.
If this were a program, compilation would definitely go wrong.
So, before submitting, we need to resolve the conflict first. In the same place, both branches have made changes. We need to choose one of the two changes and delete those fixed identifiers.
Obviously, this can only be solved manually, because the machine doesn't know which changes you want to keep.
Solution 1: Go to the directory, open source1.c, and edit it.
Insert image description here
If, in the conflict, we choose the dev branch change. Then, we will delete the crossed out part above and save it.
Insert image description here
This is the modified content. Add it to the staging area and then submit it.

Solution 2: In the command window of GIT, open it with vi or vim editor for editing

$ vim source1.c 或 $ vi source1.c

Insert image description here
After executing the command, the vim (or vi) editor will open the window of source1.c. This is the normal mode of the vim editor, as shown above.
Insert image description here
After clicking "i", the vim editor enters insert mode (editable), as shown above.
Insert image description here
After editing, click "Esc" to return to normal mode. Then enter the English character ":" to enter the command mode. Enter wq (write quite) to save and exit, then add it to the staging area and submit it.

11.A Commonly used merge methods

11.A.1 --ff give–no-ff

$ git merge --ff dev	//使用“Fast forward”(快进)模式合并,默认的,可以不写
$ git merge --no-ff dev	//禁用快进模式

Usually when merging branches, git generally uses "Fast forward" mode. In this mode, only the modifications of the branch are merged, that is, the commit records of the merged branch are merged, and then the HEAD pointing to the latest version points to the latest commit record of the merged branch. No commit is created during this process, but HEAD is pointed to the latest merged commit record.

For example, when the master branch has only two commit records, create a dev branch. After dev changes and commits 4, merge it back to the master branch.
Insert image description here
The above picture shows that the dev branch has been submitted 4 times. The first time the content of source1.c was changed to: 111111111, and a line of numbers was added each time.
Insert image description here
The above figure shows that when merging, -ff (fast-forward mode) is used by default to merge the commits added to the dev branch and point HEAD to the latest commit. No new commits are submitted during the merge.
If you roll back to the previous version, the previous version is the previous version of the merged version.
The reason why I remind you of this is because if fast-forward mode is disabled, that is, -no-ff, HEAD points to the version submitted during the merge. Rolling back the previous version is not the merged version, but the master branch before the merge. latest version.

Let’s see what difference it makes when merging with –no-ff (disables fast-forward mode).
Insert image description here
Maybe everyone can see that the difference is exactly what the text above says.

However, I would like to remind you that fast forward mode is conditional. That is, compared with the time when the branch was created, only the merged branch has changed, and the current branch has not changed.
What happens if the current branch has changes before merging, and we still specify -ff (fast-forward mode)?
Insert image description here
It can be seen that when there are changes on both sides, even if you specify -ff (fast forward mode) to merge, it is useless. The system still uses -no-ff (disable fast forward mode) to merge.

In other words, the fast-forward mode is only effective when there are unilateral changes to the merged branch, and it makes sense to use –ff and –no-ff. Otherwise, no matter which one you specify, the system will use –no-ff mode for merging.
Regardless of whether there are changes to the current branch, it is recommended that you use the –no-ff mode to merge. There are two benefits:
1. There will be new submissions during the merge (of course, if there is a conflict, the system will not automatically submit it and we need to manually resolve the conflict. Submit manually), you will know that this version is merged later by looking at the comments or graph mode ($ git log -graph).
Insert image description here
2. The version rollback route will be much cleaner, without having to worry about the messy commit records in the branch. Merging is a version, and rolling back the previous version is the version before merging.

11.A.2 --squash and rebase

From the above merge, we can find that whether it is -ff or -no-ff mode, after the merge, the commit records of the merged branch will be integrated into the commit records of the main branch. If the commit record of the merged branch is very messy, the commit record of the main branch will also become very unclean after the merge.
Is there any way to have only one more commit record on the main branch after merging?

Yes, try the following two methods.

11.A.2.1 --squash

When merging, the submission records of the merged branches are not merged, and only the final modifications of the merged branches are merged into the workspace and staging area of ​​the current branch. It is not automatically submitted after merging, and programmers need to submit it manually.

The usage is the same as –ff and –no-ff. Let’s take a look at the effect:
Insert image description here
it can be seen that after the merger, the submission record of the master branch is not integrated into the submission record of the dev branch, and the system does not automatically initiate the submission of the merged version.
So after merging, we can manually submit a version, or make appropriate modifications before submitting.
But there is another problem, that is, no trace of the dev branch modification and merge can be seen in the master's submission record. There is no historical version submitted by dev, and I don't know which version is the merged change of the dev branch.
This doesn't seem good. Is there any way to solve it?

Yes, in fact it can still be done like this, please see the next section.

11.A.2.2 rebase

Rebase can edit, delete, copy, paste, and merge a certain linear submission history. Therefore, reasonable use of the rebase command can make our submission history clean and concise.
Therefore, before merging branches, we can use rebase to derive the commit records of the merged branches into one or several with major changes.
Generally, it can be synthesized into one.
For example, create a dev branch that unilaterally modifies and submits the source1.c file three times.

If you use the general merge method:
Method 1.$ git merge dev (see 11.8.1 for details)
The master branch has not been modified, and everything is merged in fast forward (–ff) mode. Three commit records will be added to the master branch’s commit record, that is The three submitted by the dev branch.
Method 2.$ git merge --no-ff dev (see 11.A.1 for details)
Because the fast-forward (–no-ff) mode is specified to be merged, all the commit records of the master branch except those added to the dev branch Three records, and one new record will be submitted, adding a total of four records.
Method 3.$ git merge --squash dev (see 11.A.2.1 for details)
After merging, there is no automatic record submission. We can manually submit a record. However, there are no traces of modifications and merges of the dev branch on the master branch's submission record, unless it is clearly stated in the remarks.

So, let’s see what happens if we do the following.
Insert image description here
The dev branch was changed and submitted three times. We want to combine these three commits into one, and then merge the derived commits into the main branch. Then on the commit record of the master branch, the merged record will clearly indicate that it was modified and submitted by the dev branch.
First run the rebase command and specify the current master branch as the baseline. In other words, synchronize the changes on the master branch, and then edit the dev change record on this benchmark.
In other words, the modifications on the master branch after the dev branch is established will be merged. Then edit, delete, copy, paste, and merge all commit records of the current branch's modifications on this baseline. We now want to merge, that is, rebase.
Insert image description here
After executing the above command, the following command editing window will pop up.
Insert image description here

  • pick: keep the commit (abbreviation: p)
  • reword: keep the commit, but I need to modify the comment of the commit (abbreviation: r)
  • edit: keep the commit, but I want to stop and modify the commit (not just the comments) (abbreviation: e)
  • squash: merge this commit with the previous commit (abbreviation: s)
  • fixup: merge this commit with the previous commit, but I don’t want to keep the comment information of the commit (abbreviation: f)
  • exec: execute shell command (abbreviation: x)
  • drop: I want to drop this commit (abbreviation: d)

We want to derive it into one submission record, so there can only be one submission record, that is, leave one (pick), and use squash to merge the others.

Insert image description here
Keep the first commit record (because squash is merged with the previous one, so we keep the first one, and you can use squash for the rest), and use squash to merge the rest.

After editing the command, save and exit, the system will process the three submissions one by one:
1. Merge the first submission with the changes synchronized from the master branch at this time
2. Merge the second submission with the above results
3. Merge the third submission commits are merged with the results above

At each step above, conflicts are checked.
If the submission is retained (pick, etc.), we will also be asked to modify the remarks.

The first record is processed first. First, it is checked for conflicts.
If there is no conflict, enter the note editing window for this record submission.
Insert image description here
Each record is first checked for conflicts. If there is no conflict, the note editing window is entered. If there is a conflict, it will stop and let us resolve the conflict manually. After resolving the conflict, we need to add it manually (git add), and then continue (git rebase --contiune), and we will enter the editing window for the note of the record. Remember, there is no need to commit after add, just continue. After saving and exiting, start merging the next record.
The picture below is the note for editing the 4th record.
Insert image description here
Modify the relevant comments (as a reminder, it’s okay to modify all comments when editing the last one). The picture below shows the last note editing window. After saving and exiting, the rebase is complete. Before completing the suggestion, add a note at the front as a note for this rebase submission. When you view the submission record in a single line (git log --pretty=oneline), the first one will be displayed. If you don't add a general comment in front, when you view it in single line (git log --pretty=oneline), the comment of the first commit record will be displayed (add a line: 22222), which is obviously inappropriate.
Insert image description here
Note that we only kept (pick) one submission record just now, so we edit the submission remarks only once. If we keep multiple submission records (pick, etc.), then this step will be repeated multiple times and notes will be written for each submission. Of course, if a certain submission conflicts during the process, it will stop. After we resolve, add, and continue, the edit notes window for the next submission will continue to pop up.

After the rebase is successful, the following message will appear. At this point, the rebase command is completed.
Insert image description here
Let's merge and see.
Insert image description here
All modifications have been merged, and only one submission record has been added to the master branch. This record also indicates the "author" of the modification submission.

The above was done with unilateral changes made by dev. So, what will happen if there are also changes in the master branch?
Insert image description here
Obviously, after merging, there is no more record. Moreover, the submission record is not on a rollback line, which some friends are not used to.
Is there any way to solve it?

Yes, there are three methods:
1. First combine all the modification and submission records of dev into one (do not use master as the basis, otherwise it will be very troublesome if the content conflicts. The more modifications and submissions of dev, the more troublesome it will be), and then use git rebase -i master Synchronize the changes to the master branch and finally merge them into the master branch.
2. First merge the changes in master to the dev branch, then merge the modification commit records of the dev branch into one, and finally merge them into master. The merge at this time can be done in fast forward mode. No new records will be submitted. Only the submitted record of the dev rebase will be merged.
3. First merge all the modification submission records of dev into one, and then merge the modifications of the master branch. Because both parties have made changes, this merger will definitely add a new commit record, and everything will have to be rebased into one, and finally merged back to the master branch. (Not recommended)

It is recommended to use method 1. The rebased version (git log information) only has the track of dev modifications.
Method 2 is also possible, but the rebased version has the trace of merging master (the last commit record is merging master).
Method 3 is a bit stupid. It is not only troublesome, but also has traces of merging master. It is not recommended.

Method 1 is demonstrated below:
Insert image description here
Insert image description here

11.A Delete branch

11.A.1 Delete the branch in the local warehouse

$ git branch –d 分支名称 (如果该分支没有被合并,会出错并提示:The branch '***' is not fully merged.)
$ git branch –D 分支名称(强制删除分支)

11.A.2 Delete the branch of the remote warehouse

$ git push origin --delete 分支名称

12. Push to remote warehouse

12.1 Push updates of local branches to remote hosts

$ git push <远程仓库名> <本地分支名>:<远程分支名>		(与git pull命令相仿)

Note that the branch push order is written as <source>:<destination>, so git pull is <remote branch>:<local branch>, and git push is <local branch>:<remote branch>.

If the remote branch name is omitted, it means that the local branch will be pushed to the remote branch that has a "tracking relationship" with it (usually both have the same name). If the remote branch does not exist, it will be created.

If the local branch name is omitted, it means that the specified remote branch is deleted, because this is equivalent to pushing an empty local branch to the remote branch.

$ git push origin :master

Equivalent to

$ git push origin --delete master

If the current branch has only one tracking branch, the hostname can be omitted.

$ git push

For example: push the current master branch to the remote library

$ git push –u(第一次要用-u 以后不需要) origin master 

Insert image description here
Since the remote library is empty, when we push the master branch for the first time, we add the -u parameter. Git will not only push the local master branch content to the remote new master branch, but also push the local master branch to the remote master branch. By associating the master branch, commands can be simplified when pushing or pulling in the future.

The above command pushes the local master branch to the Demo_hub host and specifies Demo_hub as the default host. You can then use $git push without adding any parameters.
Insert image description here

12.2 Regardless of whether there are corresponding remote branches, push all local branches to the remote host

$ git push --all origin

Insert image description here

13. Get the latest version from remote to local

If the version in the remote warehouse is newer than the version in the local warehouse, you can use the following two commands to pull it:

$ git fetch origin master	//将远程仓库中master分支的更新拉取到本地,但不合并
$ git pull origin master	//将远程仓库中master分支的更新本拉取到本地,而且自动合并

The usage is similar to push. The specific operation will be discussed in section 15.1.3.1.

14. Version rollback

14.1 View the history of all commits

$ git log 

Many parameters can be added after git log. The commonly used ones are as follows:
-p: Displays the differences between each update by patch, which is more complete than the next - -stat command
-stat: Displays the statistical information of the modified files of each update. Each commit lists the modified file, the number of lines added and removed, and a subtotal of all added and subtracted lines at the end –abbrev-commit
: only the first few characters of SHA-1 are shown, Instead of all 40 characters
–graph: Display branch merge history represented by ASCII graphics
–pretty=oneline: One line display, only the hash value and commit description are displayed (–online itself can also be used as a separate attribute)
-n: Display before n logs
Insert image description here

14.2 View all operation records of all branches (including deleted commit records and reset operations)

Insert image description here

14.3 Roll back to a previous version, and all versions submitted after that version will be discarded.

You can use DEAD to specify the recovery version, or you can use the version ID number to specify the recovery version. If you use a version ID number, it can be either the ID number in the commit record (git log) or the ID number in the operation record (git reflog).

14.3.1 Use HEAD to specify the recovery version

$ git reset --hard HEAD

HEAD: current version
HEAD^: previous version
HEAD^^: previous version
HEAD~100: 100th version up

14.3.2 Restore version using version ID number

$ git reset --hard bf5b760d5a18246d516e7fa62853c6c151623e21

Insert image description here
It can be seen that after using reset to restore, the version with the ID number "ba36bfe75e5d7b3c275acd2f0b7928801bf98fd0" is gone.

14.4 Restore a file to a historical version

14.4.1 Restore a certain file to a historical version and overwrite it back to the current workspace and temporary storage area

$ git checkout 7a655ee57a031c4387d38e2a9042ea9411dd881c -- source4.c

Insert image description here

14.4.2 Restore a file to a historical version and overwrite it back to the current temporary storage area

$ git reset HEAD -- source1.c

14.5 Undo a commit (this version is not a merge type), undo the changes in this version, but want to keep all previous versions

git revert undoes a commit. The commit records (viewed by $ git log) and history records (viewed by $ git reflog) before and after the submission will be retained, and this revocation will be regarded as the latest submission.
Git revert is to submit a new version and reversely modify the contents of the version that needs to be reverted. The version will be incremented and will not affect the version submitted before git revert.
For example: We submitted three times before, and the latest submission was to add source5.c. Later we found that source5.c was redundant and wanted to cancel this submission.
Insert image description here Insert image description here
Tip: Not only can you undo the latest one, but you can also undo any of the commit records ($ git log to view) and history records ($ git reflog to view). The operation is the same.
Insert image description hereInsert image description hereInsert image description hereInsert image description here
Remember to switch to the English input method when typing ":wq", otherwise the command window will flash white when typing ":", and you may not realize that it is a problem with the Chinese and English input methods. Because there are no other prompts, you may not realize what the problem is.
Insert image description here
After completion, check the committed version and you will find that the previously submitted versions are all there, but a new version has been created.
Differences from reset:
1. After using reset to restore to a certain version, all versions newer than this version will be cleared. After using revert to cancel the submission of a certain version, all previous versions will be retained and a new version will be created.
2. After using reset to restore to a certain version, the content will be exactly the same as that version. After using revert to undo the changes made in a certain version of the submission, the content is reversely modified based on the current version. For example, this version is modified by adding source5.c. After reverting this version, the content is that source5.c is deleted in the current version.
Insert image description here
Looking at the directory, you can find that source5.c has been deleted.

If you want to undo the most recently submitted modifications, you can directly use:

$ git revert HEAD		//HEAD指向最近一次提交

For example: Just now we revoked the last submission, which resulted in the deletion of source5.c. Later, we suddenly found that source5.c is still useful, so we can revoke the modifications of the latest submission. Because after we just revoked the last revocation, we also submitted it, which is also a submission record. After completion, you can do it again based on this submission record.

Description of common parameters of $ git revert:

$ git revert --no-edit    //不启动提交消息编辑器,就是不需要写提交备注
$ git revert -n 或 $ git revert --no-commit	//不提交,只是恢复到暂存区

For other parameters of git revert, please refer to the official documentation: https://git-scm.com/docs/git-revert

15. Three ways of multi-person collaborative development

Today's projects are getting larger and larger, with more and more functions, requiring a team for development. If multiple developers develop a project together, how do they collaborate?

Three ways for multi-person collaborative development on GitHub:

  • fork method
  • Organization, team approach
  • Partner mode

15.1 fork method

Approximate process:

1. The project leader builds the original warehouse of a project, called origin.

The source warehouse has two functions:
1. To summarize the code of various developers participating in the project
; 2. To store stable and releasable code. The source warehouse should be protected, and developers should not directly develop it. Only the project manager can perform higher-level operations on it.

2. Developer fork source repository

No developer will directly operate the source warehouse. After the source warehouse is established, what each developer needs to do is to "copy" a copy of the source warehouse as a warehouse for his or her daily development. This copy is a fork.

3. Clone the forked warehouse locally

4. Build feature branches for development

5. Submit a pull request to the administrator

After you have completed the function you are responsible for (of course, you may have merged your develop multiple times during the process), and after testing, if you think there is no problem, you can ask the administrator to merge the develop branch of your own warehouse into the develop branch of the source warehouse. in branch.

6. Administrator testing and merging

The administrator logged into gitlab and saw the pull request initiated by the developer to the source repository. What the administrator needs to do is:
1. Review the developer's code.
2. Create a new test branch in his local test, test the developer's code, and determine whether he agrees to merge it into the develop of the source warehouse.

Among the above 6 steps, many of them have been mentioned in the previous chapters, and other fork, clone and pull request steps will be mentioned below.

15.1.1 fork

Below is the warehouse managed by the project leader.
Insert image description here
No one has forked (copied) this warehouse yet. The following developer "kejirenshen" will perform the copy operation.
Insert image description hereAfter the fork is completed, the project will be available in kejirenshen's warehouse.
Insert image description here
In the GitHub warehouse list, you can also see which warehouse was forked.
Insert image description here

15.1.2 Clone the remote repository to local

Clone is to copy the warehouse in the remote warehouse to the local one, including each branch, submission record and all files. This is a process from scratch, usually done when a computer is changed or the local warehouse is lost.

Cloning steps:
1. Make sure that the local SSH KEY has been added to the github allowed list (please refer to Section 9.3 for details).
2. Right-click where you want the warehouse to be stored and open the Git Base black box.
3. Enter the clone command.

The command format is as follows:

$ git clone <版本库的网址> <本地目录名(可省略)>

like:

方法一(用SSH协议):$ git clone [email protected]:wuzulie/Demo_hub.git(速度最快)
方法二(用HTTPS协议):$ git clone https://github.com/wuzulie/Demo_hub.git

The difference between using SSH and HTTPS:

  • It is more convenient for beginners to use https url to clone. Copy the https url and then
    use the clone command in git Bash to clone it locally. However, you need to enter your account and password every time you fetch and push the code. This is also the https method. of trouble.
  • Using SSH url to clone requires configuring and adding the SSH key before cloning. Therefore, if you want to use SSH url to clone, you must be the owner of this project. Otherwise, you will not be able to add an SSH key. In addition, by default, SSH does not require you to enter your account and password every time you fetch and push the code. If you want to enter your account and password every time to fetch and push, you can also set it up separately.

Next, it is assumed that the developer "wuzulie" has forked the project to his own github repository, then he can clone it locally for development.
Insert image description here
At this point, the remote warehouse has been cloned and the next development can be carried out.

Operations such as viewing files in the current directory (ls -a) and viewing commit records (git log) are not necessary steps. I just want to highlight the effects of certain operations.

Note:
If you are using someone else's computer, or if you have not set a default user name for GIT on your own computer, you must set it first to facilitate identification of submissions from different users.

$ git config --global user.name "wuzulie"			//设置用户名为:wuzulie
$ git config --global user.email "[email protected]"	//设置用户邮箱为:[email protected]

With this parameter, it means that all Git warehouses on your machine will use this configuration. Of course, you can also specify different user names and emails for a certain warehouse. Just remove –global when configuring. If it is for all users in the system , use –system.

In addition, the origin/master above indicates which branch is selected by default (that is, when cloning). By default origin/HEAD points to the origin/master branch, such as origin/HEAD -> origin/master.
The remote branch marked as the default branch can be deleted or modified.
Insert image description here

When cloning, the default branch (master by default) is automatically created locally. Although other branches (such as dev) are not automatically created, the corresponding remote branches (such as origin/dev) have been cloned locally. You can create this branch and let it track the corresponding branch in the remote branch.

$ git branch dev origin/dev			//创建dev分支,同让其跟踪远程的dev分支
$ git checkout -b dev origin/dev	//创建并切换到dev分支,同时让其跟踪远程的dev分支
$ git checkout dev					//如果你确定有这个远程分支,可以直接切换过去,系统会自己创建、切换和跟踪。

Note that the remote warehouse names are not always origin. If the local repository is cloned from a remote repository, the remote repository name defaults to origin. But if the warehouse is not cloned, then this name is named after we add the remote warehouse (git remote add xxx). Generally, it is named origin. If you name or change it to another name (such as myhub), origin/dev in the above command will be changed to myhub/dev.

The above is the process of using cloning to achieve something from scratch. If there is already a local warehouse, but it may not be the latest version, then do you still use cloning? Please see the next section.

15.1.3 Pull the latest version from the remote warehouse

In team collaboration development, everyone is constantly updating the code in the remote warehouse, so our local version may not be the latest.
Sometimes we need to get the latest code version:

  • For example, we need to use the modification results of others during the advanced process we are responsible for.
  • For another example, if we want to push the modification results of the current branch to the remote warehouse, we must first obtain the latest version in the remote warehouse and merge it locally with the current branch, and then push it. If you push directly, it is very likely that other colleagues have updated several versions before you. The version you are currently modifying is older than the version in the current remote warehouse, and an error will occur when pushing. If you force push, it will overwrite other people's modifications, which will cause big problems.

Review the instructions for pulling from the remote warehouse:

$ git fetch origin master	//将远程仓库中master分支的更新拉取到本地,但不合并
$ git pull origin master	//将远程仓库中master分支的更新本拉取到本地,而且自动合并

Suppose that since the last time the remote repository was cloned locally, other colleagues have pushed an updated version to the remote repository. At this time, if we want to pull the latest version locally, we need to use the above two instructions.

15.1.3.1 pull

Insert image description here
If the automatic merge of pull causes a conflict, and you don't want to resolve the conflict and want to cancel the merge, you can use:

$ git merge --abort	//取消合并

Insert image description here
However, the merge is generally not canceled. Instead, conflicts are resolved, submissions are added, and then the local repository is updated to the latest state.

15.1.3.2 fetch

Insert image description here
Before merging, you can also check the changes of the pulled updates to the current version:
Insert image description here
After fetch, you can merge in the following two ways:

1.$ git merge FETCH_HEAD	//将FETCH_HEAD指向的版本合并到当前分支
2.$ git merge origin/master	//将远程仓库的master分支合并到当前分支

However, FETHC_HEAD does not necessarily point to the master branch of the remote warehouse. How to determine it?

The key to understanding fetch is to understand FETCH_HEAD. FETCH_HEAD refers to: the latest status of a certain branch on the server.
Generally speaking, there are two situations:
1. If the remote branch is not explicitly specified, the master of the remote branch will be used as the default FETCH_HEAD.
2. If a remote branch is specified, use this remote branch as FETCH_HEAD.

There are four ways to use git fetch:

1.$ git fetch

This step actually performs two key operations:
1. Create and update local remote branches of all remote branches.
2. Set the FETCH_HEAD of the current branch to the master branch of the remote server (the first case mentioned above).

It should be noted that: unlike push, fetch will automatically obtain the remote 'newly added' branch.

2.$ git fetch origin

Same as above, except that remote is manually specified as origin.

3.$ git fetch origin master

Set the FETCH_HEAD of the current branch to the latest version of the master branch of the remote server.

This command can also be used to test whether a remote branch of the remote host exists. If it exists, it returns 0. If it does not exist, it returns 128 and throws an exception.

4.$ git fetch origin master:dev

This means updating the master branch of the remote warehouse to the local dev branch, but not switching there. If the local dev branch does not exist, it will be created automatically.

git fetch origin :dev
is equivalent to:
git fetch origin master:dev

15.1.4 The process of modifying and pushing to the remote warehouse

Assume that the project collaboration has just begun, the initial version is saved in the remote warehouse, and each programmer starts his own responsible part.

15.1.4.1 Modification and submission of xiaming (non-standard)

Insert image description here
Insert image description here
After xiaming completes the modification and submission, only the local dev branch has been changed. If he wants to update this modification to the master branch of the remote warehouse, what should he do?

Some friends may say that it is very simple, just merge the modifications of the dev branch into the master branch, and then push it up, as follows: Push it up and
Insert image description here
see what changes will happen in the remote warehouse.
Insert image description here
After clicking on the submission record, you can view the details of this submission.
Insert image description here
At this point, the modified version of xiaming has been updated to the remote warehouse, and other colleagues can see and use it.

The above operation process seems to be OK, but in fact the operation is very irregular.
1. The latest version in the remote warehouse is not extracted and merged locally before pushing. If there is a newer version in the remote warehouse, an error will occur.
2. Only the master branch is pushed, and the relevant records of the dev branch are not pushed. Let's check the records of the dev branch in the remote warehouse:
Insert image description here
xiaming later discovered this problem and made a supplementary push:
Insert image description here
Insert image description here
The records of the dev branch were supplemented. However, it should be noted that the above push operation is only successfully pushed up when the dev record has not been updated by other colleagues. If the dev branch has been updated, the push will fail. If you force push (git push origin dev --force), the updates of other colleagues will be overwritten. Unless you pull the branch locally first, merge it, and then push it.

In short, xiaming's operation of modifying and pushing new versions is very irregular. So what should be the standardized operation process? Let’s take a look at xiahua’s operation in the next section:

15.1.4.2 Modification and submission of xiahua (specification)

Insert image description here
Insert image description here
Insert image description here
Insert image description here
The push is successful, let's take a look at the changes in the remote warehouse:
Insert image description here
To summarize, the standard operation of modifying and updating to the remote warehouse is:

  • 1. Clone the remote repository to local
  • 2. Develop on local dev or other branches
  • 3. Pull updates from the remote repository and merge them into the local master branch
  • 4. Derive all local modification records into one record
  • 5. Synchronize the updates of the master branch to the rebase records of the dev branch
  • 6. Merge the synchronized dev branch into the master branch
  • 7. Push the merged master branch and dev branch to the remote warehouse

The first step is used when obtaining the project file for the first time. In subsequent development, steps 2 to 7 will be cycled continuously.
Therefore, the commonly used instructions are:

$ git checkout dev				//切换分支
$ git pull origin				//拉取远程仓库的更新
$ git rebase -i HEAD~n			//编辑最近n条提交记录,一般是衍合成一条
$ git rebase -i master			//同步master分支上的更新,并编辑master之外的所有记录
$ git merge dev					//合并dev分支到当前(master)分支
$ git push origin master(或dev)	//推送master分支和dev分支到远程仓库

15.1.5 pull request

Insert image description here

15.2 Partner method

15.2.1 Add collaborators

First open the warehouse that needs to be developed cooperatively, and you can add collaborators in "Settings". You can add it by entering your username or email address.
Currently, the private library of GitHub's free personal account can only add 3 collaborators. If you want to add more collaborators, you must use a paid account, or use a public library as open source.
Insert image description here
After clicking "Add collaborator", the invitee will receive an invitation email with a link, which can be accepted or rejected by clicking the link.
The inviter can also click "copy invite link" in the picture below to copy the invitation link and send it to the invitee, who can accept or reject it after clicking it.
Insert image description here
After the invitee agrees, the repository will be added to his github repository list.
Insert image description here

15.2.2 Collaborator process

The subsequent development process is the same as the fork method, except that "pull request" is not used. Please refer to Sections 15.1.2-15.1.4 for the specific operation process.

15.3 Organization and team approach

15.3.1 Creating an organization

Click the "+" sign in the upper right corner of github, and then click "New organization".
Insert image description here
step1, fill in the organization-related information.
Insert image description here
Insert image description here
If you choose the paid type, you also need to fill in the payment method and other information. There is no need to fill in the free type.
Insert image description here
After step1 is completed, enter step2.
Insert image description here
step3, do some research, it is not necessary and can be skipped.
Insert image description here
Insert image description here
At this point, the organization is successfully created.
Insert image description here

15.3.2 Add and delete warehouses to the organization

15.3.2.1 Add a warehouse to the organization

Insert image description here
Insert image description here
Insert image description here

15.3.2.2 Deleting a repository in an organization

If you want to delete a warehouse, the method is the same as a normal warehouse.
Insert image description here
Then scroll to the bottom of the page.
Insert image description here

15.3.3 Add members to the organization

Insert image description here
When the invitation window pops up, enter your username or email to invite.
Insert image description here
Set the role of this member.
Insert image description here
The user will receive an invitation email with a URL attached, and can accept or reject it after entering.
After the other party accepts it, they will join your organization, as shown below.
Insert image description here
If you want to delete a member from the team, it's even easier, just click on the cross in the image above.

15.3.4 Create teams for organizations

Insert image description here
Fill in the team related information.
Insert image description here
After successful creation, as shown below.
Insert image description here
You can also view it by entering the organization to which the team belongs.
Insert image description here
If the team is responsible for many tasks, it can also be divided into teams. For example, the "avionics system" team can also be divided into teams such as "flight control system", "display system", "communication system" and "radar system", all of which are managed by the "avionics system" team.
When creating a sub-team, you only need to select the parent team when creating. The other steps are no different from the above. If you click New within the parent team, you don’t even need to select the parent team.

15.3.5 Add a repository to the team

Insert image description here
Fill in the warehouse name.
Insert image description here

15.3.6 Set team permissions

The descriptions of the five permissions are all in English. If you don’t understand, please translate them.
Insert image description here

15.3.7 Add and delete team members

15.3.7.1 Add team members

Insert image description here
Insert image description here
There will be a reminder next.
Insert image description here
After adding, GitHub will send a notification email to the added person. This addition process does not require the consent of the person being added, because the user is already a member of the organization, and the manager has the right to decide which team to add.
Insert image description here
Then the team and the team's warehouse can also be seen on the github homepage of the person being added.
Insert image description here

15.3.7.2 Delete team members

Insert image description here
A reminder will follow.
Insert image description here

15.3.8 Set permissions for team members

You can use the method in the previous section, first check the box, and then click "change role" in the drop-down menu to set permissions.

You can also click on the member's name to enter the member's page, or set roles, that is, permissions.
Insert image description here
Insert image description here
After changing permissions, the member will receive a notification email.

15.3.9 Team development

Each member can see the team's repository on their own github. They can clone the repository locally and then start writing the code they are responsible for.
Next, each team member can develop in the usual way. The development process is the same as the fork method, except that there is no need for "pull request". For the specific operation process, please refer to Sections 15.1.2-15.1.4.

15.3.A Discuss communication functions

Insert image description here
After the content is sent, each member will receive an email, as follows:
Insert image description here
Each member can also see it in the "Discussions" of the github team, and can participate in discussions and exchanges here.
Insert image description here
Of course, the late-night dinner date was just a joke, and the content discussed here is related to the project. Although discussions can be done using WeChat, QQ, etc., some important discussions are recommended here. Because if we discuss here, the discussion records can be saved in github together with the warehouse as project data for easy viewing later.

At this point, the content related to git has almost been introduced. Friends who are interested can learn more about Gitlab. In addition, you can also learn git-related auxiliary tool software, such as GitHub Desktop and Gitflow.

Guess you like

Origin blog.csdn.net/qq_18677445/article/details/91534993