1
头图

This article has been included in the Github repository. Welcome everyone to watch and star. This warehouse is used to share the core knowledge of Java, including Java basics, MySQL, SpringBoot, Mybatis, Redis, RabbitMQ, etc. It is necessary for interviews.

github address: https://github.com/Tyson0314/Java-learning

If github is not accessible, you can visit the gitee repository.

gitee address: https://gitee.com/tysondai/Java-learning

Introduction to Git

Git is an open source distributed version control system that can effectively and quickly manage project versions. Git is an open source version control software developed by Linus Torvalds to help manage the development of the Linux kernel.

Git workflow

The Git workflow is as follows:

  • Clone resources from remote warehouses as local warehouses;
  • Modify the code in the local warehouse;
  • Submit the code to the staging area before submitting to the local warehouse;
  • Submit the modification and submit it to the local warehouse. Save all historical versions of changes in the local warehouse;
  • When you need to share code with team members, you can push the modified code to a remote warehouse.

The workflow of Git is as follows:

git-work-flow

Image source: https://blog.csdn.net/ThinkWon/article/details/94346816

Storage principle

When Git saves the project state, it mainly makes a snapshot of all files and saves the index of this snapshot. If the file is not modified, Git will not re-store the file, but only keep a link to the previously stored file.

Git snapshot

The snapshot is to keep the space occupied by the old file and save a reference. The new file will continue to use the same part of the disk space as the old file content, and different parts will be written into the new disk space.

Three states

There are three states of Git: modified, staged, and committed. Modified means that the file has been modified, but it has not been saved to the database. Staged means that the current version of a modified file is marked so that it will be included in the next snapshot. Submitted means that the data has been safely saved to the local database.

Basic Git workflow: modify files in the working directory; temporarily store the files, put the file snapshots in the temporary storage area; submit the update to the local library. The temporary storage area saves the file list information that will be submitted next time, generally in the Git warehouse directory.

Git工作流程

Image source: https://img2018.cnblogs.com/blog/1252910/201907/1252910-20190726163829113-2056815874.png

Configuration

Set user name and email address:

git config --global user.name "dabin"
git config --global user.email xxx@xxx.com

If you use the --global option, then the command only needs to be run once, because Git will use that information no matter what you do on the system afterwards. When you want to use a different user name and email address for a specific project, you can run the command without the --global option in that project directory to configure it.

View configuration information: git config --list

View a configuration: git config user.name

Get help

Get the manual of the config command: git help config

Git basics

Get the Git repository

Initialize the warehouse in the existing directory: git init

Clone the existing warehouse: git clone https://github.com/...

File status

View file status: git status

git生命周期

Image source: https://img2018.cnblogs.com/blog/1252910/201907/1252910-20190726163854195-886320537.png

Status summary:

The newly added untracked files are marked with??, the newly added files in the temporary storage area are marked with A, and the modified files are marked with M, as shown in the following figure, MM Rakefile appears two Ms, which appear on the left M indicates that the file has been modified and put into the temporary storage area, and the M that appears on the right indicates that the file has been modified but has not been put into the temporary storage area.

$ git status -s
 M README # 右边的 M 表示该文件被修改了但是还没放入暂存区
MM Rakefile # 左边的 M 表示该文件被修改了并放入了暂存区;右边的 M 表示该文件被修改了但是还没放入暂存区
A lib/git.rb # A表示新添加到暂存区中的文件
?? LICENSE.txt # ??表示新添加的未跟踪文件

Configure alias

Some people may often type the wrong command. You can simplify the command by configuring aliases:

Simplify git config --global alias.st status to git status by command git st :

$ git config --global alias.st status

$ git st
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Work area

View work area modification: git diff

$ git diff
diff --git a/md/leetcode刷题笔记.md b/md/leetcode刷题笔记.md
deleted file mode 100644
index 63a7c90..0000000
--- a/md/leetcode刷题笔记.md
+++ /dev/null

Undo work area modification: git checkout -- file_name , it will undo the work area modification, it is irreversible, and will not undo the temporary storage area modification.

You can also use the restore command to undo the modification (introduced in git 2.23 version).

git restore --worktree demo.txt //撤销文件工作区的修改
git restore --staged demo.txt //撤销暂存区的修改,将文件状态恢复到未add之前
git restore -s HEAD~1 demo.txt //将当前工作区切换到上个 commit 版本,-s相当于--source
git restore -s hadn12 demo.txt //将当前工作区切换到指定 commit id 的版本

storage cache

git add filename the files in the work area into the temporary storage area through 06132cc2abd7bc.

git add README.md

View the modification of the temporary storage area: git diff --staged . You can see that there is a README.md file in the temporary storage area, indicating that the README.md file is placed in the temporary storage area.

$ git diff --staged
diff --git a/README.md b/README.md
index ecd6c7a..653f001 100644
--- a/README.md
+++ b/README.md

Undo the modification/unstage of the temporary storage area: git reset HEAD file_name , move the file modification out of the temporary storage area and put it in the work area.

git reset plus the --hard option will cause all changes in the working directory to be lost.

submit

Any uncommitted changes are likely to be unrecoverable after they are lost. Submit the order: git commit -m "add readme.md"

git commit -a -m "xxx" equivalent to git add and git commit -m "xxx" . Submit the tracked file directly. Untracked files cannot be submitted directly using this command. You need to execute the git add command first, and then execute git commit.

If you execute git commit alone without the -m parameter, you will enter the vim editor interface:

This should be done at this time:

  1. Press the letter key i or a or o to enter the editable state
  2. After entering the commit information, press the Esc key to exit the editing state and return to the normal mode
  3. Enter: wq (save and exit) or: wq! (force to exit without saving)

Modify commit information

If you find that some files are missing or the submission information is git commit --amend after submission, use 06132cc2abd93a to resubmit:

git commit -m 'initial commit'
git add forgotten_file
git commit --amend

View submission history

git log lists all submitted updates.

git log -p -2 , -p is used to display the content difference of each submission, -2 means to display the last two submissions.

git log --stat will list all the files that have been modified, how many files have been modified and which lines have been modified, etc. below each submission.

git log --pretty=oneline displays each submission on one line.

git log --pretty=format:"%h %s" --graph format means formatted output, %h is the short hash string of the submitted object, %s is the submission description, and --graph can show the branch and merge history more vividly.

$ git log --pretty=format:"%h %s" --graph
* 75f8b36 update
* cd72e4f 删除查询性能优化
* 6bddc95 MySQL总结整理
* f8ace0e java常见关键字总结
* 0c4efeb 删除android
* 4844de5 mysql执行计划
* 635c140 redis分布式锁
* 7b65bc3 update
* e563eec update
* 67e1cf7 update readme
* 218f353 调整目录结构
* 9428314 整理Java基础内容

git log --since=2.weeks is restricted by time.

Version rollback

For version rollback, use the git reset command.

git reset --hard commit_id
git reset --hard HEAD^ # 回退所有内容到上一个版本
git reset --hard HEAD^^ # 回退所有内容到上上一个版本
git reset --hard HEAD~100 # 回退到之前第100个版本  
git reset HEAD readme.txt  # 把暂存区的修改撤销掉(unstage), 重新放到工作区 

stash

Save the uncommitted changes. Used to restore the current working directory later.

git stash
git stash pop stash@{id} //恢复后删除
git stash apply stash@{id}  //恢复后不删除,需手动删除
git stage drop
git stash list //查看stash 列表
git stash show -p stash@{0} //查看stash具体内容,-p查看diff,stash@{0}可以省略

rm and mv

git rm readme.md : The file has not been modified. Remove the file from the temporary storage area and submit it, which is equivalent to rm readme.md and git add . . If you simply delete files manually from the working directory, you will see "Changes not staged for commit" when you run git status.

git rm --cached README.md : Keep the file in the workspace, but don't want Git to continue tracking. This can be achieved using the --cached option. If the file has been modified and has not been placed in the temporary storage area, you must use the forced delete option -f to prevent accidentally deleting data that has not been added to the temporary storage area. Such data cannot be restored by Git.

git rm supports regular expressions: git rm log/\*.log .

Rename the file: git mv README.md README

It is equivalent to running three commands:

mv README.md README
git rm README.md
git add README

Ignore files

.gitignore can only ignore files that are not tracked.

If the remote warehouse already has a logs folder, git rm --cached logs/xx.log can delete the tracking status of the file, and the local workspace is still modified at this time. Then update the .gitignore file, and finally git add . & git commit -m "xx" & git push can delete the file corresponding to the remote warehouse.

skip-worktree and assume-unchanged

skip-worktree:

  • git update-index --skip-worktree [file] can realize the need to modify local files without being submitted, but can pull the latest changes. It is suitable for files that do not change frequently, but must be localized.
  • Cancel skip-worktree: git update-index --no-skip-worktree [file]
  • Check the skip-worktree list: git ls-files -v | grep '^S\ ' .

assume-unchanged:

  • git update-index --assume-unchanged [file] This command only assumes that the file has not changed. When reset is used, the file will be modified back. When the corresponding file in the remote warehouse is modified, after the pull update, --assume-unchanged will be cleared.
  • Cancel ignore: git update-index --no-assume-unchanged file/path
  • See which files are ignored: git ls-files -v | grep '^h\ '

Remote warehouse

Remote warehouse refers to the project version library hosted on the network.

View remote warehouse

View the remote warehouse address:

$ git remote -v
origin https://github.com/schacon/ticgit (fetch)
origin https://github.com/schacon/ticgit (push)

Add remote warehouse

Run git remote add <shortname> <url> add a remote Git repository and specify a short name.

git remote add pb https://github.com/paulboone/ticgit

As with the above command, you can use the string pb in the command line to replace the entire URL. Such as git fetch pb .

If you use the clone command to clone a warehouse, the command will automatically add it as a remote warehouse and use origin as the default abbreviated name by default.

git remote remove origin Git repository 06132cc2abdcd2

If you want to set two remote warehouse addresses for origin (git add will report an error), you can use git remote set-url --add origin url to set them.

$ git remote add origin  xxx.git
fatal: remote origin already exists.

$ git remote set-url --add origin xxx.git
#success

Modify remote warehouse

Modify the remote warehouse address:

git remote set-url origin git@github.com:Tyson0314/Blog.git

pull and fetch

Get data from remote warehouse: git fetch [remote-name]

The git fetch command pulls data to the local warehouse, but it will not be automatically merged into the local branch. You must manually merge it into the local branch.

Git pull usually pulls data from remote warehouses and automatically tries to merge to the current branch.

git pull = git fetch + git merge FETCH_HEAD 
git pull --rebase =  git fetch + git rebase FETCH_HEAD 

Upload git server from local warehouse

git init # 将目录变成本地仓库
git add .
git commit -m 'xxx' # 提交到本地仓库
git remote add origin https://github.com/Tyson0314/profile # 关联远程仓库
git branch --set-upstream-to=origin/master master  # 本地分支关联远程分支
git pull origin master --allow-unrelated-histories # 允许合并不相关的历史
git push -u origin master  # 如果当前分支与多个主机存在追踪关系,则-u会指定一个默认主机,这样后面就可以不加任何参数使用git push。

Push to remote warehouse

Push command: git push [remote-name] [branch-name]

git push origin master

View remote warehouse

git remote show origin

Remote warehouse removal and naming

Remove remote warehouse:

git remote rm paul

Rename the remote warehouse:

git remote rename old-name new-name

Label

Tag a certain commit in the history, such as marking the release node (v1.0, etc.).

The tag tag can help us roll back to a certain version of the code. We can roll back through the name of the tag, without needing to roll back based on a lengthy commit ID:

  • View local tag: git tag
  • New tag: git tag -a v2.0 -m'msg'
  • Push the specified tag to the remote: git push origin v2.0
  • Push all tags from the local to the remote: git push origin --tags
  • Delete the local tag: git tag -d v2.0
  • Delete remote tag: git push origin --delete tag 2.0
  • View the code of different tags locally: get checkout v1.0
  • View label details (including commitId): git show v1.0
  • Roll back to a certain version: git reset --hard commitId
  • Get remote branch: git fetch origin tag V2.0

Create label

Git uses two main types of tags: lightweight and annotated. A lightweight tag is a lot like a branch that doesn't change-it's just a reference to a specific commit. However, the annotation tag is a complete object stored in the Git database. They can be verified; they contain the tagger's name, e-mail address, date and time; there is also a tag information; and can be signed and verified using GNU Privacy Guard (GPG). It is generally recommended to create a note label.

The tags created are only stored locally and will not be automatically pushed to the remote.

Note label

git tag -a v1.4 -m 'my version 1.4' -m option specifies a piece of information that will be stored in the label.

Use the git show v1.4 command to see the tag information and the corresponding submission information.

Lightweight label

git tag v1.4-tyson At this time, running git show v1.4-tyson will not see the additional label information, only the submission information.

Push label

Push a label to the remote, use the command git push origin <tagname>
Push all the local tags that have not been pushed to the remote at one time git push origin --tags
Delete the remote label (delete the local label first) git push origin :refs/tags/<tagname>

Tagging later

For example, tag the modified readme.md git tag -a v1.2 c1285b

$ git log --pretty=oneline
22fb43d9f59b983feb64ee69bd0658f37ea45db6 (HEAD -> master, tag: v1.4-tyson, tag: v1.4) add file note.md
aab2fda0b604dc295fc2bd5bfef14f3b8e3c5a98 add one line
c1285bcff4ef6b2aefdaf94eb9282fd4257621c6 modified readme.md
ba8e8a5fb932014b4aaf9ccd3163affb7699d475 renamed
d2ffb8c33978295aed189f5854857bc4e7b55358 add readme.md

Shared label

The git push command does not send tags to the remote warehouse server. After creating the label, you must explicitly push the label to the shared server: git push origin v1.5

Send all tags that are not on the remote warehouse server to there: git push origin --tags

Check out the label

If you want the working directory to be exactly the same as the specific tag version in the warehouse, you can use git checkout -b [branchname] [tagname] to create a new branch on a specific tag:

$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'

git alias

git config --global alias.unstage 'reset HEAD --' alias: 06132cc2abe0a9

Last commit: git config --global alias.last 'log -1 HEAD'

git branch

Git encourages frequent use of branching and merging in the workflow.

What Git saves is not file changes or differences, but a series of file snapshots at different times. The git commit object will contain a pointer to a snapshot of the staging content.

Branch creation

$ git branch testing

View the remote branch: git branch -r

Branch switching

Use git checkout branch-name switch branches:

git checkout testing

View the objects currently referred to by each branch: git log --oneline --decorate

$ git log --oneline --decorate
22fb43d (HEAD -> master, tag: v1.4-tyson, tag: v1.4, tyson) add file note.md
aab2fda add one line
c1285bc (tag: v1.2) modified readme.md
ba8e8a5 renamed
d2ffb8c add readme.md

Both the master and tyson branches point to the commit object with a checksum of 22fb43d.

$ git checkout -b iss53 equivalent to git branch iss53 plus git checkout iss53

Branch merge

Merge the iss53 branch to the master branch:

git checkout master
git merge iss53

squash merge: merge multiple commits into one. After merging, you need to resubmit. The original commit information will be modified, including the author.

Merge conflict

When the merge conflicts, a new merge commit is not automatically created. Git will pause and wait for you to resolve conflicts arising from the merge. You can use the git status command at any time after the merge conflict to view the files that are in the unmerged state due to the merge conflict.

<<<<<<< HEAD:index.html
<div id="footer">contact : email.support@github.com</div>
=======
<div id="footer">
please contact us at support@github.com
</div>
>>>>>>> iss53:index.html

After you have resolved the conflicts in all files, use the git add command on each file to mark it as conflict resolved. Then enter git commit -m "merge branch iss53" complete the merge submission.

rebase

Now we have such two branches, test and master, submitted as follows:

       D---E test
      /
 A---B---C---F--- master

Executing git merge test on the master will generate an additional commit node G:

       D--------E
      /          \
 A---B---C---F----G---   test, master

Execute git rebase test on the master, and the local commit will be at the end of the branch as a patch:

A---B---D---E---C‘---F‘---   test, master

The merge operation will generate a new node, and the previous commits will be displayed separately.
The rebase operation does not generate new nodes, but merges the two branches into a linear submission.

Merged commit: git rebase -i

pick c38e7ae rebase content
s 595ede1 rebase

# Rebase 8824682..595ede1 onto 8824682 (2 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

s 595ede1 rebase will merge 595ede1 with the previous commit. After pressing :wq , a dialog box will pop up to merge the commit message.

Delete branch

Delete the local branch: git branch -d iss53

Delete the remote branch: git push origin --delete master

Branch management

Get a list of all current branches:

$ git branch
* master
  tyson

*Represents the branch pointed to by the current HEAD pointer.

View the last commit of each branch:

$ git branch -v
* master 22fb43d add file note.md
  tyson  22fb43d add file note.md

Check which branches have been merged into the current branch:

$git    branch    --merged        
iss53 
*master

View all branches with unmerged work:

$git branch --no-merged
testing

If a branch contains unconsolidated work, use git branch -d testing be wrong to delete, you can use git branch -D testing forcibly removed.

Remote branch

Push

git push origin master the local master branch to the origin/master branch of the remote warehouse. git push origin tyson:tyson-branch the local tyson branch to the tyson-branch branch of the remote warehouse.

If the current local branch is tyson, after fetching the remote warehouse data, it needs to be merged:

git fetch origin
git merge origin/tyson

Push all local branches to the remote host: git push -all origin

Mandatory push: git push --force origin

Tracking branch

$ git checkout --track origin/tyson
Branch tyson set up to track remote branch tyson from origin.
Switched to a new branch 'tyson'

The local branch and the remote branch are set to different names:

$ git checkout -b tyson-branch origin/tyson
Branch tyson-branch set up to track remote branch tyson from origin.
Switched to a new branch 'tyson-branch'

To set an existing local branch to track a remote branch that has just been pulled down, use the -u or --set-upstream-to option:

git branch -u origin master

View all tracking branches set:

$ git branch -vv
iss53 7e424c3 [origin/iss53: ahead 2] forgot the brackets
master 1ae2a45 [origin/master] deploying index fix
* serverfix f8674d9 [teamone/server-fix-good: ahead 3, behind 1] this should do it
testing 5ea463a trying something new

These data are locally cached server data. If you need the latest data, you can run: git fetch --all and then run: git branch -vv

fetch and pull

git fetch will pull the updates of the remote warehouse to the copy of the local remote warehouse, and will not automatically merge them into the local warehouse.

git fetch steps:

git fetch origin master:tmp  //在本地新建一个tmp分支,并将远程origin仓库的master分支代码下载到本地tmp分支
git diff tmp //来比较本地代码与刚刚从远程下载下来的代码的区别
git merge tmp//合并tmp分支到本地的master分支
git branch -d tmp//如果不想保留temp分支 可以用这步删除

git pull = git fetch + git merge

Delete remote branch

git push origin --delete tyson Git server will retain data for a period of time, and remote branches deleted by mistake can be easily restored.

Create remote branch

Create a remote branch based on the local branch: git push origin backup_foreign:backup_foreign

The local new branch is associated with the remote new branch: git push --set-upstream origin backup_foreign

cherry-pick

Reference from: cherry-pick

It can be used to modify commits on other branches and migrate to the current branch.

git cherry-pick <commit-id>

After cherry-pick is executed, a new commit will be automatically generated for submission, and there will be a new commit ID. The commit information is consistent with the commit information of cherry-pick. If conflicts are encountered, the conflicts will be resolved, and then git add will generate conflicting files, and then use git cherry-pick --continue to continue. In this process, you can use git cherry-pick --abort to restore the state before branching to cherry-pick.

git cherry-pick -x <commit_id> adds the -x parameter, which means to keep the original submission author information for submission.

Starting with Git 1.7.2, batch cherry-pick support has been added, which means that you can set a start and end commit to perform cherry-pick operations at a time for commits in a continuous time series.

git cherry-pick <start-commit-id>…<end-commit-id>

The above command will merge all commit-id submission records from start-commit-id to end-commit-id. It should be noted that start-commit-id must be submitted earlier than end-commit-id.

The difference between cherry-pick and rebase

Cherry-pick operates on one or several commits, and rebase operates on the entire branch.

patch

git apply xx.patch needs to re-commit by yourself. xx.patch must be obtained from git diff in order to use git apply .

git am yy.patch will keep the commit information, and yy.patch is obtained from git format–patch .

The codeword is not easy, if you think it is helpful to you, you can encourage it!


程序员大彬
468 声望489 粉丝

非科班转码,个人网站:topjavaer.cn