Skip to content

Commit 172b642

Browse files
Clemens Buchachergitster
authored andcommitted
do not overwrite untracked during merge from unborn branch
In case HEAD does not point to a valid commit yet, merge is implemented as a hard reset. This will cause untracked files to be overwritten. Instead, assume the empty tree for HEAD and do a regular merge. An untracked file will cause the merge to abort and do nothing. If no conflicting files are present, the merge will have the same effect as a hard reset. Signed-off-by: Clemens Buchacher <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 2caf20c commit 172b642

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

builtin/merge.c

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,24 @@ static void save_state(void)
231231
die("not a valid object: %s", buffer.buf);
232232
}
233233

234+
static void read_empty(unsigned const char *sha1, int verbose)
235+
{
236+
int i = 0;
237+
const char *args[7];
238+
239+
args[i++] = "read-tree";
240+
if (verbose)
241+
args[i++] = "-v";
242+
args[i++] = "-m";
243+
args[i++] = "-u";
244+
args[i++] = EMPTY_TREE_SHA1_HEX;
245+
args[i++] = sha1_to_hex(sha1);
246+
args[i] = NULL;
247+
248+
if (run_command_v_opt(args, RUN_GIT_CMD))
249+
die("read-tree failed");
250+
}
251+
234252
static void reset_hard(unsigned const char *sha1, int verbose)
235253
{
236254
int i = 0;
@@ -979,7 +997,7 @@ int cmd_merge(int argc, const char **argv, const char *prefix)
979997
die("%s - not something we can merge", argv[0]);
980998
update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
981999
DIE_ON_ERR);
982-
reset_hard(remote_head->sha1, 0);
1000+
read_empty(remote_head->sha1, 0);
9831001
return 0;
9841002
} else {
9851003
struct strbuf merge_names = STRBUF_INIT;

t/t7607-merge-overwrite.sh

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,20 @@ test_expect_success 'will not overwrite removed file with staged changes' '
8484
test_cmp important c1.c
8585
'
8686

87+
cat >expect <<\EOF
88+
error: Untracked working tree file 'c0.c' would be overwritten by merge.
89+
fatal: read-tree failed
90+
EOF
91+
92+
test_expect_success 'will not overwrite untracked file on unborn branch' '
93+
git reset --hard c0 &&
94+
git rm -fr . &&
95+
git checkout --orphan new &&
96+
cp important c0.c &&
97+
test_must_fail git merge c0 2>out &&
98+
test_cmp out expect &&
99+
test_path_is_missing .git/MERGE_HEAD &&
100+
test_cmp important c0.c
101+
'
102+
87103
test_done

0 commit comments

Comments
 (0)