原本是将 PAM 的“开发”文件放在一个大的集合仓库下的其中一个文件夹里面的,今天觉得这样有些不妥,遂决定将其保留提交记录的前提下单独创建一个 git 仓库。
将子文件夹拆分为新存储库
通过此方法可以将子文件夹拆分为新存储库,将文件夹拆分为单独的仓库时不会丢失任何 Git 历史记录或更改。
需要 Git 版本 2.22.0 或更高版本才能按照这些说明进行操作,否则
git filter-repo将不起作用。
但是,请注意,新存储库不会具有原始存储库的分支和标记。
- 打开终端终端Git Bash。
- 将当前工作目录切换到您要创建新仓库的目录位置。
- 克隆包含该子文件夹的仓库。
git clone https://github.com/USERNAME/REPOSITORY-NAME
- 将当前工作目录切换到克隆的存储库。
cd REPOSITORY-NAME
- 若要从存储库中的其余文件中筛选出子文件夹,请安装
git-filter-repo,然后使用以下参数运行git filter-repo。FOLDER-NAME:项目中要在其中创建单独存储库的文件夹。
Windows用户应使用
/分隔文件夹。$ git filter-repo --path FOLDER-NAME/ # Filter the specified branch in your directory and remove empty commits
现在,该仓库应仅包含您的子文件夹中的文件。
如果希望将某个特定子文件夹用作新存储库的新根文件夹,可使用以下命令:$ git filter-repo --subdirectory-filter FOLDER-NAME # Filter the specific branch by using a single sub-directory as the root for the new repository
- 创建新存储库。
- 复制新的存储库远程 URL
- 使用您为仓库复制的 URL 来新增远程名称。 例如:
origin或upstream是两个常见的选项。git remote add origin https://github.com/USERNAME/REPOSITORY-NAME.git
- 用新的存储库名称验证是否已添加远程 URL。
$ git remote -v # Verify new remote URL > origin https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (fetch) > origin https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (push)
- 将更改推送到 GitHub 上的新存储库。
git push -u origin BRANCH-NAME
推送失败
错误日志
将切分出文件夹做新的仓库后推送时遇到以下问题:
error: failed to push some refs to 'https://git.cyzwb.com/xxx/Linux-PAM-Login-2FA.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
解决
- 先执行
git pull origin master --rebase拉取最新版本:From https://git.cyzwb.com/xxx/Linux-PAM-Login-2FA * branch master -> FETCH_HEAD Successfully rebased and updated refs/heads/master.
- 再执行
git push -u origin master推送:Enumerating objects: 259, done. Counting objects: 100% (259/259), done. Compressing objects: 100% (182/182), done. Writing objects: 100% (258/258), 42.56 KiB | 3.27 MiB/s, done. Total 258 (delta 152), reused 92 (delta 71), pack-reused 0 remote: Resolving deltas: 100% (152/152), done. To https://git.cyzwb.com/xxx/Linux-PAM-Login-2FA.git 9115e25..8a23e1c master -> master branch 'master' set up to track 'origin/master'.
当然操作前还是备份备份备份比较稳妥!
参考
- 将子文件夹拆分为新存储库
https://docs.github.com/zh/get-started/using-git/splitting-a-subfolder-out-into-a-new-repository - Quickly rewrite git repository history (filter-branch replacement)
https://github.com/newren/git-filter-repo - Git 推送失败解决教程——error: failed to push some refs to – 教程
https://www.cnblogs.com/yfceshi/p/18999257
ChiuYut
2026年05月14日