This is the 103rd original article without water. If you want to get more original articles, please search the official account and follow us.
How do I use Git at work
preface
Recently there is a real case on the Internet more fire, said is a new employee, can not use Git pull code, the next day was fired. From this, we can see the importance of Git to our work, both front and back end, can not do without Git, let’s take a look at it.
The above example raises a question. When you work in a new company, how do you configure the local Git environment and pull the code after your leader assigns you the permission of the warehouse? Don’t panic, follow the four steps below to ensure that you can pull code without any problems with Git!
- Download Git download address, select the corresponding version of your system to download.
-
Generate the SSH key on your computer, open the terminal, execute ssh-keygen-t rsa-c “internal email address of your company”, if successful, switch to ~/.ssh directory, the directory should look like the following. Copy the contents of id_rsa.pub.
-
Take GitHub as an example, go to settings-> SSH and GPG keys as shown in the figure below, go to cat command to view the contents of the file id_rsa.pub, then copy it, click Add SSH key, This step is equivalent to hosting your public key on GitHub.
- Globally configure the Git username and mailbox
git config --global user.name "xxx"
git config --global user.email "[email protected]"
After completing the above four steps, you should be happy to pull code development. Unlike HTTPS pull, which requires you to manually enter your username and password before each commit, Git will use your local private key and the public key of the remote repository to verify whether it is a pair of secret keys, thus simplifying the operation process.
Introduction of Git
Before I introduce you to Git, I think it’s important to understand where Git came from and what problems Git is used to solve. Git is an open source distributed version control system that can handle versioning from very small to very large projects efficiently and at high speed. Linus Torvalds, who I’m sure you all know, is the inventor of the open source Linux system. Most of the servers you see today are actually running Linux, and it’s amazing that this great programmer didn’t just create Linux. So how is Linux code managed? Before 2002, volunteers around the world sent source code files to Linus by diff, and Linus himself merged the code manually! You know, the amount of Linux code at that time has been very large, through manual management, one is prone to error, the other is inefficient. Linus chose BitKeeper, a commercial version control system, which BitMover, a company that owns BitKeeper, licensed to the Linux community for free in the spirit of humanitarianism. Eventually, for some reason, Bitmover took back its free rights to the Linux community, so Linus spent two weeks writing his own distributed version control system in C, and that’s where Git came from.
Git’s workspace and flow
To understand how Git manages our code, the first step is to understand how Git’s workspace is structured. Because only by thoroughly understanding the structure of your Git workspace can you use the right commands in the right place. The following diagram shows Git’s four workspaces and some common operations.
Workspace: Workspace is the place where changes are made at ordinary times. It is the place where the latest content is seen. In the process of development, it is the operation of the Workspace
Index: staging area. When you execute git add, files in the workspace will be moved to staging area. The staging area marks the contents in the current workspace that are managed by git.
Repository: The Repository is located on your computer, and you commit the contents of the staging area through git commit.
Remote: A server used to host code. The contents of a Remote repository can be modified by a cooperative local repository located in multiple locations. The local repository makes the changes and synchronizes the code to the Remote repository through git push.
In general, the Git workflow is divided into the following steps
1. Develop, add and modify files in the workspace. 2. Put the modified file into the temporary storage area. 3. Submit the files in the staging area to the local warehouse. 4. Push the changes from the local repository to the remote repository.
Git Basic Operations
git add
Add file to staging area
Git add xxx. git add xxx. git add xxx. git add xxx. git add xxx. git add xxx. git add .
git commit
Git commit * git commit * git commit * git commit * git commit * git commit * git commit * git commit * Git add. && git commit -m git commit -am # to modify the hash of the last commit git commit --amend
git pull
# pull code from remote repository and merge it locally Git pull is equivalent to git fetch && git merge git pull < remote host name > < remote branch name >:< local branch name > # use rebase mode to merge git pull --rebase < remote host name > < remote branch name >:< local branch name >
git fetch
Unlike Git Pull, Git Fetch only pulls remote changes and does not merge automatically. Has no effect on your current code
Git fetch < remote hostname > < branch name > # get git fetch --all for all branches of the remote repository
git branch
# create a new local branch Git branch -r git branch -r git branch -r git branch -r git branch -r git branch -r Git branch -m <old-branch-name> <new-branch-name>. Git branch -m <old-branch-name> <new-branch-name>
Use Git to solve a problem at work
Git rebase makes your commit records more readable
The use of git rebase
Rebase is similar to merge. It is used to merge changes from a branch into the current branch.
As shown in the figure below, the submission history changes after rebasing.
Now let’s use an example to illustrate the above process.
Suppose we have two branches, one for master and the other for feature/1, and they both check out branches based on the initial submission add readme. Later, we add files of 3.js and 4.js to the master branch, and commit them twice respectively. Feature /1 also adds 1.js and 2.js files, which correspond to the following two commit records.
At this point, the commit record for the corresponding branch is as follows.
The master branch is shown below:
Feature /1 branch is shown below
This is what it looks like in combination
At this point, switch to the feature/1 branch, execute git rebase master, and after success, check the records through git log.
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 based on the last commit of the master branch.
Therefore, our submission record will be very clear and there will be no fork. The situation demonstrated above is relatively smooth, but in most cases, conflicts will occur in the process of rebase. In this case, the conflict needs to be resolved manually. Git rebase –continue git rebase — git rebase –continue git rebase –continue To skip this rebase, use git rebase –skip.
Git Merge and Git Rebase
Unlike Git rebase, a Git merge produces an additional merge record if it is not a fast-forward, similar to a commit message for merge branch ‘XXX’ into ‘XXX’.
When you merge, you only need to resolve a conflict once. When you rebase, you need to resolve each conflict in turn before committing.
Git rebase interaction mode
In development, it is common to encounter a lot of invalid commits on a branch. In this case, the interactive mode of rebase can be used to compress the multiple commits that have occurred into a single commit, and a clean commit history can be obtained. For example, the commit history of a branch is as follows:
The way to enter interactive mode is to execute:
git rebase -i <base-commit>
The base-commit parameter specifies the base object on which the rebase operation is based. For the example above, we would like to compress the commits before the last commit object (AC18084) into a single commit. The format of the command we need to execute is:
git rebase -i ac18084
An interactive page of Vim is brought to you, with the editor listing information like the following.
To merge this bunch of changes, we use a Squash strategy, which merges the current commit with its last commit, roughly expressed as the following: under interactive rebase, keep at least one pick, otherwise the command will fail.
pick ... . s ... . s ... . s ... .
After modifying the file, press: and then WQ save to exit. At this time, an editing page will pop up. This page is used to edit the submitted information. You can use git branch to check the commit information of your project. You can also use git branch to check the commit information of your project. The rebase operation makes our commit history clearer.
In particular, you can only rebase on the Feature branch that you are using. Rebase on the Integration branch is not allowed, because this will modify the history of the Integration branch.
Use git cherry-pick to get the specified commit
Git cherry – pick can be understood as “pick” submitted, and a branch merge to merge all submitted, it will get a branch a single submission, and introduced as a new submission to your current branch. Git cherry-pick is used when you need to merge other branch commits locally, if you don’t want to merge the entire branch, but just want to merge a commit into the current branch locally.
Feature /cherry-pick1 and feature/cherry-pick2 are two functional branches detected by master. The corresponding branch log is as follows
The master branch commits as follows
Now the master only needs changes to feature/cherry-pick1 and feature/cherry-pick2 and does not care about changes to fix contents. At this point, you can use the cherry-pick directive.
Syntax: git cherry-pick [commit-hash]
Commit -hash represents the hash value of a commit. Git cherry-pick e0bb7f3, git cherry-pick c9a3101, git cherry-pick c9a3101, git cherry-pick c9a3101, git cherry-pick c9a3101, git cherry-pick c9a3101 Then execute git cherry-pick –continue, and finally, the commit on the master looks like this
At this point, the required commit is applied to the master branch, and we have the desired effect. Git cherry-pick
… git cherry-pick
… git cherry-pick
… Git cherry-pick
^… git cherry-pick
^… git cherry-pick
^…
, which means that all commits from first-commit-id to last-commit-id will be merged.
Use git revert to roll back a commit
Imagine a scenario where you have two versions of your project coming out recently, and these two versions are accompanied by bug fixes. At the beginning, you put the bug fixes on the release branch of the first version, and all of a sudden, the day before the release, the testing side gets feedback. It is necessary to change the bug fixes of the first version to the second version. At this time, the submission of the integration branch of the first version should include the functional contents of the first version, the submission of the legacy bug fixes and the submission of other colleagues. It is not a good idea to try to reset the previous commit for a bug fix. It is also dangerous. What should we do when we want to not only destroy the previous commit, but also undo the commit for a bug that we left behind? This is where Git Revert comes in handy.
git revert
Undo an operation that does not modify the original commit record, but creates a new commit record to offset the operation.
Git revert
Git revert
-m commit to merge
To understand this command, let’s use an example, as shown in the figure below. Let’s assume that the place marked in red is a bug-causing commit, and that his commit is followed by two more commits, including other colleagues’ commits.
If you want to eliminate the bug that caused the commit, execute git revert 1121932 and then open the log. As shown in the figure below, you can see that a new commit has been created. The revert is automatically generated by the revert. The COMMIT record followed by the retracted COMMIT-MSG message does not disappear, and the effect of code rollback is achieved
Git revert can also roll back multiple commits
Git revert [commit-id1] [commit-id2]… Note that this is a front and back interval (commit1 is not included, but commit2 is included).
There are two ways to reverse your commit. One is to use git revert. The other is to use git reset.
The git revert creates a commit message to undo the changes.
Git Reset will return the committed record directly to the specified COMMIT.
For individual feature branches, you can use git reset to back and forth the history, and then use git push –force to push to the remote. However, if you are working on an integrated branch with multiple people, it is not recommended to use git reset directly. Instead, use the more secure git revert command to undo the commit. In this way, the submitted history is not erased and can be safely withdrawn.
Use Git Stash to temporarily store files
There is a scenario where you are currently developing a new feature using your Feature branch. At this point, there is a bug in the production environment that needs to be fixed urgently, but you haven’t developed this part of the code yet and don’t want to commit it. What should you do? At this time, you can use the git stash command to temporarily save the modified files in the workspace, and then switch to the hotfix branch for bug repair. After the repair is completed, switch back to the feature branch and restore the newly saved contents from the stack.
The basic commands are as follows
Git stash save "message" git stash save "message" // Apply a store, but it does not remove the store from the store list. The first store is used by default, stash@{0}. If you want to use another one, you can use the first one. Git stash apply stash@{$num}. Git stash list // see what stash is stored in git stash clear
Let’s take a look at Stash’s commands in a few images below.
At this point, I was working on a new feature, which changed the contents of the 1.js file
If I want to switch to the hotfix branch to fix the bug, I have to pause the development and switch to the hotfix branch. However, there is still content in the workspace. If I switch to Git branch at this time, the following error will be reported
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
Git stash = git stash = git stash = git stash = git stash = git stash = git stash = git stash = git stash = git stash
Saved working directory and index state WIP on stash: 22e561c feat: add 1.js
At this time, our workspace is clean and we can switch to hotfix branch for bug fixing. Suppose we have finished bug fixing now, and continue to cut back to feature branch for original function development. At this time, we only need to execute git stash pop. The changes we temporarily saved before are restored to the workspace, as shown in the figure below.
When you want to hold files, switch branches and do something else, you can use the Git Stash mechanism to help with development.
It is recommended that you do not use the Git Stash command to save the “message…” whenever you save a git stash. In this way, make a record of the information for the submission. So, when you want to apply changes, go through the Git Stash List and look at all the staging lists. It is recommended to use git stash apply stash@${num} to apply the corresponding stash. In this way, the list items of the existing stash will not be cleared, and it can be applied to the current workspace. If you do not need this temporary storage, it can be manually cleared.
Undo changes in different work areas
In development, we often need to reverse the operation of code, and the way to reverse the code is different in different work areas. As shown in the figure below, suppose you want to develop on the Feature/Revoke branch now,
First check the current status with git status.
At present, our workspace is very clean and there is no modification operation. At this time, modify the code and check the status again. You can see that the 1.js file has been modified.
Git checkout:
> git checkout:
> git checkout:
> git checkout:
> The workspace is clean again.
Git reset = ‘filename>’; git reset = ‘filename>’; git reset = ‘filename>’; git reset = ‘filename>’; Check the status before and after the file was successfully withdrawn to the workspace.
Configure Git Alias for productivity
Generally, when we receive a development task at work, we need to create a new branch for development. At this time, we need to use git branch, git checkout, git pull and other commands. After a single operation, the development is finished and the code is submitted. As a programmer, the development of programs is to improve our efficiency. Lazy is the source of human progress. So we can simplify these commands through the configuration of alias.
Its basic usage is git config –global alias.< simplified character > original command
Here’s an example:
$ git config --global alias.co checkout
$ git config --global alias.ci commit
$ git config --global alias.br branch
CO means checkout, CI means commit, and BR means branch, which can be abbreviated as commit
–global is the global parameter, meaning that once configured, these commands can be applied to all the repositories on this computer. These commands update your global.gitconfig file, which is used to store your global git configuration, vim ~/.gitconfig. When you run this command, it looks like this: The following figure shows the alias you just added via git config –global alias.
In addition to the above direct command method, you can also set the alias by modifying the alias entry of the file.
Here is a list of my own common alias Settings. Replace the following configuration in the area of [alias] in the. GitConfig file, and then you can happily use ~
[alias] st = status -sb co = checkout br = branch mg = merge ci = commit ds = diff --staged dt = difftool mt = mergetool last = log -1 HEAD latest = for-each-ref --sort=-committerdate --format=\"%(committername)@%(refname:short) [%(committerdate:short)] %(contents)\" ls = log --pretty=format:\"%C(yellow)%h %C(blue)%ad %C(red)%d %C(reset)%s %C(green)[%cn]\" --decorate --date=short hist = log --pretty=format:\"%C(yellow)%h %C(red)%d %C(reset)%s %C(green)[%an] %C(blue)%ad\" --topo-order --graph --date=short type = cat-file -t dump = cat-file -p lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
In this way, every time you want to view your Git history, you can use the Git LG without typing a long list of commands. The following image shows the commit record from the Axios source code, using the enclosed Git LG
The relationships between branches are clear at a glance, and the merge operation is also clear at which Commit, which helps us to trace historical commits and resolve problems.
conclusion
This article explains Git environment construction, basic usage, and the use of relatively high frequency Git commands in work from the shallow to the deep. No matter you are the front-end and back-end development or other end development, you must use Git in your daily work. We should not only know how to use Git, but also use it in a beautiful, flexible and stable way. In this way, you can be more handy when collaborating with colleagues on projects. After learning these Git using skills in this article, you can practice more in your daily work, which I believe will bring you great harvest!
reference
Ruan Yifeng’s git tutorial
Git merge and rebase branch merge commands
Open source works
- Politics gathers cloud front tabloids
Open source address www.zoo.team/openweekly/ (there is WeChat communication group on the homepage of the tabloid official website)
, recruiting
ZooTeam, a young, passionate and creative front-end team, is affiliated to the R&D Department of ZooTeam, based in the picturesque city of Hangzhou. There are more than 40 front-end partners in the team, with an average age of 27. Nearly 30% of them are full stack engineers, no problem young storm group. The members are not only “old” soldiers from Ali and netease, but also fresh graduates from Zhejiang University, University of Science and Technology of China and Hangzhou Electric University. In addition to daily business connection, the team also carries out technical exploration and practical practice in the directions of material system, engineering platform, construction platform, performance experience, cloud application, data analysis and visualization, promotes and lands a series of internal technical products, and continues to explore the new boundary of the front-end technical system.
If you want to change what you’ve been doing, you want to start doing it. If you want to change the way you’ve been told you need to think a little bit, you can’t break it. If you want to change, you have the power to do it, but you don’t need to; If you want to change what you want to do, you need a team to support it, but there is no place for you to bring people. If you want to change the established pace, it will be “5 years and 3 years experience”; If you want to change the original savvy is good, but there is always a layer of window paper fuzzy… If you believe in the power of belief, the ability of ordinary people to do extraordinary things, to meet better people. If you want to be a part of the take-off process and personally drive the growth of a front end team that has a deep business understanding, a sound technology system, technology that creates value, and influence that spills over, I think we should talk. Anytime, waiting for you to write something down and send it to [email protected]