This article has been included in Github warehouse, welcome everyone to watch, star. This repository is used to share core Java knowledge, including Java basics, MySQL, SpringBoot, Mybatis, Redis, RabbitMQ, etc.

Github address: github.com/Tyson0314/J…

If Github is not available, access the Gitee repository.

Gitee address: gitee.com/tysondai/Ja…

Introduction of Git

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

Git Workflow

Git workflow is as follows:

  • Clone resources from remote repositories as local repositories;
  • Code changes in the local repository;
  • Commit code to staging area before committing to local repository;
  • Commit changes to the local repository. All historical versions of changes are saved in the local repository.
  • When you need to share code with team members, you can push the modified code to a remote repository.

Git workflow flowchart is as follows:

Image: blog.csdn.net/ThinkWon/ar…

Storage principle

When Git saves project status, it mainly takes a snapshot of all the files and saves the index of the snapshot. If the file has not been modified, Git does not re-store the file, but only keeps a link to the previously saved file.

Git snapshots

The snapshot saves the space occupied by the old file and saves a reference. The new file continues to use the same disk space as the old file, and the different parts are written to the new disk space.

Three states

Git can be in three states: Modified, staged, and Committed. Modified indicates that the file has been modified but not saved to the database. Staging means that the current version of a modified file is marked for inclusion in the next committed snapshot. Committed Indicates that data has been safely saved to the local database.

Basic Git workflow: Modify files in your working directory; Temporary file, file snapshot to the temporary storage area; Commit updates to the local library. The staging area holds a list of files to commit next time, typically in a Git repository directory.

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

configuration

Set the user name and email address:

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

If you use the –global option, then this command only needs to be run once, because Git uses that information later on, whenever you do anything on the system. When you want to use a different user name and email address for a particular project, you can configure it by running a command in that project directory without the –global option.

Git config –list

Git config user.name

Get help

Git help config: git help config

Git basis

Obtaining Git repository

Initialize the repository in an existing directory: Go to the project directory and type git init

Git Clone https://github.com/…

File status

Check the file status: git status

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

Status overview:

The newly added untraced file is preceded by?? The newly added file in the staging area is preceded by A mark, and the modified file is preceded by an M mark. As shown in the figure below, the MM Rakefile appears with two M’s, where the M appearing on the left indicates that the file has been modified and put into the staging area, and the M appearing on the right indicates that the file has been modified but not yet put into the staging area.

$ git status -s
 M README The M on the right of # indicates that the file has been modified but is not yet in the staging area
MM Rakefile # the M to the left indicates that the file has been modified and placed in staging; The M on the right indicates that the file has been modified but is not yet in the staging area
A lib/git.rb # A represents A newly added file in the staging area
?? LICENSE.txt #?? Represents a newly added untraced file
Copy the code

Configure an alias

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

Git config –global alias.st status

$ 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
Copy the code

The workspace

View workspace changes: 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/nullCopy the code

Git checkout — file_name will undo workspace changes and not undo staging changes.

Changes can also be undone using the restore command (introduced in git2.23).

git restore --worktree demo.txt // Undo file workspace changes
git restore --staged demo.txt // Undo the changes in the staging area and restore the file state to before add
git restore -s HEAD~1 demo.txt // Switch the current workspace to the previous commit version. -s is equivalent to --source
git restore -s hadn12 demo.txt // Switch the current workspace to the version with the specified COMMIT ID
Copy the code

The staging area

Drop the files from the workspace into the staging area by git add filename.

git add README.md
Copy the code

Git diff — Staged Modification You can see the readme. md file in the staging area, indicating that the readme. md file has been placed in the staging area.

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

/unstage: git reset HEAD file_name moves the file changes out of the staging area and into the workspace.

Git reset with the –hard option causes all changes in the working directory to be lost.

submit

Any uncommitted changes that are lost are likely to be unrecoverable. Git commit -m “add readme.md”

Git commit -a -m “XXX” is equivalent to git add and git commit -m “XXX”, which commits the file tracked directly. A file untracked cannot be submitted using this command. You need to run the git add command and then the git commit command.

Git commit without -m

Here’s what you should do:

  1. Press the letter keyioraoroTo enter the editable state
  2. After entering the COMMIT information, pressEscKey to exit the editing state and return to general mode
  3. Enter :wq (save and exit) or :wq! (Forcibly exit without saving)

Modifying Commit Information

If you miss some files or write the commit information wrong after committing, use git commit –amend to commit again:

git commit -m 'initial commit'
git add forgotten_file
git commit --amend
Copy the code

View submission History

Git log lists all committed updates.

Git log -p -p displays the difference between each commit and the last two commits.

Git log –stat Lists all files that were modified, how many files were modified, which lines were modified, and so on, below each commit.

Git log –pretty=oneline displays each commit on a single line.

Git log –pretty=format:”%h %s” –graph format for formatting output, %h short hash string for submission, %s for submission instructions, –graph can be a more graphic representation of branching, merging history.

$ git log --pretty=format:"%h %s"Graph * 75f8b36 update * cd72e4f delete query performance optimization * 6bddc95 MySQL 解 决 * f8ace0e Java 解 决 * 0c4eFeb delete Android * 4844de5 Mysql execution plan * 635c140 REDis distributed lock * 7b65bc3 update * e563eec update * 67e1cf7 update readme * 218f353 Modify directory structure * 9428314 Tidy up the Java basicsCopy the code

Git log –since=2. Weeks

Version back

Run the git reset command to roll back the version.

git reset --hard commit_id
git reset --hard HEAD^ # Roll back everything to the previous version
git reset --hard HEAD^^ # Rollback everything to the previous version
git reset --hard HEAD~100 # rollback to previous version 100
git reset HEAD readme.txt  Unstage the staging area and put it back into the workspace
Copy the code

stash

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

Stash stash pop stash@{id} // Stash stash@{id} // Drop git stage drop git stash list git stash list git stash show -p stash@{0Copy the code

Rm and mv

Git rm readme.md: Remove the file from the staging area and commit it, equivalent to rm readme.md and git add. If you simply manually delete files from your working directory, running Git status will result in “Changes not Staged for Commit”.

Git rm –cached readme. md: Keeps the file in your workspace, but doesn’t want Git to track it. You can do this using the –cached option. If a file has been modified and has not yet been put into the staging area, you must use the forcible delete option -f to prevent accidental deletion of data that has not been added to the staging area. Such data cannot be recovered by Git.

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

Git mv readme. md README

This is equivalent to running three commands:

mv README.md README
git rm README.md
git add README
Copy the code

Ignore files

.gitignore can only ignore files whose state is not tracked.

If the remote repository already has the logs folder, git rm –cached logs/xx.log can remove the tracking state of the file while the local workspace changes are still in place. Git add. & git commit -m “xx” & git push

Skip – worktree and assume – unchanged

Skip – worktree:

  • Git update-index –skip-worktree [file] can be used to change local files that will not be committed, but can also pull the latest changes. This works for files that do not change often, but must be localized.

  • Git update-index –no-skip-worktree [file]

  • To view the skip – worktree list: git ls – files – v | grep ‘^ S \’.

assume-unchanged:

  • Git update-index — assumption-unchanged [file] Git update-index — assumption-unchanged [file] This command only assumes that the file is unchanged. When the remote repository corresponding files are modified, the — assumption-Unchanged is removed after the pull update.

  • Git update-index — no-assumption-unchanged file/path

  • View ignores what files: git ls – files – v | grep ‘^ h \’

Remote warehouse

A remote repository is a project version repository hosted on a network.

Viewing the Remote Warehouse

To view the remote warehouse address:

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

Adding a remote repository

Run git remote add


to add a remote git repository and specify a shortname.

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

As shown above, you can replace the entire URL with the string pb on the command line. Such as Git fetch PB.

If you clone a repository using the clone command, the command automatically adds it to the remote repository with origin as the default shorthand name.

Unassociate the Git repository with Git remote remove Origin

If you want to set origin to two remote repositories, you can use git remote set-url –add Origin URL to set origin.

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

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

Modifying the Remote Repository

Modify the remote warehouse address:

git remote set-url origin [email protected]:Tyson0314/Blog.git
Copy the code

Pull and fetch

Git fetch [remote-name]

The git fetch command pulls data to the local repository, but it is not automatically merged into the local branch; it must be merged into the local branch manually.

Git pull typically pulls data from a remote repository and automatically tries to merge it into the current branch.

git pull = git fetch + git merge FETCH_HEAD 
git pull --rebase =  git fetch + git rebase FETCH_HEAD 
Copy the code

Upload the Git server to the local repository

git init Make the directory a local repository
git add .
git commit -m 'xxx' Commit to local repository
git remote add origin https://github.com/Tyson0314/profile Associate the remote repository
git branch --set-upstream-to=origin/master master  The local branch is associated with the remote branch
git pull origin master --allow-unrelated-histories # allow merging unrelated histories
git push -u origin master  If the current branch is traced to multiple hosts, -u will specify a default host so that git push can be used without any arguments.
Copy the code

Push to remote repository

Git push [remote-name] [branch-name]

git push origin master
Copy the code

Viewing the Remote Warehouse

git remote show origin
Copy the code

Remote repository removal and naming

Remove remote repository:

git remote rm paul
Copy the code

Rename remote repository:

git remote rename old-name new-name
Copy the code

The label

Label a commit in history, such as the release node (V1.0, etc.).

Tag tags allow us to back up to a version of code by using the name of the tag instead of a lengthy COMMIT ID:

  • Check the local tag: git tag
  • Git tag -a v2.0 -m ‘MSG’
  • Git push Origin v2.0
  • Git push origin –tags
  • Delete a local tag: git tag -d v2.0
  • Git push Origin –delete tag 2.0
  • Code for viewing different tags locally: Get Checkout V1.0
  • View label details (including commitId) :Git show v1.0
  • Rollback to a version: git reset — Hard commitId
  • Git fetch Origin tag V2.0

Create a label

Git uses two main types of tags: Lightweight and annotated. A lightweight label is a lot like a branch that doesn’t change – it’s just a reference to a particular submission. However, the annotation tag is a complete object stored in a Git database. They can be verified; This includes the name, email address, date and time of the labeler; There is also a tag information; You can also use the GNU Privacy Guard (GPG) for signature and authentication. It is usually recommended to create an annotation label.

The created labels are stored locally and are not automatically pushed to the remote device.

Note the label

Git tag -a v1.4 -m ‘My version 1.4’ -m specifies a piece of information that will be stored in the tag.

You can run git show v1.4 to see the tag information and the corresponding commit information.

Lightweight tag

Git tag v1.4- Tyson Running git show v1.4- Tyson does not see additional tag information, only submission information.

Push the label

Push a tag to the remote, Use git push origin

to push all local tags that have not yet been pushed to a remote location. Git push origin –tags delete remote tags :refs/tags/

Post labeling

For example, tag the following commit (Modified readme.md) : git tag-a v1.2c1285b

$ 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
Copy the code

Shared label

Git push does not transfer labels to remote repository servers. After creating the tag you must explicitly push it to the shared server: Git Push Origin V1.5

Send all tags that are not on the remote repository server there: git push Origin –tags

Check out the tag

Git checkout -b [branchname] [tagname] If you want the working directory to be exactly the same as the specific tag version in the repository, 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'
Copy the code

Git alias

Git config –global alias.unstage ‘reset HEAD –‘

Git config –global alias.last ‘log-1 HEAD’

Git branch

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

Git does not store changes or differences in files, but a series of snapshots of files at different times. Git commits contain a pointer to a snapshot of the staging content.

Branch to create

$ git branch testing

Check the remote branch: git branch -r

The branch switch

Git checkout branch-name

git checkout testing
Copy the code

See what the branches are currently pointing to: 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
Copy the code

Both the Master and Tyson branches point to the submitted object with a checksum of 22fb43D.

Git branch iss53 + git checkout ISS53

Branch merge

Merge iss53 branch to master branch:

git checkout master
git merge iss53
Copy the code

Squash merge: Multiple commits are merged into a squash merge. After merging, you need to commit the commit again. The commit information of the original commit, including author, is modified.

Merge conflicts

A new merge commit is not automatically created when a merge conflict occurs. Git will pause and wait for you to resolve merge conflicts. You can use git status at any time after a merge conflict to view files that are unmerged due to the inclusion of merge conflicts.

<<<<<<< HEAD:index.html
<div id="footer">contact : [email protected]</div>
=======
<div id="footer">
please contact us at [email protected]
</div>
>>>>>>> iss53:index.html
Copy the code

After you resolve conflicts in all files, use git add for each file to mark it as resolved. Then enter git commit -m “Merge branch ISS53” to complete the merge commit.

rebase

Now we have two branches like this,test and master, commit as follows:

       D---E test
      /
 A---B---C---F--- master
Copy the code

Git merge test: git merge test

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

Git rebase test: git rebase test: git rebase test: git rebase test

A - B - D - E - C 'F' - - -test, master
Copy the code

The merge operation generates a new node, and previous commits are displayed separately. The rebase operation does not generate a new node, but fuses the two branches into a linear commit.

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
Copy the code

S 595ede1 rebase merges 595ede1 to the previous commit. Press :wq and a dialog box is displayed to merge the commit message.

Delete the branch

Delete a local branch: git branch -d iss53

Git push origin –delete master

Branch management

Get a list of all current branches:

$ git branch
* master
  tyson
Copy the code

* represents the branch to which the current HEAD pointer points.

View the last commit for each branch:

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

To see which branches have been merged into the current branch:

$git	branch	--merged		
iss53 
*master
Copy the code

View all branches that contain unmerged work:

$git branch --no-merged
testing
Copy the code

If the branch contains work that is not merged, git branch -d testing will cause an error when deleting it. You can use git branch -d testing to force the deletion.

Remote branch

push

Git push origin master push origin/master branch to remote repository. Git push Origin Tyson: Tyson -branch pushes the local Tyson branch to the Tyson -branch in the remote repository.

If the current local branch is Tyson, after fetching the remote warehouse data, it needs to merge:

git fetch origin
git merge origin/tyson
Copy the code

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

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'
Copy the code

Set local and remote branches 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'
Copy the code

To set up an existing local branch to track a remote branch that just pulled down, use the -u or — set-upupstream option:

git branch -u origin master

View all trace 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
Copy the code

This data is locally cached server data. If you need the latest data, run git fetch –all and then git branch -vv

The fetch and pull

Git Fetch pulls updates from a remote repository to a copy of the local remote repository and does not automatically merge into the local repository.

Git Fetch

git fetch origin master:tmp  // Create a new TMP branch locally and download the master branch code from the remote Origin repository to the local TMP branch
git diff tmp // to compare the local code with the code you just downloaded remotely
git merge tmp// Merge the TMP branch to the local master branch
git branch -d tmp// If you do not want to keep the temp branch, you can use this step to delete it
Copy the code

git pull = git fetch + git merge

Deleting a Remote Branch

Git Push Origin — Delete Tyson Git servers retain data for a while, and remote branches that are mistakenly deleted are easy to recover.

Create a remote branch

Git push origin backup_foreign:backup_foreign to create a remote branch based on the local branch

Git push –set-upstream origin backup_foreign git push –set-upstream origin backup_foreign

cherry-pick

From: cherry-pick

You can use it to migrate COMMIT changes made on other branches to the current branch.

git cherry-pick <commit-id>
Copy the code

After the cherry-pick command is executed, a new commit is automatically generated and a new COMMIT ID is provided. The commit information is the same as that of the cherry-pick command. If a conflict is encountered, resolve it, then git add the conflicting file, and continue with git cherry-pick –continue. You can use git cherry-pick –abort to restore the branch to the state before cherry-pick.

Git cherry-pick -x

If -x is added, the original author information is reserved for commit_id.

Git 1.7.2 adds support for batch cherry pick, which allows you to set a start and end commit for a consecutive time series at a time.

Git cherry - pick < start - commit - id >... <end-commit-id>Copy the code

This command merges all commit-id commits from start-commit-id to end-commit-id. Note that start-commit-id must be committed before end-commit-id.

Difference between cherry-pick and rebase

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

The patch

Git apply xx.patch requires a self-commit. Xx. patch must be obtained from git diff in order to use Git apply.

Git am YY. Patch retains commit information. Yy. Patch is obtained from Git format — patch.


Code word is not easy, if you think it is helpful, you can click a “like” to encourage!