首页 > 解决方案 > 如何通过 .gitattributes 覆盖子目录中的行尾以无扩展名+指定扩展名?

问题描述

我需要将包含 bash 和 PowerShell 脚本的 repo 克隆到 MacOS 和 Windows 系统,在两者上通过 Atom 进行编辑,在 MacOS 上运行本机 bash 脚本或在 Windows 上通过 Ubuntu WSL shell,在 Windows 上的 PowerShell 窗口中运行 PowerShell 脚本。

在 MacOS 上,所有文件都应以 Native (LF) 结尾签出。

在 Windows 上,所有文件都应以 Native (CRLF) 结尾签出,但以下情况除外:

基本上,我们可以使用 * text=auto,然后覆盖特定的文件扩展名,但有一种特殊情况 - 任何级别的 bin 目录中的 bash 脚本通常不会有任何扩展名,包括 *.sh。

需要这样做的原因是,在正常行为下,以 Windows 文件系统结尾的 CRLF 行检出的 bash 脚本在通过 WSL 中的 /mnt/c 路径访问时无法运行。我们需要在提交之前编辑并运行它们。

我已经找到并尝试了此处发现的问题中显示的解决方案,这似乎表明我可以使用特定于目录的覆盖来覆盖默认的自动文本处理。这可行,但是更具体的其他覆盖不起作用。

/.git 属性:

# Autodetect text files
* text=auto

# Explicitly identify binary files
*.xls binary
*.xlsx binary
*.doc binary
*.docx binary
*.vsd binary
*.vsdx binary
*.pdf binary
*.png binary
*.jpg binary
*.gif binary

# Explicitly identify script files
*.sh text eol=lf
*.ps1 text
*.bat text
*.cmd text
bin/* text eol=lf
bin/*.ps1 text=auto
bin/*.bat text=auto
bin/*.cmd text=auto

# Explicitly identify text files
*.txt text
*.md text
*.json text
*.yaml text

Linux 上的预期结果 = 所有文件都使用本机的 LF 行结尾。这似乎有效。

Windows 上的预期结果:

/test - expect CRLF - correct
/test.sh - expect LF - correct
/test.ps1 - expect CRLF - correct
/bin/test - expect LF - correct
/bin/test.sh - expect LF - correct
/bin/test.ps1 - expect CRLF - INCORRECT, uses LF
/bin/test.bat - expect CRLF - INCORRECT, uses LF

我没有明确地测试过,但也期待这个:

/templates/test - expect CRLF
/templates/test.sh - expect LF
/templates/test.yaml - expect CRLF
/templates/test.ps1 - expect CRLF

/section1/test - expect CRLF
/section1/test.sh - expect LF
/section1/test.ps1 - expect CRLF
/section1/bin/test - expect LF
/section1/bin/test.sh - expect LF
/section1/bin/test.ps1 - expect CRLF

标签: gitgithub

解决方案


“在 Windows 上”是否意味着“有core.autocrlf设置”?Afaik Git 没有硬连线默认操作系统,但 Windows 安装的模板通常已经core.autocrlf设置。

无论如何,我想你可能错过了

当多个模式与路径匹配时,后面的行会覆盖前面的行。这种覆盖是按属性完成的

在属性文档中;你有一个明确的

bin/* text eol=lf

设置eol中的所有内容bin,以及您的bin/*.ps1

bin/*.ps1 text=auto

不会覆盖它,因此bin/*.ps1继承了显式eol=lf属性。git check-attr eol bin/any.ps1您可以使用或进行验证git check-attr -a bin/any.ps1

因此,如果我的咖啡仍然正常运行,修复应该是添加-eol到您的bin/*.ps1属性模式以覆盖您之前的bin/* eol=lf力量。


推荐阅读