如何将特定文件仅推送到单个Git远程仓库?
解决方法
针对你的需求(让secondary仓库保留.forgejo/目录,同时禁止推送到primary仓库),可以采用以下几种实用方案:
方案一:推送时临时过滤目标目录
Git支持在推送时通过--filter参数临时移除指定目录的内容,不会修改本地提交,非常适合你的场景:
直接使用带过滤的推送命令:
git push primary develop --filter=tree:0:.forgejo/这个命令会在推送到primary时,临时从提交中剔除
.forgejo/目录,而本地和推送到secondary的提交依然保留该目录。为了简化操作,添加Git别名:
git config alias.push-primary 'push primary develop --filter=tree:0:.forgejo/'之后只需执行
git push-primary即可完成对primary的过滤推送。
方案二:一键推送两个远程(自动区分过滤规则)
调整你的Git配置,移除origin的多pushurl,分别管理两个远程,再用别名实现一键推送:
修改
.git/config为如下内容(清理冗余配置):[remote "primary"] url = ssh://git@git.primary.com/projectname/android.git fetch = +refs/heads/*:refs/remotes/primary/* [remote "secondary"] url = git@git.secondary.com:projectname/android.git fetch = +refs/heads/*:refs/remotes/secondary/* [branch "develop"] remote = primary merge = refs/heads/develop添加一键推送的别名:
git config alias.push-all '!git push secondary develop && git push primary develop --filter=tree:0:.forgejo/'执行
git push-all时,会先将完整的提交推送到secondary,再将过滤掉.forgejo/的版本推送到primary,一次操作完成两个远程的同步。
方案三:独立分支管理私有文件
如果需要长期维护私有文件的独立提交历史,可以创建专门的分支:
基于
develop创建本地私有分支:git checkout -b develop-local develop在
develop-local分支添加.forgejo/目录的文件并提交:git add .forgejo/ git commit -m "Add Forgejo automation files"推送分支到secondary:
git push secondary develop-local:develop(如果希望secondary的
develop分支始终包含私有文件,用上面的命令覆盖;也可以保留develop-local作为独立分支)推送到primary时,切换回干净的
develop分支推送:git checkout develop git push primary develop同步primary的更新时,在
develop分支拉取后合并到develop-local:git checkout develop git pull primary develop git checkout develop-local git merge develop
内容的提问来源于stack exchange,提问作者Tauri
相关产品推荐
相关产品推荐

