preface

Who knows how to use Git these days? Git is a distributed version control system that is familiar to development, both front and back, but can you really use Git well? Encounter problems in a Baidu? All kinds of anomalies will be listed for you. Please keep them well.

Scenario 1: Create a project and associate the remote repository

Little A received the task, asked to do A new project, and she, little B, little C work together to develop. At this time, little A has two choices, one is to create A remote warehouse and clone to the local

// The prerequisite is that a remote repository (omitted in this article) git has been createdclone 'github/yidongying.com'// Clone to localCopy the code

One is to create a local repository and push it to a remote repository.

Mkdir projectA // Create an empty foldercdGit add remadme. md // Commit the file to the staging area git commit -m'Add readme file'Git remote add Origin'Remote warehouse address'Git push -u origin master commits file changes to the remote repositoryCopy the code

And then little “A” starts building branch “A” and getting ready to develop, so

Git push --set-upstream origin feature/a //Copy the code

B also needs to develop on branch feature/ A, so she chooses to check out the remote branch

Git checkout -- Track origin/feature/a //Copy the code

Scenario 2: Forward and backward versions

A. Preserve the site and roll back the version

Description: After the release of the new version, xiao A cut to the branch feature/ A to start the development of the new task. Suddenly, he was informed that there was an urgent bug in the online version, so Xiao A decided to clean up the workspace, roll back the version and pull the hotfix branch to fix it

Git checkout master # Git reset rollback version and push to remote git reset -- hard Git push -f origin master; // After the rollback, it is mandatory to push the current version to the remote end to keep the remote and local synchronization. Git checkout -b git checkout hotfix -b git checkout hotfix Git checkout feature/a && git checkout master // Here's how # Recover Live and continue developing Git Stash PopCopy the code

Tips: There are two ways to indicate a version number for HEAD, one is HEAD^, and one is ^ to indicate a step back and start at 0,

The other option is HEAD~1, // the ~ symbol is followed by a digit, which indicates the rollback of one version. Git reset –hard b2968d5 // reset the current version to b2968d5

If you add the –hard parameter, it will return to the last commit state. This means that all changes made since the last commit will be reset. 1. The –soft parameter: moves the HEAD pointer only in the local library. 2, –mixed: moves the HEAD pointer in the local library and resets the staging area. 3. The –hard parameter: moves the HEAD pointer in the local library, resets the staging area, and resets the workspace.

C has a master branch, and her local git is the same as before the rollback. If she does git pull, then everything is fine.Git push and nothing. How? Git Revert

The git revert command means to undo a commit. It produces a new commit, and even though the code reverts, the version is still forward, so when you use revert and everyone pulls, their code automatically reverts.

Git revert HEAD~1 git revert HEAD~1 git revert HEAD~1 git revert HEADCopy the code

If a conflict occurs during the revert process and you don’t want to resolve it, you can abort the revert operation:

git revert --abort
Copy the code

B. Go to the specified version

Small A found himself back wrong, but also can remedy? Git allows you to regret your mistakes

Git reset --hard 924341d2d git reset --hard 924341d2dCopy the code

Scenario 3: Commit wrong and Git will fix it for you

A. Discard changes to a file (or delete a file by mistake) in the workspace

When you make changes in your workspace, change the contents of a file, discard it, or delete a problem by mistake, you need to restore it

git checkout -- <file>
Copy the code

B. Git add error

If you find that a file should not be committed after git add. method 1(recommended) : reset

Git reset HEAD [<file>] //<file> indicates that only the file is resetCopy the code

Git reset does not have an argument. By default, the –mixed parameter is executed, which means that the reset repository is used to the specified version and the cache is reset. In the above command, the specified directory version is HEAD, so there is no change, just the cache is reset.

Method 2: RM

Git rm --cached <file> // remove the file from the cache to an untracked state and delete it from the local library the next time you commitCopy the code

C.com MIT: Modifies the latest commit information

git commit --amend -m "your new message"// This operation modifies your last commit and does not create a new commitCopy the code

D. Modify a historical record commit

Little A found that one of the information submitted by little C was wrong, so she helped her to modify (1) check the modification

git rebase -i master~1 # last time (can be used as a branch ~ number, the number n indicates the NTH time)
git rebase -i HEAD~3   The last three submissions can also be in the form of HEAD^
git rebase -i afb927b3 # specified commit
Copy the code

(2) Press vi to go to the editing interface, modify information,esc, and :wq to exit

Git rebase contains the following Commands: P, pick: normally select r, reword: select and modify commit information e, edit: select, rebase is paused and allowed to modify commit s, squash: If this option is selected, the current commit and the previous commit are merged f. Fixup: is the same as a squash, but the commit information of the current commit is not saved X. Exec: Executes other shell commands b, break: Git rebase –continue d, drop: Drop commit

The following prompt appears:And your branch name has reps

Run at this pointGit commit - amendCommit or run immediatelyGit rebase - continueContinue to modify, also can rungit rebase --abortDiscard the rebase operation

appearSuccessfully rebased and updated refs/heads/XXX.The modification is successful.

E. Merge multiple commit commits into one commit (Git compression)

Git rebase -i HEAD~3 git rebase -i HEAD~3Copy the code

On the editing screen, change the following two picks to S (squash) or F (fixup). Save the Settings and exit

Error: Cannot ‘squash’ without a previous commit Do not merge previously committed records that have been committed to a remote branch.

If you exit the vi window unexpectedly, don’t panic: git rebase –edit-todo If you encounter a conflict, resolve it first, then git rebase –continue

In addition, when merge merges branches, it is also possible to merge multiple commits into one commit using squash

Git merge --squash Feature1 commit -m "message" git branch -d feature1Copy the code

F. Clean up commit submissions during branch merge to keep branches clean

The feature1 branch was pulled from the master branch to develop new requirements. After the Hotfix bug was fixed and merged into the Mster, the Feature1 branch needed to be kept in sync with the Master branch.

You can use

git merge master
Copy the code

Git rebase can be used to merge information in the git log

git rebase master
Copy the code

So what does Rebase do? First, Git cancels every commit in the Feature1 branch. Git /rebase. Then, update the Feature1 branch to the latest master branch. Finally, the patch files saved above are applied to feature1 branch.

The Feature1 branch is a hotfix merged master branch, which is naturally the leading branch, and the feature1 branch feels better without a merge commit.

G. How to break if the wrong branch is submitted?

B was working on feature2, but got stuck one day, cut dev and submitted it. Method 1: Reset

Cancel the latest submission and leave the site as it is
git reset HEAD~ --soft
git stash

Switch to the correct branch
git checkout feature2
git stash pop
git add .    # or add a specific file
git commit -m "commit message"
Copy the code

Method 2: Cherry -pick

Git checkout feature2 # git cherry-pick commitId # git checkout feature2 # Git checkout dev git reset HEAD~ --hardCopy the code

Cherry picking is also useful for merging a commit from another branch into the current branch.

H. Too fast hand speed, wrong branch name?

In the new branch feature/test, B accidentally typed feature/tset.

Git branch -m feature/tset feature/testCopy the code

Scenario 4: Undo/Delete commit, undo branch merge, delete branch

A. Request changes and submission is withdrawn

The product manager told Little A that the requirements were changed and the original content was no longer needed, that is, A history submission was no longer needed. Little A thought it was the latest submission, so

Git reset --hard HEAD // Reset the commit to the previous commit, HEAD points to the previous commit git push -fCopy the code

But it’s actually a submission somewhere in the middle of history, so

git revert -n commitId
git commit -m 'commit message'
Copy the code

Unlike RESET, which undoes the current submission and generates a new one (as opposed to this one), HEAD is forward and does not change past history.

There are two common parameters to revert: -n –no-commit: cancel out temporary and workspace file changes and do not cause new commits. -e, –edit: Execute without opening the default editor and use the commit information automatically generated by Git. If there is a conflict, git Revert –continue can continue, or git Revert –abort can abort after the conflict is resolved

B. The submission is incorrect, and the submission is deleted

Little A accidentally submitted A modification of configuration information and wanted to delete this submission

Git rebase -i commitId git rebase -i commitIdCopy the code

C. Cancel the merge of a branch

Method 1: Reset to the previous version of the merge and redo the following operations, but this requires other collaborators to roll back all local heads as well;

Git reset --hard commitId git push origin HEAD --forceCopy the code

Method 2: Use Git Revert when you merge with other operations and changes

git revert -m commitId
Copy the code
D. The remote branch is deleted and the local branch is disassociated

Little A deleted the branch Feature1 and pushed it to the remote end. At this time, little C could not push it to the remote end. In order to re-establish its association with the remote warehouse, it should first delete its original association with the deleted remote branch.

Git push origin --delete Feature1, git branch -vvCopy the code

Scenario 5: Restore commit (file)/branch

A. Restore the commit of the deleted branch

Small C submitted the changes to the local warehouse after the operation of the feature/collect-luck1 branch. After cutting to dev, it planned to merge feature/collect-luck1, but it was temporarily interrupted, and then thought it had been merged. Git branch -d feature/collect-luck1

Git FSCK --lost-found# returns information dangling commit f665fc6024d16e42d4332b07f7588cb1937ad6d 7Git rebase 7f665fc git rebaseCopy the code

Git FSCK: git FSCK: git FSCK: git FSCK: git FSCK: git FSCK: git FSCK: git FSCK: git FSCK

B. Restore the local branch that is mistakenly deleted

As mentioned above, C deleted feature/collect-luck1 by mistake. She still wants to retrieve the branch, so

Git reflog // find the commitid you deletedCopy the code

git checkout -b feature/collect-luck1 HEAD@{2}
Copy the code

appearunknow switch 'e'Don’t worry, just change it to commitId,git checkout -b feature/collect-luck1 c38bda30

The branch is currently in the feature/collect-luck1 branch, but the latest commit test111 is missing. You can use git reset to restore the branch.

Some git commands are often confused. Not sure which one to use?

Some of the commands are similar, so don’t be silly and confuse them.

Git log and git reflog

Git log can display all submitted information,You can add --pretty=onelineOnly the version number and remarks at the time of submission are displayedGit reflog displays all operations, including deletions, merges, etc.If you do not need to restore reset or rebase records, it is more convenient to use git log.

Git reset and Git Revert

The difference is that Git Revert simply undoes a commit, while Git reset reverses all subsequent operations to the staging area. Git Revert rolls back the previous COMMIT with a new COMMIT. The new COMMIT is the reverse of what you want to revert. Git reset deletes the specified commit and moves the HEAD to the last commit.

Git merge git rebase

Git merge creates a new commit. If a conflict occurs, you can modify it and commit it directly. Git rebase merges the previous commit history and does not generate a new commit. In case of a conflict, git add and then run git rebase –continue (if it does not work, run git rebase –skip). The golden rule of Git Rebase is: Never use it on public branches. Git Rebase is a devil or an angel. Check out the blog posts

For more on merge or rebase, check out Merging vs. Rebasing

At the end of the article’s welfare

1. I recommend a practical tool to you.gitignore.

Check MAC, window, vscode files to see if they need to be ignored.

2. Git commit specification

A standard COMMIT information, not only make it easy to troubleshoot problems, but also help others review, write a commit is also very necessary.

A commit message is broken down into three parts (separated by blank lines): Header line: Mandatory, describing the main change type and content topic content: describes why the change was made, what the change was made, and how it was developed, etc. Footer comments: Release Breaking Changes or Closed Issues

They are composed of the following parts:

Type: Indicates the type of the commit

Feat: new features fix refactor docs style: CSS test Case: Modify chore among other modifications, such as build process and dependency management Commit scope of influence, such as route, Component, utils, build… Specific changes can be divided into multiple lines, and 50/72 formatting footer is recommended: Some notes, usually a link to BREAKING CHANGE or fixing a bug.

Such a compliant COMMIT message is like an email.

Git Commit Message, Git Commit Message, Git Commit Message