手动创建git之类的标记,并与diff冲突

时间:2018-10-02 18:08:56

标签: git

发生git merge冲突时,会出现类似以下的标记:

<<<<<<< HEAD:file.txt
Hello world
=======
Goodbye
>>>>>>> master:file.txt

想象一下我是否有file.txt,然后从中手动编辑

Hello world

Goodbye

当我执行git diff(使用默认的分页器)时,我得到以下信息:

diff --git a/file.txt b/file.txt
index 802992c..2b60207 100644
--- a/file.txt
+++ b/file.txt
@@ -1 +1 @@
-Hello world
+Goodbye

有没有一种方法可以将这种格式转换为上面给出的所有更改都带有冲突标记的格式? (是否覆盖文件无关紧要。)

1 个答案:

答案 0 :(得分:1)

这是一种方法-以下命令将打开一个如下所示的差异:

diff --git a/file.txt b/file.txt
index 2b34ae8..a27a6bd 100644
--- a/file.txt
+++ b/file.txt
@@ -1,16 +1,16 @@
 Line 1
+Addition here
 Line 2
 Line 3
 Line 4
 Line 5
 Line 6
 Line 7
-Line 8
+Line 8 Change here, and deletion on line 15
 Line 9
 Line 10
 Line 11
 Line 12
 Line 13
 Line 14
-Line 15
 Line 16

放入一个看起来像这样的文件:

Line 1
<<<<<<< HEAD
=======
Addition here
>>>>>>> temp
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
<<<<<<< HEAD
Line 8
=======
Line 8 Change here, and deletion on line 15
>>>>>>> temp
Line 9
Line 10
Line 11
Line 12
Line 13
Line 14
<<<<<<< HEAD
Line 15
=======
>>>>>>> temp
Line 16

命令和说明如下:

branch=$(git symbolic-ref --short HEAD)                # Get the current branch name
git checkout --orphan temp                             # Change to a branch with no parents, so to force a merge conflict
git add -A                                             # Add everything there
git commit -m 'temp'                                   # Commit
git checkout "$branch"                                 # Go back to your previous branch
(git merge --allow-unrelated-histories temp || true)   # Merge the unrelated branches, which causes a conflict with your changes. This is done in a subshell with the '|| true' so that it doesn't return an error code - I have this in a git alias, so this is necessary for me so the command isn't aborted halfway.
git add -A                                             # Add your conflict markers as additions to the file
GIT_EDITOR=true git merge --continue                   # Commit. When --continue is used it doesn't accept the flag --no-edit, so to stop git opening an editor for the commit message, use the command 'true' as the editor.
git reset HEAD^                                        # Get rid of the last commit but keep its changes (the markers). This is needed because there is no way to get out of a conflicting merge commit but keep the conflict markers.
git b -D temp                                          # Clean up

您当然可以使用此脚本或别名。请注意,它会将暂存的更改和未暂存的更改视为相同。