fatal: refusing to merge unrelated histories 解决方案

问题描述

当本地分支与远程分支没有共同祖先时,会出现 fatal: refusing to merge unrelated histories 的问题。

解决方案

可以使用 rebase 的方式来进行合并。

git pull --rebase origin master

实例验证

可以通过一个小实验来体会一下:

cd
mkdir rebaseTmp
cd rebaseTmp
echo "hello a line" > tmp.txt
git init
git add .
git commit -m "Local first commit"
git remote add origin  https://github.com/HustLion/java_console_log4j.git
git pull --rebase origin master

得到的结果:

warning: no common commits
remote: Counting objects: 32, done.
remote: Compressing objects: 100% (21/21), done.
remote: Total 32 (delta 3), reused 28 (delta 2), pack-reused 0
Unpacking objects: 100% (32/32), done.
From https://github.com/HustLion/java_console_log4j
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> origin/master
First, rewinding head to replay your work on top of it...
Applying: Local first commit

此时文件结构是:

.
├── LICENSE
├── README.md
├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       ├── com
│   │       │   └── hustlion
│   │       │       └── java_console_log4j
│   │       │           └── App.java
│   │       └── log4j2.properties
│   └── test
│       └── java
│           └── com
│               └── hustlion
│                   └── java_console_log4j
│                       └── AppTest.java
└── tmp.txt

可以看到我们的本地 commit 带来的 tmp.txt 与远程项目通过 rebase 很好地合并在了一起。

参考

  • Git没有共同祖先的两个分支如何合并?
  • git无法pull仓库refusing to merge unrelated histories
  • https://stackoverflow.com/a/41765529/4394850

你可能感兴趣的:(Linux)