Table of Contents

  • Record every update to the repository * remove files
  • * Limit the output length
  • Undo operations * Cancel temporary files * Undo changes to files
  • Four, the use of remote warehouse * view remote warehouse * add remote warehouse * grab and pull from remote warehouse
  • 5. Label * List label * Note label * Lightweight label * Post label * Shared label * Checked label
  • Create and merge branches * Create branches * merge branches
  • 7. Branch management
  • Remote branch * Push * Trace branch * pull * delete remote branch
  • Base change * Basic operation of base change * more interesting base change examples * The risk of base change & with base change to solve the base change
  • Distributed workflow
  • Contribute to a project * submit criteria * Private management team * derived public project
  • Select revised version * reference log * Ancestor reference * Commit interval * Multiple points * three points
  • Interactive temporary storage
  • Storage and Cleaning * Storage work * Creative storage * Create a branch from storage
  • Git Grep
  • Rewrite history * Modify last commit * Modify multiple commit information * reorder commit * compress commit * Split commit * Nuclear options: filter-branch * Remove a file from each commit * Globally change mailbox address
  • * Resetting * resetting * compression * checking out * summary * resetting * resetting * resetting * compression * checking out * summary
  • Advanced merge * Merge conflict
  • Use Git to debug * file annotation * binary search
  • Configure Git * external merge and compare tool * formatting with redundant white space characters
  • Git properties * Merge strategy
  • Git hooks * Client hooks
  • Git object * tree object * commit object
  • Git reference * HEAD reference
  • 25. Maintenance and Data Recovery * Data Recovery * Object removal

I. Record every update to the warehouse

Remove the file

  1. To remove a file from Git, you must remove it from the staging area and commit it. You can do this with git rm and remove the specified files from the working directory so that they don’t show up in the untracked files list later.

  2. Git rm must use the force-delete option -f if it has been modified before deletion and has been placed in the staging area

  3. If you want to keep files on disk but don’t want Git to keep track of them. Use the –cached option when you forget to add a.gitignore file and accidentally add a large log file or a stack of.a build files to the staging area:

    $ git rm --cached READMECopy the code
  4. To rename a file in Git, use Git’s mv command

    $ git mv file_from file_toCopy the code

View the commit history

Limit output length

  1. Git log displays submissions by the specified author with the –author option and searches for keywords in the submission instructions with the –grep option. (Note that you must use the –all-match option if you want to get a submission that meets both of the search criteria. Otherwise, commits that meet any of the criteria will be matched.)

  2. Another very useful filter option is -s, which lists submissions that add or remove strings. For example, if you want to find a commit that adds or removes a reference to a particular function, you can use:

    $ git log -Sfunction_nameCopy the code
  3. Options to restrict git log output

    Options to restrict git log output

Undo operation

  • After the submission, we found that some files were not added or the submission information was incorrectly written. At this point, you can run the commit command with the –amend option to try to recommit:

    $ git commit --amendCopy the code

Cancel the temporary file

  • usegit reset HEAD <file>...To cancel temporary storage

Undo changes to a file

  1. Git checkout —

    … To undo changes to the file

  2. It’s important to know that git checkout — [file] is a dangerous command. Any changes you made to that file disappear – you just copied another file to overwrite it

4. Use of remote warehouse

Viewing the Remote Warehouse

  1. Git remote -v displays the git shorthand and URL for reading and writing remote repositories

    image

  2. To view more information about a remote repository, run git remote show [remote-name]. It lists the URL of the remote repository and trace branch information. This information is useful as it tells you that you are in the Master branch and that if you run Git pull, you will grab all the remote references and merge the remote master branch into the local master branch

    image


    This command will list when you execute it on a particular branchgit pushWhich remote branch is automatically pushed to. It will also list which remote branches are not local to you, which remote branches have been removed from the server, and when you executegit pullWhich branches are merged automatically

  3. Git remote rm

Adding a remote repository

  • rungit remote add <shortname> <url>Add a new remote Git repository

Fetching and pulling from remote repositories

  1. If you want to pull information you don’t have in Paul’s repository, you can run git Fetch PB

  2. If you have a branch set to trace a remote branch, you can use git pull to automatically grab and merge the remote branches into the current branch. By default, the git clone command automatically sets the local master branch to track the master branch (or whatever the default branch is called) of the cloned remote repository. Running Git pull will typically grab data from the originally cloned server and automatically try to merge it into the current branch.

  3. Another easy way to do this is to use git pull –rebase instead of git pull directly. Or you can do this manually by git fetch and git rebase.

  4. Git config –global pull. Rebase true Git config –global pull. Rebase true git config –global pull.

    image

Five, label

  • Git uses two main types of tags:Lightweight tag(lightweight) withNote the label(annotated)

List the tag

  • Listing existing tags is straightforward. Just enter the Git tag

    $git tag v0.1 v1.3Copy the code

Note the label

  1. The easiest way to create an annotation tag is to specify the -a option when you run the tag command:

    $git tag v0.1 v1.3 v1.4 $git tag v0.1 v1.3 v1.4Copy the code
  2. The git show command displays the label information and the corresponding commit information

Lightweight tag

  • The lightweight tag essentially stores the submitted checksum in a file – without saving any other information. To create a lightweight label, do not use the -a, -s, or -m options, just provide the label name:

    $git tag v1.5 $git tag v0.1 v1.3 v1.4 v1.5Copy the code

Post labeling

  • Let’s say that in V1.2 you forgot to label the project, i.e., “updated RakeFile” is submitted. You can fill in the label later. To label which commit, you need to specify the checksum of the commit at the end of the command:

    $git tag -a v1.29fceb02Copy the code

Shared label

  1. By default, git push does not transfer tags to remote repository servers. After creating the tag you must explicitly push the tag to the shared server.

    git push origin [tag_name]Copy the code
  2. If you want to push many tags at once, you can also use git push Origin –tags, which will push all tags that are not on the remote repository server.

Check out the tag

  • You can’t really check out tags in Git because they don’t move around like branches. If you want your working directory to be exactly the same as a particular tag version in your repository, you can use Git checkout -b [branchname] [tagname] to create a new branch on a particular tag

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

Six, branch creation and merger

The new branch

  1. Before you switch branches, keep it clean. There are ways: Save schedule (stashing) and commit amending)

  2. When merging, you should notice the word “fast-forward”. Since the current master branch points to a commit directly upstream of your current commit, Git simply moves the pointer forward. In other words, when you try to merge two branches, if you follow one branch to the other, Git will simply move the pointer forward (move the pointer right) when merging them, because there is no divergence to resolve in this case.

Merging branches

  1. Your development history diverged from an earlier place. Git has to do some extra work because the master commit is not the direct ancestor of the ISS53 commit. When this happens, Git does a simple three-way merge using the snapshots indicated at the ends of the two branches (C4 and C5) and the working ancestors of both branches (C2). Highlight [57]

  2. Git takes a new snapshot of the result of the three-way merge and automatically creates a new commit pointing to it. This is called a merge commit and is special in that it has more than one parent commit highlight [58]

7. Branch management

  1. To see the last commit for each branch, run the git branch -v command

    $ git branch -v 
      iss53 93b412c fix javascript issueCopy the code
  • master 7a98805 Merge branch ‘iss53’

    testing 782fd34 add scott to the author list in the readmes
    Copy the code
  1. If the branch contains work that has not yet been merged, try using itgit branch -dCommand to delete it will fail, if you really want to delete branches and lose those jobs-DOption Forcible deletion.

8. Remote branches

  1. The remote trace branch is a reference to the state of the remote branch. They are local references that you can’t move, and they move automatically when you do any network communication.

  2. If you do some work on your local master branch, and at the same time someone else pushes a submission to git.ourcompany.com and updates its Master branch, your commit history will go in a different direction. Perhaps, as long as you are not connected to the Origin server, your Origin/Master pointer will not move

  3. To synchronize your work, run git fetch Origin. This command finds which server “Origin” is (in this case, git.ourcompany.com), grabs data from it that is not available locally, and updates the local database by moving the Origin /master pointer to the new, updated location

push

  1. When you want to share a branch publicly, you need to push it to a remote repository that has write permission. Local branches are not automatically synchronized with remote repositories – you must explicitly push the branch you want to share. This way, you can put content that you don’t want to share on the private branch, and push content that requires collaboration to the public branch.

  2. You can also run Git Push Origin Serverfix: Serverfix and it will do the same thing – equivalent to saying, “Push the local serverfix branch as the serverfix branch of the remote repository.” This format allows you to push local branches to a remote branch with a different name. If you don’t want the branch on the remote repository to be called Serverfix, you can run Git Push Origin Serverfix: awesomeBranch to push the local Serverfix branch to the AwesomeBranch branch on the remote repository.

  3. It is important to note that when a new remote trace branch is captured, an editable copy (copy) is not automatically generated locally. That is, in this case, there is no new serverfix branch – only an origin/ Serverfix pointer that cannot be modified.

  4. You can merge this work into your current branch by running Git Merge Origin/Serverfix. If you want to work on your own Serverfix branch, you can build it on top of the remote trace branch:

    $ git checkout -b serverfix origin/serverfixCopy the code

Tracking branch

  1. Checking out a local branch from a remote trace branch automatically creates a “trace branch” (sometimes called an “upstream branch”). Trace branches are local branches that are directly related to remote branches. If you type Git pull on a trace branch, Git automatically identifies which server to fetch and which branch to merge into.

  2. To do this, run git checkout -b [branch] [remotename]/[branch]. This is a very common operation, so Git provides the –track shortcut:

    $ git checkout --track origin/serverfix
    Branch serverfix set up to track remote branch serverfix from origin. 
    Switched to a new branch 'serverfix'Copy the code
  3. If you want to set the local and remote branches to different names, you can easily add a local branch with a different name:

    $ git checkout -b sf origin/serverfixCopy the code
  4. To set up an existing local branch to track a remote branch that has just been pulled down, or to modify an upstream branch that is being traced, you can run Git Branch explicitly at any time with the -u or — set-upupstream option.

    $ git branch -u origin/serverfixCopy the code
  5. When the trace branch is set up, it can be referenced via @{upstream} or @{u} shortcuts.

  6. If you want to see all trace branches set up, you can use the -vv option of Git Branch.

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

    If you want to count the latest leading and trailing numbers, you need to grab all remote warehouses before running this command. $git fetch –all; git branch -vv

pull

  • Git pull in most cases means a Git fetch followed by a Git merge command.

Deleting a Remote Branch

  • You can delete a remote branch by running git push with the –delete option. If you want to remove the Serverfix branch from the server, run the following command:

    $ git push origin --delete serverfix
    To https://github.com/schacon/simplegit
    - [deleted] serverfixCopy the code

Nine, rebase

The basic operation of rebasing

  1. There is one way: you can take the patches and changes introduced in C4 and apply them again on top of C3. In Git, this operation is called rebasing. You can use the rebase command to move all changes committed to one branch to another, as if to “replay.” In the example above, run:

    $ git checkout experiment 
    $ git rebase master
    First, rewinding head to replay your work on top of it...
     Applying: added staged commandCopy the code

    Its principle is to first find C2, the most recent common ancestor of the two branches (experiment, the current branch, master, the target base branch of base change operation), and then compare the previous commits of the current branch with the ancestor to extract the corresponding modifications and save them as temporary files. The current branch is then directed to the target base C3, where changes previously saved as temporary files are applied sequentially. Highlight [80]

  2. Whether through rebasing or a three-way merge, the end result of consolidation is always the same snapshot to point to, but with a different commit history. Rebasing is applying a series of commits in their original order to another branch, while merging is combining the final result.

A more interesting example of a radical

  1. Suppose you want to merge the changes in the client into the main branch and publish them, but you don’t want to merge the changes in the Server for now because they need to be more thoroughly tested. In this case, you can use the –onto option of git rebase to select changes that are in the client branch but not in the server branch (i.e. C8 and C9) and repeat them on the master branch:

    $ git rebase --onto master server clientCopy the code

    Fetch the client branch, find the changes after the common ancestor of the client and server branches, and then repeat them on the Master branch.

  2. Next you decide to incorporate the changes in the Server branch as well. Using git rebase [BaseBranch] [topicbranch] you can base the feature branch (server in this case) directly on the target branch (Master). This will save you many steps of switching to the Server branch and then executing base commands on it.

    $ git rebase master serverCopy the code

Risk of base change & Solve base change with Base change

  1. Git config –global pull. Rebase true Git config –global pull. Rebase true git config –global pull.

  2. If you perform base changes on commits that have already been pushed to a shared repository, and thus discard some of the commits that other people’s development is based on, you will be in big trouble and your colleagues will despise you for it.

Distributed workflow

  • Git allows multiple remote repositories to exist, making it possible to have a workflow where each developer has write permission to his repository and read permission to everyone else’s repository.

11. Contribute to a project

Submission guidelines

  1. First of all, you don’t want to commit whitespace errors (which are Spaces at the end of a line, tabs, and tabs followed by a space at the beginning of a line). Git provides an easy way to check for this – before committing, run Git diff –check, which will find possible blank errors and list them for you.

  2. Want to know what must be merged into work to push

    git log --no-merges issue54.. origin/masterCopy the code

    issue54.. The Origin/Master syntax is a log filter that requires Git to display only a list of all commits that are on the later branch (origin/ Master in this case) but not on the previous branch (issue54 in this case).

Private management team

  • The merged work on the featureB branch needs to be pushed to the featureBee branch on the server. She can do this by specifying the local branch with a colon (:) and the remote branch to git push:

    $ git push -u origin featureB:featureBee ... To jessica@githost:simplegit.git fba9af8.. cd685d1 featureB -> featureBeeCopy the code

    Note the -u flag; This is short for –set-upstream, which configudes branching for easy push and pull later

Derived public project

  • Because you rebase the branch, you must specify the -f option for the push command to replace a featureA branch on the server that has a commit that is not a descendant of it. An alternative option is to push the new work to a different branch of the server (perhaps called featureAv2).

Xii. Select the revised version

Refer to the log

  1. Git keeps a reference log (reflog) in the background while you’re at work. The reference log records the history of where your HEAD and branch references have been pointing in recent months. You can use Git reflog to view reference logs.

  2. If you want to see the commits in the repository that the HEAD pointed to five times ago, you can use @{n} to refer to the commit record output in reflog.

    $ git show HEAD@{5}Copy the code

    You can run git log -g to view referenced log information in a format similar to git log output

  3. A reference log exists only in the local repository, a log of what you do in your own repository. Someone else’s copy of the repository reference log will not be the same as yours; When you clone a new repository, the reference log is empty because you haven’t done anything in the repository yet. Git show HEAD@{2.months.ago} this command will only be useful if you cloned a project for at least two months – if you cloned the repository five minutes ago, it will not return results.

Ancestors reference

  1. Ancestor references are another way to indicate a commit. If you add a ^ to the end of a reference, Git will resolve it to the last commit of that reference. You can use git show HEAD^ to see the previous commit, which is the parent commit of the HEAD.

  2. You can add a number after ^ — for example, d921970^2 stands for “second parent commit of D921970.” This syntax only applies to merge commit, because merge commit has multiple parent commits. The first parent commit is the branch where you merged, and the second parent commit is the branch where you merged

  3. Another way to indicate an ancestor commit is ~. It also refers to the first parent, so HEAD~ and HEAD^ are equivalent. The difference is when you add numbers. HEAD~2 stands for “first parent commit” — Git will fetch the corresponding first parent commit as many times as you specify.

  4. HEAD~3 can also be written as HEAD^^^ ^, which is also the first parent submitted by the first parent submitted by the first parent. You can also combine these two grammars-you can get the second parent commit of the previous reference by HEAD~3^2 (assuming it is a merge commit)

Submit the interval

  1. image


    You want to see what other commits in the Experiment branch have not been merged into the Master branch. You can usemaster.. experimentTo get Git to display these commits. It is”Commit in the Experiment branch but not in the Master branch“.

    This lets you keep the Experiment branch up to date and see what you’re about to merge.

  2. Another common scenario is to view what you are about to push to a remote end:

    $ git log origin/master.. HEADCopy the code

    This command will output submissions that are in your current branch and not in remote Origin. If you leave one side blank, Git defaults to HEAD. For example, git log origin/master.. The output is the same as in the previous example — Git uses HEAD instead of the empty side.

multipoint

  1. Git allows you to prefix any reference with the ^ character or –not to indicate which branch you don’t want to commit to be included in. Therefore, the following three commands are equivalent:

    $ git log refA.. refB $ git log ^refA refB $ git log refB --not refACopy the code
  2. This syntax allows you to specify more than two references in a query. For example, to view all submissions that are included in refA or refB but not included in refC, you can type either of the following commands

    $ git log refA refB ^refC
    $ git log refA refB --not refCCopy the code

At three o ‘clock

  • The last major range-selection syntax is the three-point syntax, which can select a submission that is contained by one of two references but not by both.

    $ git log master... experiment F E D CCopy the code

    You can use the –left-right argument, which shows which side of the branch each commit is on.

    $ git log --left-right master... experiment < F < E > D > CCopy the code

Interactive temporary storage

Run git add with the -i or –interactive option and Git will enter an interactive terminal mode

Storage and cleaning

Storage work

  1. To push the new stash onto the stack, run git Stash or Git Stash Save

  2. To see what’s stored, use the Git stash list:

    $ git stash list
    stash@{0}: WIP on master: 049d078 added the index file 
    stash@{1}: WIP on master: c264051 Revert "added file_size"
    stash@{2}: WIP on master: 21d80a5 added number to logCopy the code
  3. Reapply the work you just saved: Git Stash apply. If you want to apply one of the older repositories, you can specify it by name, like this: git stash apply stash@{2}. If you do not specify a store, Git assumes that the specified store is the most recent.

  4. You can save a store on one branch, switch to another, and then try to reapply the changes. There can also be changes and uncommitted files in the working directory while the application is stored – If anything isn’t applied cleanly, Git can cause merge conflicts.

  5. File changes are reapplied, but previously staged files are not re-staged. To do that, you must run the git Stash apply command with the –index option to try to reapply the staging changes (that is, to the appropriate staging area).

  6. The Apply option only tries to apply temporary work – it’s still on the stack. You can remove it by running the Git Stash drop plus the name of the stash to be removed. You can also apply the store by running git Stash pop and immediately drop it off the stack.

Creative storage

  1. There are several stored variants that may also be useful. The first very popular option is the –keep-index option of the Stash save command. It tells Git not to store anything that you have temporarily stored with Git add. This is useful when you have made several changes and just want to commit some of them and come back later to deal with the rest.

  2. Another is storing untracked files as if they were tracked. By default, git Stash stores only files that are already in the index. Git also stores any created untracked files if you specify the –include-untracked or -u tags.

Create a branch from the store

  • If you store some work, leave it there for a while, and then continue to work on the branch of the store, you may have problems reapplying the work. If the application tries to modify the file you just modified, you will get a merge conflict and have to resolve it. If you want an easy way to test changes to a store again, you can run the Git Stash Branch to create a new branch, check out the commit where the store work was, apply work there again, and then drop the store when the application succeeds

    $ git stash branch testchanges Switched to a new branch "testchanges" # On branch testchanges # Changes to be committed:  # (use "git reset HEAD <file>..." to unstage) # # modified: index.html # # Changed but not updated: # (use "git add <file>..." to update what will be committed) # # modified: lib/simplegit.rb # Dropped refs/stash@{0} (f0dfc4d5dc332d1cee34a634182e168c4efc3359)Copy the code

    This is a great way to easily resume storage work and continue working on the new branch.

Xv. Search

Git Grep

  1. Git provides a grep command that makes it easy to find a string or regular expression from your commit history or working directory. Compared with some common search commands such as grep and ACK, git grep command has some advantages. The first is that it is very fast, and the second is that you can search not only the working directory, but also any Git tree.

  2. By default Git looks for files in your working directory. You can pass the -n argument to print the matching line numbers Git finds

    $ git grep -n gmtime_r 
    compat/gmtime.c:3:#undef gmtime_r 
    compat/gmtime.c:8: return git_gmtime_r(timep, &result); 
    compat/mingw.c:606:struct tm *gmtime_r(const time_t *timep, struct tm *result)
    date.c:429: if (gmtime_r(&now, &now_tm))Copy the code
  3. You can use the –count option to have Git output an overview of just which files contain matches and how many matches each file contains.

    $ git grep --count gmtime_r 
    compat/gmtime.c:2
    compat/mingw.c:1  
    date.c:1Copy the code
  4. If you want to see which method or function the matching line belongs to, you can pass in the -p option: $git grep -p gmtime_r *.c

  5. You can also use the –and flag to view complex string combinations that contain multiple matches on the same line.

  6. If we want to find out when the ZLIB_BUF_MAX constant was introduced, we can use the -s option to show commits to add and remove the string.

    $ git log -SZLIB_BUF_MAX --oneline
    e01503b zlib: allow feeding more than 4GB in one go 
    ef49a7a zlib: zlib can only process 4GB at a timeCopy the code

Rewrite history

Modify last commit

  • If you have completed the commit and want to change the committed snapshot by adding or modifying the file because you forgot to add a newly created file in the previous commit, you can do the same. By modifying the file and then runninggit addgit rmA traced file is then rungit commit --amendTake the current staging area and make it the newly committed snapshot.

    You need to be careful when using this technique because corrections change the submitted SHA-1 checksum. It is similar to a small base change – if the last commit has been pushed, do not fix it.

Modify multiple commit information

  • For example, if you want to modify the last three commits, or any of the commits in that group, pass the parent commit of the last commit you want to modify as a parameter togit rebase -iCommand, that is,HEAD~2^HEAD~3. Keep in mind that~ 3It might be easier because you are trying to modify the last three commits;

    But notice that the previous four commits are actually specified, i.e. the parent commit that wants to modify the commit:$ git rebase -i HEAD~3Remember again this is a base change command – inHEAD~3.. HEADEvery submission in the scope will be overwritten, whether you modify the information or not.

Reorder commit

Compression to submit

Disaggregation of

Nuclear weapon grade option: Filter-Branch

Remove one file from each commit
  • Filter-branch is a tool that might be used to scrub the entire commit history. To remove a file called elections.txt from the entire commit history, use the –tree-filter option for filter-branch:

    $ git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
    Rewrite 6b9b3cf04e7c5686a9cb838c3f36a8cb6a0fc2bd (21/21) 
    Ref 'refs/heads/master' was rewrittenCopy the code
Change the mailbox address globally

17. Reset disclosure

Three tree HEAD, Index, Working Directory

  1. HEAD is a pointer to the current branch reference, which always points to the last commit on that branch. This means that HEAD will be the parent of the next commit. In general, the simplest way to understand a HEAD is to think of it as a snapshot of your last commit.

  2. The index is your expected next submission. We’ll also refer to this concept as Git’s “staging area,” which is what Git looks like when you run Git Commit.

The role of reset

  • If you specify the –mixed option, it undoes a previous commit, but it also unloads everything. So, we roll back all git add and git commit commands, and all changes are in the Working Directory.

Reset by path

  • You can also provide a path to reset. If a path is specified, reset limits its scope to the specified file or collection of files. This makes sense, of course, because HEAD is just a pointer and you can’t make it point to both parts of the commit. However, indexes and working directories can be partially updated, so resetting continues with steps 2 and 3.

    If we rungit reset file.txt(This is actuallygit reset --mixed HEAD file.txtBecause you did not specify either a committed SHA-1 or branch--soft--hard), it will:
    1. Move the point of the HEAD branch (skipped)
    2. Make the index look like HEAD (stop here) so it essentially just copies file.txt from HEAD into the index.

The compression

Check out the

  • Suppose we have the Master and Develop branches that point to different commits; We are now on Develop (so HEAD points to it). If we rungit reset masterDevelop itself will now point to the same commit as the master. And if we rungit checkout masterDevelop doesn’t move, HEAD itself moves. Now HEAD is going to point to master.

    image

conclusion

  • The following quick reference lists the effect of the command on the tree. The “REF” in the “HEAD” column indicates that the command moves the branch citation to which the HEAD points, while the “HEAD” column indicates that only the HEAD itself is moved. Pay special attention to WD Safe? One column – If it is marked NO, think about it before running the command.


    image

18. Advanced merge

Merge conflicts

  1. Git merge — Abort attempts to restore to the state you were in before you ran the merge. But it doesn’t work perfectly when there are unstored, uncommitted changes in the working directory before you run a command, and otherwise it works fine.

  2. A useful tool is Git Checkout with the –conflict option. This rechecks out the file and replaces the merge conflict flag. This is useful if you want to reset the tags and try to resolve them again. This can be passed to the –conflict parameter Diff3 or merge (the default option). If you pass diff3, Git uses a slightly different version of the conflict flag: not only do they give you the “ours” and “theirs” versions, but they also have a “base” version in the middle to give you more context.

    $ git checkout --conflict=diff3 hello.rb
    
    #! /usr/bin/env ruby
    
    def hello 
    <<<<<<< ours
      puts 'hola world' 
    ||||||| base
      puts 'hello world'
    =======
      puts 'hello mundo'
    >>>>>>> theirs 
    end
    
    hello()Copy the code

Use Git for debugging

Documents marked

  1. You can tag the file with git blame to see when each line of the method was last modified and by whom, and use the -l option to limit the output range

  2. One interesting feature is that you can tell Git to find all the code moves. If you add -c to git Blame, Git will analyze the file you’re annotating and try to find the original source of any code snippet in the file that was copied from somewhere else. For example, if you split the file gitServerHandler. m into several files, one of which is gitPackupload. m. To see where the code block came from, run the blame command with the -c argument to gitPackupload. m

    $git blame -c -l 141,153 gitPackupload.mCopy the code

Binary search

  1. Start with git bisect start, followed by git bisect bad to tell the system that your current commit is faulty. Then you must tell Bisect which commit was the last known normal state, using git bisect good [good_commit]

    $git bisect start $git bisect bad $git bisect good V1.0 6 revisions left to test after this [ecb6e1bc347ccecc5f9350d878ce677feb13d3b2] error handling on repoCopy the code

    Assuming the test results are clean, you can tell Git with git bisect Good and keep looking. You run the test again and find that there is a problem under the commit, so you can tell Git with git bisect bad

  2. When you’re done, you should run git bisect reset to reset your HEAD pointer to the starting position, otherwise you’ll be stuck in a weird state

Configure Git

External merge and compare tools

Formatting with redundant white space characters

Git properties

Merge strategy

  • Git attributes also allow you to specify different merge strategies for specific files in your project. A very useful option is to tell Git not to try to merge specific files when they collide, and to use your side of the file instead.

Git hooks

Client-side hook

  1. The pre-commit hook runs before the commit information is typed. It is used to check incoming snapshots, for example, to see if anything is missing, to make sure tests are running, and to check code. If the hook exits with a non-zero value, Git will abandon the commit, but you can bypass this by using Git commit — no-verify. You can use this hook to check if the code style is consistent (running lint-like programs), if trailing whitespace exists (the built-in hooks do this), or if the new method is properly documented.

  2. The post-commit hook runs after the entire commit process is complete. It doesn’t take any arguments, but you can easily get the last commit information by running Git log-1 HEAD. This hook is usually used for things like notifications.

Git objects

  1. You can demonstrate this effect with the underlying command hash-object, which stores arbitrary data in the.git directory and returns the corresponding key.

  2. The -w option indicates that the hash-object command stores data objects; If this option is not specified, only the corresponding key value is returned. The –stdin option indicates that the command reads from standard input; If this option is not specified, the path of the file to be stored must be specified at the end of the command.

  3. You can retrieve data from Git using the cat-file command. This command is like a Swiss Army knife for dissecting Git objects. Specifying the -p option for cat-file instructs the command to automatically determine the type of content and display us formatted content

  4. With the cat-file -t command, you can tell Git to tell us the type of any object it stores internally, given its SHA-1 value

The tree object

  1. Everything is stored as tree objects, which correspond to UNIX directory entries, and data objects, which roughly correspond to inodes or file content. A tree object contains one or more tree entries. Each entry contains a SHA-1 pointer to a data object or subtree object, and the corresponding mode, type, and file name information.

  2. The master^{tree} syntax represents the tree object to which the latest commit on the Master branch points.

  3. Git creates and records a tree object based on the state represented by the staging area at a certain time, so that a sequence of tree objects can be recorded by repetition. You can create a staging area for a single file using the underlying command update-index. The –add option must be specified for the above command because the file was not previously in the staging area. The — cacheInfo option is also required because the file to be added is in the Git database, not in the current directory.

  4. The file mode is 100644, indicating that this is a normal file; 100755, represents an executable file; 120,000, that’s a symbolic link.

  5. The contents of the staging area can be written to a tree object using the write-tree command. There is no need to specify the -w option — if a tree object does not already exist, when the write-tree command is called, it automatically creates a new tree object based on the current staging state

  6. By calling the read-tree command, you can read a tree object into the staging area. In this case, an existing tree object can be read into the staging area as a subtree by specifying the –prefix option on read-tree

  7. If you create a working directory based on this new tree object, you will find that the root of the working directory contains two files and a subdirectory named bak that contains the first version of the test.txt file

Submit the object

  1. Each of these three commit objects points to one of the three tree object snapshots created earlier. Now, if you run git log on the last committed SHA-1 value, you may be surprised to find that you have a real Git commit history that can be viewed by git log

  2. This is what Git does every time we run git add and git commit — save the overwritten file as a data object, update the staging area, record the tree object, and finally create a commit object that specifies the top-level tree object and the parent commit. The three main Git objects — data objects, tree objects, and commit objects — were originally stored as separate files in the.git/ Objects directory.

Git references

  1. This is basically the essence of a Git branch: a pointer or reference to the beginning of a series of commits.

  2. When you run a command like git branch (branchname), 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 reference

  1. The HEAD file is a symbolic reference that points to the branch you are currently in. A symbolic reference means that it does not contain a SHA-1 value like a regular reference — it is a pointer to another reference.

  2. When we execute git commit, the command creates a commit object and sets its parent commit field with the sha-1 value pointed to by the reference in the HEAD file.

25. Maintenance and Data Recovery

Data recovery

  1. The easiest and most common way to do this is to use a tool called Git reflog. Git silently records the value of HEAD every time you change it while you’re working. The reference log is updated every time you commit or change branches. Reference logs (reflog) can also be updated with git update-ref.

  2. Since the reference log data is stored in the.git/logs/ directory, you no longer have reference logs. How do I recover that commit at this point? One way is to use the Git FSCK utility, which checks the integrity of the database. If you run it with a –full option, it will show you all objects that are not pointed to by other objects

Remove the object

  1. Warning: Removing an object is destructive to commit history changes. It overrides every commit from the earliest tree object that you have to modify or remove a large file referencing. If you do this after importing the repository, before anyone starts working on these commits, then there won’t be any problems otherwise, you have to notify all contributors that they need to base their work on your new commits.

  2. Perform gc to see how much space is being used by the database, or use the count-objects command to quickly see how much space is being used. Let’s say you don’t know how to figure out which files or files are taking up so much space. If you run git gc, all the objects will be put into a package file. You can find this large file by running git verify-pack and sorting the output by the third column (the file size). You can also pipe the results of this command to tail, since you only need to find the last few large objects listed. To find out which file it is, you can use the Revlist command, which we mentioned in specifying a particular submission information format. If you pass the –objects argument to the rev-list command, it lists all the submitted SHA-1, the sha-1 of the data objects, and the file paths associated with them. To find out the name of your data object, use the following command

  3. You must override all commits after commit 7b30847 to completely remove this file from Git history. To do this, we use the filter-branch command.

    $ git filter-branch --index-filter \ 
    'git rm --ignore-unmatch --cached git.tgz' -- 7b30847^..
    
    Rewrite 7b30847d080183a1ab7d18fb202473b3096e9f34 (1/2)rm 'git.tgz' 
    Rewrite dadf7258d699da2c8d89b09ef6670edb7d5f91b4 (2/2) 
    Ref 'refs/heads/master' was rewrittenCopy the code

    The –index-filter option is similar to the –tree-filter option mentioned in the rewrite history, except that this option does not allow the command to modify files checked out on the hard disk, but only files in staging or indexes. You have to use git rm –cached to remove the file, not something like rm file — because you need to remove it from the index, not from disk. Another reason is speed – Git doesn’t check out every revision to disk when it runs the filter, so the process can be very fast. If desired, you can do the same with the –tree-filter option. The –ignore-unmatch option of git rm tells the git rm command that no error will be displayed if the schema you are trying to delete does not exist. Finally, use the filter-Branch option to rewrite the history since 7B30847 was submitted, where this problem arose. Otherwise, the command will start with the oldest commit, which will take a lot of unnecessary time.

  4. Your history will no longer contain references to that file. However, there are references to this file in your reference log and the new references you added in.git/refs/original with the filter-branch option, so you’ll have to remove them and repackage the database. Any files that contain Pointers to those old commits need to be removed before repackaging…