Git ignore trailing whitespace in markdown files only

自作多情 提交于 2020-01-02 07:07:38

问题


I have a markdown file with lines that have trailing whitespace (which is correct and should be commited). I'm unable to add these changes using git add -p to the index because git complains about trailing whitespace. They are added correctly if I use git add -A, but I want it to work with git add -p.

I have in my ~/.gitconfig:

[core]
  whitespace = trailing-space,space-before-tab

This has been working fine since for the most part I DO want to warn on trailing whitespace (it is incorrect in HTML, JS and Ruby files).

How do I ignore the trailing whitespace in Markdown files only?


回答1:


In a .gitattributes file add the following:

**/*.md  -whitespace

https://git-scm.com/docs/gitattributes#_checking_whitespace_errors

More specifically you could instead do the following:

**/*.md  whitespace=space-before-tab

(dropping the trailing-space for markdown files.)

Treat .gitattributes in the same way you do .gitignore and check it into the repo.




回答2:


Use this in .gitattributes:
**/*.md text whitespace=-cr-at-eol,-trailing-space

**/*.md whitespace=space-before-tab does not work:

C:\Users\kevin\Documents\trailing>git config --show-origin --get core.whitespace
file:C:/Users/kevin/.gitconfig  trailing-space,space-before-tab,cr-at-eol

C:\Users\kevin\Documents\trailing>git init .
Initialized empty Git repository in C:/Users/kevin/Documents/trailing/.git/

C:\Users\kevin\Documents\trailing>cat > README.md
Trailing space here:
check it

C:\Users\kevin\Documents\trailing>git add README.md

C:\Users\kevin\Documents\trailing>git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

C:\Users\kevin\Documents\trailing>echo **/*.md  -whitespace > .gitattributes

C:\Users\kevin\Documents\trailing>git check-attr --all -- README.md
README.md: whitespace: unset

C:\Users\kevin\Documents\trailing>git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904

C:\Users\kevin\Documents\trailing>echo **/*.md  whitespace=space-before-tab > .gitattributes

C:\Users\kevin\Documents\trailing>git check-attr --all -- README.md
README.md: whitespace: space-before-tab

C:\Users\kevin\Documents\trailing>git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

C:\Users\kevin\Documents\trailing>echo **/*.md text whitespace=-cr-at-eol,-trailing-space > .gitattributes

C:\Users\kevin\Documents\trailing>git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904


来源:https://stackoverflow.com/questions/39752867/git-ignore-trailing-whitespace-in-markdown-files-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!