Git, as an open source distributed version control system, occupies a certain position in daily development. It can be said that every developer needs to master the common operations of Git. This article will explain and demonstrate the common operations of Git.
If you have any objection to the content of this article, please comment on it. If you are interested, please click “like” and collect it.
Introduction of git
Git is an open source distributed version control system that can handle project version management from very small to very large projects efficiently and quickly. Linus Torvalds, the inventor of the open source Linux system, I’m sure you all know him. Most servers you see today actually run Linux, and it’s amazing that this god-like programmer didn’t just create Linux. So how does Linux code manage that? Before 2002, volunteers from around the world sent source code files to Linus via Diff, and Linus merged the code by hand! You know, the amount of Linux code at that time has been very large, through the way of manual management, one is prone to error, the second is low efficiency. Linus chose a commercial version control system, BitKeeper, which BitMover, the owner of BitKeeper, licensed to the Linux community for free out of humanitarian concern. Eventually, for some reason, BitMover took back free access to the Linux community, so Linus spent two weeks writing his own distributed version control system in C, and that’s where Git came in.
Git’s workspace and workflow
To understand how Git manages our code, the first step is to understand how git’s workspace is structured. Until you understand the composition of git’s workspace, you can use the right commands in the right areas. The figure below shows git’s four workspaces and some common operations.
Workspace: a place where changes are usually made, where the latest content is currently seen and the operation of the workspace is performed during the development process.
Git add indicates that the contents of the workspace are managed by Git. The first step is to commit the code to the staging area after completing a requirement or function.
Repository: a local Repository, located on your own computer, that is accessed by committing the contents of the staging area with git commit.
Remote: a server used to host code in a Remote repository. The contents of the Remote repository can be modified by collaborative local repositories distributed in multiple locations. After the code is modified in the local repository, the code is synchronized to the Remote repository through git push command.
In general, git’s workflow is divided into the following steps:
-
0. Pull the code for the remote repository.
-
1. Create, add, and modify files in the workspace.
-
2. Place the modified file in the temporary storage area.
-
3. Submit the files in the staging area to the local repository.
-
4. Push the modified files from the local repository to the remote repository.
The preparatory work
Installing Git locally
- Git download address, according to their own needs to download.
Configure the SSH key
-
If you do not want to configure the SSH key, you can use HTTPS to associate the remote repository, but you may need to re-enter the user name and password
-
To configure the SSH key, perform the following steps:
-
1. Open the console (CMD window) on the PC and run the ssh-keygen -t rsa -c < your email address > command. After the command is successfully executed, perform the following operations.
-
2. Go to the ~/. SSH directory, open the id_rsa.pub file, and copy all contents in the file.
-
3. On Github, copy the locally generated public key content to Github and host it. On github, click Settings ==> SSH and GPG keys ==> Add SSH key. Then paste in the contents of the id_rsa.pub file that you copied in the previous step and save it.
-
Configure the user name and email address
// To set a separate username and email address for a project, run the following command: Git config user.name "XXXXXXX" git config user.email "[email protected] Git config --global user.name "XXXXXXX" git config --global user.email "[email protected] --global --unset user. Name git config --global --unset user. Email --global --unset user. If you want to set the username and mailbox Settings separately for a project after configuring them globally, it may not take effect. 1. Go to the. Git directory of the project. Git config --local --unset user.name git config --local --unset user.email //2 Git config user.name "XXXXXXX" git config user.email "[email protected]" //3 Run the following command to check whether the Settings are successful: // Run the following command in the hidden folder. Git: cat configCopy the code
Git Workflow
1. Pull the remote repository code to the local repository
- Used if the project code is pulled for the first time
git clone
Command. For details about how to use the command, see
Git clone -b < branch name > < remote repository url https://github.com/gujunling/vue-template.gitCopy the code
- Update remote repository code to local (pull code to local before, not first pull code)
Git pull origin pre // Git pull is the same as git fetch && git mergeCopy the code
2. Initialize the local repository (this step is required only for a new project and the first git operation. Otherwise, this step is not required.)
// Create a new git repository in the current directory, that is, create a new git folder in the current folderCopy the code
3. Add native code to the staging area
Note: Before submitting code, please check to see if the branch you are in is the branch you want to submit code to
// It lists all branches and marks git branch * before its current branchCopy the code
Git add. Or git add * // Add the specified files to the staging area. If you need to add multiple files, separate them with Spaces. git add <filename1> <filename2> <filename3>Copy the code
If some files or directories do not want to commit, you can create a.gitignore file in the root directory and add related files or directories to the file.
Note that the.gitignore file can only ignore files that were not originally tracked, and if some files are already in version management, they will be modified. Gitignore is also invalid, so you can re-pull the code or manually remove the changes you don’t want to commit.
If you accidentally added an unwanted file to the staging area, you want to delete the file from the staging area.
-
A:
Git reset <filename1> <filename2> <filename3> // Delete all files in the staging areaCopy the code
-
Method 2:
Git rm --cache xxx.vue git rm --cache xxx.vue Git rm -f xxx.vue // Check whether the file is successfully deleted. You can run the following command to check the git status: git status // If the listed files do not contain the deleted files, the file is successfully deleted from the staging area.Copy the code
4. Commit code to the local repository
Commits are Conventional Commits. Commits to the repository can be **git Cz ** or VSCode (vsc-Commitizen). Pull code and resolve conflicts according to your personal habits, using commands, plug-ins, and graphical interfaces.
// git commit 'commit description' // Git cz: // git cz: // git cz: // git cz: // git cz: / If you make a mistake in this process or want to uncommit code to the local repository, Git reset HEAD~ git reset HEAD~ git reset HEAD~ git reset HEADCopy the code
Pay attention to
If the project does not support git cz, you can use the following command to install git cz.
Commitizen NPM install -g Commitizen // Run the following command in the project directory to support Angular's Commit Message format. commitizen init cz-conventional-changelog --save --save-exactCopy the code
git cz
After the command is executed, the system enters interactive mode. For details about the type, see the following table
value | describe |
---|---|
feat | Add a new feature |
fix | Fix a Bug |
docs | Document change |
style | Code formatting (does not affect functionality, such as space, semicolon, and other formatting fixes) |
refactor | Code refactoring |
perf | To improve the performance |
test | test |
build | Changing project builds or external dependencies (e.g. scopes: webpack, gulp, NPM, etc.) |
ci | Change the scripts commands in the continuous integration software configuration files and packages, such as scopes: Travis, Circle, etc |
chore | Change the build process or assistive tools |
revert | Code back |
Pay attention to
Select the type you submitted, press Enter, and enter the change scope, short description, long description, whether the modification is destructive, and what problem is fixed, etc. After filling in, Husky will call commitLint to verify the format of message. By default, type and Subject are mandatory.
Research the type of change that you're doing (<type>) 2.What is the scope of this change (e.g. component or) file name)? 3.Write a short, imperative tense description of the change: 4.Provide a longer description of the change: (Press enter to skip) Write a long description of the changes (<body>). Is (y/ N) a destructive modification? Default n (<footer>) 6.Does this change affect any openreve issues? What problem did the (y/n) change fix? The default n (< footer >)Copy the code
The following is an example of a description of a commit to a local repository:
-
Fix (XXX): Fixed the XXX bug
-
Feat (Component): Added the XXX function of a component
-
Chore (Configuration): Git hides file configuration modifications
-
.
5. Commit code from the local repository to the remote repository
// Note that you need to pull the code from the remote repository before submitting it to the remote repository. Git push origin < branch name > git pull origin < branch name > // For example: // pull the code from the master branch of the remote repository, but recently the name of the main branch of the new project on GitHub has been changed to main branch, because some people think that the master branch is not respectful. Git pull origin master git pull origin master git pull origin master git pull origin master Git push origin main --forceCopy the code
Pay attention to
If an error occurs while committing code, check to see if it is the first commit and the local repository is not bound to the remote repository.
If you need to bind goods from the remote warehouse to disassociate the goods from the remote warehouse, see the following sections.
Other Common Commands
git remote
Git remote add origin Git remote add origin / / https://github.com/gujunling/vue-template.git to view the current warehouse binding remote warehouse information git remote - v / / remove the binding between the local code and the remote warehouse git remote remove originCopy the code
git fetch
This operation only pulls remote changes and does not automatically merge. There is no effect on the current code
Git fetch --all git fetch --all git fetch --allCopy the code
git rebase
Rebase, which translates to rebase, is similar to merge. It is used to merge changes from one branch into the current branch.
Suppose we now have two branches, one for master and one for feature/1, and they both check out branches based on the initial commit add readme. After that, the master branch adds 3.js and 4.js files, and commits twice respectively. Js and 2.js files are also added to feature/1, corresponding to the following two submission records respectively.
The master branch submission record is shown as follows:
The submission record of feature/1 branch is shown below
It looks like this when combined:
In this case, switch to the feature/1 branch and run the git rebase master command. After the command is successful, run the git log command to view the record.
As shown in the figure below, you can see that the changes of the Mater branch are applied one by one, and then each change of feature/1 is applied one by one, using the last commit of the Master branch as a base point.
As a result, our commit record will be very clear. There will be no forks. This is a fairly smooth case, but most of the time, there will be conflicts in the rebase process. Then use git add and git rebase –continue to handle conflicts and rebase. If you don’t want the result of a rebase, use git rebase –skip to skip the rebase.
Git merge git rebase
Unlike Git rebase, git merge produces an additional merge record that is not fast-forward, similar to a commit message for merge branch ‘XXX’ into ‘XXX’.
For conflict resolution, merge can be used to resolve only one conflict, while Rebase can be used to resolve conflicts over and over again. However, rebase is more comfortable to use after you get used to it. (This does not mean that rebase is the most suitable, but it needs to be selected according to the actual situation).
Git Rebase interaction mode
In this case, the interactive mode of Rebase can be used to compress multiple commits into a single commit to get a clean commit history. For example, the commit history of a branch is as follows:
To enter interactive mode, run the following command:
git rebase -i <base-commit>
Copy the code
The base-commit parameter specifies the base commit object for the operation, based on which the rebase operation is performed. For the commit history example above, we want to compress the commit after the first commit object (AC18084) to a single commit. We need to execute the following command:
git rebase -i ac18084
Copy the code
You will enter a Vim interactive page with the editor listing information like the following.
This information represents four commits from the AC18084 object commit operation. Each commit is represented by a single line, displayed in chronological order, with the first line being the oldest commit and the last line being the most recent.
When the file is modified, Git will re-execute each commit in turn as an action. There are several actions, all of which default to pick, which means that the commit is used without any changes.
We now want to squash the last three commits into the first one. We need to use a squash. This action means we use this commit, but we merge it with the previous commit, so we just need to squash the last four actions.
Pick 7751DF4 feat: Correction 1 Squash cd94601 feat: Correction 2 Squash 0a137a8 feat: Correction 3 Squash ff6349f feat: Correction 4Copy the code
After you save (press: then save), the editor will prompt you to create a new commit based on the historical commit information. Then use git log to view the commit information. The commit record after rebase is shown below. Rebase operation can make our commit history clearer.
Note: Rebase operations can only be performed on the feature branch used by the user. Rebase operations are not allowed on the integration branch because such operations will modify the history of the integration branch
- Git rebase interactive reference
Git Revert rolls back a commit
Imagine a scenario where you have two recent releases coming out, and these two releases are accompanied by bug fixes. At the beginning, you fix the bug in the release branch of the first release, and suddenly, the day before the release, the test team says, It is necessary to change the bug fixes of the first version to the second version. At this time, the integration branch of the first version should include the functional contents of the first version, the submission of legacy bug fixes and other contents submitted by colleagues. If you want to reset a commit for a bug fix, it is not a good idea to reset a commit for a bug fix. It is dangerous to reset a commit for a bug fix. Git Revert comes in handy.
Git Revert Reverses an operation that does not modify the original commit record, but adds a new commit record to cancel the operation.Copy the code
Grammar:
-
Git Revert addresses common COMMIT
-
Git revert -m Commit for merge
Case demonstration is as follows:
As shown in the figure below, assume that the red box is a bug causing submission. After his submission, two more submissions are made, including those of other colleagues.
If you want to remove the code from the remote repository, run git revert 1121932, and then open the log. As shown in the following figure, you can see that a commit record has been added. The previous commit record does not disappear.
Git Revert also allows you to roll back multiple commits.
Git revert [commit1] [commit2]… , note that this is an open before closed interval, that is, commit1 is not included, but COMMIT2 is included.
The git revert command can be used to rollback the submitted code. The git revert command can be used to rollback the submitted code.
Git Revert will create a commit message to undo the changes.
Git reset returns the commit directly to the specified COMMIT. (It is not recommended to roll back the code in this way because the code will be lost if there are new commit records.)
For individual feature branches, you can use git reset to roll back the history, and then use git push –force to push the history to the remote branch. However, it is not recommended to use git reset directly on multiple collaborative integrated branches. Instead, use the more secure Git Revert command to undo the commit. This way, the submitted history is not erased and can be safely withdrawn.
Git Stash to temporarily store files
There is a scenario where you are now developing new features on your feature branch. At this time, there is a bug in the production environment that needs to be fixed urgently, but you have not finished developing this part of the code and do not want to submit it. What should you do? Then switch to the prod branch to fix the bug. When the fix is done, switch back to the feature branch to restore the content just saved from the stack.
The detailed steps are as follows:
-
1. At this point, I am working on a new feature in the feature branch and have modified the contents of the 1.js file
-
I want to fix the bug on the prod branch, so I have to stop the development and switch to the prod branch. However, there is still content in the workspace. If I switch to the prod branch, Git will report the following error:
error: Your local changes to the following files would be overwritten by checkout:
1.js
Please commit your changes or stash them before you switch branches.
Aborting
Copy the code
- 3. A file has been modified in the workspace and cannot be committed
commit
orstash
Operation, executiongit stash
After the operation, the result is as follows
Saved working directory and index state WIP on stash: 22e561c feat: add 1.js
Copy the code
- 4. At this time, ourThe workspace is clean, you can
Switch to the PROd branch for bug fixing
Assuming we’re done fixing the bug now, continue cutting backfeature
The branch develops the original functionality and only needs to be executedgit stash pop
Command, and the changes we temporarily saved will be restored to the workspace, as shown below.
- Tip:This is used when we want to temporarily store a file and switch branches to do something
git stash
This mechanism AIDS development.
It is recommended that when using stash commands, do not directly use git stash command for staging, but use git stash save “message…” This is a way to keep track of the commit so that when you want to apply changes, you have a look at all the staging lists through the Git Stash list. After that, it is recommended to use git stash apply stash@${num} to apply the corresponding Stash. In this way, the list of existing Stash items will not be emptied and can be applied to the current workspace. If this temporary stash is not needed, you can manually clear it.
Git status Displays the Git status
Git status git statusCopy the code
Git log Displays logs
// Check the version history of the current branch, i.e. the log, (check the commit record) git logCopy the code
Git help check for help
// git helpCopy the code
Git branch command
Git checkout -b XXX // create a new branch and switch to the XXX branch. Git branch -r git branch -d XXX // delete the XXX branch Git merge < branch name > // Merge local branches. Merge the specified branch into the current branch. Git merge < remote repository name >/< branch nameCopy the code
Reference documentation
-
Juejin. Cn/post / 697418…
-
www.liaoxuefeng.com/wiki/896043…
-
My.oschina.net/javazhiyin/…
-
www.jianshu.com/p/36d970a2b…