我在我的python程序中使用制表符缩进,但我想与使用空格的人合作(使用git)。

有没有一种方法让git在推/取时自动在空格和制表符之间转换(比如,4个空格= 1个制表符)?(类似于CR/LF转换)


是的,一个潜在的解决方案是使用git属性过滤器驱动程序(参见GitPro书籍),来定义一个涂抹/清除机制。

这种方式:

每次签出回购文件时,空格可以转换为制表符, 但是当您签入(以及推送和发布)时,这些相同的文件将仅使用空格存储回来。

你可以在.git/info/attributes(用于应用于Git repo中的所有文件的过滤器)中声明这个过滤器驱动程序(这里命名为'tabspace'),内容如下:

*.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'

关于这种涂抹/清洁指令集的具体工作示例,请参阅Olivier的回答。


以下是完整的解决方案:

在你的存储库中,添加一个文件.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

首先安装coreutils与brew:

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文件现在都有制表符而不是空格。

编辑:修改强制签出命令。当然,你应该先完成你的工作。


非常有用的信息,每个人使用GitHub(或其他类似的服务)

~ / . 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

然后我有两个文件: 属性

*.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个空格缩进的项目上使用普通制表符。

当然,你也可以编写类似的解决方案,将4个空格转换为2个空格,如果你想为我发布的项目做出贡献,你在开发时倾向于使用2个空格。


如果你是在窗口上,那么你有几个额外的步骤来让@Olivier Verdier的解决方案工作。

下载用于windows的CoreUtils 安装后,将安装位置放在PATH中(如何添加路径变量) 我将expand.exe重命名为gexpand.exe,因为已经有一个windows扩展实用程序。