我在编写 Python 程序时使用制表符进行缩进,但我想与使用空格缩进的人合作(使用 git)。
是否有一种方法可以让 git 在推送/获取时自动在空格和制表符之间转换(例如,4 个空格 = 1 个制表符),类似于 CR/LF 转换?
我在编写 Python 程序时使用制表符进行缩进,但我想与使用空格缩进的人合作(使用 git)。
是否有一种方法可以让 git 在推送/获取时自动在空格和制表符之间转换(例如,4 个空格 = 1 个制表符),类似于 CR/LF 转换?
以下是完整的解决方案:
在您的代码库中添加一个名为.git/info/attributes
的文件,其中包含:
*.py filter=tabspace
Linux/Unix
现在运行以下命令:
git config --global filter.tabspace.smudge 'unexpand --tabs=4 --first-only'
git config --global filter.tabspace.clean 'expand --tabs=4 --initial'
OS X
首先使用brew安装coreutils:
brew install coreutils
现在执行以下命令:
git config --global filter.tabspace.smudge 'gunexpand --tabs=4 --first-only'
git config --global filter.tabspace.clean 'gexpand --tabs=4 --initial'
所有系统
现在您可以检查项目的所有文件。您可以使用以下方法完成:
git checkout HEAD -- **
现在所有的Python文件将使用制表符而不是空格。
编辑:更改了强制检出命令。当然,您应该先提交您的工作。
homebrew
,然后运行brew install coreutils
)。 - Olivier Verdier~/.config/git/attributes
中,配置文件放在~/.gitconfig
中会更容易一些,这样这些规则就适用于所有项目,而无需在每个项目中进行操作。 - SurpriseDog是的,一个潜在的解决方案是使用Git属性过滤器驱动程序(另请参见GitPro书),定义一个smudge/clean机制。
这样做的好处是:
您可以在.git/info/attributes
中声明此过滤器驱动程序(此处命名为'tabspace
')(适用于Git存储库中的所有文件的过滤器),其内容如下:
*.py filter=tabspace
现在运行以下命令:
# local config for the current repo
git config filter.tabspace.smudge 'script_to_make_tabs'
git config filter.tabspace.clean 'script_to_make_spaces'
.gitattributes
的项目使用@CommuSoft。但是,如果将配置保留在存储库本地,则更易于理解。我已经编辑了答案。 - VonC~/.gitconfig
[filter "tabspace"]
smudge = unexpand --tabs=4 --first-only
clean = expand --tabs=4 --initial
[filter "tabspace2"]
smudge = unexpand --tabs=2 --first-only
clean = expand --tabs=2 --initial
那么我有两个文件:
attributes
*.js filter=tabspace
*.html filter=tabspace
*.css filter=tabspace
*.json filter=tabspace
和attributes2
*.js filter=tabspace2
*.html filter=tabspace2
*.css filter=tabspace2
*.json filter=tabspace2
mkdir project
cd project
git init
cp ~/path/to/attributes .git/info/
这样,当你最终将你的工作推到github上时,在代码查看器中,它不会因为浏览器都默认使用8个空格缩进而显得很愚蠢。
mkdir project
cd project
git init
cp ~/path/to/attributes2 .git/info/attributes
git remote add origin git@github.com:some/repo.git
git pull origin branch
这样,您就可以在 2 空格缩进
的项目中使用普通标签进行工作。
当然,如果您想要为我的项目做出贡献,并且在开发过程中倾向于使用 2 个空格,可以编写类似的解决方案以将缩进从 4 个空格转换为 2 个空格
。
$XDG_CONFIG_HOME/git/config
而不是$HOME/.gitconfig
来组织配置文件并保持主目录的清洁。 - toastal.git
中,因为项目具有不同的设置并不罕见。 - toastal