Skip to content

📦 Git LFS 大文件管理

为什么需要 LFS?

Git 擅长管理文本文件(代码、配置),但不适合管理大二进制文件(视频、设计稿、数据集、模型权重)。因为 Git 会把每个版本的完整文件存下来,100MB 的 PSD 改 10 次就占 1GB。

Git LFS(Large File Storage)用一个"指针文件"替换大文件,实际内容存在 LFS 服务器上。克隆时只下载你需要的版本,不是全部历史。

安装和配置

bash
# 安装 LFS
git lfs install

# 告诉 LFS 管理哪些文件(在仓库根目录执行)
git lfs track "*.psd"
git lfs track "*.zip"
git lfs track "*.mp4"
git lfs track "*.bin"
git lfs track "assets/models/*"

# 这会创建/更新 .gitattributes 文件
cat .gitattributes
*.psd filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
assets/models/* filter=lfs diff=lfs merge=lfs -text

# 提交 .gitattributes
git add .gitattributes
git commit -m "chore: configure Git LFS"

日常使用

bash
# 查看 LFS 管理的文件
git lfs ls-files
5d2a0cbf9e - design-v3.psd
8f94173c2a - video-demo.mp4
a1b2c3d4e5 - models/weights.bin

# 查看 LFS 文件的实际大小(不是指针大小)
git lfs ls-files --size

# 克隆一个有 LFS 文件的仓库(自动下载 LFS 文件)
git clone https://github.com/user/repo.git
# 如果 LFS 文件没自动下载:
git lfs pull

# 推送 LFS 文件
git add design.psd
git commit -m "feat: add design mockup"
git push origin main
# LFS 文件会自动上传到 LFS 服务器

# 切换分支后更新 LFS 文件
git checkout main
git lfs pull

迁移已有仓库到 LFS

bash
# 把已提交的大文件迁移到 LFS(重写历史!需要 force push)
git lfs migrate import --include="*.psd,*.zip,*.mp4" --everything

# ⚠️ 这会重写所有包含这些文件的提交
# 团队成员需要重新克隆仓库

# 更安全的方式:只迁移未来的文件,历史不动
git lfs track "*.psd"
git add .gitattributes
git commit -m "chore: track PSD files with LFS from now on"
# 历史中的 PSD 仍然占空间,但新文件走 LFS

⚠️ 注意: ⚠️ 注意事项:LFS 有免费额度(GitHub 1GB 存储 + 1GB/月带宽),超出需付费不要 track 文本文件(.js/.py/.json),LFS 会降低 diff 可读性团队所有人都要安装git lfs,否则大文件会变成指针文件.gitattributes必须提交到仓库