Git basics

Git basics

Git related documentation

Two years of squash merge

Git features

  • Directly record snapshots, not comparisons of differences (the main differences with other version control systems?)
  • Ensure integrity. The mechanism used by Git to calculate the checksum is called SHA-1 hash (hash) (SHA-1 principle?). This is a string consisting of 40 hexadecimal characters (0-9 and af), calculated based on the content of the file or directory structure in Git. E.g
//The string of the git log command is also similar 24b9da6552252987aa493b52f8696cd6d3b00373 Copy code
  • Git generally only adds data to the database (how is the local database implemented?)
  • All operations are performed locally
  • Any submitted operation can always be restored, and uncommitted operation cannot be restored

3.states

  • modified
    modify
  • staged
    Staging. Mark the current version of the modified file to be included in the next snapshot
  • committed
    Stored in the local database

git configuration

Query git configuration

  • /etc/gitconfig
    . Contains the general configuration of every user on the system and their warehouses. --system
  • ~/.gitconfig ~/.config/.gitconfig
    Only for the current user. --global
  • The config file of the current directory.
  • git config --list --show-origin
    Show all current configurations and sources

Check configuration information

  • git config --list
    Check all information
  • git config user.name
    Check the corresponding information

Set user information

  • git config --global user.name'xxx'
  • git config --global user.email'xxx@xxx.xxx'

Get help

  • git help config
    git conifg --help man-git-<verb>
    Get detailed help
  • git config -h
    Get concise help

git repository

  • git add *.c
  • git add LICENSE
  • git commit -m'initial project version'

Clone remote warehouse to local

  • git clone
    3.protocols https://git://SSH

File status

  • Tracked
  • Not tracked
    git add
    -> Not tracked -> Tracked? ? ?
  • Temporary storage
    git add
    Tracked and modified files -> temporary storage? ? ?
  • git status
    You can query the status of the file and the current branch
  • git status -s
    Output a more compact file status
    • ?? Newly added untracked files
    • M modified file
    • M has been modified and temporarily saved
    • MM has modified and temporarily stored content and also modified content
    • A Files newly added to the temporary storage area
  • git add
    • You can use it to start tracking new files
    • Put the tracked files into the temporary storage area
    • Mark conflicting files as resolved when merging
  • .gitignore
    Ignore files, a project can have multiple ignore files
  • git diff
    Compare changes to files that have not yet been staged
  • git diff --staged (--cached)
    Compare changes to the staged file
  • git commit
    submit
    • git commit -m'xxx'
      Submit and enter submission information
    • It records the snapshot in the staging area at the time of submission, and you can return to this state in the future. git log
    • git commit -a
      Temporarily store the tracked files and submit them together
    • git commit -a -m'xxx'
      git commit -am''
  • git rm
    • When manually deleting a file, remove a file from the staging area, so you don t need git add -> git commit, you can directly git commit
    • git rm -f
      Delete previously modified or have been placed in the staging area
    • git rm --cache
      Remove the file from the git repository and keep it in the current workspace
  • git mv move the file, rename the file git mv fileA fileB
    • mv fileA fileB
    • git rm fileA
    • git add fileB

git query history

  • git log
  • git log -p
    Show the differences introduced by each commit
  • git log -2
    Show the last two records
  • git log --stat
    See summary statistics for each submission, such as the number of changed lines, changed files, etc.
  • git log --pretty=oneline
    Format the log output as one line
  • git log --pretty=format:'%h %s' --author='' --since='' --before='' --no-merge
  • git log --no-merges <branch>..<branch>
    Ask Git to only display a list of all commits that are on the back branch but not on the previous branch.

-

git log branch --not master
The query is not submitted on the master

  • git shortlog --no-merges master --not v1.0.1
  • git log --abbrev-commit
    Generate short and unique abbreviations for SHA-1 values
  • git log -1 --name-only --pretty=format:'' <SHA-1>
    Find out the file name of the modified file in a submission

Cancel submission

  • git commit --amend
    Forgot to add a file when submitting, you can pass
    git add
    Execute the command after adding, so that there will only be one commit
  • git reset HEAD filename
    Unstage a file. Essentially move to HEAD first, and then make the index look like HEAD. So it essentially just copies file.txt from HEAD to the index.
    • HEAD is the pointer referenced by the current branch, and it always points to the last commit on that branch.
    • git reset --soft HEAD
      Move the HEAD to the specified snapshot, and the index and working directory after the specified snapshot will not change. At this time, you can use git commit to complete what git commit --amend does. Mainly used to compress submissions, that is, merge multiple local commits into one commit
    • git reset --mixed HEAD
      (
      get reset HEAD
      ) Move the HEAD to the specified snapshot, but it will cancel the staging of all the commits before the specified snapshot
    • git reset --hard HEAD
      Move HEAD to the specified snapshot, and clear all commits before the specified snapshot
    • git reset HEAD filename
      Restore the specified file to the HEAD version
    • reset
      with
      checkout
      The difference
      • git checkout [branch]
        Relative to
        git reset --hard [branch]
        It is safe. In the process of switching branches, checkout will synchronize the code in the work area and temporary storage area to another branch without branch conflicts.
      • reset [branch]
        Will move the current HEAD point, that is, change the commit branch of the current branch, while chekcout moves HEAD itself to point to another branch
      • git checkout
        The file path is similar to git reset --hard [branch] file, check out the corresponding file directly to cover the file in the workspace
  • git checkout - filename
    Restore a file, directly restore to the database version

restore

  • git reflog
    Query submissions that have been lost. Whenever the head changes, Git will store this information in the history record of the reference log. The reference log only exists in the local warehouse.
  • git update-ref
    Update reference log (reflog)
  • git log -g
    Output reference log in standard format
  • git branch branchname sha-1
    Create a new branch named branchname to point to the commit referenced as sha-1
  • The reference log is stored in ./git/logs/
  • git fsck --full
    Used to recover when there is no reference log
  • git clone
    Will download the entire project history, including every version of every file

Remote warehouse information

  • git remote -v
    View remote warehouse address and read and write information
  • git remote add shortname url
    Add a new remote warehouse and give a shortname alias
  • git fetch
    Pull the information you don't have in the remote warehouse. Only pull remote data to the local, and will not actively merge or modify the current work
  • git pull
    Grab and merge the remote branch to the current branch
  • git clone
    Will automatically add remote warehouses and default to origin as abbreviation
  • git fetch origin
    Will automatically pull all jobs newly pushed after the last crawl or clone
  • git push remote branch
    Push to the branch branch of the remote remote warehouse
  • git remote show remote
    View remote warehouse information
  • git remote rename prename curname
    Rename a remote warehouse
  • git remote remove/rm
    Remove a remote warehouse

Tagging

  • git tag
  • Lightweight label
    git tag v1.2
  • Note label
    git tag -a v1.2 -m'xx'
    The name, email address, date and time of the tagger will be kept, and there is also a tag information, and it can be signed and verified by GNU Privacy Guard (GPG)
  • Push to the remote branch:
    git push tag v1.4
    Push the specified branch
    git push origin --tags
    Push all local branches that are not available in the remote warehouse
  • delete
    tag git tag -d tagname
    Local delete push to remote
    git push origin --delete tagname
  • Check out and create branch
    git checkout -b branchname tagname
    Switch to the corresponding tag
    git checkout tag

Alias

  • Internal command to set alias:
    git config --global alias.customCommand'gitCommand'
  • External command to set alias:
    git config --global alias.customCommand'!outsideCommand'

Branch

  • Create a branch:
    git branch branchName
  • Switch branches:
    git checkout branchName
  • Create a new branch and switch:
    git checkout -b branchName
    . Shorthand for the above two commands.
  • Create a branch and associate to the remote branch:
    git checkout -b <branch> <origin/branch>
  • Name the local branch after the remote branch name:
    git checkout -b --track <origin>/<branch>
    . Shorthand:
    git checkout <branch>
  • Change the remote branch bound to the local branch:
    git branch -u <origin>/<branch>
    git branch --set-upstream-to <origin>/<branch>
  • Delete branch: git branch -d branchName force delete git branch -D branchName
  • Delete the remote branch:
    git push origin --delete <branch>
    . Only delete the pointer, the git server usually keeps it for a period of time until gc is executed, so the data is easy to restore
  • Branch merge:
    git merge <branch>
    Switch to the corresponding branch and execute the command. Tripartite merger? The merged result generates a new commit snapshot
  • This command will only display the work in the branch starting from the common ancestor of the current topic branch and the master branch:
    git diff master...branch
  • Rebasing:
    git rebase
    Compared with merge, it can make the branch more tidy. First find the common ancestor of the two branches, then compare the previous commits of the current branch relative to the ancestor, extract the corresponding changes and save them as temporary files, then point the current branch to the target base, and finally save the previous changes as temporary files. Order application. The essence of the rebasing operation is to discard some existing submissions, and then create some new submissions with the same content but different in fact.
  • git rebase --onto master ab
    The b branch is created based on the a branch, and the a branch is created based on the master. This command is used to merge the b branch, there is no commit of the a branch, and merge to master
  • git rebase master a
    Rebase a branch directly on the master branch
  • git rebase -i
    Compress work into a single submission
  • Baseline change: If the submissions exist outside of your warehouse, and others may develop based on these submissions, then do not perform a rebase.
  • git pull --rebase
    Equivalent to?
    git fetch, git rebase <origin>/<master>
    . Use pull default option --rebase,
    git config --global pull.rebase true
  • The general principle is to only perform rebasing operations to clean up the history of local modifications that have not been pushed or shared with others, and never perform rebasing operations on commits that have been pushed elsewhere. In this way, you can enjoy the convenience brought by the two methods.
  • View the current local branch: git branch
  • Filter has been merged/not merged into the current branch: git branch --merge/--no-merge
  • Local branch naming
    <branch>
    And remote branch naming
    <remote>/<branch>
  • View remote branches:
    git ls-remote
    Get more information about remote branches
    git remote show <remote>
  • Synchronize the remote branch data of a given warehouse:
    git fetch <origin>
    Grab all warehouse data:
    git fetch --al
  • Push:
    git push <remote> <branch>
  • Avoid entering the password every time the https warehouse submits:
    git config --global credential.helper cache
  • Pull:
    git pull
    Equivalent to
    git fetch
    git merge
  • git show <branch> | <SHA-1>

The principle of git branch switching

  • Only record the submitted snapshot, the blob object of the changed file (the snapshot corresponding to each file), a tree object (record the directory structure and blob object index), and a commit object (contains a pointer to the aforementioned tree object and all commit information) )
  • The specific principle is that other version management systems generally copy files, and git branches are essentially only objects that contain the checksum of the pointed object.
  • Pick the corresponding submission:
    git cherry-pick ecf34
  • rerere: configure first
    git config --global rerere.enabled true

other

Submit contribution

  • git clone
    Corresponding warehouse

  • git checkout <branch>
    Switch branches for development

  • git remote add origin <url>

  • git push -u origin <branch>
    Push commit to the branch of the corresponding warehouse. There is no need to merge to the master branch. The advantage of this is that you don't need to roll back the code on the master when your suggestion is not adopted.

  • Inform the maintainer of his submission information:

    git pull-request <origin>/<branch> <url>
    Get your submission information and send it to the maintainer

  • When the warehouse maintainer cannot merge cleanly, he can rebase and resubmit:

    git checkout <branch>
    git rebase origin/master
    git push -f origin branch
    .

  • another way

    git checkout -b <branch> <origin>/<branch>
    Generate a new branch; merge on the new branch
    git merge --squash <branch>
    git commit
    git push origin <branch>

  • Mail method. If there are multiple commits, you can pass

    git format-patch -M origin/master
    Convert every submission into an email

  • Mail sent. Need to be in

    ~/.gitconfig
    Set the imap block in the file. Then pass
    git config --global imap.xxx xxx
    Set up

    [imap] folder = "[Gmail]/Drafts" host = imaps://imap.gmail.com user = user@gmail.com pass = YX]8g76G_2^sFbd port = 993 sslverify = false Copy code
  • carried out

    cat *.patch |git imap-send
    Put the patch sequence in the Drafts folder of the specific IMAP server

  • You can also send mail through the smtp service, and configure as follows

    [sendemail] smtpencryption = tls smtpserver = smtp.gmail.com smtpuser = user@gmail.com smtpserverport = 587 Copy code
  • Can be executed afterwards

    git send-email *.patch
    Send patch

Apply patch

  • git apply
    Check the patch before applying:
    git apply --check *.patch
  • git am
    a apply m mail contains conflicts, resolve the conflicts, and execute
    git add
    , Then execute git am --reslove
  • git am -3 *.patch
    Submit in a smart way. Make Git try a three-way merge. If the commit to create the patch is not in your repository, it is useless to do so.

Useful commands

View

  • Current submission:
    git show
    View the commit record of the current head
  • Last submission:
    git show HEAD^
    Viewing the last commit record is equivalent to
    git show HEAD~
  • The first two submissions:
    git show HEAD~2
    git show HEAD~~
    ``
  • Submission interval: Exists on the dev branch and does not exist on the master.
    git log master..dev
  • View the content that will be pushed to the remote branch:
    git log origin/master..HEAD
    Equivalent to
    git log origin/master..
  • The double-dot syntax cannot show the difference of multiple branches, you can use:
    git log refa refb --not refc
    or
    git log refa refb ^refc
  • 3.points:
    git log master...dev
    If you want to see the commits contained in master or dev but not shared by both. can use
    git log --left-right master...dev
    You can easily check which branch the commit belongs to

Interactive cache

  • Can help you split and merge commit
  • git add -i
    Similar to git status but the display is more concise
  • Ability to temporarily store part of the submitted documents and a certain part of the documents
    git add -p
    git add --patch
    This function can also be realized.
    git reset --patch
    Partial reset file
    git checkout --patch
    Partially checked out file
    git stash save --patch
    Part of the temporary file

Storage and cleaning

  • Save the current working directory and switch to another branch
    git stash
    or
    git stash push
  • Query storage records:
    git stash list
  • Application storage records:
    git stash apply
    Application specified storage
    git stash apply stash@{2}
  • Remove staging:
    git stash drop stash@{0}
  • Update staging:
    git stash apply --index
  • Temporarily store and keep in the index:
    git stash --keep-index
  • By default, git stash will only temporarily store tracked files. To temporarily store untracked files,
    git stash -u
    . But it will not include ignored files.
    git stash -a
    , Including ignored files.
  • Create a branch from the repository:
    git stash branch <new branchname>
  • Empty the directory:
    git clean
    git clean -f -d
    Remove tracked files and empty subdirectories in the working directory. This command is not safe, the safer command is
    git stash --all
  • Clear directory preview:
    git clean -d -n
  • Empty ignored files:
    git clean -n -d -x
  • Interactive emptying:
    git clean -x -i

Signing work

search for

  • git grep -n gmtime_r
    -n output the line number of the matching line found by Git
  • Log search:
    git log -S ZLIB_BUF_MAX --oneline
    -S query when ZLIB_BUF_MAX was introduced

Rewriting history

  • git commit --amend
    The SHA-1 checksum submitted last time will be changed, which can be used to modify information and modify the submitted content. If you modify the submission content and need to be reflected in the submission information, you can use this command. But if you just missed the file, you can use
    git commit --amend --no-edit
    .
  • git rebase -i
    Interactive revision history submission. Note that the commit checksum and log display are opposite. Modify pick to edit. Delete, delete the corresponding record directly. Merged, pick changed to squash. Split, modify pick to edit, execute
    git reset HEAD^
    , And then execute after multiple commits to the workspace file,
    git rebase --continue
    . All submitted SHA-1 checksums in the list will be changed.
  • Nuclear weapon level options:
    git-filter-repo
  • If you want to remove all editor backup files that were accidentally submitted, execute:
    git filter-branch --tree-filter'rm -f *~' HEAD
  • Modify email address globally:
    git filter-branch --commit-filter ' if ["$GIT_AUTHOR_EMAIL" = "schacon@localhost" ]; then GIT_AUTHOR_NAME="Scott Chacon"; GIT_AUTHOR_EMAIL="schacon@example.com"; git commit-tree "$@"; else git commit-tree "$@"; fi' HEADCopy code

Advanced merge

  • Do not want to continue to merge:
    git merge --abort
    . It can't handle perfectly when there are unstored, uncommitted changes in the working directory, but it works well except for that.
  • For some reason want to do it again, execute:
    git reset --hard HEAD
    . Go back to the last submitted state. The same will be lost as the submitted file
  • Ignore blank line modification;
    git merge -Xignore-space-change whitespace
    .
    -Xignore-space-change
    A blank character and multiple consecutive blank characters are considered equivalent.
    -Xignore-all-space
    Ignore whitespace modification completely
  • Pass to
    --confilict
    diff3
    merge
    The option can show three versions of the code including ours, thiers, and base.
    git checkout --conflict=diff3 hello.rb
    . Can be set,
    git config --global merge.conflictstyle diff3
    To make diff3 the default option for merge conflicts
  • Get the merge log:
    git log --oneline --left-right HEAD...MERGE_HEAD
  • Undo merge: Undo local merge
    git reset --hard HEAD-
    . If someone else already has the commit you want to rewrite, this method is invalid.
  • another way:
    git revert -m 1 HEAD
    . After revert, if you want to continue the merge, you need to revert again
    git revert HEAD
  • Unilateral merger, just use our code or only use their code:
    git merge Xours <branch>
    git merge Xtheirs <branch>
  • Use one project as a subdirectory of another project:
    git read-tree --prefix=rack/-u rack_branch
    . Update the code, first switch back to the branch execution of the formation warehouse
    git pull
    command. Then switch back to the original branch and execute
    git merge --squash -s recursive -Xsubtree=rack rack_branch
    . Compare with the original branch,
    git diff-tree -p <branch>

Rerere

  • It allows you to make Git remember the way to resolve a block conflict, so that the next time you see the same conflict, Git can automatically resolve it for you. reuse recorded resolution
  • Turn on the function:
    git config --global rerere.enabled true
  • If the file conflict has been resolved before. After the rollback operation, if rerere is turned on, git will help us resolve the conflict using the last resolution method.
    git diff
    See how the conflict is resolved. Restore the file to a conflict state:
    git checkout --conflict=merge hello.rb
    . carried out
    git rerere
  • If you need to rebase frequently, turning on the rerere function can help your life become better

### Debugging with Git

  • Query the submission record of each line of the code
    git blame
  • Use dichotomy to locate the wrong commit:
    git bisect start
    git bitect bad
    git bitect good <good_commit>
    Test on the checked out commit, and then execute
    git bisect good
    or
    git bisect bad
    After locating the error, execute
    git bisect reset

Submodule

Bale

replace

Credential storage

  • No account password is required for http access
  • git config --global credential.helper cache
    The cache will store the credentials in memory for a period of time
  • git config --global credential.helper'store --file ~/.my-credentials'
    store Permanently saved in plaintext

Customize Git

Configure git

  • Get the list of supported configurations:
    man git config
  • commit.templete
    git config --global commit.template ~/.gitmessage.txt
    Set the default submission template
  • core.excludesfile
    Configure globally effective
    .gitignore
    file
  • core.autocrlf
    Solve the problem of multi-system collaboration. true, line feed is converted to carriage return + line feed. input, carriage return + line feed is converted to line feed. false, window developers retain carriage return + line feed
  • core.whitespace
    . Git presets some options to detect and correct the problem of extra white space characters.
  • Server-side configuration.
    receive.fsckObjects
    Jiaoyan pushed the SHA-1 of the file.
    receive.denyNonFastForwards
    Rebase the pushed commit, and then push or push a commit. The commit currently pointed to by the current remote branch is no longer in the commit that should be pushed.
    receive.denyDeletes
    , It is forbidden to delete branches and tags through push.

Git hook

Submit workflow hook:

  • pre-commit
    . Run before entering submission information. Used to do pre-submission inspection, pass
    git commit --no-verify
    You can skip it.
  • prepare-commit-msg
    The hook is run after the default message is created before starting the submission message editor. For those submissions that automatically generate default information, such as submission information templates, merge submissions, compressed submissions, and revision submissions are very useful. You can use it in conjunction with the submission template to insert information dynamically.
  • commit-msg
    The hook receives a parameter, which is the path of the temporary file that contains the current submission information, as mentioned above. . Can be used to verify the status of the project or submit information before the submission is passed.

-

post-commit
. The hook runs after the entire submission process is completed. This hook is generally used for things like notifications.

Git internal principles

The typical structure of the newly initialized .git directory is as follows:

$ ls -F1 config contains project-specific configuration options description is for GitWeb application only, we don t need to care HEAD points to the currently checked out branch (Still to be created) index file saves temporary storage area information hooks/hooks info/contains a global exclude file to place ignored patterns that you don t want to be recorded in the .gitignore file. objects/store all data content refs/stores a pointer to the submission object of the data (branch, remote warehouse, tag, etc.) Copy code

Git object

  • One file corresponds to one content, and the file is named after the SHA-1 checksum of the content plus specific header information. The first two characters of the checksum are used to name the subdirectory, and the remaining 38 characters are used as the file name.
  • Header information composition: object type + space + bytes of data content + null bytes
  • Create a file git object
    git hash-object -w <filePath>
  • Obtain the corresponding file through the object:
    git cat-file -p <SHA-1>
  • Get the type of data stored in the file:
    git cat-file -t <SHA-1>
  • Tree object, a tree object can contain multiple objects or other tree objects. Git uses tree objects to resolve file names and also allows us to organize multiple files together.
    git cat-file -p master^{tree}
    Get the current tree object of a project
  • Create staging area:
    git update-index
    . File mode, 100644 ordinary file, 100755 executable file, 12000 means a symbolic link. You can write the contents of the temporary storage area into a tree object through the git write-tree command.
  • Create a commit object: You can create a commit object by calling the commit-tree command. For this, you need to specify the SHA-1 value of a tree object and the parent commit object (if any) of the commit.
  • A label object, similar to a submission object. However, the submission object generally points to a tree object, and the label object points to a submission object. It contains a label creator information, a date, a piece of comment information, and a pointer. It always points to a submission object, just add a friendlier name to the submission object. Lightweight tags point to fixed references. Note tags will generate a tag object, and only the current tag object will be used with a reference.

Git references

  • If we are interested in a submission from a warehouse, we need to know the SHA-1 checksum of the corresponding submission. But you can also use refs for quick access.
  • git update-ref refs/heads/master 1a410efbd13591db07496601ebc7a059dd55cfe9
  • When running a command like git branch, Git will actually run the update-ref command to get the SHA-1 value corresponding to the latest commit of the current branch and add it to any new references you want to create.
  • HEAD reference. The HEAD file is usually a symbolic reference, pointing to the current branch. The so-called symbolic reference means that it is a pointer to other references.
  • View the HEAD reference value:
    git symbolic-ref HEAD
    ; Set
    git symbolic-ref HEAD refs/heads/test
  • Label reference. It can be used not only as a reference to a label object, but also as a reference to other objects.
  • Remote reference. Point to a reference containing the remote warehouse address and moniker, namely remotes

Package file

  • The format that Git originally used to store objects on disk is called the "loose" object format. However, Git will pack multiple of these objects into a binary file called "packfile" from time to time to save space and improve efficiency. Can be executed manually
    git gc
    View after command
    .git/obejcts
    file
  • After packing. The index file contains the offset information of the package file, and we can quickly locate any specified object through the index file.
  • View the contents of the packaged object:
    git verify-pack .git/objects/pack/pack-978e03...
  • Git often automatically repackages the warehouse to save space. Of course, you can also manually execute the git gc command at any time to do so.

Reference norm

  • The format of the reference specification consists of an optional + sign followed by:, which is a pattern, which represents the reference in the remote version library; it is the location of the remote reference that is tracked locally. The + sign tells Git to (force) update the reference even if it cannot fast forward.
  • Define push or fetch push/pull rules

Transfer Protocol

Maintenance and data recovery

Environment variable