单分支维护
Dionysen

单分支获取仓库

如果需要跨平台,但仓库很大,应对磁盘不足的情况,可以只在一个平台上处理分支的合并,在其他平台上只处理单分支的拉取和提交,这样能大大减少磁盘占用。

  • 拉取单分支
git clone --depth=1 --single-branch --branch main ssh://git@***.git
  • 如果有submodule
git submodule update --init --recursive --depth=1
  • 新建分支 - 照常进行

提升为完整分支

补全提交:

git fetch --unshallow

只补全某个分支:

git fetch --depth=1000

接触单分支限制:

git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch

切换分支

如果只想拉取另一个特定分支、不想把所有分支都拉下来,不需要解除单分支限制,直接拉取指定分支即可。

有两个方法:

直接关联远程分支

git fetch --depth=1 origin dev:refs/remotes/origin/dev
git switch dev

为了之后 git fetch / git pull 能自动更新新分支,把它加入映射(仍是单分支模式):

git config --add remote.origin.fetch "+refs/heads/dev:refs/remotes/origin/dev"

直接Fetch

  • 直接 fetch 时不写 :refs/remotes/origin/<分支>,结果只会存进临时引用 FETCH_HEAD,git switch 会报 invalid reference。此时对象已在本地,不必重新拉取,直接补上:
git fetch --depth=1 origin dev
git switch -c dev FETCH_HEAD
git config --add remote.origin.fetch "+refs/heads/dev:refs/remotes/origin/dev"

Note

  • --depth=1 让新分支保持浅克隆(只拉最新 1 层提交)。不加 --depth 时新分支会在原来的浅边界处截断,若与旧分支分歧较大,会意外拉下不少历史。
  • 日常提交、切换够用;如需 merge/rebase,再 git fetch --unshallow 补全历史。
  • 想省磁盘,可以删除旧分支的本地引用:git branch -dr origin/<旧分支>,然后 git gc。

后续拉取

如果远端有更新:

子模块

有 submodule 时,切分支后依然重新浅更新:

git submodule update --init --recursive --depth=1

若报找不到对应提交(浅克隆按 SHA 拉取失败),先补全子仓库:

git submodule foreach 'git fetch --unshallow'
git submodule update --init --recursive
显示评论