Git Git

Two years of squash merge

Git characteristics

  • Record snapshots directly, not comparing differences (major differences from other version control systems?)
  • Ensure integrity. The mechanism Git uses to compute checksums is called sha-1 hashes. . This is a string of 40 hexadecimal characters (0-9 and a-f) calculated based on the contents or directory structure of the files in Git. For example,
The git log command has a similar string
24b9da6552252987aa493b52f8696cd6d3b00373
Copy the code
  • Git generally only adds data to a database.
  • All operations are performed locally
  • Any committed actions can always be recovered, and uncommitted actions cannot be recovered

Three states

  • modifiedModify the
  • stagedThe staging. The current version of the modified file is marked to be included in the next committed snapshot
  • commitedStore it in a local database

Git configuration

Querying Git Configuration

  • /etc/gitconfig. Contains a common configuration for each user on the system and their repository. –system
  • ~/.gitconfig ~/.config/.gitconfigOnly for the current user. –global
  • Config file of the current directory –local
  • git config --list --show-originShows all current configurations and sources

Checking Configuration Information

  • git config --listCheck all information
  • git config user.nameCheck the corresponding information

Setting User Information

Get help

  • git help config git conifg --help man-git-<verb>Get detailed help
  • git config -hGet simple Help

Git repository

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

Clone the remote repository locally

  • git cloneThree protocols https:// git:// SSH

File status

  • Have been tracking
  • No tracegit add-> Not tracked -> Tracked??
  • The staginggit addTraced and modified files -> Temporary??
  • git statusYou can query the file status and current branch
  • git status -sOutput a more compact file state
    • ?? Newly added untraced file
    • M Modified file
    • M has been modified and temporarily saved
    • MM has modified the temporary content, also has modified the content
    • A New file added to the staging area
  • git add
    • You can use it to start tracking new files
    • Place traced files in the staging area
    • Mark conflicting files as resolved when merging
  • .gitignoreIgnore files. A project can have multiple ignore files
  • git diffCompares changes to files that have not yet been temporarily stored
  • Git diff -- Staged (--cached)Compares changes to temporary files
  • git commitsubmit
    • git commit -m 'xxx'Submit and enter the submission information
    • Git log is a snapshot that was placed in the staging area at commit time and can be returned to this state later
    • git commit -aPut tracked files in temporary storage and submit them together
    • git commit -a -m 'xxx' git commit -am ''
  • git rm
    • When deleting a file manually, remove a file from the staging area so that you can commit it without git add -> git commit
    • git rm -fDelete previously modified or already in the staging area
    • git rm --cacheRemove files from git repository and keep them in your current workspace
  • Git mv Move the file and rename it git mv fileA fileB
    • mv fileA fileB
    • git rm fileA
    • git add fileB

Git Query History

  • git log
  • git log -pDisplays the differences introduced with each commit
  • git log -2Displays the last two records
  • git log --statSee brief statistics for each commit, such as changed rows, changed files, and so on
  • git log --pretty=onelineFormat 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 display only a list of all commits that are in the later branch but not in the previous one.

– Git log branch –not master

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

Cancel the submission

  • git commit --amendIf you forget to add a file when committing, you can passgit addAdd before executing the command, so that only one commit exists
  • git reset HEAD filenameCancel staging a file. Essentially move to HEAD and make the index look like HEAD. So it essentially just copies file.txt from the HEAD into the index.
    • HEAD is a pointer to the current branch reference, which always points to the last commit on that branch.
    • git reset --soft HEADGit commit To do what amend does by moving the HEAD to the specified snapshot without changing the index or the working directory. It is used to compress commits, that is, merge multiple local commits into one COMMIT
    • git reset --mixed HEAD (get reset HEAD) moves HEAD to the specified snapshot, but cancels the staging of all commits before the specified snapshot
    • git reset --hard HEADMoves HEAD to the specified snapshot and clears all commits before the specified snapshot
    • git reset HEAD filenameRestores the specified file to the HEAD version
    • resetcheckoutThe difference between
      • git checkout [branch]Relative to thegit reset --hard [branch]It’s safe. When you switch branches, Checkout synchronizes your workspace and staging code to the other branch without branch conflicts
      • reset [branch]Moves the direction of the current HEAD, changing the commit branch of the current branch, whereas Chekcout moves the HEAD itself to point to another branch
      • git checkoutThe file path is similar to git reset –hard [branch] file
  • git checkout -- filenameRestore a file directly to the database version

restore

  • git reflogQuery for submissions that have been lost. Whenever the head changes, Git stores this information in the reference log history. Reference logs exist only in the local repository.
  • git update-refUpdate reference log (reFLOg)
  • git log -gOutput reference logs in standard format
  • git branch branchname sha-1Create a branch named BranchName to point to the commit that references SHA-1
  • Reference logs are stored in./git/logs/
  • git fsck --fullUsed to recover when no log is referenced
  • git cloneThe entire project history is downloaded, including every version of every file

Remote warehouse information

  • git remote -vView the remote warehouse address and read/write information
  • git remote add shortname urlAdd a new remote repository and give it a shortname alias
  • git fetchPull information you don’t have in the remote repository. Only remote data is pulled locally, and current work is not actively merged or modified
  • git pullFetching and merging remote branches into the current branch
  • git cloneThe remote repository is automatically added with the default origin abbreviation
  • git fetch originWill automatically pull the last capture or clone after the new push all work
  • git push remote branchPush to the branch branch of the remote repository
  • git remote show remoteView information about the remote repository
  • git remote rename prename curnameRename a remote repository
  • git remote remove/rmRemove a remote repository

tagging

  • git tag
  • Lightweight tagGit tag v1.2
  • Note the labelGit tag -a v1.2 -m 'xx'The tagger’s name, email address, date and time are retained, in addition to a tag information, and can be signed and verified using the GNU Privacy Guard (GPG)
  • Push to remote branch:Git push tag v1.4Push specified branchgit push origin --tagsPush all local branches that the remote repository does not have
  • deletetag git tag -d tagnameLocal delete push to remotegit push origin --delete tagname
  • Check out and create branchesgit checkout -b branchname tagnameSwitch to the corresponding taggit checkout tag

The alias

  • Internal commands set aliases:git config --global alias.customCommand 'gitCommand'
  • External commands set aliases: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. Is the abbreviation of the preceding two commands.
  • Create a branch and associate it with a remote branch:git checkout -b <branch> <origin/branch>
  • Name the local branch with the remote branch name:git checkout -b --track <origin>/<branch>. Abbreviations: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 a branch: git branch -d branchName Forcibly deletes git branch -d branchName
  • Delete remote branches:git push origin --delete <branch>. By simply removing the pointer, git servers will usually wait until GC executes, so data can be easily recovered
  • Branch merging:git merge <branch>Switch to the corresponding branch and run the command. A three-way merger? The merge results in a new commit snapshot
  • This command only displays the work in the branch since the current topic branch and the master branch share a common ancestor:git diff master... branch
  • Rebase:git rebaseCompared to merge, it makes branches cleaner. First, find the common ancestor of the two branches, then compare the previous commits of the current branch to the ancestor, extract the corresponding changes and save them as temporary files, then point the current branch to the target base, and finally apply the changes previously saved as temporary files in sequence. The essence of the rebasing operation is to discard some existing commits and create some new commits that are the same but actually different.
  • git rebase --onto master a bBranch B is created based on branch A, and branch A is created based on master. This command is used to merge the commit of branch B, which does not exist, and merge it to master
  • git rebase master aRebase a directly on the master branch
  • git rebase -iCompress the work into a single commit
  • Benchmarking: If commits exist outside of your repository and others may be developing on them, do not perform benchmarking.
  • git pull --rebaseEquivalent to?git fetch``git rebase <origin>/<master>. Use pull with the default option –rebase,git config --global pull.rebase true
  • As a general rule, only base cleanup history on local changes that haven’t been pushed or shared with others, and never base commits that have been pushed elsewhere, so you can get the benefit of both approaches.
  • View the current local branch: Git Branch
  • Git branch –merge/–no-merge: git branch –merge/–no-merge
  • Local branch naming<branch>And the remote branch name<remote>/<branch>
  • View remote branches:git ls-remoteGet more information about remote branchesgit remote show <remote>
  • Synchronize remote branch data for a given warehouse:git fetch <origin>Fetch all warehouse data:git fetch --al
  • Push:git push <remote> <branch>
  • Avoid HTTPS warehouse to submit input password each time:git config --global credential.helper cache
  • Pull:git pullThe equivalent ofgit fetch git merge
  • git show <branch> | <SHA-1>

Git branch switching principle

  • Records only committed snapshots, bloBs of changing files (snapshots for each file), a tree object (records directory structure and BLOB object index), and a commit object (contains Pointers to the aforementioned tree object and all commit information)
  • While other version management systems copy files, git branches are essentially objects that contain checksums of objects
  • Pick the corresponding submission:git cherry-pick ecf34
  • Rerere: Configure firstgit config --global rerere.enabled true

other

  • Submit the information template

Commit contribution

  • Git Clone repository

  • Git Checkout

    Switch branches for development

  • git remote add origin <url>

  • Git push -u origin

    pushes a commit to the corresponding branch of the repository. There is no need to merge into the Master branch. The advantage of this is that you do not have to roll back the code on the Master if your suggestion is not accepted.

  • Git pull-request

    /

    < URL > get your commit information and send it to your maintainer

  • Git checkout

    Git rebase origin/master git push -f origin branch

  • Git checkout -b


    /

    generates a new branch;

    git commit git push origin




  • By email. Git format-patch -m Origin /master can be used to convert each commit into an email

  • Email sending. You need to set the IMAP block in the ~/.gitconfig file. Git config –global map. XXX XXX

    [imap]
      folder = "[Gmail]/Drafts"
      host = imaps://imap.gmail.com
      user = [email protected]
      pass = YX]8g76G_2^sFbd
      port = 993
      sslverify = false
    Copy the code
  • Perform the cat *. Patch | git imap – send to patch sequence in a specific imap server Drafts folder

  • You can also use the SMTP service to send emails

    [sendemail]
      smtpencryption = tls
      smtpserver = smtp.gmail.com
      smtpuser = [email protected]
      smtpserverport = 587
    Copy the code
  • Then you can run git send-email *. Patch to send the patch

Apply the patch

  • git applyCheck patches before application:git apply --check *.patch
  • git amA apply m mail contains conflicts, resolve conflicts, executegit addGit am –reslove
  • git am -3 *.patchSubmit in an intelligent way. Make Git try a three-way merge. This is useless if the commit to create the patch is not in your repository.

Handy command

To view

  • Current submission:git showView the commit record for the current head
  • Last submission:git show HEAD^Viewing the last COMMIT record is equivalent togit show HEAD~
  • The first two submissions:git show HEAD~2 git show HEAD~~` `
  • Commit interval: exists on dev branch but not on mastergit log master.. dev
  • To see what is being pushed to a remote branch:git log origin/master.. HEADIs equivalent togit log origin/master..
  • Double dot syntax does not show the difference between multiple branches. Use:git log refa refb --not refcorgit log refa refb ^refc
  • Three points:git log master... devIf you want to look at commits that are not common to either Master or Dev. You can usegit log --left-right master... devYou can easily see which branch that commit belongs to

Interactive cache

  • Can help you split and merge commit
  • git add -iSimilar to Git status but more concise
  • Ability to temporarily store part of the submitted document and a part of the documentgit add -p git add --patchThis function can also be implemented.git reset --patch Partial reset filegit checkout --patchPartially check out filesgit stash save --patchPartial temporary files

Storage and cleaning

  • Save the current working directory and switch to another branchgit stashorgit stash push
  • Query storage records:git stash list
  • Application storage records:git stash applyApply the specified storagegit stash apply stash@{2}
  • Remove temporary storage:git stash drop stash@{0}
  • Update temporary storage:git stash apply --index
  • Temporary and retained in the index:git stash --keep-index
  • By default, git Stash only holds traced files temporarily. To temporarily save untracked files,git stash -u. It does not include ignore files.git stash -aContains ignore files.
  • Create a branch from a store:git stash branch <new branchname>
  • Clear directory:git clean git clean -f -dRemoves trace files and empty subdirectories from the working directory. This command is not secure. A safer command would begit stash --all
  • Clear the directory rehearsal:git clean -d -n
  • Empty ignored files:git clean -n -d -x
  • Interactive cleanup:git clean -x -i

Signed work

search

  • git grep -n gmtime_r-n Displays the line number of the matching line found by Git
  • Log search:git log -S ZLIB_BUF_MAX --onelineWhen was the -s query ZLIB_BUF_MAX introduced

Rewrite history

  • git commit --amendChanges the sha-1 checksum from the last submission, which can be used to modify information and the submission. This command is used when you modify the submission content and need to reflect the submission information. But if you just missed a file, you can use itgit commit --amend --no-edit.
  • git rebase -iInteractive change history submission. Note that the commit checksum and log display the opposite. Change pick to edit. Delete: directly deletes the corresponding record. Merge, change pick to squash. Split pick, change pick to edit, and rungit reset HEAD^Commit multiple times to the workspace filegit rebase --continue. Changes all sha-1 checksums submitted in the list.
  • Nuclear-weapon-grade options:git-filter-repo
  • If you want to remove all accidentally committed editor backup files, execute:git filter-branch --tree-filter 'rm -f *~' HEAD
  • Change the mailbox address globally:
    git filter-branch --commit-filter ' if [ "$GIT_AUTHOR_EMAIL" = "schacon@localhost" ]; then GIT_AUTHOR_NAME="Scott Chacon"; GIT_AUTHOR_EMAIL="[email protected]"; git commit-tree "$@"; else git commit-tree "$@"; fi' HEAD
    Copy the code

Senior merger

  • Do not want to continue the merger:git merge --abort. It doesn’t work perfectly when there are unstored, uncommitted changes in the working directory, but otherwise it works fine.
  • If you want to start again for some reason, execute:git reset --hard HEAD. Returns to the state of the last submission. Submitted files will also be lost
  • Ignore blank line modifications;git merge -Xignore-space-change whitespace.-Xignore-space-changeTreat a whitespace character as equivalent to multiple consecutive whitespace characters.-Xignore-all-spaceIgnore whitespace modification entirely
  • Passed to the--confilict diff3 mergeOptions to display code including ours, thiers, base three versions.git checkout --conflict=diff3 hello.rb. You can set it up,git config --global merge.conflictstyle diff3To make DIFF3 the default option for merge conflicts
  • Get merge log:git log --oneline --left-right HEAD... MERGE_HEAD
  • Undo merge: Undo local mergegit reset --hard HEAD-. If someone else already has a commit you want to override, this method will not work.
  • Another way:git revert -m 1 HEAD. After revert, if you want to continue the merge, you need to revert againgit revert HEAD
  • Unilateral merge, just using our code or just using their code:git merge Xours <branch> git merge Xtheirs <branch>
  • Use one project as a subdirectory of another:git read-tree --prefix=rack/ -u rack_branch. Update the code, first cut back to the queue warehouse branch executiongit pullCommand. Then cut back to the original branch and executegit merge --squash -s recursive -Xsubtree=rack rack_branch. Compared to the original branch,git diff-tree -p <branch>

Rerere

  • It allows you to have Git remember how 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
  • Enable function:git config --global rerere.enabled true
  • If file conflicts have been resolved before. If rerere is turned on after the rollback operation, Git will help us resolve the conflict using the last resolution.git diffSee how conflicts are resolved. Restore file to conflict state:git checkout --conflict=merge hello.rb. performgit rerere
  • If you need to change frequently, turning on rerere can help you change your life for the better

Use Git for debugging

  • Query the commit record for each line of codegit blame
  • Commit with binary bit error:git bisect start git bitect bad git bitect good <good_commit>Test on the checked commit, then executegit bisect goodorgit bisect badAfter the error is located, executegit bisect reset

The child module

packaging

replace

Credential store

  • You do not need to enter a password for HTTP access
  • git config --global credential.helper cacheThe cache stores credentials in memory for a period of time
  • git config --global credential.helper 'store --file ~/.my-credentials'Store Stores the permanent plaintext

Custom Git

Configure git

  • Get a list of supported configurations:man git config
  • commit.templete git config --global commit.template ~/.gitmessage.txtSet the default submission template
  • core.excludesfileThe configuration takes effect globally.gitignorefile
  • core.autocrlfSolve multi-system collaboration problems. True, line feed is converted to carriage return + line feed. Input, enter + newline converts to newline. False, Window developers keep carriage return + line feed
  • core.whitespace. Git has preset options to detect and correct redundant whitespace.
  • Server configuration.receive.fsckObjectsThe sha-1 file that Delicate Yan pushed over.receive.denyNonFastForwardsBase pushed submissions, then push or push a commit, and the current remote branch is no longer pointing to a commit for that push.receive.denyDeletesTo disable branch and label deletion through push.

Git hooks

Submit workflow hooks:

  • pre-commit. Run before you type the submission information. Used for pre-submission check. Passedgit commit --no-verifyYou can skip it.
  • prepare-commit-msgThe hook runs after the default information is created before starting the commit information editor. It is useful for commits that automatically generate default information, such as commit information templates, merge commit, compress commit, and revise commit. You can use it in conjunction with the submission template to dynamically insert information.
  • commit-msgThe hook receives an argument that is the path to the temporary file mentioned above that holds the current commit information. . Can be used to verify project status or submission information before submission is approved.

– post – commit. The hook runs after the entire commit process is complete. This hook is usually used for things like notifications.

Git internals

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

$ls-f1 config contains the project-specific configuration option description for GitWeb applications only, Hooks/hook info/ contains a global exclude file, Used to place Pointers to submitted objects that do not want to be recorded in.gitignore files (ignored Patterns Objects/Store all data content refs/ Store Pointers to data (branches, remote repositories, tags, etc.)Copy the code

Git object

  • Each file corresponds to a content and is named with the sha-1 checksum of that content plus the specific header information. The first two characters of the checksum are used to name subdirectories, and the remaining 38 characters are used as file names.
  • Header information composition: object type + space + number of bytes of data content + null bytes
  • Create a file git objectgit hash-object -w <filePath>
  • Get the corresponding file from the object:git cat-file -p <SHA-1>
  • Get the data type of the file stored:git cat-file -t <SHA-1>
  • Tree objects. A tree object can contain multiple objects or other tree objects. Git uses tree objects to save file names and also allows you to group multiple files together.git cat-file -p master^{tree}Gets the current tree object for an item
  • Create staging area:git update-index. File mode, 100644 common file, 100755 executable file, 12000 indicates a symbolic link. You can write the staging area contents to a tree object using the git write-tree command.
  • Create a commit object: You can create a commit object by calling the commit-tree command, specifying the SHA-1 value of a tree object and the parent commit object (if any) of the commit.
  • Label object, similar to a submit object. But the submission object usually points to a tree object, and the label object points to a submission object. It contains a tag creator information, a date, a piece of comment information, and a pointer. It always points to a submission object, but gives the submission object a friendlier name. The lightweight label points to a fixed reference, and the annotation label generates a label object and uses a reference to think of the current label object.

Git reference

  • Interested in a commit for the repository, we need to know the SHA-1 checksum for the commit. But quick access is also possible through refs.
  • git update-ref refs/heads/master 1a410efbd13591db07496601ebc7a059dd55cfe9
  • When you run a command like Git branch, git actually runs update-ref to get the sha-1 value for the latest commit of the branch you are currently in and add it to any new references you want to create.
  • The HEAD references. A HEAD file is usually a symbolic reference that points to the branch where it is currently located. A symbolic reference means it is a pointer to another reference.
  • Check the HEAD reference value:git symbolic-ref HEAD; Set up thegit symbolic-ref HEAD refs/heads/test
  • Tag reference. It can be used as a reference not only to label objects, but also to other objects.
  • Remote reference. A reference to an object containing the address and name of the remote repository, called remotes

Package files

  • The format Git originally used to store objects on disk is known as the “loose” object format. From time to time, however, Git packs multiple of these objects into a binary called a packfile to save space and improve efficiency. You can do it manuallygit gcCommand and then check.git/obejctsfile
  • After packaging. The index file contains the offset information of the package file, through which we can quickly locate any given object.
  • View the contents of the packaged object:git verify-pack .git/objects/pack/pack-978e03...
  • Git often repackages repositories automatically to save space. You can always do this manually by executing git GC.

Reference standard

  • The format of a reference specification consists of an optional + sign followed by:, where a pattern represents a reference in a remote repository; Is the location of the remote reference tracked locally. The + sign tells Git to update references even when it can’t fast forward.
  • Define push/pull rules for push or fetch

Transfer protocol

Maintenance and data recovery

The environment variable