A. Introduction of Git

Git is the most advanced distributed version control system in the world. There is no central server, everyone’s computer is a complete version library, so when working, there is no need to network, because the version is on their own computer. Once you’re done, push your changes to each other so that you can see each other’s changes. (To make it easier for all developers on the project to share code, we put it in a remote Git repository like Github.) In contrast, the SVN is a centralized version control system, and the version library is centralized on the central server. Therefore, all users use their own computers to obtain the latest version from the central server, and then do the work. After the work is done, they need to push their work to the central server. And centralized version control systems must be networked to work.

Git file status

  • Untracked: Not traced, this file is in the folder, but not added to git repository, does not participate in version control. throughgit addState changes toStaged
  • Unmodify: The file has been stored and has not been modified. That is, the snapshot content of the file in the version library is the same as that in the folder. This type of file has two places to go if it is modified toModified.If usinggit rmTo move the publication library, thenUntrackedfile
  • Modified: The file has been modified, just modified, and nothing else has been done. This file also has two places to go, throughgit addAccess to temporary storagestagedState, usinggit checkoutDiscard the modification and return tounmodifyState, this onegit checkoutThat is, take the file out of the library and overwrite the current change
  • Staged: Temporary status executiongit commitThen the changes are synchronized to the library, and the files in the library and the local files become consistent again. The file isUnmodifyStatus Executiongit reset HEAD filenameCancel temporary storage, file status isModified

Git common commands

1. Set correlation

  • git config --listCheck the configuration
  • git config user.nameViewing user Names
  • git config user.emailCheck E-mail
  • git config --global user.name "nameVal"Configure the global user name
  • git config --global user.email "[email protected]"Configuring the Global Mailbox
  • git config --global credential.helper storeGlobally cache login credentials
  • Git config user. The name "XXXX"Configure a single project user name (go to the root of the project folder)
  • git config user.email "[email protected]" Configure a single project mailbox (go to the root of the project folder)
  • Git config -- Global credential.helper cacheSet to remember passwords (default15 minutes)
  • Git config credential.helper 'cache - timeout=3600'Set remember password custom expiration time (here set to expire after 1 hour)
  • Git config - Global credential.helper storeSet remember password for long-term storage
  • git config --global credential.helper wincredClear cached login credentials
  • git credential-manager uninstallClear user names and passwords cached in Git
  • git versionCheck the Version of the Git software.

2. To create

  • git initInitialize the
  • git clone git@git... .gitClone project (git:// protocol)
  • git clone http://... .gitClone project (HTTP (s)://)
  • Git clone (username and passwordSpecify email or username clone project, if username or email and password contain @ sign, so need to replace @ code :@- >%40
  • Git clone -b Specifies the branch name and repository address to be clonedClone the project for the specified branch.

3. Add to the staging area and commit

  • git add readme.txt Submit the file to the staging area
  • git add . Commit all changes in the working area to the staging area, including modified and new files, but not deleted files.
  • git add -uMonitoring only files that have been added (tracked File) submits the modified file to the staging area. An Add-U does not submit a new untracked file. (Git add –update)
  • git add -AIs a combination of the above two, commit all changes. Git add — short for all
  • git commit -m "first"Commit to the repository
  • git statusStatus view (Check the status of the working directory, for example: files not committed, etc.)

4. Remove

  • Git rm my filesDelete files in the local repository
  • Git rm -r my folder /Delete folders in the local repository. -r means recursively all subdirectories. If you’re deleting an empty folder, you don’t need to add -r.

Deleted files can be recovered using git reset Head file and Git Checkout file.

5. Branch (branch)

  • git branch [branch-name]Create a new branch, but remain in the current branch
  • git checkout -b [branch-name]Create a new branch and switch to it
  • git branchList all branches (all local branches)
  • git branch -rList all branches (all remote branches)
  • git branch -aList all branches (all local and remote branches)
  • git checkout [branchname]Switch to the specified branch and update the workspace
  • git branch -d [branchname]Deleting a Local Branch
  • git push origin --delete [branchName]Deleting a Remote Branch
  • git branch -m [oldname] [newName]Branch renaming
  • git reflog --date=local | grep nikeglassView the parent branch of the current branch
  • git merge [branchname]Merge the changes on the BranchName branch to the current branch
  • git rebase [branchname]Change the base of the current branch based on branchName

6. Remote branch.

  • Git checkout -b [branch name]Establish branches locally and synchronize with remote branches
  • Git remote add origin git remote add origin git remote add origin
  • git remoteLists all associated remote warehouses.
  • git remote update origin --pruneUpdate the list of remote branches
  • git remote -vLists all associated remote warehouses (details).
  • Git remote rm origin:Delete the associated remote repository.
  • fetch+mergeGit fetch is a merge between a remote repository and a local repository.
    Git log -p master... Git merge origin/master // git merge origin/master /Copy the code
  • git pull origin masterThis is equivalent to getting the latest version remotely and merging it locally.
  • Git push < remote hostname > < local branch name >Push to remote repository. If the current branch has only one trace branch, then the host name and the end can be omitted:git push.

Git push:git push -u origin :master :master git push -u origin :master

  • git pull origin master --allow-unrelated-historiesBranches are forcibly merged

Git fetch and Git pull differ: Fetch and pull differ: fetch is equivalent to fetching the latest version from remote to local, does not automatically merge, so the local repository code has not been updated.

Git merge origin/master git merge origin/master git merge origin Pull is equivalent to fetching the latest version remotely and merging it locally (equivalent to Git FETCH and Git merge). If you want more control, it is recommended to use fetch + merge, because git fetch is more secure. Before merge, we can check the update status and then decide whether to merge

7. The label

  • git tagList all tags
  • git show [tag]Viewing tag Information
  • git tag [tagname]Use light weight labels
  • git tag -a [tagname] -m [message]Label and annotate (for example, label V1.0Git tag -a v1.0 -m 'v1.0 release')
  • git tag -a [tagname] [commit_id]Label past submissions
  • git tag -d [tagname]Deleting a Local Tag
  • git push origin --delete tag <tagname>Deleting a Remote Tag
  • git push [remote] [tag]Commit the specified tag(for example, push the V1.0 tag to a remote serverGit push origin v1.0)
  • git push [remote] --tagsSubmit all tags
  • git checkout [tagname]Go to the corresponding tag state (At this point Git might tell you that you are in a “detached HEAD” state. Because a tag is a snapshot, you cannot change its code. To make changes to the tag code, you need a branch:git checkout -b [branchname] [tagname])

Log 8.

  • git logRecord each operation
  • git reflogYou can view all operations (including commit and reset operations) on all branches, including deleted commit records. Git log cannot view deleted commit records, and follow-up results can be reversed to a specific change.
  • git log --oneline --graphWhen did a branch or merge occur in your history
  • git diffCompares all file difference changes between workspace and staging
  • git diff <file name>Compares the differences between the specified files in the workspace and staging area
  • git diff --statCompares a list of all file changes in the workspace and staging area
  • git shortlog -n-The output is grouped by the number of submissions per author.
  • git show commit_idView the details of a submission

8. Undo modified version backtracking

  • git checkout -- fileDiscard changes to files in the workspace (for example :git checkout — readme.md)
  • git checkout . Discard all file changes in the workspace

Git checkout — readme. TXT: git checkout — readme. TXT: git checkout — readme.

One is that readme. TXT has been added to the staging area and then modified. Now, undoing the modification will return to the state after it was added to the staging area. Return the file to the state it was at the last Git commit or git add.

  • git reset HEAD <file>Undo files that have been added to the staging area.
  • git reset HEAD .Undo all files that have been added to the staging area.

Git checkout is useless if the file has already been added to staging. You should use git reset HEAD to undo the file added to the staging area, and then use git checkout to restore the file to its last commit.

  • git reset --hard HEAD^Rollback to the previous version
  • git reset --hard commit_idBack to/forward to the specified commit_id

There are three cases of undoing a change

Git checkout — filepathname — git checkout — filepathname — git checkout — filepathname — git checkout — filepathname — git checkout — filepathname Discard all files and modify Git Checkout.

Git add has been used to cache code: You can use git reset HEAD filepathname (e.g. Git reset HEAD readme.md) to discard the cache of a specified file, or use git reset HEAD.** ‘to discard all caches. This command is used to clear git’s cache for file changes. This is equivalent to undoing the git add command.

You can use git reset –hard HEAD^ to return to the last commit state. You can use git reset –hard commitid to go back to any version

3. Git is ignored

1. Use the. Gitignore file

If you want to ignore a file in Git and not commit it to the repository, you can modify the.gitignore file in the root directory (if not, you need to create the file yourself).

Create gitignore.

Touch. Gitignore Open Git Bash-> navigate to the Git repository location -> create a.gitignore file for the repository

. Gitignore Matching rule
Git will ignore all.a files! Lib. a# except lib.a /TODO # ignores only the TODO files in the project root directory, Doc /*.txt # will ignore doc/notes. TXT but not doc/server/arch.txtCopy the code
Gitignore does not take effect

Adding certain directories or files to the ignore rule does not take effect because **. Gitignore can only ignore files that have not been traced before **. If some files are already in version management, only modifying. Therefore, if the file to be ignored has been submitted to the local repository, delete the file from the local repository. If the file has been submitted to the remote repository, delete the file from the remote repository for the.gitignore file to take effect. The solution is to delete the local cache first (to an untracked state) and then commit (push) so that no files are ignored. Git clear local cache:

Git -r --cached. Git commit -m 'local commit comment' commitCopy the code

2. Ignore the local modification

  • Files needed for local development cannot be submitted to remote, but cannot yet be written to. Gitignore files.
  • Files that already exist in the remote repository have been modified locally. You don’t want to commit to a remote repository (such as some editor configuration files, which may vary from version to version). The gitignore configuration caused the configuration file to be added to the repository

In this case, either add the ignore rule to.gitignore and modify the cache).

Git update-index — assumption-unchanged /XX/XX/ xxx.file Ignores a single file locally

Git ls – files – z | xargs 0 git update – index – assume – unchanged into the folder (ignoring all files in the folder)

Git ls – files – v | grep ‘^ h \’ find all files are ignored

Git ls – files – v | grep ‘^ h \ | awk’ {print $2} ‘find all ignored the file path

Git update-index — no-assumption-unchanged — path /XX/XX/ xxx.file Unmounts a single ignored file

Git ls – files – v | grep ‘^ h | awk’ {print $2} ‘| xargs git update – index – no – assume – unchanged cancel all files are ignored

Note: This approach also has a side effect, if the file ignored locally is modified locally, the remote file is also modified by someone else. When pulling remote branches, inconsistent updates to local and remote files can cause pull failures. In this case, the file should be ignored before the pull operation.

Git branch merge

Merge Two modes

There are two general modes of merge:

  • Fast forward model

In general, merging branches moves the file pointer directly if no disagreement is resolved. This is the Fast Forward mode, which is the default mode of merge.

For example, development was going on in the Master branch, but suddenly I had a new idea, so I created a new dev branch, and I made a series of commits on it, and when I was done, I went back to the Master branch,

At this point, the master branch does not produce any new commits after the dev branch is created. Merging the dev branch with the master branch does not result in a new commit. Later, when the merged branch is deleted, it is not known which branch the corresponding commit came from. The merger is called “fast forward”. Git merge –no-ff if you want to automatically generate a COMMIT in this case, you can use git merge –no-ff mode to record the merge.

  • – no – ff mode

git merge --no-ff -m "merge with no-ff" devSince this merge is creating a new COMMIT, add the -m parameter to write the commit description.

Summary: Fast Forward ensures that no one else’s code is forced to be overwritten, ensuring collaborative development. Try not to commit code using the Non Fast Forward method.

Merge conflict problem

Git conflict scenarios:

  • Scenario 1: Multiple branch codes are merged into one branch;
  • Scenario 2: When multiple branches push code to the same remote branch;

In effect, the push operation merges local code into a remote library branch. Push and pull are actually merging local branches into remote branches and remote branches into local branches, so there may be conflicts between these two processes.

Git merge:

  1. Changed the same file in both branches (no matter where)
  2. Changed the name of the same file in both branches

The two branches modify parts of different files, so there is no conflict, and the two parts can be directly merged.

Merge Conflict Resolution

  1. Git push Origin Master
  2. If someone else commits a change before you, Git will tell you that push failed. You need to start with git pull origin/master
  3. Git pushes origin master to merge auto merge. If auto merge fails, Git pushes origin master to merge auto merge.
  4. Git add. Git commit -m ‘git push origin master

Avoid conflict

Code conflicts are inevitable in modern software development projects, but we should try to reduce the occurrence of conflicts and avoid unnecessary conflicts. Here are some practical lessons:

  1. Work on different branches, and frequent synchronization code, if due to project requirement, such as the long-term development of a feature that allows the function code merge into the main branch before the development is complete, although at this time we do not have method to often merge code to the main branch, also need at least frequent synchronization main branch code into the development branch

To avoid too many conflicts when the final merge is on the main branch. 2. Try to use short life branches rather than long life branches. 3. In addition to technical measures, it can also be avoided through project management measures. For example, do not assign different tasks for the development of the same component to different developers at the same time, otherwise the component will have too many conflicts when merging the code. The component development teams communicate frequently to understand each other’s development status and take measures in time when conflicts may arise.

Merge and rebase

Merge merges the common branch with your current commit to form a new commit:

Rebase puts the commit of your current branch at the end of the common branch, so it’s called rebase. It’s like you’re pulling out the branch from the common branch. For example, if you pull a feature branch from the master, and you commit a few commits, then someone merges the feature into the master. If you rebase the master, you will place your current number of commits after that person’s commit. Switch to the master branch and merge with the merge.

advantages

  • The best thing about Rebase is that your project history will be very clean
  • Rebase results in a perfectly linear final project history — you can browse from the end of the project to the beginning without having to fork anything. This makes it easier to view project history using Git log, Git Bisect, and Gitk

disadvantages

  • Security, rewriting project history can have disastrous effects on your collaboration workflow if you violate Rebase’s golden rule
  • Traceability, rebase doesn’t have the information that comes with the merge commit — you can’t see which changes are incorporated upstream in the feature branch

  1. You can see that the merge results reflect the timeline, but rebase scrambles the timeline.
  2. Rebase looks neat, but merge looks a little less neat.
  3. The end result is a combination of code, so how you use these two commands depends on your project.

Note:

  1. Do not use Rebase in public branches
  2. The local and remote branches correspond to the same branch. Rebase is preferred over merge

Git temporary storage and recovery

The git stash command is used

  1. When you are developing a project on the Dev branch and there is a bug in the project that needs to be fixed urgently, but the project is only half finished and you don’t want to commit, you can use the git Stash command to save the changes to the stack.

It then smoothly switches to the Hotfix branch for bug fixes, and when it’s done, it cuts back to the Dev branch again to recover what it just saved from the stack. 2. Because of the negligence, the content that should have been developed in the dev branch was developed in the master branch. Therefore, it needs to be restored to the dev branch.

The git stash command is used to save changes to the stack that you don’t want to commit yet. You can then recover the contents of the stack on a branch. That is to say, stash content can be restored not only to the branch originally developed, but also to any other designated branch.

The scope of git Stash includes both workspace and staging, meaning that anything not committed is stored on the stack.

  • git stashThe ability to save all uncommitted changes (workspaces and staging areas) to the stack for subsequent restoration of the current working directory.
  • git stash save "notes"This is the same as git Stash, except you can add some annotations
  • git stash list Look at the contents of the current Stash
  • git stash pop idPop up the contents of the current Stash and apply it to the working directory corresponding to the current branch. Id is optional. By default, it is temporarily stored last time, and the specific value can be checked through git Stash list. You can only recover once.
  • git stash apply idApply the contents of the stack to the current directory. Unlike git Stash pop, this command does not remove the contents from the stack and can be restored multiple times. In other words, this command can apply the contents of the stack to the working directory multiple times, suitable for multiple branches.
  • git stash drop stash idTo delete a save, the ID is optional. Check the git Stash list to see the value
  • git stash clearDelete all the saved snapshots

Git removes large files

  1. Git’s top five files:
    git verify-pack -v .git/objects/pack/pack-*.idx | sort -k 3 -g | tail -5
    Copy the code

    Or:

    git rev-list --objects --all | grep "$(git verify-pack -v .git/objects/pack/*.idx | sort -k 3 -n | tail -5 | awk '{print$1}')"
    Copy the code

    Or:

    git rev-list --all | xargs -rL1 git ls-tree -r --long | sort -uk3 | sort -rnk4 | head -10
    Copy the code
  2. Find the file name using the id of the file in step 1:
    git rev-list --objects --all | grep fileId 
    Copy the code
  3. Delete file submission records
    git filter-branch --index-filter 'git rm --cached --ignore-unmatch <your-file-name>' rm -rf .git/refs/original/ git reflog expire --expire=now --all git fsck --full --unreachable git repack -A -d git gc --aggressive --prune=now git push  --forceCopy the code

Git Flow

Git, as a source code management system, inevitably involves multi-party collaboration. In order to avoid confusion during the collaboration process, there must be a regular workflow that allows people to work together effectively and keep the project in order. Gitflow is a set built on Git’s powerful branching capabilitiesSoftware Development workflowThese processes should be seen as guidelines, not “iron laws”. Gitflow useMultiple branches to document the history of project development, rather than using a single Master branch.

1. Main branches

The main branches include Master, which is used for official release, and Develop(Dev), which is used for daily development. A permanent branch needs only these two and nothing else.

Master branch: The name of the Master branch of Git. Code on this branch can be deployed to production at any time, this branch can only be merged from other branches, and no direct changes can be made in this branch. After each version seal, the main programmer merges the release branch code into it. After release, tag it, and developers can’t operate it at will.

Develop branch: A branch used for development, usually directly on top of which development needs to be synchronized after every release and urgent online bug fix. In theory, this version is only used during development and cannot be modified directly during testing, but is merged into it by the Release branch after testing. If you want to formally publish, merge the Develop branch on the Master branch.

2. Temporary branches

In addition to the permanent branches, there are temporary branches for release development for specific purposes. There are three types of temporary branches: feature branches, pre-release branches, and fixbug branches. These branches should be removed so that only Master and Develop have permanent branches.

Release branch: We may need to have a pre-release version to test before we release the official version (that is, before develop merges into the Master branch). The pre-release branch is a separate branch from the Develop branch, where all test bugs are fixed and must be merged into the Develop and Master branches after testing. It can be named as release-xx.

Feature branch: Separate from the Develop branch to Develop a specific feature. Once the development is complete, it is incorporated into Develop. The name of the function branch can be named in the form of feature-xx. If the development cycle of a feature is longer than the current version, it is recommended that a feature be developed separately. If this feature is needed, merge it into the Develop branch and test it next time. This is designed to avoid unpredictable instability when the feature gets mixed in with a release when it is not yet developed or tested. Of course, multiple feature branches can be opened at the same time to develop different new functions, which can be combined and tested when appropriate.

Hotfix branch (bug fix) : After the software is officially released, it is inevitable that there will be bugs. This is where you need to create a branch to fix the bug. The branch is separated from the Master branch. After the patch is complete, merge into the Master and Develop branches. It can be named in the form of fixbug-xx. The hot patch branch for online bug fixes should be pulled out by the master and merged into master and Develop after the fix is complete to ensure that the bugs in both branches are fixed.

3. Work flow of each role in the development of new functions

(1) Pre-stage (new function launch)
  • Development lead -> Create a Develop branch based on the Master trunk.

Existing trunk branches: Master, Develop

(2) Development stage (start development)
  • Feature developer -> Create a feature_XX branch based on the Develop branch.
  • Feature Developers -> Develop new features on the feature_XX branch.
  • Feature developer -> After the new feature is developed, launch a Pull request on Git to merge the code into the Develop branch.
  • Development lead -> Verify that the code is ok and approve the merge request.

Existing trunk branches: Master, Develop, feature_XX

(3) Test phase (development completed)
  • Development lead -> Create a pre-release version called relex-1.0.0 based on the Develop branch.
  • The tester -> tests the release-1.0.0 code on the master branch by making a Pull request in Git and merging the release-1.0.0 code on the Master branch.

There are several main branches: Master, Develop, feature_XX, feature-1.0.0

(4) Release stage (test passed)
  • Development lead -> Create a milestone Release (TAG) named 1.0.0-release based on the Master branch.
  • Remove other branches that complete the mission: Feature_login, release-1.0.0.

Master, Develop, 1.0.0-release (tag)

4. Work flow of each character when there are bugs in online code

(1.) Pre-stage (bug submission)
  • The tester -> finds the problem and creates a new issue on Git based on the 1.0.0-release milestone.

Master, Develop, 1.0.0-release (tag)

(2) Repair phase (start to fix bugs)
  • Functionality developer -> Create a hotfix_XX branch based on 1.0.0-releaseTag, fix the bug on the hotfix_XX branch, and then issue a Pull request on Git to merge the code into the master trunk.
  • Development lead -> Verify that the code is ok and approve the merge request.

Existing trunk branches: Master, Develop, 1.0.0-release (tag), hotfix_0001

(3) Test phase (bug fixed)
  • Tester -> Tests the code for the Master branch.

Existing trunk branches: Master, Develop, 1.0.0-release (tag), hotfix_0001

(4) Release stage (test passed)

Development lead -> Create a milestone fix (TAG) based on the Master branch named ** 1.0.1-release, ** remove the other branch that completed the mission :hotfix_XX.

Master, develop, 1.0.0-release (tag), 1.0.1-release (tag)

8. Frequently asked Questions.

  1. The first time you enter the wrong gitlab user name and password, the second time you clone the box without prompting the solution for the user name and password.
git clone remote: HTTP Basic: Access denied
Copy the code

Method 1: Delete the credentials in the control panel.

Method 2: Run the git command to reset the credentials.

git config --system --unset credential.helper
git config --global credential.helper store
Copy the code