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 quite popular. It was about a new employee who did not use Git to pull code and was fired the next day. From this, we can see the importance of Git to our work, whether it is front-end or back-end, it is inseparable from Git, let us find out below. The above case raises a question. After joining a new company and your leader has assigned you warehouse permissions, how do you configure the local Git environment and pull code? Don't panic, follow the four steps I talked about below to ensure that you can use Git to pull code smoothly!

  1. Download the Git download address and select the version corresponding to your system to download.

  2. Generate the ssh key on your computer, open the terminal, and execute

    ssh-keygen -t rsa -C
    "Your company's internal email address", if the execution is successful, switch to
    ~/.ssh
    Under the directory, the directory should now look like the following. copy
    id_rsa.pub
    Content.

  1. Take Github as an example, as shown in the figure below, enter
    settings -> SSH and GPG keys
    by
    cat
    Command to view files
    id_rsa.pub
    And then copy it over, click
    add ssh key
    , This step is equivalent to putting your public key on Github for hosting.

  1. Configure Git username and email globally
config git - , Ltd. Free Join user.name "xxx" git config - , Ltd. Free Join user.email "xxx@xx.com" Copy the code

After completing the above four steps, you can happily develop the pull code. Unlike the https pull method, the https method requires you to manually enter the user name and password before each submission. After the ssh method is configured, Git will use your local private key and the public key of the remote warehouse to verify whether it is a pair of secrets. Key, which simplifies the operation process.

Introduction to Git

Before introducing the related operations of Git, I think it is necessary to understand the origin of Git and what problems Git is used to solve. Git (pronounced/g t/) is an open source distributed version control system that can effectively and quickly handle the version management of projects from very small to very large. Linus Torvalds, I believe everyone knows this person, the inventor of the open source Linux system. Nowadays, most of the servers you see are actually running on Linux systems. What is amazing is that this great-level programmer not only created Linux systems. How is the Linux code managed? Before 2002, volunteers from all over the world sent the source code files to Linus via diff, and then Linus himself merged the code manually! You should know that the amount of Linux code at that time was already very large. Through manual management, one is prone to errors and the other is low efficiency. So Linus chose a commercial version control system BitKeeper. BitMover, the owner of BitKeeper, authorized the Linux community to use this version control system free of charge out of humanitarian spirit. Finally, for some reason, BitMover took back the free use rights of the Linux community, so Linus spent two weeks writing a distributed version control system in C language by himself. This is the origin of Git.

Git's work area and process

To understand how Git manages our code, the first thing to do is to understand how Git's work area is structured. Because, only when you thoroughly understand the composition of the Git work area can you use the appropriate commands in the appropriate area. As shown in the figure below, this figure contains 4 workspaces of Git and some common operations.

Workspace: The workspace is the place where development and changes are usually made. It is the latest content that is currently seen. During the development process, it is the operation of the workspace.

Index: Temporary storage area, when executed

git add
After the command, the files in the workspace will be moved to the temporary storage area. The temporary storage area marks the content in the current workspace that is managed by Git. When a requirement or function is completed, the code needs to be submitted. The first step is to pass
git add
Submit to the staging area first.

Repository: local warehouse, located on your own computer, through

git commit
Submit the contents of the temporary storage area and enter the local warehouse.

Remote: A remote warehouse, a server used to host the code. The content of a remote warehouse can be modified by a local warehouse in a collaborative relationship distributed in multiple locations, and the local warehouse is passed after the code is modified.

git push
Command synchronization code to remote warehouse.

Generally speaking, the workflow of Git 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 temporary storage area to the local warehouse. 4. Push the modification of the local warehouse to the remote warehouse. Copy code

Git basic operation

git add

Add files to the staging area

# Add a file to the temporary storage area, followed by multiple files, separated by spaces git add xxx # Add all currently changed files to the temporary storage area. git add. Copy code

git commit

# Submit the temporary changes, a new editor will be opened for editing git commit # Submit the temporary changes and record the remarks git commit -m "you message" # Same as git add. && git commit -m git commit -am # Modify the most recently submitted information, this operation will modify the hash value of the commit git commit --amend Copy code

git pull

# Pull code from a remote warehouse and merge it locally, which can be abbreviated as git pull, which 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> Copy code

git fetch

versus

git pull
the difference is
git fetch
The operation only pulls remote changes, not automatically
merge
operating. No effect on your current code

# Get the update of a specific branch of the remote warehouse git fetch <remote host name> <branch name> # Get the updates of all branches of the remote warehouse git fetch --all Copy code

git branch

# Create a new local branch, but don t switch git branch <branch-name> # View 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 branch Branch -m Git <<Old-Branch-name> new new -branch-name> copy the code

Scenarios of using Git to solve problems at work

git rebase makes your commit record more clear and readable

The use of git rebase rebase translates to rebase, and its role is very similar to merge, which is used to merge the changes of a branch into the current branch.

As shown in the figure below, the figure below describes the changes in the submission history after rebase.

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

Suppose we now have 2 branches, one is master and the other is feature/1. They are all based on the initial submission of add readme to check out the branch. After that, the master branch adds 3.js and 4.js files, respectively. After two submissions, feature/1 also added files 1.js and 2.js, corresponding to the following two submission records.

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

The master branch is shown below:

The feature/1 branch is as shown below

It looks like this when combined

At this point, switch to

feature/1
Under the branch, execute
git rebase master
, After success, pass
git log
View records.

As shown in the figure below: you can see that it is applied one by one first

mater
Branch changes, and then end with
master
The last commit of the branch is used as the base point, and then applied one by one
feature/1
Every change.

Therefore, our submission record will be very clear, there is no fork, the above demonstration is a relatively smooth situation, but in most cases,

rebase
Conflicts will occur during the process. At this time, you need to manually resolve the conflicts, and then use
git add, git rebase --continue
Way to handle conflicts and complete
rebase
Process, if you don t want a certain time
rebase
Results, then you need to use
git rebase --skip
Come skip this time
rebase
operating.

git merge
with
git rebase
The difference

Different from

git rebase
Is that
git merge
Is it
fast-forward
(Quick merge), an additional merge record will be generated, similar to
Merge branch'xxx' into'xxx'
A submission of information.

In addition, when resolving conflicts, you only need to resolve the conflict once with merge, which is simple and rude, while when using rebase, you need to resolve each conflict in turn before submitting.

git rebase interactive mode

In development, we often encounter many invalid submissions on a branch. In this case, using the interactive mode of rebase can compress the multiple submissions that have occurred into one submission, and get a clean submission 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

parameter

base-commit
It is to specify the base point submission object of the operation, and perform the rebase operation based on this base point. For the above submission history example, we need to compress the submission before the last submission object (ac18084) into one submission. The command format we need to execute is:

git rebase -i ac18084 copy the code

At this point, you will enter a vim interactive page, and the editor will list information like the following.

To merge this bunch of changes, we need to use the Squash strategy to merge, that is, to merge the current commit and its previous commit content, which can be expressed as the following. Under the rebase of the interactive mode, at least one pick is retained, Otherwise, the command will fail to execute.

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

After modifying the file, press: Then wq saves and exits. At this time, an editing page will pop up. This page is used to edit the submitted information, and modify it to

feat
: Correct, save at the end, then use
git branch
View submitted
commit
information,
rebase
The subsequent submission record is shown in the figure below, is it a lot more refreshing?
rebase
Operations can make our submission history clearer.

Pay special attention to the rebase operation only on the feature branch you use, and rebase on the integrated branch is not allowed, because this operation will modify the history of the integrated branch.

Use git cherry-pick to get the specified commit

git cherry-pick
Can be understood as "picking" submission, and
merge
The difference between merging all the commits of a branch is that it will get a single commit of a certain branch and introduce it to your current branch as a new commit. When we need to merge the commits of other branches locally, if we do not want to merge the entire branch, but only want to merge a certain commit into the local current branch, then we must use
git cherry-pick
Up. In the following scenario, there are three branches below,
feature/cherry-pick1
with
feature/cherry-pick2
Are based on
master
Two functional branches detected, corresponding branches
log
Record as follows

master
The commit of the branch is as follows

Now the master only needs feature/cherry-pick1 and feature/cherry-pick2 for changes related to changes, and does not care about the modification of fix content. At this point, you can use the cherry-pick command.

syntax:

git cherry-pick [commit-hash]

commit-hash represents the hash value of a certain commit. Now, execute the following two instructions in sequence

git cherry-pick e0bb7f3, git cherry-pick c9a3101
, During the process, if there is a conflict, proceed after the conflict is resolved
git add
, Then execute
git cherry-pick --continue
And finally, the submission on the master is as follows

At this point, the required submission is applied on the master branch, and the desired effect is achieved. If multiple cherry-pick needs to be synchronized to the target branch, it can be abbreviated as

git cherry-pick <first-commit-id>...<last-commit-id>
, This is an interval that opens on the left and closes on the right, that is to say
first-commit-id
The code changes brought by the submission will not be merged in the past, if you need to merge the past, you can use
git cherry-pick <first-commit-id>^...<last-commit-id>
, It means that it contains
first-commit-id
To
last-commit-id
All submissions inside will be merged.

Use git revert to roll back a certain commit

Imagine a scenario where you have two versions of your project to go online recently. These two versions are also accompanied by the fixes of the previous bugs. At the beginning, you fixed the bugs on the release branch of the first version. Suddenly, one day before the release, the feedback from the testing side needed to change the content of the bug fixes in the first version to the second version. At this time, the submission of the integration branch of the first version should include the first version. Functional content, the submission of remaining bug fixes and the content submitted by other colleagues, it is definitely impossible to rudely remove the previous commits about bug fixes through reset. At the same time, this approach is more dangerous. At this time, we don t want to destroy it. What should I do if I want to withdraw the commit records of our remaining bugs from previous submission records? git revert comes in handy.

git revert
To cancel an operation, this operation will not modify the original submission record, but will add a new submission record to offset a certain operation.

syntax:

git revert <commit-id>
For ordinary commit

git revert <commit-id> -m
Commit for merge

Let s use a case to understand this command. As shown in the figure below, suppose that the place framed by the red box is a submission that will cause a bug. After his submission, two more submissions were made, which included other colleagues submit.

At this time, I want to kill the bug that caused the submission, and execute

git revert 1121932
After performing the operation, open and view the log again. As shown in the figure below, you can see that a new commit record has been added. The msg generated by this commit is automatically generated. The beginning of Revert is followed by the one before the withdrawn commit-msg information. The commit record has not disappeared, and the effect of code rollback has also been achieved at this time

In addition, git revert can also roll back multiple submissions

syntax:

git revert [commit-id1] [commit-id2] ...
Note that this is a front opening and closing interval, that does not include commit1, but includes commit2.

There are two ways to roll back our submission, one is mentioned above

git revert
In addition to commands, you can also use
git reset
Command, then what is the difference between the two?

git revert
A new commit message will be created to withdraw the previous modification.

git reset
The submission record will be returned directly to the specified commit.

For individual feature branches, you can use

git reset
Go back and forth from the history, and use it later
git push --force
Push to remote, but if it is on the integrated branch of multi-person collaboration, it is not recommended to use it directly
git reset
Command, but use the safer
git revert
Order to withdraw the submission. In this way, the submitted historical records will not be erased and can be withdrawn safely.

Use git stash to stage files

There will be such a scenario, and now you are using your feature branch to develop new features. At this time, there is a bug in the production environment that needs to be fixed urgently, but this part of your code has not been developed yet and you don't want to submit it. What should you do? At this time, you can use the git stash command to temporarily store the files that have been modified in the workspace, and then switch to the hotfix branch to fix the bug. After the repair is complete, switch back to the feature branch to restore the just saved content from the stack. The basic commands are as follows

git stash //temporarily save the local changes git stash save "message" When performing storage, add notes for easy search. git stash pop //Apply the last temporary modification and delete the temporary record git stash apply //Apply a certain storage, but will not delete the storage from the storage list, and use the first storage by default, that is, stash@ {0}, if you want to use another one, git stash apply stash@{$num}. List stash git //What to see stash storage git stash the Clear //delete all cached stash copy the code

Let's learn more about stash commands through a few pictures.

At this time, I am developing a new feature and amended the content in the 1.js file

The development has not been completed yet. At this time, I want to switch to the hotfix branch to fix the bugs. I have to pause the development and switch to the hotfix branch, but now there is still content in the workspace. At this time, if I switch the 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 code

The above sentence means that there are file modifications in the workspace, which cannot be submitted. You need to perform a commit or stash operation first, and execute

git stash
, The results are as follows

Working Directory State index and the Saved the WIP ON stash: feat. 22e561c: the Add 1. JS duplicated code

At this point, our workspace is clean, and we can switch to the hotfix branch for bug fixes. Assuming that we have now completed the bug fixes, we continue to switch back to the feature branch for the original function development. At this time, we only need to execute git stash pop. The changes we temporarily saved before will be restored to the workspace, as shown in the figure below.

When we want to temporarily store files and switch branches to do something, we can use

git stash
This mechanism helps development.

It is recommended that when using stash related commands, do not use it directly every time you temporarily store

git stash
Command to temporarily save it, but use
git stash save "message..."
In this way, make a record of information for this submission. In this way, when you want to apply the changes, first pass
git stash list
Check out all the staging lists. After that, it is recommended to use
git stash apply stash@${num}
The corresponding stash is applied in the method, so that the existing stash list items will not be cleared, and can be applied to the current workspace. If this temporary storage is not needed, then manually clear it.

Undo changes in different work areas

During development, we often need to roll back the code operation, and in different work areas, the way to roll back the code is also different. As shown in the figure below, suppose you want to develop on the feature/revoke branch now,

First pass

git status
Check the current status.

At present, our work area is very clean, without any modification operations. At this time, modify the code and check the status again. You can see that the 1.js file has been modified.

Now we want to restore the 1.js file to the state before the modification, that is, to withdraw the modification of the workspace, you can use it

git checkout - <filename>
If you want to withdraw the modification of multiple files, separate the files with spaces. As shown in the figure below, we have withdrawn the modification of the 1.js file, and the workspace is also clean.

If we have modified the file and submitted it to the temporary storage area, if we don t want this part of the file, then we can pass

git reset <filename>
Command to undo a specific file,
git reset
All files in the temporary storage area will be withdrawn, as shown in the figure below. Checking the status before and after, you can see that the files were finally withdrawn to the working area successfully.

Configure git alias to improve work efficiency

Generally, in our work, after receiving the development task, we need to create a new branch for development. At this time, we need to use it

git branch
,
git checkout
,
git pull
Wait for the order, after we have a meal, the development is completed, and when it comes to the stage of submitting the code, we need to do so
git add
,
git commit
,
git push
Although the commands are simple, they are not concise enough to input. As a programmer, the purpose of developing programs is to improve our efficiency. Laziness is the source of human progress, so we can simplify these commands by configuring aliases.

Its basic usage is

git config --global alias.<simplified character> original command

Such as the following example:

$ git config - global alias.co checkout $ git config - global alias.ci commit Git config $ - , Ltd. Free Join alias.br Branch copy the code

Here, co stands for checkout, ci stands for commit, and br stands for branch. Subsequent submissions can be abbreviated as

--global
It is a global parameter, that is, after one configuration, these commands can be applied to all warehouses under this computer. These commands actually update your global .gitconfig file, which is used to save the global git configuration.
vim ~/.gitconfig
, After executing this command, it will be displayed as follows, the following figure shows just passed
git config --global alias
Additional
alias
.

In addition to the above-mentioned way of direct command, you can also modify this file

alias
Item to set the alias. Here I share a commonly used alias setting. Replace the following configuration with the area of [alias] in the .gitconfig file, and then you can use it happily~

[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 code

In this way, every time we want to view the history of Git, we don t need to enter a long list of commands and use it directly.

git lg
, The following figure is the submission record in the axios source code, after using the package
git lg
Viewed renderings

The relationship between branches is clear at a glance, and the merge operation on which commit is performed is also very clear, which can help us trace the history of submissions and solve problems well.

summary

This article explains the Git environment construction, basic usage, and usage of the more high-frequency Git commands in your work from the shallower to the deeper. Whether you are a front-end or back-end development, the daily work of Git is indispensable. Not only need to be able to use it, but also to use it beautifully, flexibly, and steadily. In this way, you can be more comfortable when collaborating on projects with colleagues. After learning the Git usage skills in this article, practice more in your daily work, I believe it will bring you great gains!

Author: Zheng Caiyun front-end team

Link: juejin.cn/post/697418...

Source: Nuggets

The copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Welcome to search my public account

Front-end growth manual
Thank you