How do I use Git in my work

Introduction of Git

Git is the most advanced distributed version control system in the world

Centralized vs. Distributed centralized:

  1. You need a central server
  2. Must be connected to the Internet
  3. There is a risk of loss of source code if the central server is corrupted
  4. Example: CVS, SVN

Distributed:

  1. You also need a central server, but only to exchange branch changes,
  2. Every developer has a complete version library and doesn’t need an Internet connection to work
  3. High safety
  4. Case: Git

Create a version library

A repository is a directory in which all files are managed by Git. Changes, deletions, and changes to files are tracked so that they can be traced at any time or restored at some point in the future

The first step is to select a suitable place and create an empty directory

mkdir learngit
cd learngit
pwd
/Users/michael/learngit

Copy the code

The PWD command is used to display the current directory.

Step 2: use git init to make this directory a git managed repository:

git init
Initialized empty Git repository in /Users/michael/learngit/.git/
Copy the code

The.git directory is used to track and manage the repository. Do not easily manually modify the files in this directory, to avoid damaging the Git repository!

If you do not see the.git directory, it is hidden by default and can be seen with the ls-ah command

One thing to be clear: all version control systems can only track changes to text files, while image, video and other binary files version control systems don’t know what changes have been made.

Add files

Putting a file into a Git repository only takes two steps:

The first step is to tell Git to add the file to the repository with the command git add

git add readme.txt
Copy the code

Execute the above command, nothing is displayed, that’s right, the Unix philosophy is “no news is good news”, indicating success

Git commit:

git commit -m 'wrote a readmen file'
[master (root-commit) @aadf4e]wrote a readme file
1 file changed, 2 insertions(+)
create mode 100644 readme.txt
Copy the code

Git commit: 1 file changed: 1 file changed (our newly added readme.txt file); 2 insertions: Two lines are inserted (readme.txt has two lines).

Summary:

  1. Initialize a Git repository usinggit init
  2. Add files to Git repository in two steps:
    1. Using the commandgit add <file>, note that it can be used repeatedly to add multiple files
    2. Using the commandgit commit -m <message>To complete

Modify the file

Git status allows you to keep track of the current status of your repository

git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   readme.txt

no changes added to commit (use "git add" and/or "git commit -a")
Copy the code

Git diff: Git diff: Git diff: Git diff: Git diff: Git diff

The first step is git add. Before git commit, run git status to check the current repository status and commit again

git status
On branch master
nothing to commit, working tree clean
Copy the code

Git tells us that there are currently no changes to commit, and that the working tree clearn directory is clean.

Summary:

  1. To keep abreast of the state of work to usegit statusThe command
  2. ifgit statusTo tell you that a file has been modifiedgit diffYou can view the modified content.

The git log command displays historical records

The git log command displays commit logs from the most recent to the most distant

$ git log
commit 1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master)
Author: Michael Liao <[email protected]>
Date:   Fri May 18 21:06:15 2018 +0800

    append GPL

commit e475afc93c209a690c39c13a46716e8fa000c366
Author: Michael Liao <[email protected]>
Date:   Fri May 18 21:03:36 2018 +0800

    add distributed

commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0
Author: Michael Liao <[email protected]>
Date:   Fri May 18 20:59:18 2018 +0800

    wrote a readme file
Copy the code

Git log –pretty=oneline

$ git log --pretty=oneline
1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master) append GPL
e475afc93c209a690c39c13a46716e8fa000c366 add distributed
eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0 wrote a readme file
Copy the code

See a bunch of things like 1094adb… Is the COMMIT ID (version number), which is a very large number calculated by SHA1 in hexadecimal notation

Version back

How do I roll back readme.txt to a previous version?

Git must be aware of the current version. In Git, the current version is represented by HEAD, i.e. the latest commit. The previous version is HEAD^, and the previous version is HEAD^^

You can now use git reset –hard HEAD^ to roll back the current version to the previous version

The latest version of the Append GPL is no longer visible. If you go from the 21st century to the 19th century on a time machine, what if you want to go back to the 21st century?

If the command line window is still open, you can see that the commit ID of the append GPL is 1094adb… , so you can specify a future version:

Run git reset –hard 1094a

It is not necessary to write the full version number, just the first few digits will do, Git will find it automatically

Git version rollback is very fast because Git has an internal HEAD pointer to the current version. When you roll back Git, you just change the HEAD pointer and update the working file

If you shut down your computer and did not record the latest version of your COMMIT ID, how do you get back to the latest version?

Git reflog git reflog git reflog

Summary:

  • HEADThe version you point to is the current version, so Git allows you to run commands through the history of versionsgit reset --hard commit_id
  • Before the shuttle, usegit logYou can view the commit history to determine which version you want to fall back to.
  • To go back to the future, usegit reflogReview the command history to determine which version to go back to in the future.

Work area and staging area

A Working Directory is a Directory that you can see on your computer, such as my Learngit folder

Git is not a workspace, but a Repository of Git versions.

Git’s repository contains many things, the most important of which is a staging area called stage (or index), the first branch that Git automatically creates for us, master, and a pointer to master called HEAD

When we add files to the Git repository, we do it in two steps:

The first step is to add the file with git add, which essentially adds the file changes to the staging area.

The second step is to commit the changes with git commit, which essentially commits the entire contents of the staging area to the current branch.

Git commit Is committing changes to the master branch because Git automatically created the only master branch for us when we created the Git repository.

The simple idea is that all file changes that need to be committed are put into the staging area, and then all changes in the staging area are committed at once.

Every time you make a change, if you don’t add git to the staging area, it won’t be added to the commit.

Undo modify

Git checkout —

can discard workspace changes

Git checkout — readme. TXT git checkout — readme. TXT git checkout — readme. TXT git checkout — readme. TXT git checkout — readme. TXT git checkout — readme. TXT

  1. readme.txtIt has not been put into staging since the changes were made. Now, to undo the changes is to return to the same state as the repository.
  2. readme.txtAfter it was added to the staging area, it was changed again. Now, undoing the changes will return you to the status after it was added to the staging area.

Git reset HEAD

unstage the changes in the staging area and put them back into the workspace.

The git reset command can roll back both the version and the changes made in the staging area to the workspace. When we use HEAD, we mean the latest version.

Assuming you have added to the staging area and committed to the repository, use git reset –hard commit_id to rollback.

Summary:

  1. Scenario 1, when you tamper with the contents of a file in the workspace and want to discard the changes in the workspace, use the commandgit checkout -- <file>
  2. Scenario 2, when you not only change the contents of a file in the workspace, but also add it to the staging area, you want to discard the changes, in two steps, the first step is to use the commandgit reset HEAD <file>, return to scenario 1. Step 2 follow scenario 1
  3. Scenario 3: If an inappropriate change has been committed to the repository and you want to cancel the commit, refer to version Rollback if it has not been pushed to the remote repository.

Delete the file

Git status will immediately tell you which files have been deleted if you delete them directly in the file manager, or if you use the rm command again.

$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	deleted:    test.txt

no changes added to commit (use "git add" and/or "git commit -a")
Copy the code

Now you have two options:

If you do want to delete the file from the repository, run git rm to delete it and git commit

$ git rm test.txt
rm 'test.txt'

$ git commit -m "remove test.txt"
[master d46f35e] remove test.txt
 1 file changed, 1 deletion(-)
 delete mode 100644 test.txt
Copy the code

Tip: Manually delete the file first, then usegit rm <file>andgit add <file>The effect is the same

You can easily restore the deleted file to the latest version because it is still in the repository:

git checkout -- text.txt

Git Checkout is a one-click restoration of your workspace, with the version in the repository being replaced by the version in the repository.

Note: files deleted without ever being added to the repository are not recoverable!

The git rm command is used to delete a file. If a file has been committed to the repository, then you never have to worry about deleting it by mistake, but be careful, you can only restore the file to the latest version, and you will lose the changes you made since the last commit.

Remote warehouse

  1. To associate a remote library, use the command git remote add origin git@server-name:path/repo-name

  2. When associating a remote library, you must specify a name for the remote library. Origin is the default common name.

  3. After the association, run the git push -u origin master command to push all contents of the master branch for the first time. Git push origin master can be used to push the latest changes whenever necessary after each local submission.

    One of the biggest benefits of the distributed version of the system is that the local work does not need to consider the existence of the remote warehouse, that is, without the network can work normally, and SVN refuses to work without the network! When the network is available, the local submission is pushed to complete the synchronization, which is very convenient!

Clone from a remote repository

  1. To clone a warehouse, first must choose to know the address of the warehouse, and then usegit cloneCommand the cloning
  2. Git supports several protocols, includinghttps, butsshProtocol is the fastest to usehttpsIn addition to being slow, the biggest problem is that you have to enter a password every time you push, which is not available internally in some companies that only open HTTP portssshProtocol and only usehttps

Branch management

Git fetch && Git mergeGit pull < remote host name > < remote branch name >Get updates for a specific branch of the remote repositoryGit fetch < remote host name ># create dev branch, then switch to dev branch:
git checkout -b dev
# corresponds to the following two commands:
Create a branch
git branch dev
# Switch branches
git checkout dev
The latest version uses the git switch command to switch branches in order to distinguish it from the version rollback
Git switch -c dev
# Switch directly to the existing master branch, available
git switch master
The # command lists all local branches, preceded by an *
git branch
# merge branches # merge branches # merge branches # merge branches # merge branches # merge branches # merge branches # merge branches
git merge dev
# delete local branch
git branch -d dev
# View local and remote branches -a, where * represents the branch where your current working directory is located
git branch -a
Delete the remote version
git branch -r -d origin/branch-name
git push origin :branch-name
Copy the code

Summary:

Check out the branch: Git Branch

Git branch

Git checkout

Git checkout -b

Git merge

Git branch -d

Resolve the conflict

Summary:

  1. If Git cannot merge branches automatically, the conflict must be resolved first. After the conflict is resolved, the commit is completed.
  2. Resolving the conflict is to manually edit the files that Git failed to merge into the desired content and then commit.
  3. withgit log --graphCommand to see the branch merge diagram

Branching strategy

Summary:

When merging branches, add –no-ff parameter to merge branches in normal mode, merge history has branches, you can see that the merge, and fast forward does not see that the merge.

$ git merge --no-ff -m "merge with no-ff" dev

Bug branch

summary

  1. When fixing bugs, we fix them by creating new bug branches, then merging them, and finally deleting them
  2. When the work at hand is not finished, put the work on the spot firstgit stashAnd then fix the bug, and then fix it, and thengit stash pop, return to the work site; You can use stash multiple timesgit stash "message..."You can make a record of a message to the temporary storage, recovery time, first usegit stash listView and then restore the specified stash with the commandgit stash apply stash@{0}.git stash clearYou can remove all cached Stash
  3. Bugs fixed on the master branch that you want to incorporate into the current dev branch can be usedgit cherry-pick <commit_hash>Command to “copy” changes submitted by the bug branch to the current branch to avoid duplication of effort. During the process, if a conflict occurs, resolve the conflict after the processgit add ., then executegit cherry-pick --continue

Feature branch

Summary:

  1. To develop a new feature, it is better to create a branch.
  2. If you discard a branch that has not been merged, you can passgit branch -D <branch_name>Forcibly delete.

collaboration

Summary:

  • To view remote library information, usegit remote -v
  • Branches created locally are not visible to others unless they are pushed remotely
  • To create a local branch that corresponds to a remote branch, usegit checkout -b branch-name origin/branch-name, local and remote branch names should be the same;
  • Push branch from local, usinggit push origin branch-nameIf push fails, use it firstgit pullFetching new commits remotely;
  • ifgit pullpromptno tracking information“, the link relationship between the local branch and remote branch is not created. Run thegit branch -set-upstream-to <branch-name> origin/<branch-name>Establish associations between local and remote branches
  • Fetching branches from remote, usinggit pullIf there are conflicts, deal with them first
  • Push local branch to remote repository:git push --set-upstream origin <branch-name>
  • Pull the specified branch from a remote Git repository locally:git pull <origin-name> <origin-branch-name>:<branch-name>.git pullThe operation retrieves updates to a branch from a remote library and automatically merges the locally specified branch (even if the branch does not exist locally)

Rebase

Function 1: Rebase translates to edit. This function is similar to merge. It is used to merge changes made in one branch into the current branch

The following figure shows how the commit history changes after rebase.

Now let’s use an example to illustrate the above process:

Suppose we now have two branches, one for master and the other for feature/1. They both check out the branch based on the initial submission 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.

In this case, the submission record of the corresponding branch is as follows:

The master branch is shown below:

Feature /1 branches are shown as follows:

It looks like this when combined:



At this point, switch to the feature/1 branch and executegit rebase masterAfter success, passgit logCheck the records.

As shown in the figure below, you can see that the changes of the master branch are applied one by one, and then each change of the 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, with no forks. The above is a relatively smooth case, but most of the time there will be conflicts in the rebase process, at which point we need to resolve the conflicts manually, and so ongit add ..git rebase --continueIf you do not want the result of a rebase, you need to use this methodgit rebase --skipTo skip the rebase operation.

Role 2: Merge multiple Commits on the development branch

In development, it is common to have many invalid commits on a branch. In this case, rebase is used to compress multiple commits into sequential commits to 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  [startpoint]  [endpoint]
Copy the code

[startPoint] [endpoint] specifies an editing interval. If [endpoint] is not specified, By default, the end of the interval is the commit that the current branch HEAD points to. For the commit history example above, we compress the commit before the last commit object (AC18084) into a single commit. The command we need to execute is:

git rebase -i ac18084
Copy the code

A Vim interactive page is displayed with the following information listed in the editor:



The uncommented section above lists all the commits we included in the rebase operation, and the commented section below is the command description git provided for us. Git provides the following commands:

Pick: Keep the commit (p) reword: Keep the commit, but I need to modify the comment on the commit (R) Edit: Keep the commit, but I need to stop and modify the commit (not just the comment) (e) Squash: Exec: Execute shell command (x) DROP: discard the commit (d)

To merge these changes, we use a Squash strategy, which combines the current COMMIT with its previous commit, roughly as follows: Under interactive rebase, keep at least one pick, or the command will fail.

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

Press I to edit the file, then press: and then wq to save and exit. A new editing page will pop up. After rebase, git log is used to check the commit information, as shown in the picture below. The rebase operation makes our commit history clearer.

summary

  • Git rebase makes your commit records more legible
  • The rebase operation organizes the history of local unpushed forked commits into a straight line
  • The purpose of Rebase is to make it easier to see changes in historical commits, since forked commits require three-way comparisons
  • Special note: Rebase operations can only be performed on the feature branch you use, not on the integration branch, because such operations will modify the history of the integration branch.

Git merge git rebase

  • Different from thegit rebaseIs,git mergeIn cases other than fast-forward, an additional merge record is generated, similarlymerge branch 'xxx' into 'xxx'A submission message from.

  • In addition, when resolving conflicts, merge only resolves sequential conflicts, which is simple and crude. When rebase is used, each conflict needs to be resolved in sequence before committing.

Label management

When we release a version, we usually put a tag in the version library, which identifies the version at the time of the tag. Whenever we take a version of a tag in the future, we pull out the historical version at that time of change. So, the label is also a snapshot of the repository.

Git tags are snapshots of the repository, but they are actually Pointers to a commit (much like branches, but branches can be moved, tags cannot).

Create a label

summary

  • The commandgit tag <tagname>Use to create a new label. Default isHEADYou can also specify a commit ID
  • The commandgit tag -a <tagname> -m "balabalbala..."You can specify label information
  • The commandgit tagYou can view all labels

Operating the label

summary

  • The commandgit push origin <tagname>You can push a local TAB
  • The commandgit push origin --tagsYou can push all unpushed local tags
  • The commandgit tag -d <tagname>You can remove a local label
  • The commandgit push origin :refs/tags/<tagname>You can delete a remote label

Making use of the

Visit the home page of an open source project and click “Fork” to clone the repository under your own account. Then clone the repository from your own account, be sure to clone the repository from your own account, otherwise you will not have the permission to push changes

Custom Git

Git config –global color. UI true

Ignore special files

If you want to add a file to Git and cannot do so because the file was ignored by.gitignore, you can use -f to force the file to Git

git add -f App.class
Copy the code

Git check-ignore -v

git check-ignore -v App.class
.gitignore:3:*.class   App.class
Copy the code
* * # Exclude all. Class files: *. Class # exclude.gitignore and app.class:! .gitignore! App.classCopy the code

To exclude specified files from the. Gitignore rule: + file name, so just add the exception file.

Configure an alias

# co = checkout, CI = commit, br = branch
git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.br branch
# unstage: reset HEAD
git config --global alias.unstage 'reset HEAD'
# last displays the last submission information c
git config --global alias.last 'log -1'
# configuration, lg
git config --global alias.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

Git lg effect

Git /config –global — Git /config — Git /config — Git /config — Git /config — Git /config

$ cat .git/config 
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = [email protected]:michaelliao/learngit.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[alias]
    last = log- 1Copy the code

Alias: [alias] alias: [alias] alias: [alias] alias: [alias

The current user’s Git configuration file is in a hidden file in the user’s home directory.gitconfigIn the

Git branch naming conventions

branch named instructions
The main branch master The master branch, where all official releases are made available to users, are published
Development branch dev The development branch is always the latest and most complete branch
Function branch feature-* A new feature branch, a feature point under development
Release branch release-* Release features that go live regularly
Repair branch bug-* Fix bugs in online code

Daily development process

First, the code base should have one and only one Master branch. All official releases for user use are published on this main branch.

The name of the Master Git branch, which is called Master by default. It is built automatically, and once the repository is initialized, development is done in the main branch by default.

Dev The main branch should only be used to distribute major releases, and daily development should be done on the other branch. Let’s call our development branch, Dev, and this branch is used to generate the latest overnight version of our code. If you want to officially publish, merge the Dev branch on the Master branch.

Git create Dev branch

git checkout -b dev master

Git checkout Master git checkout Master

Git merge — no — ff Dev

Here’s a little explanation of what the -no-ff parameter of the previous command means. By default, Git performs a “fast-farward merge” that points the Master branch directly to the Dev branch. With the -no -ff parameter, a normal merge is performed to create a new node on the Master branch. In order to keep version evolution clear, we want to do this.

Feature Branch The name of a Feature branch can be named in the form of Feature – *.

Create a functional branch:

git checkout -b feature-x dev

Git checkout dev git merge — no-ff feature-x

Git branch -d feature-x

The second type of pre-release branch is the pre-release branch, which means we may need to have a pre-release version to test before releasing the official version (i.e. before merging into the Master branch). The pre-release branch is separated from the Dev branch and must be merged into the Dev and Master branches after pre-release. It can be named release- star.

Create a pre-published branch:

Git checkout -b release-1.2dev

Git checkout master Git merge — no-ff release-1.2

Git tag -a 1.2 for the new node generated by the merge

Git checkout dev git merge — no-ff release-1.2

Finally, delete the pre-published branch: git branch -d relex-1.2

The last method is to fix Bug branches. After the software is released, it is inevitable that there will be bugs. This is where you need to create a branch to fix the bug. The branch is separated from the Master branch. After the patch is complete, merge into the Master and Dev branches. It can be named in the form fixbug- *.

Create a bug fixing branch:

Git checkout -b fixbug-0.1 master

Git checkout master git merge — no-ff fixbug-0.1 git tag -a 0.1.1

Git checkout dev git merge — no-ff fixbug-0.1

Finally, delete the “fixbug branch” : git branch -d fixbug-0.1

git tag usage

# add git tag -a v0.1.110811-m

Git tag -d V0.1.110811

Git push Origin V0.1.110811

Git push – tags

Git commit record specification

Each Git commit record must follow a fixed format: First line: author: module name (or module ID) Second line: Commit description + : Add code * : Modify code – : Delete code

If Control + C fails to end the process, exit with Q