How do I use Git at work? How do I use Git at work

preface

Recently, there was a real case on the Internet that was more popular. It said that a new employee who could not pull code with Git was fired the next day. From this, it can be seen that Git is important to our work, both front-end and back-end, are inseparable from Git, let’s take a look at it.

How to configure the local Git environment and pull the code after your leader has assigned you the repository permission? Follow these four steps to make sure you can pull code with Git!

  1. Download Git download address, select your own system version to download.

  2. Open the terminal and run the ssh-keygen -t rsa -c “your internal email address” command. If the command is successfully executed, switch to the ~/. SSH directory, which should be as follows: Copy the contents of id_rsa.pub.

  3. Go to Settings -> SSH and GPG keys and run the cat command to view the contents of the id_rsa.pub file, copy it, and click Add SSH key. This step is equivalent to hosting your public key on Github.

  4. Configure Git username and mailbox globally

git config --global user.name "xxx"
git config --global user.email "[email protected]"
Copy the code

Complete the above four steps, and you’re ready to happily pull code. In SSH mode, 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 Git operations, I think it’s important to understand the origin of Git and what it is designed to solve. Git (pronounced /gɪt/) is an open source distributed version control system that can handle versioning projects from very small to very large efficiently and quickly. Linus Torvalds, who I’m sure you all know, is the inventor of the open source Linux system. Most of the servers you see these days are actually running on Linux, and the amazing thing is 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 via Diff, and Linus merged the code by hand! You should know that the amount of Linux code at that time has been very large, through the manual management of the way, one is prone to error, two is inefficient. So Linus chose BitKeeper, a commercial version control system that BitMover, the company that owns BitKeeper, granted free access to the Linux community for humanitarian reasons. 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 from.

Git work areas and processes

One of the first things you need to understand about how Git manages your code is how Git’s workspace is structured. You can use the right commands in the right areas only if you understand the Git work area thoroughly. As shown in the following figure, this figure contains four workspaces for Git and some common operations.

Workspace: Workspace, is usually the development of the change of the place, is the current to see the latest content, in the development process is the operation of the Workspace

Index: staging area, when the git add command is executed, the files in the workspace will be moved to the staging area. The staging area marks the contents in the current workspace that are managed by Git. When the code needs to be submitted after completing a requirement or function, the first step is to submit to the staging area through Git add.

Repository: a Repository that is located on your own computer and is entered by committing the contents of your staging area through Git Commit.

Remote: a server used to host code in a Remote repository. The contents of the Remote repository can be modified by a collaborative local repository located in multiple locations. After modifying the code, the local repository synchronizes the code to the Remote repository by using git push commands.

In general, the Git workflow is divided into the following steps

1. Develop, add and modify files in the workspace. 2. Place the modified file into the temporary storage area. 3. Submit the files in the staging area to the local repository. 4. Push the changes in the local repository to the remote repository.Copy the code

Git Basic Operations

git add

Adds a file to the staging area

# Add a file to the staging area, which can be followed by multiple files, separated by Spaces
git add xxx
# Add all files currently changed to the staging area.
git add .
Copy the code

git commit

# Commit temporary changes, the new editor will be opened for editing
git commit 
# Commit the temporary changes and record the comments
git commit -m "you message"
Git add.&& git commit -m
git commit -am
This operation will change the hash value of the commit
git commit --amend
Copy the code

git pull

# Pull code from a remote repository and merge it locally. Abbreviated as git fetch && Git mergeGit pull < host name > < branch name >:< branch name ># Use rebase's schema to mergeGit pull --rebase < host name > < branch name >:< local branch name >Copy the code

git fetch

Unlike Git pull, git FETCH only pulls remote changes and does not merge automatically. Has no effect on your current code

Get updates for a specific branch of the remote repositoryGit fetch < host name > < branch name >Get updates for all branches of the remote repository
git fetch --all
Copy the code

git branch

# Create a local branch without switching
git branch <branch-name> 
Check the local branch
git branch
# View remote branch
git branch -r
View local and remote branches
git branch -a
Delete local branch
git branch -D <branch-nane>
# Rename the branch
git branch -m <old-branch-name> <new-branch-name>
Copy the code

Scenarios where you use Git to solve problems at work

Git Rebase makes your commit record more readable

Use of Git Rebase

Rebase translates to rebase. This function is similar to merge. It is used to merge changes made in a branch into the current branch.

The following figure shows the change of the commit history after rebase.

Now let’s use an example to explain the above process.

Let’s assume that we have two branches, one for master and one for feature/1, and they both check out the branch based on the initial commit add readme, and then add 3.js and 4.js files to the master branch, and commit them twice, respectively. Feature /1 also adds 1.js and 2.js files, corresponding to the following two commit records.

At this point, the commit record of the corresponding branch is as follows.

The master branch is shown below:

The feature/1 branch is shown below

The combination looks like this

If the feature/1 branch is running, run git rebase master, and check the git log.

As shown in the figure below, you can see that the changes to the Mater branch are applied one by one, then each change to Feature /1 is applied one by one, based on the final commit of the Master branch.

Therefore, our submission record will be very clear and there will be no fork. The above demonstration is a relatively smooth situation, but in most cases, conflicts will occur during the rebase process. In this case, conflicts need to be resolved manually. Git add, git rebase –continue (git add, git rebase –continue) You need to use git rebase –skip to skip the rebase operation.

The difference between git merge and Git Rebase

Unlike git rebase, git merge generates an additional merge record when it is not fast-forward, such as merge branch ‘XXX’ into ‘XXX’ for a commit.

In addition, when solving conflicts with merge, only one conflict needs to be resolved, which is simple and rude. When using rebase, each conflict needs to be resolved in order to commit.

Git Rebase interactive mode

In development, it is common to encounter many invalid commits on a branch. In this case, the interactive mode of Rebase can be used to compress multiple commits that have occurred into one commit and get a clean commit history. 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>
Copy the code

The base-commit parameter indicates the base commit object on which the commit object is to be rebase. For the example above, we need to compress the commit object before the last commit object (AC18084) into a single commit. We need to run the following command:

git rebase -i ac18084
Copy the code

This leads to a Vim interactive page, where the editor lists information like this.

To merge this pile of changes, we use the Squash policy to merge the current commit and its previous commit, which can be expressed as: in interactive mode rebase, keep at least one pick, otherwise the command will fail.

pick ... . s ... . s ... . s ... .Copy the code

After modifying the file, press: and then wq to save and exit. At this time, an editing page will pop up again. This page is used to edit the submitted information, and it is modified as feat: After rebase, you can see the commit record as shown in the figure below. The rebase operation makes our commit history much clearer.

In particular, rebase operations can only be performed on the feature branch you are using. Rebase operations are not allowed on the integration branch because such operations can modify the history of the integration branch.

Use Git cherry-pick to get the specified commit

Git cherry-pick can be understood as “picking” commits. Instead of merging all commits for a branch, git cherry-pick takes a single commit from a branch and introduces it as a new commit to your current branch. Git cherry-pick is used when we need to merge commits from other branches locally, if we 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 based on the master check out. The corresponding branch log is recorded as follows

The commit for the master branch is as follows

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Now you can use the Cherry pick command.

Syntax: git cherry-pick [commit-hash]

Commit-hash Indicates the hash value of a commit. Git cherry-pick e0bb7F3 and git Cherry-pick c9a3101 in sequence. If there is a conflict, resolve the conflict and proceed with Git add. Git cherry pick –continue, and finally, the commit on master is as follows

At this point, the required commit is applied on the master branch and we have the desired effect. Git cherry-pick

= git cherry-pick

= git cherry-pick Git cherry-pick

^…

, which indicates that all commits from first-commit-id to last-commit- ID will be merged.

Use Git Revert to roll back a commit

Imagine a situation where you have two versions of your project coming online recently, both of which are accompanied by bug fixes that you’ve left behind. Initially, you fix bugs on the release branch of the first version, and suddenly, the day before the release, you get feedback from the testers, The bug fixes of the first version need to be changed to the second version. At this time, the integration branch of the first version should include the functions of the first version, the legacy bug fixes and other colleagues’ submissions. It is not a good idea to reset a previous commit for a bug fix. It is also dangerous. What should we do if we do not want to break the commit record and want to withdraw the commit record for our remaining bug fix? Git Revert comes in handy.

Git Revert revoking an action. This action does not alter the original commit, but instead adds a new commit to offset the action.

Git Revert

Git Revert

-m Commit for merge

Let’s use an example to understand this command. As shown in the figure below, suppose that the place in the red box is a commit that causes a bug. After his commit, there are two more commits, including other colleagues’ commits.

Git Revert 1121932, open the log again, as shown in the figure below, you can see that a new commit record has been added. The MSG generated by the commit is automatically generated. The commit record before the withdrawn 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 an open and closed interval, that is, commit1 is not included, but commit2 is included.

There are two ways to roll back our commits. You can use the git reset command in addition to the Git Revert command mentioned above, so what’s the difference?

Git Revert will create a commit message to undo the previous change.

Git reset returns the commit record directly to the specified commit.

For individual branches, you can use git reset to backtrack the history, and then use git push –force to push the history to a remote location. However, it is not recommended to use git reset directly on integrated branches with multiple partners. Instead, use the more secure Git Revert command to revoke the commit. This way, the submitted history is not erased and can be safely withdrawn.

Use git Stash to stash files

There will be a scenario where you are developing new features on your feature branch. At this time, there is a bug in the production environment that needs urgent repair, but you have not finished the development of this part of the code, do not want to submit, what to do? You can use the Git Stash command to save the modified files in your workspace and then switch to the HotFix branch to fix the bug. When the fix is complete, switch back to the Feature branch to restore the saved contents from the stack.

The basic commands are as follows

Git stash // Stash local changes to be saved"message"During storage, add remarks for easy search. Git stash pop // Applies the last cached change and removes the cached record. Git stash apply // applies a store but does not remove it from the list of stores. The default is to use the first store, stash@{0}. git stash apply stash@{$num}. Git stash list // Check what stash stores are available. Git stash Clear // Deletes all cached stash storesCopy the code

Here’s a look at some of the stash commands.

At this point, I’m working on a new feature that modifies the contents of the 1.js file

I want to switch to the Hotfix branch to fix the bug, so I have to pause development and switch to the Hotfix branch. However, there is still content in the workspace. If I switch to the hotfix 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

You need to commit or stash first. You need to execute git stash. The result is as follows

Saved working directory and index state WIP on stash: 22e561c feat: add 1.js
Copy the code

At this point, our workspace is clean and we can switch to the HotFix branch to fix the bug. Assuming that we have fixed the bug now, we can switch back to the Feature branch to develop the original function. At this point, we just need to execute git Stash Pop. The changes we saved earlier will revert to the workspace, as shown in the figure below.

Git Stash is a mechanism you can use to help when you want to temporarily store files and switch branches to do something.

It is recommended to use the git stash save “message…” instead of using the git stash command to save each time. In this way, a record of information is made for this submission. In this case, when you want to apply a change, check out all the staging lists through the Git Stash List. After that, it is recommended to use the Git stash apply stash@${num} method to apply the corresponding stash. This will not empty the existing Stash list items and will apply to the current workspace. If you do not need this temporary storage, you can manually clear it.

Different work areas undo changes

In development, we often need to roll back the operation of code, in different work area, the way to roll back the code is also different. As shown below, suppose you are developing on the feature/ REVOKE branch.

Start by checking your current status with git status.

At present, our workspace is very clean, without any modification operation, at this time, modify the code and check the status again, you can see that the 1.js file is modified.

Now we want to restore the 1.js file to its original state, that is, to withdraw the changes in the workspace, we can use git checkout —

command, if you want to withdraw the changes in multiple files, use Spaces between the files, as shown in the figure below, we have withdrawn the changes in 1.js file. The workspace is clean again.

If the file has been modified and has been submitted to the staging area, and we do not want this part of the file, then we can use the git reset

command to undo the specific file, git reset will withdraw all the files in the staging area, as shown in the figure below. Looking at the status before and after, you can see that the file was successfully withdrawn to the workspace.

Configure Git Alias to improve work efficiency

In general, after receiving the development task, 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 brief operation, the development is completed and the code is submitted. And such as git add, git commit, git push and other commands, although simple, but the input is not concise enough, as a programmer, the development program is to improve our efficiency, laziness is the source of human progress, so we can configure aliases, simplify these commands.

Its basic use is the git config –global alias.< simplified characters > original command

Here’s an example:

$ git config --global alias.co checkout
$ git config --global alias.ci commit
$ git config --global alias.br branch
Copy the code

I’m going to put co for checkout, CI for commit, br for branch, and I’m going to abbreviate that for commit

–global is a global parameter, meaning that once configured, the commands work in all repositories on the computer. These commands update your global.gitconfig file, which holds the global git configuration, vim ~/.gitconfig. Git config — Global Alias

In addition to the above direct command approach, you can also set the alias by modifying the alias entry of the file.

Here is an example of my own common alias Settings. Replace the following configuration with the area where [alias] belongs in the.gitconfig file, and you’ll be happy to 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
Copy the code

This way, every time we want to see Git history, we can use Git LG without having to type a long list of commands. Here is the commit record in the Source code of Axios

The relationship between branches is clear at a glance, and the merge on which commit is being performed is also clear, which helps us to track the commit history and resolve problems.

conclusion

This article explains the Git environment from the shallow to the deep, the basic usage, and the use of more frequent Git commands in the work, whether you are the front-end and back-end or other end of the development, the daily work of the use of Git, we not only need to use, but also use beautiful, use flexible, use steady. In this way, you can be more comfortable when collaborating with colleagues on projects. After learning these Git techniques in this article, you can practice them in your daily work, and I believe it will bring you great harvest!

reference

Ruan Yifeng’s Git tutorial

Differences between Git merge and rebase branch merge commands

Recommended reading

V8 performs the js process

Get you started with Webpack Plugin

Open source works

  • Politics in front of tabloids

Open source address www.zoo.team/openweekly/ (there is a wechat group on the homepage of the official website of the tabloid)

, recruiting

ZooTeam (ZooTeam), a young and creative team, belongs to the product RESEARCH and development department of ZooTeam, based in picturesque Hangzhou. The team now has more than 40 front end partners, the average age of 27 years old, nearly 30% are full stack engineers, no problem youth storm team. The membership consists of “old” soldiers from Alibaba and netease, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to the daily business connection, the team also carried out technical exploration and actual practice in the direction of material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of the front-end technology system.

If you want to change the things you’ve been doing, you want to start doing things. If you want to change, you’ve been told you need to think more, but you can’t change; If you want to change, you have the power to achieve that result, but you are not needed; If you want to change what you want to accomplish, you need a team to support you, but there is no place for you to bring people; If you want a change of pace, it’s “3 years of experience in 5 years”; If you want to change the original savvy is good, but there is always a layer of fuzzy window paper… If you believe in the power of belief, that ordinary people can achieve extraordinary things, that you can meet a better version of yourself. If you want to get involved in the growth of a front end team with a deep understanding of the business, a sound technology system, technology that creates value, and spillover impact as the business takes off, I think we should talk about it. Any time, waiting for you to write something, to [email protected]