创建 git 存储库并将本地目录推送到新初始化的 Azure 存储库

Creating git repo and pushing local directory to freshly initialized Azure Repos

我创建了本地 git 存储库。 (git 初始化,git 添加,git 提交)。然后我在 Azure DevOps 上创建了 git 存储库。 我也在本地执行git remote add origin <azure_repo_url>

现在当我尝试 git push origin master 我回来了:

To azure_repo_url
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'azure_repo_url'
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.

所以我先尝试 pullgit pull origin master 但又回来了:

$ git pull origin master
warning: no common commits
remote: Azure Repos
remote: We noticed you're using an older version of Git. For the best experience, upgrade to a newer version.
remote: Found 3 objects to send. (27 ms)
Unpacking objects: 100% (3/3), done.
From azure_repo_url
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> origin/master
fatal: refusing to merge unrelated histories

我可以通过git pull origin master --allow-unrelated-histories从这里so解决, 但我想知道是否有更清洁的方法来做到这一点?

当您在 Azure DevOps 上创建新的存储库时,您可以选择对其进行初始化,或将其保留。初始化存储库时,Azure DevOps 添加一个 .gitIgnore 和一个 readme.md.

这通常是您看到的 push/pull 问题的原因。

最简单的解决方法是:

git remote add origin <azure_repo_url>
git fetch origin
git rebase master --onto origin/master
... fix any merge conflicts ...
git push origin master

或:

git remote add origin <azure_repo_url>
git pull --rebase
... fix any merge conflicts ...
git push origin master

最终结果是您最终得到本地更改 生成的忽略和自述文件。如果遥控器上有更多更改,您可能需要执行更高级的合并版本,但在遥控器干净的情况下,应该这样做。