我想将本地存储库与远程存储库同步,以便本地存储库成为远程存储库的100%副本——这意味着如果这些存储库中的某些文件不同,我们将用远程存储库覆盖本地存储库,如果本地存储库中的文件在远程存储库中不存在,则本地文件将被删除。

除了重新克隆远程存储库之外,还有什么方法可以实现这一点吗?

类似的问题是一次性将本地git回购与远程同步,丢弃本地更改/提交。


当前回答

(此信息来自Git用户手册)

我也在学习,所以这可能不是问题的确切答案,但它可能会帮助一些人:

When a remote repository is initially cloned copies of all branches are stored in your local repository (view them with git branch -r) To update these copies and make them current (i.e. sync them with the remote branch) use git fetch. This will not effect any of you existing, custom created branches. To override your local branch checkout a fresh version of whatever branch you are working on (Assuming that you have already executed git add origin /path/to/repository) use git checkout origin/branch_name, this will override your locals changes on branch branch_name

其他回答

你可以使用git钩子。只需创建一个钩子,在更新后将更改推到另一个回购。

当然,您可能会遇到合并冲突,因此您必须弄清楚如何处理它们。

重置本地存储库并将其与远程分支同步

命令: 请记住用您想要同步的远程和分支来替换原点和主节点。

git fetch origin && git reset --hard origin/master && git clean -f -d

还是一步一步:

git fetch origin
git reset --hard origin/master
git clean -f -d

您的本地分支现在是远程分支的精确副本(提交和全部)。

命令输出:

下面是在Forge git存储库的本地克隆上运行该命令的示例。

sharkbook:forge lbaxter$ git fetch origin && git reset --hard origin/master && git clean -f -d
HEAD is now at 356cd85 FORGE-680
Removing forge-example-plugin/
Removing plugin-container-api/
Removing plugin-container/
Removing shell/.forge_settings
sharkbook:forge lbaxter$

这个脚本将检查哪些本地远程不存在于您的远程并将它们从本地删除

git fetch --prune; git branch -vv | egrep -v "(\[origin\/[a-zA-Z0-9/_-]+\])" | awk "{print \$1}" | xargs git branch -D

如果你想在远程上创建一个新的分支来镜像和跟踪你的本地分支(反之亦然),永久的修复方法是:

git config --global push.default current

在我克隆git之后,我总是用这个命令配置我的本地git。尽管它可以在本地-远程分支“Git fatal: the current branch has no upstream branch”错误发生时随时应用。

如果你正在谈论同步一个分叉回购,那么你可以按照这些步骤。

如何从git同步一个fork存储库

check your current git branch git branch checkout to master if you are not on master git checkout master Fetch the upstream repository if you have correct access rights git fetch upstream If you are getting below error then run git remote add upstream git@github.com:upstream_clone_repo_url/xyz.git fatal: 'upstream/master' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Now run the below command. git fetch upstream Now if you are on master then merge the upstream/master into master branch git merge upstream/master That's it!! Crosscheck via git remote command, more specific git remote -v If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.