本文标题:《用 git-filter-repo 拆分仓库历史》。

镜像链接:https://www.wdssmq.com/post/20221027545.html

有时需要把一个大仓库中的插件或子目录拆出来,作为独立仓库继续维护。git-filter-repo 可以筛选历史记录中的指定路径,并按需保留、改写或移除目录层级。

有时需要把一个大仓库中的插件或子目录拆出来,作为独立仓库继续维护。git-filter-repo 可以筛选历史记录中的指定路径,并按需保留、改写或移除目录层级。

安装 git-filter-repo

仓库如下,怎么安装问 AI 吧,这篇文章也是 AI 整理的……

newren/git-filter-repo: Quickly rewrite git repository history (filter-branch replacement)

https://github.com/newren/git-filter-repo

提取目录并调整路径

先设置插件名并克隆核心仓库,再按需求选择一种过滤方式执行。以下示例会把插件目录放到仓库根目录下的同名目录;其他两种方式请替换最后的过滤命令,不要连续执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PLUGIN_NAME="Gravatar"
git clone [email protected]:zblogcn/zblogphp.git "zbp_${PLUGIN_NAME}"
cd "zbp_${PLUGIN_NAME}"

# 筛选插件目录,并将它移动到新仓库根目录下的同名目录
git filter-repo \
--path "zb_users/plugin/${PLUGIN_NAME}/" \
--path-rename "zb_users/plugin/${PLUGIN_NAME}/:${PLUGIN_NAME}/"

# 只筛选路径并保留原目录层级时,改用:
# git filter-repo --path "zb_users/plugin/${PLUGIN_NAME}/"

# 让插件目录本身成为新仓库根目录时,改用:
# git filter-repo --subdirectory-filter "zb_users/plugin/${PLUGIN_NAME}"

从多个目录组合仓库

也可以同时筛选多个目录,并分别调整它们在新仓库中的路径。下面会把三个插件目录放到新仓库根目录下:

1
2
3
4
5
6
7
8
git filter-repo \
--path zb_users/plugin/UEditor/ \
--path zb_users/plugin/LinksManage/ \
--path zb_users/plugin/STACentre/ \
--path-rename zb_users/plugin/UEditor/:UEditor/ \
--path-rename zb_users/plugin/LinksManage/:LinksManage/ \
--path-rename zb_users/plugin/STACentre/:STACentre/

批量创建并推送 GitHub 仓库

我这边把原来塞一个仓库的 Z-BlogPHP 插件进行了拆分,每个插件都单独成为一个独立的 Git 仓库,发布操作就可以通过 GitHub CLI(gh)自动完成。

  • 需要先安装并登录:GitHub CLI
  • 以下命令会遍历 output 目录下的一级子目录,为尚未设置远程仓库的 Git 仓库创建 GitHub 仓库并推送;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
cd /path/git-pick/output

find . -mindepth 1 -maxdepth 1 -type d -print0 |
while IFS= read -r -d '' dir; do
if ! git -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
printf '跳过(不是 Git 仓库):%s\n' "$dir"
continue
fi

if [ -n "$(git -C "$dir" remote)" ]; then
printf '跳过(已有 remote):%s\n' "$dir"
continue
fi

repository_name="${dir#./}"
printf '创建并推送:%s\n' "$repository_name"

(
cd "$dir" &&
gh repo create "$repository_name" --public --source=. --remote=origin --push
)

sleep 3
done

拆分插件用的脚本

姑且也贴一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/bash

readonly OUTPUT_PATH="./output"
readonly REPOSITORY_URL="原仓库地址"
readonly PLUGIN_PREFIX="zbp_"

# 定义函数来处理主要逻辑
process_plugin() {
local PLUGIN_NAME="$1"
if [ -z "$PLUGIN_NAME" ]; then
echo "用法: $0 <插件名>" >&2
return 2
fi

local NEW_DIR="${PLUGIN_PREFIX}${PLUGIN_NAME}"

cd "$OUTPUT_PATH"

# 判断 ${PLUGIN_NAME} 是否存在
if [ -d "$NEW_DIR" ]; then
echo "目录 $NEW_DIR 已存在,跳过处理"
return 1
fi

echo "开始处理 $NEW_DIR..."
git clone "$REPOSITORY_URL" "$NEW_DIR"
cd "$NEW_DIR"

git filter-repo \
--force \
--path "${PLUGIN_NAME}"

echo "处理完成 ${PLUGIN_NAME}"
}

# 调用函数
process_plugin "$1"