git - 当我的本地存储库中只有项目的一个子目录时,是否可以推送 Git?

标签 git

我有一个本地 git 存储库,配置为通过 Gitlab 上的 SSH 远程连接(我们称它为 git@gitlab.com:myrepo/myproject.git),在克隆我喜欢保留的存储库之后只有本地项目的特定文件夹,我使用命令执行此操作:

git filter-branch --prune-empty --subdirectory-filter subdirectory HEAD~..

此命令使本地存储库跟踪远程 git 项目上的 子目录 文件夹(并忽略我项目中此文件夹之前的所有文件)。只要我只将它用于 pull 它就可以了......问题是如果我尝试将更改推送到该远程分支,如果我尝试我会看到以下错误:

$ git push -u origin master
To git@gitlab.com:myrepo/myproject.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'git@gitlab.com:myrepo/myproject.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 push --help 上没有找到任何关于这个特定案例的信息。当我的本地存储库中只有该项目的一个子文件夹时,有人知道是否可以在远程文件夹上推送吗?

最佳答案

git push 推送完整历史;您正在做的是子树 merge 。 Git 可以做到这一点,将您的过滤器分支从 HEAD 更改为 HEAD~.. 不重写整个历史记录,然后您可以

git checkout origin/master
git merge -s subtree master
git push origin HEAD:master

保留 merge 基础的任何其他过滤器分支截断都可以,这完全取决于您真正想要在本地重写的程度。


如果完整原始快照的 check out 非常痛苦,您甚至不想通过它们进行检查,即使您可以通过一些轻微的欺骗来避免不必要的工作树变动。

为草稿工作创建一个极轻的克隆并切换到它:

git branch -tf mergeback origin/master
git clone -nsb mergeback -o local . `mktemp -d`
cd $_

请注意,以这种方式完成的整个 linux 存储库的克隆在我的盒子上使用了 320KB(这不是打字错误)。然后,您可以进行最小 checkout merge :

git reset --quiet                    # load just the index, not the worktree
git merge -s subtree local/master    # merge my master branch into the right subtree
git push local mergeback             # push the results back to the main repo
cd -                                 # back to my repo

然后您可以从那里 git push origin mergeback:master 将结果推送到 gitlab。

编辑:除了使用 filter-branch 重写提交,您还可以在新提交中提升子树:git read-tree -um @:path/to/subdir; git commit,这样 merge 就不会引入现有提交的邪恶双胞胎。

关于git - 当我的本地存储库中只有项目的一个子目录时,是否可以推送 Git?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57739895/

相关文章:

git - 如何修改别人的Github pull request?

我的存储库中的 Django Rest 框架和南部迁移 - 如何正确设置?

git checkout 新分支

reactjs - 从私有(private) gitlab 存储库中使用 npm 安装依赖项

git - 致命的 : This operation must be run in a work tree

VS Code 中的 Git stash 无法存储

git - 有没有办法从 "repository.git"恢复文件

git - 获取 "git push"的默认上游远程和分支

git - 从在线 VSTS 进程或组变量填充本地 VSTS Linux 代理上的 terraform.tfvars 文件中的变量

git - 如何将本地机器上的代码推送到主分支中的 GitHub