TrumanWong

git

It is currently the most advanced distributed version control system in the world.

Supplementary instructions

git command Many people know that Linus created open source Linux in 1991. Since then, the Linux system has continued to develop and has become the largest server system software.

Although Linus created Linux, the growth of Linux relies on the participation of enthusiastic volunteers from all over the world. With so many people writing code for Linux around the world, how is the Linux code managed?

The fact is that before 2002, volunteers from all over the world sent source code files to Linus through diff, and then Linus himself merged the code manually!

You may be thinking, why doesn't Linus put the Linux code into the version control system? Aren’t there free version control systems like CVS and SVN? Because Linus firmly opposes CVS and SVN, these centralized version control systems are not only slow, but also require an Internet connection to be used. There are some commercial version control systems. Although they are easier to use than CVS and SVN, they are paid and inconsistent with the open source spirit of Linux.

However, by 2002, the Linux system had been developed for ten years. The code base was so large that it was difficult for Linus to continue to manage it manually. Brothers in the community also expressed strong dissatisfaction with this method, so Linus chose a commercial The version control system BitKeeper. BitMover, the owner of BitKeeper, authorizes the Linux community to use this version control system for free out of humanitarian spirit.

The good situation of stability and unity was broken in 2005. The reason was that the Linux community gathered a lot of talented people, and it was inevitable that they were contaminated by the martial arts habits of some Liangshan heroes. Andrew, who developed Samba, tried to crack the BitKeeper protocol (actually he was not the only one to do this), but was discovered by BitMover (the monitoring work was well done!), so BitMover was angry and wanted to take back the free use rights of the Linux community.

Linus can apologize to BitMover and promise to strictly discipline his brothers in the future. Well, this is impossible. The actual situation is this:

Linus spent two weeks writing a distributed version control system in C. This is Git! Within a month, the source code of the Linux system has been managed by Git! How is a cow defined? Everyone can experience it.

Git quickly became the most popular distributed version control system. Especially in 2008, the GitHub website was launched, which provided free Git storage for open source projects. Countless open source projects began to migrate to GitHub, including jQuery, PHP, Ruby, etc.

History is so accidental. If BitMover hadn't threatened the Linux community back then, we might not have free and super easy-to-use Git now.

[List of commonly used Git commands](https://github.com/jaywcjlove/handbook/blob/master/other/Git%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4 %E6%B8%85%E5%8D%95.md)

grammar

git [--version] [--help] [-C <path>] [-c name=value] [--exec-path[=<path>]] [--html-path] [--man- path] [--info-path] [-p | --paginate | --no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [- -work-tree=<path>] [--namespace=<name>] <command> [<args>]

Options

add adds the file contents to the index
bisect introduces erroneous changes via binary lookup
branch lists, creates or deletes branches
checkout checks a branch or path into the working tree
clone Clone the repository into a new directory
commit records changes to the repository
diff shows changes between commits, commits and working trees etc.
fetch downloads objects and references from another repository
grep prints lines matching pattern
init creates an empty Git repository or reinitializes an existing one
log shows commit log
merge joins two or more development histories
mv moves or renames files, directories or symbolic links
pull Get and merge from another repository or local branch
push updates remote references and related objects
rebase forward port local commit to updated upstream header
reset resets the current HEAD to the specified state
rm removes files from the working tree and index
show displays various types of objects
status displays the working tree status
tag Create, list, delete or verify tag objects signed with GPG

example

init

git init #Initialization

status

git status #Get status

add

git add file # .or * means add all git rm --cached <added_file_to_undo> # Undo the git add operation before commit git reset head # seems more convenient than git rm --cached above

commit

git commit -m "message" #Pay attention to the garbled characters here

remote

git remote add origin git@github.com:JSLite/test.git #Add source

push

git push -u origin master # push and set the default tracking branch
git push origin master
git push -f origin master # Force push files, abbreviation -f (full form --force)

clone

git clone git://github.com/JSLite/JSLite.js.git git clone git://github.com/JSLite/JSLite.js.git mypro #Clone to a custom folder git clone [user@]example.com:path/to/repo.git/ #There is another way to write the SSH protocol.

git clone supports multiple protocols. In addition to HTTP(s), it also supports SSH, Git, local file protocols, etc. Here are some examples. git clone <repository URL> <local directory name>

git clone http[s]://example.com/path/to/repo.git/
git clone ssh://example.com/path/to/repo.git/
git clone git://example.com/path/to/repo.git/
git clone /opt/git/project.git
git clone file:///opt/git/project.git
git clone ftp[s]://example.com/path/to/repo.git/
git clone rsync://example.com/path/to/repo.git/

Configuration

The first is to configure the account information ssh -T git@github.com to test.

Modify personal information in the project

git help config # Get help information and view parameters for modifying personal information
git config --global user.name "Little Brother Tuniao" # Modify the global name
git config --global user.email "wowohoo@qq.com" # Modify global email
git config --list # View configuration information

Configure automatic line wrapping

The automatic conversion pit is too big. When submitted to git, the newline character is automatically converted to lf.

git config --global core.autocrlf input

Common usage scenarios

Create SSH key

This key is used to communicate with github. It is generated in the local terminal and then uploaded to github.

ssh-keygen -t rsa -C 'wowohoo@qq.com' # Generate key
ssh-keygen -t rsa -C "wowohoo@qq.com" -f ~/.ssh/ww_rsa # Specify the name of the generated directory file
ssh -T git@github.com # Test whether it is successful

Multiple account ssh configuration

1. Generate a key with the specified name

ssh-keygen -t rsa -C "email address" -f ~/.ssh/jslite_rsa The two files jslite_rsa and jslite_rsa.pub will be generated

2. Copy the key to the hosting platform

vim ~/.ssh/jslite_rsa.pub Open the public key file jslite_rsa.pub and copy the content to the code hosting platform

3. Modify config file

vim ~/.ssh/config #Modify the config file, if config is not created

Host jslite.github.com
   HostName github.com
   User git
   IdentityFile ~/.ssh/jslite_rsa

Host work.github.com
   HostName github.com
   # Port server open-ssh port (default: 22, this line is generally not written by default)
   # PreferredAuthentications Configure what authority authentication is used when logging in
   # publickey|password publickey|keyboard-interactive etc.
   User git
   IdentityFile ~/.ssh/work_rsa
  • Host here is an alias and you can name it whatever you want.
  • HostName is usually a website such as: git@ss.github.com:username/repo.git Fill in github.com
  • User usually fills in git
  • The public key file address used by IdentityFile

4.Test

ssh -T git@jslite.github.com # `@` followed by the defined Host
ssh -T work.github.com # Pass alias test
ssh -i ~/Public key file address Host alias # Such as ssh -i ~/.ssh/work_rsa work.github.com

5.Use

#Original writing
git clone git@github.com:<jslite username>/learngit.git
# Current writing method
git clone git@jslite.github.com:<jslite username>/learngit.git
git clone git@work.github.com:<work’s username>/learngit.git

5.Note

If you change the name of id_rsa, you need to add the ssh key to the SSH agent, such as:

ssh-add ~/.ssh/jslite_rsa
ssh-add -l # View all keys
ssh-add -D # Delete all keys
ssh-add -d ~/.ssh/jslite_rsa #Delete the specified key

Log in to remote server without password

ssh-keygen -t rsa -P '' -f ~/.ssh/aliyunserver.key
ssh-copy-id -i ~/.ssh/aliyunserver.key.pub root@192.168.182.112 # You need to enter the password once here

Edit ~/.ssh/config

Host aliyun1
   HostName 192.168.182.112
   User root
   PreferredAuthentications publickey
   IdentityFile ~/.ssh/aliyunserver.key

After the above configuration is completed, you can log in through the command without entering the IP address and password ssh aliyun1

Submit code under https protocol without password

git clone https://github.com/username/rep.git

Cloning through the above method may require a password. The solution: enter the currently cloned project vi rep/.git/config and edit config. Modify it as follows, and you can submit the code without entering a password.

[core]
  repositoryformatversion = 0
  filemode=true
  bare = false
  logallrefupdates = true
  ignorecase=true
  precomposeunicode = true
[remote "origin"]
- url = https://github.com/username/rep.git
+ url = https://username:password@github.com/username/rep.git
  fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
  remote=origin
  merge = refs/heads/master

Push files to 3 git libraries

1. Add 3 remote library addresses

git remote add origin https://github.com/JSLite/JSLite.git
git remote set-url --add origin https://gitlab.com/wang/JSLite.js.git
git remote set-url --add origin https://oschina.net/wang/JSLite.js.git

2. Delete one of the set-url addresses

usage: git remote set-url [--push] <name> <newurl> [<oldurl>]
    or: git remote set-url --add <name> <newurl>
    or: git remote set-url --delete <name> <url>

git remote set-url --delete origin https://oschina.net/wang/JSLite.js.git

3.Push code

git push origin master
git push -f origin master # force push

4. Pull code

Only one url address in origin can be fetched, this fetch-url Defaults to the first address you add to origin

git pull origin master
git pull --all # Get all remote content including tags
git pull origin next:master # Retrieve the next branch of the origin host and merge it with the local master branch
git pull origin next # The remote branch is merged with the current branch

# The above command is equivalent to the following two commands
git fetch origin
git merge origin/next

If the remote host deletes a branch, by default, git pull will not delete the corresponding local branch when pulling the remote branch. This is to prevent git pull from unknowingly deleting the local branch due to someone else operating the remote host. However, you can change this behavior by adding the -p parameter to locally delete the remote deleted branch.

$ git pull -p
# Equivalent to the following command
$ git fetch --prune origin
$ git fetch -p

5.Change pull

You only need to change the order of the three URLs in the config file. The fetch-url will directly correspond to the first UTL connection.

Modify the remote warehouse address

git remote remove origin # Delete the remote path
git remote add origin git@jslite.github.com:JSLite/JSLite.git # Add remote path

Undo remote recording

git reset --hard HEAD~1 # Undo a record
git push -f origin HEAD:master # Synchronize to remote warehouse

Discard local file modifications

git reset --hard FETCH_HEAD # FETCH_HEAD represents the commit point formed after the last successful git pull. Then git pull

git reset --hard FETCH_HEAD error occurred

git pull
You are not currently on a branch, so I cannot use any
'branch.<branchname>.merge' in your configuration file.
Please specify which remote branch you want to use on the command
line and try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) FOR details.

Solution:

git checkout -b temp # Create new + switch to temp branch
git checkout master

It’s easiest to give up local modifications

# If there are any modifications and adding to the temporary storage area
git reset --hard
# Restore all changes, new files will not be deleted
git checkout.
# The following command will delete the newly added files
git clean -xdf

By storing the staging area in stash, local modifications are discarded by deleting the staging area.

git stash && git stash drop

Roll back to a commit submission

git revert HEAD~1 # Undo a record and commit editing will pop up.
git push # Commit rollback

Roll back to a certain version

git reset --hard <hash>
# For example git reset --hard a3hd73r
# --hard means discarding the modifications in the workspace, making the workspace exactly the same as the version code, corresponding to it,
# The --soft parameter represents retaining modifications to the workspace.

Remove a commit

# The essence is to create a new commit that is completely opposite to the original one, which offsets the effect of the original commit.
git revert <commit-hash>

Create a new empty branch

# There is no commit record for the branch (gh-pages) created in this way.
git checkout --orphan gh-pages
# Delete the original content of the newly created gh-pages branch. If not deleted, the submission will be regarded as the first commit of the current branch.
git rm -rf .
# Check the status. It is possible that the above command did not delete the files that have not yet been submitted.
git state

Merge multiple commits

# This command merges the last four commits into one, and HEAD represents the current version.
# You will enter the VIM interface, and you can modify the submission information.
git rebase -i HEAD~4
# You can see that it is divided into two parts. The uncommented part above is to fill in the instructions to be executed.
# The comments below are instructions for instructions. The command part consists of the preceding command name, commit hash and commit message.
# Currently we only need to know the two commands pick and squash.
# --> pick means to be able to execute this commit
# --> squash means that this commit will be merged into the previous commit

# We change the command in front of the commit that needs to be retained to squash or s, and then enter: wq to save and exit
# This is the editing interface where we will see the commit message

# Among them, the non-comment part is the two commit messages. What you have to do is to modify these two into new commit messages.
#
# Enter wq to save and launch. Enter git log again to view the commit history information. You will find that the two commits have been merged.
# Force the modifications to the front end
git push -f origin master

Modify remote Commit record

git commit --amend
# amend can only modify the last commit record that has not been submitted online.
git rebase -i HEAD~3
# Indicates that you want to modify the third to last status of the current version
# Change the first word pick of the record line to be changed to edit
pick 96dc3f9 doc: Update quick-start.md
pick f1cce8a test(Transition):Add transition test (#47)
pick 6293516 feat(Divider): Add Divider component.
# Rebase eeb03a4..6293516 onto eeb03a4 (3 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

Save and exit, The following prompt will pop up

# You can amend the commit now, with
#
# git commit --amend
#
# Once you are satisfied with your changes, run
#
# git rebase --continue

# Use this command to enter the editing page to change the commit, save and exit.
git commit --amend
# Save and exit to confirm the changes and continue rebase,
git rebase --continue
# If you modify multiple records, execute the above two commands repeatedly until all modifications are completed.

# Finally, make sure that others have not submitted for push. It is best not to add -f to force push.
git push -f origin master

Add ignored files

echo node_modules/ >> .gitignore

Use commit to close an issue

This function can be played on Github, but very old versions on Gitlab cannot be played. So how to close an issue following the commit? You can use the following command to close the related issue when confirm merge:

fixes #xxx, fixed #xxx, fix #xxx, closes #xxx, close #xxx, closed #xxx,

Synchronize the upstream repository of the fork

Github tutorial syncing a fork tutorial, [Synchronizing a branch (fork) on Github](http://www.miss77.net/ 549.html)

**Set up to add multiple remote warehouse addresses. **

Before synchronizing, you need to create a remote point pointing to the upstream repository (repo). If you have already derived an original repository, you can do it as follows.

$ git remote -v
# List the current remotes (List the current remote repository)
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
$ git remote add upstream https://github.com/otheruser/repo.git
# Set a new remote (Set a new remote warehouse)
$ git remote -v
# Verify new remote (verify new original song warehouse)
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
# upstream https://github.com/otheruser/repo.git (fetch)
# upstream https://github.com/otheruser/repo.git (push)

Synchronically update warehouse content

Synchronizing the upstream repository to your repository requires two steps: first you need to pull it from the remote, and then you need to merge the branch you want into your local copy branch. Pull branches and their respective commits from the upstream repository. master will be stored in the local branch upstream/master

git fetch upstream
# remote: Counting objects: 75, done.
# remote: Compressing objects: 100% (53/53), done.
# remote: Total 62 (delta 27), reused 44 (delta 9)
# Unpacking objects: 100% (62/62), done.
# From https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY
# * [new branch] master -> upstream/master

Check your fork's local master branch

git checkout master
# Switched to branch 'master'

Merge changes from upstream/master to the local master branch. This keeps your pre-fork's master branch in sync with the upstream repository without losing your local changes.

git merge upstream/master
#Updating a422352..5fdff0f
# Fast-forward
# README | 9 -------
# README.md | 7 ++++++
# 2 files changed, 7 insertions(+), 9 deletions(-)
# delete mode 100644 README
# create mode 100644 README.md

Batch modify names and emails in historical commits

1. Clone the repository

Pay attention to the parameters. This is not an ordinary clone. The cloned warehouse cannot participate in development.

git clone --bare https://github.com/user/repo.git
cd repo.git

2. Run the code in the command line

OLD_EMAILOriginal email CORRECT_NAMECorrected name CORRECT_EMAILCorrected email address

Copy the following code and put it into the command line to execute

git filter-branch -f --env-filter '
OLD_EMAIL="wowohoo@qq.com"
CORRECT_NAME="Little brother tune"
CORRECT_EMAIL="Corrected email@qq.com"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
     export GIT_COMMITTER_NAME="$CORRECT_NAME"
     export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
     export GIT_AUTHOR_NAME="$CORRECT_NAME"
     export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Implementation process

Rewrite 160d4df2689ff6df3820563bfd13b5f1fb9ba832 (479/508) (16 seconds passed, remaining 0 predicted)
Ref 'refs/heads/dev' was rewritten
Ref 'refs/heads/master' was rewritten

3. Synchronize to remote warehouse

Synchronize to push remote git repository

git push --force --tags origin 'refs/heads/*'

I also encountered the following error. Lab has added protection to the master branch by default and does not allow forced coverage. Project(project)->Setting->Repository menu Protected branches just remove the protection of the master. After the modification is completed, it is recommended to add the master's protection back. After all, forcing it is not a good thing.

remote: GitLab: You are not allowed to force push code to a protected branch on this project.

When the above push does not go up, first git pull ensures the latest code

git pull --allow-unrelated-histories
# Or specify a branch
git pull origin master --allow-unrelated-histories

View the history of a file

git log --pretty=oneline file name # List all modification history of the file
git show c178bf49 # Modification record of a certain change
git log -p c178bf49 # Modification record of a certain change
git blame filename # Displays which version of each line of the file was last modified.
git whatchanged file name # Display the submission information of each version of a file: submission date, submitter, version number, submission notes (no modification details)

Create your own git command

git config --global alias.st status
git config --global alias.br branch
git config --global alias.co checkout
git config --global alias.ci commit

After configuring, you don’t need to enter a long paragraph when entering the git command. For example, if we want to check the status, we only need to:

git st

Solution to Chinese garbled characters

git config --global core.quotepath false

Create a new warehouse

init

git init #Initialization

status

git status #Get status

add

git add file # .or * means add all git rm --cached <added_file_to_undo> # Undo the git add operation before commit git reset head # seems more convenient than git rm --cached above

commit

git commit -m "message" #Pay attention to the garbled characters here

remote

git remote add origin git@github.com:JSLite/test.git #Add source

push

git push -u origin master # Push colleagues to set the default tracking branch
git push origin master
git push -f origin master # Force push files, abbreviation -f (full form --force)

clone

git clone git://github.com/JSLite/JSLite.js.git git clone git://github.com/JSLite/JSLite.js.git mypro #Clone to a custom folder git clone [user@]example.com:path/to/repo.git/ #There is another way to write the SSH protocol.

git clone supports multiple protocols. In addition to HTTP(s), it also supports SSH, Git, local file protocols, etc. Here are some examples. git clone <repository URL> <local directory name>

git clone http[s]://example.com/path/to/repo.git/
git clone ssh://example.com/path/to/repo.git/
git clone git://example.com/path/to/repo.git/
git clone /opt/git/project.git
git clone file:///opt/git/project.git
git clone ftp[s]://example.com/path/to/repo.git/
git clone rsync://example.com/path/to/repo.git/

local

help

git help config # Get help information

add

git add * # Track new files
git add -u [path] # Add tracked files [under the specified path]

rm

rm *&git rm * # Remove files
git rm -f * # Remove files
git rm --cached * # Cancel tracking
git mv file_from file_to # Rename tracking file
git log # View commit records

commit

git commit #Submit updates
git commit -m 'message' #Commit instructions
git commit -a #Skip the use of the staging area and temporarily store all tracked files and submit them together.
git commit --amend #Modify the last commit
git commit log #View all commits, including commits without push
git commit -m "#133" #Associate issue with # symbol and issue number anywhere
git commit -m "fix #133" commit close issue
git commit -m 'Summary description'$'\n\n''1. Detailed description'$'\n''2.Detailed description' #Submit brief description and detailed description

reset

git reset HEAD * # Cancel the temporarily saved files
git reset --mixed HEAD * # Same as above
git reset --soft HEAD * #Reset to the specified state without modifying the index area and working tree
git reset --hard HEAD * #Reset to the specified state, which will modify the index area and working tree
git reset -- files * # Reset index area files

revert

git revert HEAD # Undo the previous operation
git revert HEAD~ # Undo the previous operation
git revert commit # Undo the specified operation

checkout

git checkout -- file # Cancel modifications to the file (from the staging area - overwrite the worktree file)
git checkout branch|tag|commit -- file_name # Take the file from the warehouse and overwrite the current branch
git checkout HEAD~1 [file] # will update the working directory to match a certain commit
git checkout -- . # Remove files from the staging area and overwrite the workspace
git checkout -b gh-pages 0c304c9 # This means that the node with the commit hash value 0c304c9 from the current branch is divided into a new branch gh-pages and switched to gh-pages

diff

git diff file # View the differences of the specified file
git diff --stat # View simple diff results
git diff # Compare the differences between Worktree and Index
git diff --cached # Compare the differences between Index and HEAD
git diff HEAD # Compare the differences between Worktree and HEAD
git diff branch # Compare the differences between Worktree and branch
git diff branch1 branch2 # Compare the differences between two branches
git diff commit commit # Compare the differences between two commits
git diff master..test # The above command only displays the differences between the two branches
git diff master...test # You want to find out the difference between the common parent branch of 'master', 'test' and the 'test' branch. You use 3 '.' to replace the previous two '.'

###stash

git stash #Store the workspace scene (tracked files) and continue working after recovery later.
git stash list # View the saved work site
git stash apply # Restore the work site
git stash drop # Delete stash content
git stash pop # Directly delete the stash content while restoring
git stash apply stash@{0} # Restore the specified work site when you save more than one work site.

merge

git merge --squash test # Merge and compress, compress the commits on test into one

cherry-pick

git cherry-pick commit # Pick and merge, merge the commit into the current branch
git cherry-pick -n commit # Pick multiple commits. After merging, you can continue to pick the next commit.

rebase

git rebase master # Rebase the advanced commit on master to the current branch
git rebase --onto master 169a6 # Limit the rollback scope, rebase the commits of the current branch from 169a6 onwards
git rebase --interactive #Interactive mode, modify commit
git rebase --continue # Continue merging after handling conflicts
git rebase --skip # skip
git rebase --abort # Cancel merge

branchbranch

delete

git push origin :branchName # Delete remote branch
git push origin --delete new # Delete remote branch new
git branch -d branchName # Delete local branch, use -D to force deletion
git branch -d test # Delete the local test branch
git branch -D test # Forcefully delete the local test branch
git remote prune origin # After remote deletion, you can still see the remote existence locally. This command deletes branches that do not exist remotely.

submit

git push -u origin branchName # Submit branch to remote origin host

Pull

git fetch -p #When fetching a remote branch, automatically clean up the remote branch. The remote branch has been deleted and the corresponding branch with the same name still exists locally.

Branch merge

git merge branchName # Merge branch - merge branch branchName with the current branch
git merge origin/master # Merge the remote branch on the local branch.
git rebase origin/master # Merge the remote branch on the local branch.
git merge test # Merge the test branch into the current branch

Rename

git branch -m old new #Rename branch

Check

git branch # List local branches
git branch -r # List remote branches
git branch -a # List all branches
git branch -v # View information about the last submitted object of each branch
git branch --merge # View branches that have been merged into the current branch
git branch --no-merge # View branches merged into the current branch
git remote show origin # You can view the remote address and remote branch

New

git branch test # Create a new test branch
git branch newBrach 3defc69 # Specify the hash 3defc69, and the new branch name is newBrach
git checkout -b newBrach origin/master # After retrieving the updates from the remote host, create a new branch based on it
git checkout -b newBrach 3defc69 # Create a newBrach branch with hash value 3defc69 and switch to this branch

connect

git branch --set-upstream dev origin/dev # Establish a link between the local dev branch and the remote dev branch
git branch --set-upstream master origin/next # Manually establish tracking relationship

Branch switching

git checkout test # Switch to the test branch
git checkout -b test # Create new + switch to test branch
git checkout -b test dev # Create a new test branch based on dev and switch

Remote

git fetch <remote host name> <branch name> # fetch retrieves updates from all branches (branch)
git fetch origin remotebranch[:localbranch] # Pull the branch from the remote end [to the local specified branch]
git merge origin/branch # Merge the specified branch on the remote end
git pull origin remotebranch:localbranch # Pull the remote branch to the local branch
git push origin branch # Push the current branch to the specified branch on the remote end
git push origin localbranch:remotebranch # Push the specified local branch to the specified branch on the remote end
git push origin :remotebranch # Delete the specified remote branch
git checkout -b [--track] test origin/dev # Based on the remote dev branch, create a new local test branch [also set the following trace]

submodule

Clone the project and clone the submodule at the same time

git clone https://github.com/jaywcjlove/handbook.git --depth=1 --recurse-submodules

Clone the project and then manually clone the submodule subproject

git submodule add --force 'warehouse address' 'path'
# Among them, the warehouse address refers to the submodule warehouse address, and the path refers to the path where the submodule is placed under the current project.
# Note: The path cannot end with / (the modification will not take effect), and cannot be an existing directory of the existing project (the path cannot be cloned smoothly)
git submodule init # Initialize submodule
git submodule update # Update submodule (command must be executed in the root directory)
git submodule update --init --recursive # The downloaded project comes with submodule

When the project downloaded using git clone contains a submodule, the content of the submodule will not be automatically downloaded initially. At this time, you only need to execute the following command:

git submodule foreach git pull # There are other submodules in the submodule that are updated once
git submodule foreach git pull origin master # submodule update

git submodule foreach --recursive git submodule init
git submodule foreach --recursive git submodule update

Delete Files

git rm -rf node_modules/

remote

Git is a distributed code management tool, so it can support multiple warehouses. In git, the warehouse on the server is locally called remote. In personal development, multi-source may not be used much, but multi-source is actually very useful.

git remote add origin1 git@github.com:yanhaijing/data.js.git
git remote # show all sources
git remote -v # Show all sources + detailed information
git remote rename origin1 origin2 # Rename
git remote rm origin # delete
git remote show origin # View all information about the specified source

tagtag

When development reaches a certain stage, labeling programs is a great feature.

git tag -a v0.1 -m 'my version 1.4' # Create a new annotated tag
git push origin --tags # Push all branches at once
git push origin v1.5 # Push a single tag to the origin source
git tag -v v1.4.2.1 # Verify tag, verify signed tag
git show v1.5 # See the corresponding GPG signature

git tag # List existing tags
git tag v0gi.1 # New tag
git checkout tagname # Switch to tag
git tag -d v0.1 # Delete tag
git push origin :refs/tags/v0.1 # Delete remote tags
git pull --all # Get all remote content including tags
git --git-dir='<absolute address>/.git' describe --tags HEAD # View local version information

log log

git config format.pretty oneline #When displaying history records, only one line is displayed for each submitted information
git config color.ui true #Colored git output
git log #View the commit log, starting with the most recent commit
git log --reverse #View the commit log, starting from the furthest commit
git log --pretty=oneline #Single line display of commit log
git log --graph --pretty=oneline --abbrev-commit
git log -num #Show which log (countdown)
git reflog #View all operation records of all branches
git log --since=1.day #Commits within one day; you can give various time formats, such as a specific day ("2008-01-15"), or how long ago ("2 years 1 day" 3 minutes ago").
git log --pretty="%h - %s" --author=own name #View your own log
git log -p -2 #Expand two updates to display the content differences of each submission
git log --stat #To quickly browse the changes made to the updates submitted by other collaborators
git log --pretty=format:"%h - %an, %ar : %s"#Customize the record format to be displayed
git log --pretty=format:'%h : %s' --date-order --graph # Topological order display
git log --pretty=format:'%h : %s - %ad' --date=short #Date YYYY-MM-DD display
git log <last tag> HEAD --pretty=format:%s # Only show commits
git config --global format.pretty '%h : %s - %ad' --date=short #Date YYYY-MM-DD display Write global configuration
options description options description
%H Complete hash string of the commit object %ad Author revision date (the format can be customized with the -date= option)
%h Short hash string of the submitted object %ar Author revision date, shown as how far back it is
%T The complete hash string of the tree object (tree) %cn The name of the committer
%t The short hash string of the tree object %ce The submitter's email address
%P Complete hash string of parent object (parent) %cd Commit date
%p Short hash string of the parent object %cr Commit date, shown as how far back it is
%an name of author %s submission instructions
%ae Author's email address - -

Pretty Formats

Rewrite history

git commit --amend # Change the latest commit
git rebase -i HEAD~3 # Modify the last three commit instructions, or any one of them
git commit --amend # Saved, these instructions clearly tell you what to do.
git rebase --continue # Modify the submission instructions and exit the editor.
pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

Change to

pick 310154e updated README formatting and added blame
pick f7f3f6d changed my name a bit

Delete warehouse

cd..
rm -rf repo.git

Github official tutorial

Others

git help * # Get help information for commands
git status # Get the current status, very useful, because git will prompt you for the next operations that can be done

Error reporting problem resolution

1. git fatal: protocol error: bad line length character: No s

Solution: Change the remote address to http/https

2. The requested URL returned error: 403 Forbidden while accessing

Solution to github push error:

#vim editor opens the config file in the current project
vim.git/config

#Revise
[remote "origin"]
     url = https://github.com/jaywcjlove/example.git

# is the following code
[remote "origin"]
     url = https://jaywcjlove@github.com/jaywcjlove/example.git

3. git status displays Chinese problem

When checking the status, git status will display the following situation if it is Chinese.

\344\272\247\345\223\201\351\234\200\346\261\202

The solution to this problem is:

git config --global core.quotepath false

References