indentation configuration only for some files

前端 未结 3 1824
醉梦人生
醉梦人生 2021-02-08 10:46

I want to use

git config core.whitespace tab-in-indent,tabwidth=4

I want to have these settings for c++ files, so that I get warnings when ther

3条回答
  •  梦如初夏
    2021-02-08 11:27

    Some additions to the answers by John Szakmeister and UpAndAdam.

    To set file-specific rules you'll have to add a .gitattributes file in the root of you project. docs
    (If you do not want it to be version controlled you can add it as: .git/info/attributes.)

    # Macro's
    [attr]cpp       diff=cpp whitespace=trailing-space,space-before-tab,indent-with-non-tab,tabwidth=4
    [attr]makefile  whitespace=trailing-space,indent-with-non-tab,space-before-tab,tabwidth=4
    
    *.[ch]        cpp
    *.[ch]pp      cpp
    makefile      makefile
    s.makefile    makefile
    
    • Match files using the syntax for .gitignore files. i.e. * matches everything and [ch] matches both characters c and h.
    • The whitespace option lists things to warn for.
      • Setting the tabwidth in the whitespace option is used to determine when and how to replace the tab and space characters. (The default value is 8 characters.)
      • tab-indent considers indentation using tabs an error.
      • indent-with-non-tab warns here when 4 or more spaces are used at the start of a line. Note that indentation with 3 spaces is accepted!
        Add space-before-tab to catch spaces hidden before and between the tabs.
        Note that spaces following tab are
    • Aside: diff=cpp enables smarter diffs for C and C++ files.
    • Aside 2: trailing-space warns on trailing white space characters at the end-of-line and end-of-file.

    Verify Rules

    • To verify what rules from .gitattributes are applied use:
    git check-attr --all -- 
    

    does not have to be an existing file. (i.e. some.cpp works)

    • To test the whitespace rules:
      Create a dummy file matching the filename rule and call: git diff.
    trailing space 
    trailing tab    
      2 spaces
        4 spaces
        tab
         tab and space
        space and tab
            tab, space, tab
    
    

    Usage

    Issues are marked when calling git diff and checked/ fixed when calling git -apply ---whitespace=[warn|error|fix]. Configure default behaviour of git apply with:

    git config --[global|local] apply.whitespace [warn|error|fix]
    

提交回复
热议问题