Filename too long in Git for Windows

Filename too long in Git for Windows

技术背景

在Windows系统上使用Git时,可能会遇到“Filename too long”的错误。Git本身对文件名长度限制为4096个字符,但当Git使用msys编译时,会使用较旧版本的Windows API,导致文件名长度限制为260个字符。这是msys的限制,而非Git本身的限制。

实现步骤

1. 检查和修改注册表(Windows 10 1607及更高版本)

在PowerShell中运行以下命令:

1
2
3
4
5
6
7
8
# 检查LongPathsEnabled设置
Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled

# 如果值为0,将其设置为1
# 这是系统范围的配置,需要管理员权限
# 对CurrentControlSet\Control的更改在系统重启后生效
$MyPSexe = Get-Process -PID $PID | % Path
Start-Process -Verb RunAs $MyPSexe "-c","Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -Type DWord -Value 1"

2. 设置Git的core.longpaths

系统范围设置(需要管理员权限)

在PowerShell中运行:

1
Start-Process -Verb RunAs "git" "config","--system","core.longpaths","true"

或者以管理员身份打开命令提示符或Git Bash,运行:

1
git config --system core.longpaths true

用户全局设置

在PowerShell中运行:

1
& git config "--global" core.longpaths true

或者在命令提示符或Git Bash中运行:

1
git config --global core.longpaths true

单个仓库设置

编辑仓库的.git/config文件,在[core]部分添加:

1
longpaths = true

如果使用TortoiseGit,右键项目文件夹,选择TortoiseGit -> Settings,在“Git”选项卡中点击“Edit local .git/config”,在[core]部分添加longpaths = true

3. 在克隆仓库时设置

1
git clone -c core.longpaths=true <repo-url>

核心代码

PowerShell设置注册表和Git配置

1
2
3
4
5
6
7
8
9
10
11
12
# 检查LongPathsEnabled设置
Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled

# 设置LongPathsEnabled为1
$MyPSexe = Get-Process -PID $PID | % Path
Start-Process -Verb RunAs $MyPSexe "-c","Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -Type DWord -Value 1"

# 系统范围设置Git core.longpaths
Start-Process -Verb RunAs "git" "config","--system","core.longpaths","true"

# 用户全局设置Git core.longpaths
& git config "--global" core.longpaths true

命令行设置Git配置

1
2
3
4
5
6
7
8
# 系统范围设置
git config --system core.longpaths true

# 用户全局设置
git config --global core.longpaths true

# 克隆时设置
git clone -c core.longpaths=true <repo-url>

最佳实践

  • 优先考虑系统范围或用户全局设置,以避免在每个仓库中重复配置。
  • 在克隆仓库时使用-c core.longpaths=true,确保仓库初始化时立即应用长路径支持。
  • 如果使用GUI工具(如TortoiseGit),可以在单个仓库中进行设置,减少系统范围的影响。

常见问题

权限问题

如果在运行git config --system core.longpaths true时出现权限错误,可以尝试以管理员身份运行命令提示符或Git Bash,或者使用git config --global core.longpaths true进行用户全局设置。

配置文件未锁定错误

使用--system选项时可能会出现配置文件未锁定错误,此时可以使用--global选项。

旧版本npm问题

如果问题是由旧版本的npm引起的,可以更新到npm v3,并删除node_modules文件夹,然后重新安装依赖:

1
2
rm -rf node_modules
npm install

Filename too long in Git for Windows
https://119291.xyz/posts/filename-too-long-in-git-for-windows/
作者
ww
发布于
2025年5月29日
许可协议