How does git status work internally?

前端 未结 2 498
渐次进展
渐次进展 2020-12-03 04:05

From the git object model, files and folders are saved to locations in the .git folder by their sha1 hash.

How does git internally know if a file has been deleted,

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 04:20

    The answer is bit too long and will take a while to write so here is the summary.

    The short answer is that git uses the SHA-1 to check track changes but the name of the file is stored somewhere else.


    The content is stored in a pack (*1- read below) while the names are stored in a idx.
    When you run git status, git check to see if already have this path in the idx file (metadata) and based upon the result it decide if it's a new file or not.

    If it's not a new file, git comparing the SHA-1 to track changes.


    Why do I have to use git mv to move files and not a simple mv?

    When you execute git status git search your working directory looking for a match between the "registered" paths in the idx file and your working directory.

    When you move a file with mv your working directory does not have the "original" path stored by git, and since git can't find the "registered" path anymore, the file is marked as deleted.

    But on the same time git see a new file, the new path you just the moved the file to, so the new file will be marked as a new file.

    On the other hand, when using git mv, git updates the metadata to point to the new name and the content will be marked as rename. In this case git updates the registered path of the file in the idx file.
    If you move and update it will be marked as rename + modified as well.


    How can I find out what is the SHA-1 of a file?

    Use the git ls-tree internal command to find out what is the SHA-1 of your files.


    Note

    Git starts to track content when you just add it to the staging area.
    Once the file is added git store the following information in the file

    [blob][1 white space][content length][null][content]
    
    If you have a file with the string `hello` it will look like this:
    blob 5\0Hello
    

    Now git calculate the SHA-1 of this file (using sha1sumn) compress it with z-lib and save the file with this SHA-1 as the name nuder the `.git/objects'.

    When git packs the repository it will go into the pack file.

    How can I view the content of the file?

    Since the file is compressed with z-lib we have several options to get the content:

    • First option is to view the zipped stored in the file
    • Second is to view the unzipped content (as explained above)
    • See the content of the file only without any git metadata.

    And to show that git actually use the content as described above here is the same command as git executes behind the scenes to calculate the SHA-1


    This is the illustration of a commit and how it handles file names.

    (http://shafiulazam.com/gitbook/1_the_git_object_model.html)

提交回复
热议问题