How does this pre-commit hook fix trailing whitespace?

前端 未结 3 1207
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 08:06

What is going on in this pre-commit hook? I thought changing files would cause them to be restaged.

#!/bin/sh
#
# A git ho         


        
3条回答
  •  野的像风
    2021-01-21 08:18

    The key is to commit the right content, that is:

    • only what has been stages (and added to the index)
    • plus some modifications introduced by the pre-commit hook

    The first point is achieved through the git diff-index

    Compares the content and mode of the blobs found via a tree object with the content of the current index and, optionally ignoring the stat state of the file on disk.

    exec git diff-index --check --cached $against --
    

    with the option --cached:

    do not consider the on-disk file at all

    Any modification is then taken into account to be part of the new commit.

    You can look at the source of commit.c:

    static int prepare_to_commit(const char *index_file, const char *prefix,
                     struct wt_status *s)
    {
    ...
    
        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
            return 0;
    ...
    
    
    /*
     * Re-read the index as pre-commit hook could have updated it,
     * and write it out as a tree.  We must do this before we invoke
     * the editor and after we invoke run_status above.
     */
    discard_cache();
    read_cache_from(index_file);
    

提交回复
热议问题