Skip to contentSkip to conversation

git add --resolved

PATCH Superseded Junio C Hamano 3 participants 30 messages Jul 28 – Aug 3

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover git add --resolved

When you are the maintainer of a project and make many merges day in, day out, a lot of your time is spent resolving conflicts and adding the results to the index. It is not unusual to have local changes in your working tree that are unrelated to any particular merge [*]. In such cases, 'git add -u', which adds all changes in the working tree to the index, does not help much.

Here is a new option for 'git add' that lets you add paths with resolved conflicts to the index, while keeping unrelated local changes out.

The first two patches perform preliminary refactorings.

- [1/4] consolidates a helper function to determine whether a line is a conflict marker (replacing two slightly different definitions).

- [2/4] introduces a helper that makes registering path removals from the index as easy as adding them, complete with automatic '--dry-run' and '--verbose' support.

The third patch implements the new feature.

The fourth patch is a totally unrelated code cleanup that almost disappears when viewed with 'git show -w'.

1/4: merge-ll: consolidate conflict marker scanning logic 2/4: read-cache: add remove_file_from_index_with_flags() 3/4: add: introduce '--resolved' option
4/4: read-cache: reindent

[Footnote]

* This is not limited to my own workflow. An earlier message on this topic worth mentioning is:

https://lore.kernel.org/git/CA+55aFxP8j7YbYaRXt-8Y0n8cHafB=FPKMy8gKFYH5QsKX4S=Q@mail.gmail.com/

 Documentation/git-add.adoc |  10 +++-
 builtin/add.c              |  92 ++++++++++++++++++++++++++++---
 diff.c                     |  25 +--------
 merge-ll.c                 |  53 ++++++++++++++++++
 merge-ll.h                 |   2 +
 read-cache-ll.h            |   3 ++
 read-cache.c               |  89 +++++++++++++++++-------------
 rerere.c                   |  38 +++----------
 t/t2207-add-resolved.sh    | 108 +++++++++++++++++++++++++++++++++++++
 9 files changed, 319 insertions(+), 101 deletions(-)
 create mode 100755 t/t2207-add-resolved.sh
Signature · 1 line
2.55.0-594-g42d2bf033e
#1 lore raw

PATCH 1/4 merge-ll: consolidate conflict marker scanning logic

The diff.c:is_conflict_marker() and rerere.c:is_cmarker() functions implement duplicate logic for identifying conflict marker lines (lines that begin with a run of '<', '=', '>', and '|' characters).

diff.c's original version from 049540435f (diff --check: detect leftover conflict markers, 2008-06-26) accepts any whitespace (such as a newline) immediately following '<<<<<<<' and '>>>>>>>', whereas rerere.c's version from 191f241717 (rerere: prepare for customizable conflict marker length, 2010-01-16) strictly requires a space character (' ') after them.

Implement is_conflict_marker_line() in merge-ll.c to serve as a replacement for both, and update diff.c and rerere.c to use the new helper. The unified helper intentionally adopts rerere's stricter rule, as the conflicts generated by Git always show the "ours" and "theirs" labels after these markers separated by a space.

---
 diff.c     | 25 +------------------------
 merge-ll.c | 31 +++++++++++++++++++++++++++++++
 merge-ll.h |  1 +
 rerere.c   | 38 ++++++--------------------------------
 4 files changed, 39 insertions(+), 56 deletions(-)
diff.c +1 -24
index 589c1969e4..cfe515af4e 100644
@@ -3519,29 +3519,6 @@ struct checkdiff_t {
 	int last_line_kind;
 };
 
-static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
-{
-	char firstchar;
-	int cnt;
-
-	if (len < marker_size + 1)
-		return 0;
-	firstchar = line[0];
-	switch (firstchar) {
-	case '=': case '>': case '<': case '|':
-		break;
-	default:
-		return 0;
-	}
-	for (cnt = 1; cnt < marker_size; cnt++)
-		if (line[cnt] != firstchar)
-			return 0;
-	/* line[1] through line[marker_size-1] are same as firstchar */
-	if (len < marker_size + 1 || !isspace(line[marker_size]))
-		return 0;
-	return 1;
-}
-
 static void checkdiff_consume_hunk(void *priv,
 				   long ob UNUSED, long on UNUSED,
 				   long nb, long nn UNUSED,
@@ -3571,7 +3548,7 @@ static int checkdiff_consume(void *priv, char *line, unsigned long len)
 	if (line[0] == '+') {
 		unsigned bad;
 		data->lineno++;
-		if (is_conflict_marker(line + 1, marker_size, len - 1)) {
+		if (is_conflict_marker_line(line + 1, len - 1, marker_size)) {
 			data->status |= 1;
 			fprintf(data->o->file,
 				"%s%s:%d: leftover conflict marker\n",
merge-ll.c +31 -0
index fafe2c9197..41c97fb90a 100644
@@ -468,3 +468,34 @@ int ll_merge_marker_size(struct index_state *istate, const char *path)
 	}
 	return marker_size;
 }
+
+int is_conflict_marker_line(const char *line, unsigned long len, int marker_size)
+{
+	char firstchar;
+	int cnt;
+
+	if (len < marker_size + 1)
+		return 0;
+
+	firstchar = line[0];
+	switch (firstchar) {
+	case '=': case '>': case '<': case '|':
+		break;
+	default:
+		return 0;
+	}
+
+	for (cnt = 1; cnt < marker_size; cnt++) {
+		if (line[cnt] != firstchar)
+			return 0;
+	}
+
+	if (((firstchar == '<') || (firstchar == '>')) &&
+	    line[marker_size] != ' ')
+		return 0;
+
+	if (!isspace((unsigned char)line[marker_size]))
+		return 0;
+
+	return firstchar;
+}
merge-ll.h +1 -0
index d038ee0c1e..b348aee15d 100644
@@ -109,6 +109,7 @@ enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
 	     const struct ll_merge_options *opts);
 
 int ll_merge_marker_size(struct index_state *istate, const char *path);
+int is_conflict_marker_line(const char *line, unsigned long len, int marker_size);
 void reset_merge_attributes(void);
 
 #endif
rerere.c +6 -32
index 1dda246098..4b05850479 100644
@@ -331,33 +331,6 @@ static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
 	return strbuf_getwholeline(sb, io->input, '\n');
 }
 
-/*
- * Require the exact number of conflict marker letters, no more, no
- * less, followed by SP or any whitespace
- * (including LF).
- */
-static int is_cmarker(char *buf, int marker_char, int marker_size)
-{
-	int want_sp;
-
-	/*
-	 * The beginning of our version and the end of their version
-	 * always are labeled like "<<<<< ours" or ">>>>> theirs",
-	 * hence we set want_sp for them.  Note that the version from
-	 * the common ancestor in diff3-style output is not always
-	 * labelled (e.g. "||||| common" is often seen but "|||||"
-	 * alone is also valid), so we do not set want_sp.
-	 */
-	want_sp = (marker_char == '<') || (marker_char == '>');
-
-	while (marker_size--)
-		if (*buf++ != marker_char)
-			return 0;
-	if (want_sp && *buf != ' ')
-		return 0;
-	return isspace(*buf);
-}
-
 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
 {
 	strbuf_addchars(buf, ch, size);
@@ -375,7 +348,8 @@ static int handle_conflict(struct strbuf *out, struct rerere_io *io,
 	int has_conflicts = -1;
 
 	while (!io->getline(&buf, io)) {
-		if (is_cmarker(buf.buf, '<', marker_size)) {
+		int marker = is_conflict_marker_line(buf.buf, buf.len, marker_size);
+		if (marker == '<') {
 			if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
 				break;
 			if (hunk == RR_SIDE_1)
@@ -383,15 +357,15 @@ static int handle_conflict(struct strbuf *out, struct rerere_io *io,
 			else
 				strbuf_addbuf(&two, &conflict);
 			strbuf_release(&conflict);
-		} else if (is_cmarker(buf.buf, '|', marker_size)) {
+		} else if (marker == '|') {
 			if (hunk != RR_SIDE_1)
 				break;
 			hunk = RR_ORIGINAL;
-		} else if (is_cmarker(buf.buf, '=', marker_size)) {
+		} else if (marker == '=') {
 			if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
 				break;
 			hunk = RR_SIDE_2;
-		} else if (is_cmarker(buf.buf, '>', marker_size)) {
+		} else if (marker == '>') {
 			if (hunk != RR_SIDE_2)
 				break;
 			if (strbuf_cmp(&one, &two) > 0)
@@ -442,7 +416,7 @@ static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_siz
 		git_hash_init(&ctx, the_hash_algo);
 
 	while (!io->getline(&buf, io)) {
-		if (is_cmarker(buf.buf, '<', marker_size)) {
+		if (is_conflict_marker_line(buf.buf, buf.len, marker_size) == '<') {
 			has_conflicts = handle_conflict(&out, io, marker_size,
 							hash ? &ctx : NULL);
 			if (has_conflicts < 0)
Signature · 1 line
2.55.0-594-g42d2bf033e
#2 lore raw

PATCH 2/4 read-cache: add remove_file_from_index_with_flags()

In reply to Junio C Hamano

add_file_to_index() takes flags such as ADD_CACHE_PRETEND and ADD_CACHE_VERBOSE and internally handles both reporting (e.g., "add 'path'") and suppressing index updates during dry runs.

In contrast, remove_file_from_index() takes only istate and path without flags. Callers that perform file removals (such as update_callback() in read-cache.c) are forced to manually inspect ADD_CACHE_PRETEND and ADD_CACHE_VERBOSE flags for removed files.

Introduce remove_file_from_index_with_flags() to encapsulate pretend mode and verbose reporting for index removals. Update update_callback() to use the new helper.

---
 read-cache-ll.h |  3 +++
 read-cache.c    | 19 +++++++++++++++----
 2 files changed, 18 insertions(+), 4 deletions(-)
read-cache-ll.h +3 -0
index 71b87615eb..8eb266cfd1 100644
@@ -391,11 +391,14 @@ int remove_index_entry_at(struct index_state *, int pos);
 
 void remove_marked_cache_entries(struct index_state *istate, int invalidate);
 int remove_file_from_index(struct index_state *, const char *path);
+int remove_file_from_index_with_flags(struct index_state *, const char *, int);
+
 #define ADD_CACHE_VERBOSE 1
 #define ADD_CACHE_PRETEND 2
 #define ADD_CACHE_IGNORE_ERRORS	4
 #define ADD_CACHE_IGNORE_REMOVAL 8
 #define ADD_CACHE_INTENT 16
+
 /*
  * These two are used to add the contents of the file at path
  * to the index, marking the working tree up-to-date by storing
read-cache.c +15 -4
index 38b55323dd..6fbab77225 100644
@@ -638,6 +638,20 @@ int remove_file_from_index(struct index_state *istate, const char *path)
 	return 0;
 }
 
+int remove_file_from_index_with_flags(struct index_state *istate,
+				      const char *path,
+				      int flags)
+{
+	int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
+	int pretend = flags & ADD_CACHE_PRETEND;
+
+	if (verbose)
+		printf(_("remove '%s'\n"), path);
+	if (pretend)
+		return 0;
+	return remove_file_from_index(istate, path);
+}
+
 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
 {
 	return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
@@ -4002,10 +4016,7 @@ static void update_callback(struct diff_queue_struct *q,
 		case DIFF_STATUS_DELETED:
 			if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
 				break;
-			if (!(data->flags & ADD_CACHE_PRETEND))
-				remove_file_from_index(data->index, path);
-			if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
-				printf(_("remove '%s'\n"), path);
+			remove_file_from_index_with_flags(data->index, path, data->flags);
 			break;
 		}
 	}
Signature · 1 line
2.55.0-594-g42d2bf033e
#3 lore raw

PATCH 3/4 add: introduce '--resolved' option

In reply to Junio C Hamano

During a conflicted merge, rebase, or cherry-pick, 'git add -u' is a handy way to add modified paths to the index. However, '-u' indiscriminately adds all modified tracked paths, including unmerged paths that may still contain unresolved conflict markers. It also adds tracked files modified in the worktree that are not involved in the ongoing merge.

The latter is not a huge problem for "git rebase", which refuses to start with any local changes, but is a problem for "git merge", which is often run with local changes in maintainer workflows.

Introduce 'git add --resolved' to add only unmerged paths, limited by an optional pathspec, where no conflict markers remain in the working tree.

Before modifying the index, scan unmerged regular files for leftover conflict markers using a new helper, has_conflict_markers(), defined in merge-ll.c in terms of the is_conflict_marker_line() helper we introduced earlier. If any unmerged path still contains conflict markers, show an error listing the conflicted paths and abort without updating the index. Otherwise, add these unmerged paths that do not have conflict markers to the index.

Note that unmerged paths without conflict markers (such as binary files and deletions) are added as resolved using add_file_to_index() and remove_file_from_index_with_flags(). Tracked files that were not in a conflicted state are ignored by '--resolved'.

---
 Documentation/git-add.adoc |  10 +++-
 builtin/add.c              |  92 ++++++++++++++++++++++++++++---
 merge-ll.c                 |  22 ++++++++
 merge-ll.h                 |   1 +
 t/t2207-add-resolved.sh    | 108 +++++++++++++++++++++++++++++++++++++
 5 files changed, 226 insertions(+), 7 deletions(-)
 create mode 100755 t/t2207-add-resolved.sh
Documentation/git-add.adoc +9 -1
index 941135dc63..16b06e38e1 100644
@@ -11,7 +11,7 @@ SYNOPSIS
 git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p]
 	[--edit | -e] [--[no-]all | -A | --[no-]ignore-removal | [--update | -u]] [--sparse]
 	[--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize]
-	[--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
+	[--resolved] [--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
 	[--] [<pathspec>...]
 
 DESCRIPTION
@@ -195,6 +195,14 @@ for `git add --no-all <pathspec>...`, i.e. ignored removed files.
 	while a _CRLF_ cleans to _LF_, a _CRCRLF_ sequence is only partially
 	cleaned to _CRLF_.
 
+`--resolved`::
+	Update the index for unmerged paths matching _<pathspec>_ where
+	no conflict markers remain in the working tree. Unmerged paths
+	without conflict markers (including binary files and file
+	deletions) are staged as resolved, while any path with leftover
+	conflict markers causes the command to refuse to stage any files.
+	Cannot be combined with `-u` or `-A`.
+
 `--chmod=(+|-)x`::
 	Override the executable bit of the added files.  The executable
 	bit is only changed in the index, the files on disk are left
builtin/add.c +86 -6

140 lines not on this page · raw message

merge-ll.c +22 -0
index 41c97fb90a..5e5044b9e3 100644
@@ -499,3 +499,25 @@ int is_conflict_marker_line(const char *line, unsigned long len, int marker_size
 
 	return firstchar;
 }
+
+int has_conflict_markers(struct index_state *istate, const char *path)
+{
+	FILE *f;
+	struct strbuf sb = STRBUF_INIT;
+	int marker_size = ll_merge_marker_size(istate, path);
+	int has_markers = 0;
+
+	f = fopen(path, "r");
+	if (!f)
+		return 0;
+
+	while (strbuf_getwholeline(&sb, f, '\n') != EOF) {
+		if (is_conflict_marker_line(sb.buf, sb.len, marker_size)) {
+			has_markers = 1;
+			break;
+		}
+	}
+	fclose(f);
+	strbuf_release(&sb);
+	return has_markers;
+}
merge-ll.h +1 -0
index b348aee15d..f26aef238d 100644
@@ -110,6 +110,7 @@ enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
 
 int ll_merge_marker_size(struct index_state *istate, const char *path);
 int is_conflict_marker_line(const char *line, unsigned long len, int marker_size);
+int has_conflict_markers(struct index_state *istate, const char *path);
 void reset_merge_attributes(void);
 
 #endif
t/t2207-add-resolved.sh new file +108 -0

108 lines not on this page · raw message

Signature · 1 line
2.55.0-594-g42d2bf033e
#4 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

builtin/add.c int cmd_add(int argc, · line 516

Quoted 7 lines · Junio C Hamano
builtin/add.c +3 -2
-       if (addremove && take_worktree_changes)
-               die(_("options '%s' and '%s' cannot be used together"), "-A", "-u");
+       die_for_incompatible_opt3(take_worktree_changes, "-u/--update",
+                                 0 <= addremove_explicit, "-A/--all",
+                                 add_resolved, "--resolved");

Should this be "0 < addremove_explicit"? I thought addremove_explicit being set to 0 indicates either --no-all or --ignore-removal (via ignore_removal_cb) was specified by the user. I think this causes "git add --resolved --no-all" to die naming "-A/--all" as the culprit even though the opposite flag was set. Also, it may cause "git add -u --ignore-removal" and "git add -u --no-all" to now die, whereas they were accepted before.

t/t2207-add-resolved.sh

Quoted 6 lines
t/t2207-add-resolved.sh new file +0 -0
new file mode 100755
index 0000000000..f88e3f413e

Does this new test file need a t/meson.build entry?

#5 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

Quoted 10 lines · Michael Montalbo

builtin/add.c int cmd_add(int argc, · line 516

Quoted 7 lines · Junio C Hamano
builtin/add.c +3 -2
-       if (addremove && take_worktree_changes)
-               die(_("options '%s' and '%s' cannot be used together"), "-A", "-u");
+       die_for_incompatible_opt3(take_worktree_changes, "-u/--update",
+                                 0 <= addremove_explicit, "-A/--all",
+                                 add_resolved, "--resolved");

Should this be "0 < addremove_explicit"?

Thanks for noticing. '0 <=' is absolutely bogus.

I wonder if we should simply write 'addremove', as this part of the change is about rewriting the open-coded die_for_incompatible_opt2() in the original and using die_for_incompatible_opt3() to add a third option.

Quoted 7 lines

t/t2207-add-resolved.sh

Quoted 5 lines
t/t2207-add-resolved.sh new file +0 -0
new file mode 100755
index 0000000000..f88e3f413e

Does this new test file need a t/meson.build entry?

Yeah, it shows that I rarely exercise meson build.

Thanks.

#6 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

Quoted 11 lines · Junio C Hamano
Quoted 9 lines · Michael Montalbo
Quoted 7 lines · Junio C Hamano
builtin/add.c +3 -2
-       if (addremove && take_worktree_changes)
-               die(_("options '%s' and '%s' cannot be used together"), "-A", "-u");
+       die_for_incompatible_opt3(take_worktree_changes, "-u/--update",
+                                 0 <= addremove_explicit, "-A/--all",
+                                 add_resolved, "--resolved");
Quoted 8 lines
Quoted 1 line

Should this be "0 < addremove_explicit"?

Thanks for noticing. '0 <=' is absolutely bogus.

I wonder if we should simply write 'addremove', as this part of the change is about rewriting the open-coded die_for_incompatible_opt2() in the original and using die_for_incompatible_opt3() to add a third option.

Not really. I forgot that addremove is futzed before this part when add_resolved is present, so using addremove would mean both addremove and add_resolved are on, mistakenly complaining about -A that the user never gave us.

So "0 < addremove_explicit" that is.

Quoted 12 lines
Quoted 8 lines

t/t2207-add-resolved.sh

Quoted 6 lines
t/t2207-add-resolved.sh new file +0 -0
new file mode 100755
index 0000000000..f88e3f413e

Does this new test file need a t/meson.build entry?

Yeah, it shows that I rarely exercise meson build.

Thanks.

#7 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

Quoted 11 lines · Junio C Hamano
Quoted 4 lines

I wonder if we should simply write 'addremove', as this part of the change is about rewriting the open-coded die_for_incompatible_opt2() in the original and using die_for_incompatible_opt3() to add a third option.

Not really. I forgot that addremove is futzed before this part when add_resolved is present, so using addremove would mean both addremove and add_resolved are on, mistakenly complaining about -A that the user never gave us.

So "0 < addremove_explicit" that is.

Well, this episode illustrates that the option parsing in "git add" is unnecessarily confusing, and I think the reason is because it conflates the presence of each command line option and the behaviour the program wants to exhibit into the same variable. addremove for example is about "removals are also recorded in the index", and that becomes effective primarily when "-A" option is given, but "-A" is not the only thing to turn it on.

Perhaps revamping the way the options are parsed so that the incompatible options are noticed upfront, and then deciding the behaviour based on the primary operating mode that was parsed by the ooption parser in a separate step might make things less confusing?

#8 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

In reply to Junio C Hamano
Quoted 12 lines · Junio C Hamano
(quoted diff) +12 -0
+
+int has_conflict_markers(struct index_state *istate, const char *path)
+{
+	FILE *f;
+	struct strbuf sb = STRBUF_INIT;
+	int marker_size = ll_merge_marker_size(istate, path);
+	int has_markers = 0;
+
+	f = fopen(path, "r");
+	if (!f)
+		return 0;
+

Review

Quoted 10 lines
(quoted diff) +10 -0
+	while (strbuf_getwholeline(&sb, f, '\n') != EOF) {
+		if (is_conflict_marker_line(sb.buf, sb.len, marker_size)) {
+			has_markers = 1;
+			break;
+		}
+	}
+	fclose(f);
+	strbuf_release(&sb);
+	return has_markers;
+}

Left unchecked, this loop may end up scanning a large binary file to the end in vain. We may squeeze in something like this to punt early.

 merge-ll.c | 3 +++
 1 file changed, 3 insertions(+)
merge-ll.c +3 -0
index 5e5044b9e3..ef5287dee8 100644
@@ -516,6 +516,9 @@ int has_conflict_markers(struct index_state *istate, const char *path)
 			has_markers = 1;
 			break;
 		}
+		if (buffer_is_binary(sb.buf,
+				     ULONG_MAX <= sb.len ? ULONG_MAX : sb.len))
+			break;
 	}
 	fclose(f);
 	strbuf_release(&sb);
Signature · 1 line
2.55.0-609-g9a17695db7
#9 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

Quoted 14 lines · Junio C Hamano

Left unchecked, this loop may end up scanning a large binary file to the end in vain. We may squeeze in something like this to punt early.

 merge-ll.c | 3 +++
 1 file changed, 3 insertions(+)
merge-ll.c +0 -0
index 5e5044b9e3..ef5287dee8 100644

merge-ll.c int has_conflict_markers(struct index_state *istate, const char *path) · line 522

Quoted 7 lines
merge-ll.c +3 -0
@@ -516,6 +516,9 @@ int has_conflict_markers(struct index_state *istate, const char *path)
                        has_markers = 1;
                        break;
                }
+               if (buffer_is_binary(sb.buf,
+                                    ULONG_MAX <= sb.len ? ULONG_MAX : sb.len))
+                       break;
        }

Should this check be before the conflict marker line check in case the first iteration accidentally matches for a binary file and breaks with has_markers = 1?

#10 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

Quoted 10 lines · Michael Montalbo
Quoted 9 lines · Junio C Hamano

Left unchecked, this loop may end up scanning a large binary file to the end in vain. We may squeeze in something like this to punt early.

 merge-ll.c | 3 +++
 1 file changed, 3 insertions(+)
Quoted 16 lines

merge-ll.c int has_conflict_markers(struct index_state *istate, const char *path) · line 522

Quoted 12 lines
merge-ll.c +3 -0
index 5e5044b9e3..ef5287dee8 100644
@@ -516,6 +516,9 @@ int has_conflict_markers(struct index_state *istate, const char *path)
                        has_markers = 1;
                        break;
                }
+               if (buffer_is_binary(sb.buf,
+                                    ULONG_MAX <= sb.len ? ULONG_MAX : sb.len))
+                       break;
        }

Should this check be before the conflict marker line check in case the first iteration accidentally matches for a binary file and breaks with has_markers = 1?

If we misidentify early, that is a desirable outcome, isn't it?

We did not have to scan much and we gave control back to the user as soon as we saw "<<<<<<", telling them that we refused to add the path to the index, so that the user can inspect the situation more deeply. In this application, false positives are much better than false negatives, and failing early is better than failing late.

So, no, I do not think so, even though in practice I do not think it would matter either way.

A question that may have much more impact is whether the attribute system should have any say in this code path. I am somewhat torn on this.

#11 lore raw

Re: [PATCH 3/4] add: introduce '--resolved' option

Quoted 10 lines · Junio C Hamano

If we misidentify early, that is a desirable outcome, isn't it?

We did not have to scan much and we gave control back to the user as soon as we saw "<<<<<<", telling them that we refused to add the path to the index, so that the user can inspect the situation more deeply. In this application, false positives are much better than false negatives, and failing early is better than failing late.

I didn't fully consider the case of the false negative that would come with switching the order of the checks. I agree false positives are much better in this scenario.

Quoted 6 lines

So, no, I do not think so, even though in practice I do not think it would matter either way.

A question that may have much more impact is whether the attribute system should have any say in this code path. I am somewhat torn on this.

I do think something in that direction might make things more clear. When looking at "has_conflict_markers()" in isolation my instinct was to guard against the case that the file is binary (among other "easy" checks to eliminate non-conflict marker paths upfront) and return right away. That rested on the assumption the check for a binary file had an unambiguous result as opposed to being a heuristic.

Would it be possible to check the merge driver used and return early if a non-text driver was used? I tried tracing the path where conflict markers end up being generated and it seems like the binary and union drivers cannot emit conflict markers. That might be conceptually more straightforward and eliminate the need for a "buffer_is_binary()" check. Not sure if that would be brittle in the face of new merge drivers being added, but directly relating this conflict marker check with the drivers that emit those markers seems to make sense to me.

#12 lore raw

PATCH 4/4 read-cache: reindent

In reply to Junio C Hamano

I do not know how this happened without anybody noticing, but a few months ago we added a16c4a245a (read-cache: submodule add need --force given ignore=all configuration, 2026-02-06), and almost all lines the patch added were incorrectly indented.

Reindent these lines so that they play better with surrounding lines in the same file.

---
 read-cache.c | 70 +++++++++++++++++++++++++++-------------------------
 1 file changed, 36 insertions(+), 34 deletions(-)
read-cache.c +36 -34
index 6fbab77225..ad77c0d5e2 100644
@@ -3924,32 +3924,33 @@ static int fix_unmerged_status(struct diff_filepair *p,
 }
 
 static int skip_submodule(const char *path,
-						struct repository *repo,
-						struct pathspec *pathspec,
-						int ignored_too)
-{
-    struct stat st;
-    const struct submodule *sub;
-    int pathspec_matches = 0;
-    int ps_i;
-    char *norm_pathspec = NULL;
-
-    /* Only consider if path is a directory */
-    if (lstat(path, &st) || !S_ISDIR(st.st_mode))
+			  struct repository *repo,
+			  struct pathspec *pathspec,
+			  int ignored_too)
+{
+	struct stat st;
+	const struct submodule *sub;
+	int pathspec_matches = 0;
+	int ps_i;
+	char *norm_pathspec = NULL;
+
+	/* Only consider if path is a directory */
+	if (lstat(path, &st) || !S_ISDIR(st.st_mode))
 		return 0;
 
-    /* Check if it's a submodule with ignore=all */
-    sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
-    if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
+	/* Check if it's a submodule with ignore=all */
+	sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
+	if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
 		return 0;
 
-    trace_printf("ignore=all: %s\n", path);
-    trace_printf("pathspec %s\n", (pathspec && pathspec->nr)
-									? "has pathspec"
-									: "no pathspec");
+	trace_printf("ignore=all: %s\n", path);
+	trace_printf("pathspec %s\n",
+		     ((pathspec && pathspec->nr)
+		      ? "has pathspec"
+		      : "no pathspec"));
 
-    /* Check if submodule path is explicitly mentioned in pathspec */
-    if (pathspec) {
+	/* Check if submodule path is explicitly mentioned in pathspec */
+	if (pathspec) {
 		for (ps_i = 0; ps_i < pathspec->nr; ps_i++) {
 			const char *m = pathspec->items[ps_i].match;
 			if (!m)
@@ -3963,28 +3964,29 @@ static int skip_submodule(const char *path,
 			}
 			FREE_AND_NULL(norm_pathspec);
 		}
-    }
+	}
 
-    /* If explicitly matched and forced, allow adding */
-    if (pathspec_matches) {
+	/* If explicitly matched and forced, allow adding */
+	if (pathspec_matches) {
 		if (ignored_too && ignored_too > 0) {
 			trace_printf("Add submodule due to --force: %s\n", path);
 			return 0;
 		} else {
 			advise_if_enabled(ADVICE_ADD_IGNORED_FILE,
-				_("Skipping submodule due to ignore=all: %s\n"
-					"Use --force if you really want to add the submodule."), path);
+				  _("Skipping submodule due to ignore=all: %s\n"
+				    "Use --force if you really want to "
+				    "add the submodule."), path);
 			return 1;
 		}
-    }
+	}
 
-    /* No explicit pathspec match -> skip silently */
-    trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
-    return 1;
+	/* No explicit pathspec match -> skip silently */
+	trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
+	return 1;
 }
 
 static void update_callback(struct diff_queue_struct *q,
-							struct diff_options *opt UNUSED, void *cbdata)
+			    struct diff_options *opt UNUSED, void *cbdata)
 {
 	int i;
 	struct update_callback_data *data = cbdata;
@@ -3994,7 +3996,7 @@ static void update_callback(struct diff_queue_struct *q,
 		const char *path = p->one->path;
 
 		if (!data->include_sparse &&
-			!path_in_sparse_checkout(path, data->index))
+		    !path_in_sparse_checkout(path, data->index))
 			continue;
 
 		switch (fix_unmerged_status(p, data)) {
@@ -4003,8 +4005,8 @@ static void update_callback(struct diff_queue_struct *q,
 		case DIFF_STATUS_MODIFIED:
 		case DIFF_STATUS_TYPE_CHANGED:
 			if (skip_submodule(path, data->repo,
-								data->pathspec,
-								data->ignored_too))
+					   data->pathspec,
+					   data->ignored_too))
 				continue;
 
 			if (add_file_to_index(data->index, path, data->flags)) {
Signature · 1 line
2.55.0-594-g42d2bf033e
#13 lore raw

v2 cover git add --resolved

In reply to Junio C Hamano

When you are the maintainer of a project and make many merges day in, day out, a lot of your time is spent resolving conflicts and adding the results to the index. It is not unusual to have local changes in your working tree that are unrelated to any particular merge [*]. In such cases, 'git add -u', which adds all changes in the working tree to the index, does not help much.

Here is a new option for 'git add' that lets you add paths with resolved conflicts to the index, while keeping unrelated local changes out.

The first three patches perform preliminary refactorings.

- [1/4] is a totally unrelated code cleanup that almost disappears when viewed with 'git show -w', but it was an eyesore to have so many lines with broken indentation while working in the vicinity.

- [2/4] consolidates a helper function to determine whether a line is a conflict marker (replacing two slightly different definitions).

- [3/4] introduces a helper that makes registering path removals from the index as easy as adding them, complete with automatic '--dry-run' and '--verbose' support.

The fourth patch implements the new feature. Relative to v1, the detection of the use of the '-A' option was fixed and the Meson build file was updated to include the new test script, both thanks to Michael Montalbo. In addition, the has_conflict_markers() helper has been tightened to bail early on a binary file.

1/4: read-cache: reindent
2/4: merge-ll: consolidate conflict marker scanning logic 3/4: read-cache: add remove_file_from_index_with_flags() 4/4: add: introduce '--resolved' option

[Footnote]

* This is not limited to my own workflow. An earlier message on this topic worth mentioning is:

https://lore.kernel.org/git/CA+55aFxP8j7YbYaRXt-8Y0n8cHafB=FPKMy8gKFYH5QsKX4S=Q@mail.gmail.com/

 Documentation/git-add.adoc |  10 +++-
 builtin/add.c              |  92 ++++++++++++++++++++++++++++---
 diff.c                     |  25 +--------
 merge-ll.c                 |  56 +++++++++++++++++++
 merge-ll.h                 |   2 +
 read-cache-ll.h            |   3 ++
 read-cache.c               |  89 +++++++++++++++++-------------
 rerere.c                   |  38 +++----------
 t/meson.build              |   1 +
 t/t2207-add-resolved.sh    | 108 +++++++++++++++++++++++++++++++++++++
 10 files changed, 323 insertions(+), 101 deletions(-)
 create mode 100755 t/t2207-add-resolved.sh

Range-diff against v1:

4:  c503fbb785 = 1:  e46fe3e887 read-cache: reindent
1:  03ea86d803 = 2:  b5490819bd merge-ll: consolidate conflict marker scanning logic
2:  e94e3c1390 = 3:  e1f4aba480 read-cache: add remove_file_from_index_with_flags()
3:  73679d6b69 ! 4:  b1308a0ca1 add: introduce '--resolved' option
    @@ builtin/add.c: int cmd_add(int argc,
     -	if (addremove && take_worktree_changes)
     -		die(_("options '%s' and '%s' cannot be used together"), "-A", "-u");
     +	die_for_incompatible_opt3(take_worktree_changes, "-u/--update",
    -+				  0 <= addremove_explicit, "-A/--all",
    ++				  0 < addremove_explicit, "-A/--all",
     +				  add_resolved, "--resolved");
      
      	if (!show_only && ignore_missing)
    @@ merge-ll.c: int is_conflict_marker_line(const char *line, unsigned long len, int
     +			has_markers = 1;
     +			break;
     +		}
    ++		if (buffer_is_binary(sb.buf,
    ++				     ULONG_MAX <= sb.len ? ULONG_MAX : sb.len))
    ++			break;
     +	}
     +	fclose(f);
     +	strbuf_release(&sb);
    @@ merge-ll.h: enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
      
      #endif
     
    + ## t/meson.build ##
    +@@ t/meson.build: integration_tests = [
    +   't2204-add-ignored.sh',
    +   't2205-add-worktree-config.sh',
    +   't2206-add-submodule-ignored.sh',
    ++  't2207-add-resolved.sh',
    +   't2300-cd-to-toplevel.sh',
    +   't2400-worktree-add.sh',
    +   't2401-worktree-prune.sh',
    +
      ## t/t2207-add-resolved.sh (new) ##
     @@
     +#!/bin/sh
Signature · 1 line
2.55.0-609-g9a17695db7
#14 lore raw

PATCH v2 1/4 read-cache: reindent

I do not know how this happened without anybody noticing, but a few months ago we added a16c4a245a (read-cache: submodule add need --force given ignore=all configuration, 2026-02-06), and almost all lines the patch added were incorrectly indented.

Reindent these lines so that they play better with surrounding lines in the same file.

---
 read-cache.c | 70 +++++++++++++++++++++++++++-------------------------
 1 file changed, 36 insertions(+), 34 deletions(-)
read-cache.c +36 -34
index 38b55323dd..58c378414a 100644
@@ -3910,32 +3910,33 @@ static int fix_unmerged_status(struct diff_filepair *p,
 }
 
 static int skip_submodule(const char *path,
-						struct repository *repo,
-						struct pathspec *pathspec,
-						int ignored_too)
-{
-    struct stat st;
-    const struct submodule *sub;
-    int pathspec_matches = 0;
-    int ps_i;
-    char *norm_pathspec = NULL;
-
-    /* Only consider if path is a directory */
-    if (lstat(path, &st) || !S_ISDIR(st.st_mode))
+			  struct repository *repo,
+			  struct pathspec *pathspec,
+			  int ignored_too)
+{
+	struct stat st;
+	const struct submodule *sub;
+	int pathspec_matches = 0;
+	int ps_i;
+	char *norm_pathspec = NULL;
+
+	/* Only consider if path is a directory */
+	if (lstat(path, &st) || !S_ISDIR(st.st_mode))
 		return 0;
 
-    /* Check if it's a submodule with ignore=all */
-    sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
-    if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
+	/* Check if it's a submodule with ignore=all */
+	sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
+	if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
 		return 0;
 
-    trace_printf("ignore=all: %s\n", path);
-    trace_printf("pathspec %s\n", (pathspec && pathspec->nr)
-									? "has pathspec"
-									: "no pathspec");
+	trace_printf("ignore=all: %s\n", path);
+	trace_printf("pathspec %s\n",
+		     ((pathspec && pathspec->nr)
+		      ? "has pathspec"
+		      : "no pathspec"));
 
-    /* Check if submodule path is explicitly mentioned in pathspec */
-    if (pathspec) {
+	/* Check if submodule path is explicitly mentioned in pathspec */
+	if (pathspec) {
 		for (ps_i = 0; ps_i < pathspec->nr; ps_i++) {
 			const char *m = pathspec->items[ps_i].match;
 			if (!m)
@@ -3949,28 +3950,29 @@ static int skip_submodule(const char *path,
 			}
 			FREE_AND_NULL(norm_pathspec);
 		}
-    }
+	}
 
-    /* If explicitly matched and forced, allow adding */
-    if (pathspec_matches) {
+	/* If explicitly matched and forced, allow adding */
+	if (pathspec_matches) {
 		if (ignored_too && ignored_too > 0) {
 			trace_printf("Add submodule due to --force: %s\n", path);
 			return 0;
 		} else {
 			advise_if_enabled(ADVICE_ADD_IGNORED_FILE,
-				_("Skipping submodule due to ignore=all: %s\n"
-					"Use --force if you really want to add the submodule."), path);
+				  _("Skipping submodule due to ignore=all: %s\n"
+				    "Use --force if you really want to "
+				    "add the submodule."), path);
 			return 1;
 		}
-    }
+	}
 
-    /* No explicit pathspec match -> skip silently */
-    trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
-    return 1;
+	/* No explicit pathspec match -> skip silently */
+	trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
+	return 1;
 }
 
 static void update_callback(struct diff_queue_struct *q,
-							struct diff_options *opt UNUSED, void *cbdata)
+			    struct diff_options *opt UNUSED, void *cbdata)
 {
 	int i;
 	struct update_callback_data *data = cbdata;
@@ -3980,7 +3982,7 @@ static void update_callback(struct diff_queue_struct *q,
 		const char *path = p->one->path;
 
 		if (!data->include_sparse &&
-			!path_in_sparse_checkout(path, data->index))
+		    !path_in_sparse_checkout(path, data->index))
 			continue;
 
 		switch (fix_unmerged_status(p, data)) {
@@ -3989,8 +3991,8 @@ static void update_callback(struct diff_queue_struct *q,
 		case DIFF_STATUS_MODIFIED:
 		case DIFF_STATUS_TYPE_CHANGED:
 			if (skip_submodule(path, data->repo,
-								data->pathspec,
-								data->ignored_too))
+					   data->pathspec,
+					   data->ignored_too))
 				continue;
 
 			if (add_file_to_index(data->index, path, data->flags)) {
Signature · 1 line
2.55.0-609-g9a17695db7
#15 lore raw

PATCH v2 2/4 merge-ll: consolidate conflict marker scanning logic

In reply to Junio C Hamano

The diff.c:is_conflict_marker() and rerere.c:is_cmarker() functions implement duplicate logic for identifying conflict marker lines (lines that begin with a run of '<', '=', '>', and '|' characters).

diff.c's original version from 049540435f (diff --check: detect leftover conflict markers, 2008-06-26) accepts any whitespace (such as a newline) immediately following '<<<<<<<' and '>>>>>>>', whereas rerere.c's version from 191f241717 (rerere: prepare for customizable conflict marker length, 2010-01-16) strictly requires a space character (' ') after them.

Implement is_conflict_marker_line() in merge-ll.c to serve as a replacement for both, and update diff.c and rerere.c to use the new helper. The unified helper intentionally adopts rerere's stricter rule, as the conflicts generated by Git always show the "ours" and "theirs" labels after these markers separated by a space.

---
 diff.c     | 25 +------------------------
 merge-ll.c | 31 +++++++++++++++++++++++++++++++
 merge-ll.h |  1 +
 rerere.c   | 38 ++++++--------------------------------
 4 files changed, 39 insertions(+), 56 deletions(-)
diff.c +1 -24
index 589c1969e4..cfe515af4e 100644
@@ -3519,29 +3519,6 @@ struct checkdiff_t {
 	int last_line_kind;
 };
 
-static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
-{
-	char firstchar;
-	int cnt;
-
-	if (len < marker_size + 1)
-		return 0;
-	firstchar = line[0];
-	switch (firstchar) {
-	case '=': case '>': case '<': case '|':
-		break;
-	default:
-		return 0;
-	}
-	for (cnt = 1; cnt < marker_size; cnt++)
-		if (line[cnt] != firstchar)
-			return 0;
-	/* line[1] through line[marker_size-1] are same as firstchar */
-	if (len < marker_size + 1 || !isspace(line[marker_size]))
-		return 0;
-	return 1;
-}
-
 static void checkdiff_consume_hunk(void *priv,
 				   long ob UNUSED, long on UNUSED,
 				   long nb, long nn UNUSED,
@@ -3571,7 +3548,7 @@ static int checkdiff_consume(void *priv, char *line, unsigned long len)
 	if (line[0] == '+') {
 		unsigned bad;
 		data->lineno++;
-		if (is_conflict_marker(line + 1, marker_size, len - 1)) {
+		if (is_conflict_marker_line(line + 1, len - 1, marker_size)) {
 			data->status |= 1;
 			fprintf(data->o->file,
 				"%s%s:%d: leftover conflict marker\n",
merge-ll.c +31 -0
index fafe2c9197..41c97fb90a 100644
@@ -468,3 +468,34 @@ int ll_merge_marker_size(struct index_state *istate, const char *path)
 	}
 	return marker_size;
 }
+
+int is_conflict_marker_line(const char *line, unsigned long len, int marker_size)
+{
+	char firstchar;
+	int cnt;
+
+	if (len < marker_size + 1)
+		return 0;
+
+	firstchar = line[0];
+	switch (firstchar) {
+	case '=': case '>': case '<': case '|':
+		break;
+	default:
+		return 0;
+	}
+
+	for (cnt = 1; cnt < marker_size; cnt++) {
+		if (line[cnt] != firstchar)
+			return 0;
+	}
+
+	if (((firstchar == '<') || (firstchar == '>')) &&
+	    line[marker_size] != ' ')
+		return 0;
+
+	if (!isspace((unsigned char)line[marker_size]))
+		return 0;
+
+	return firstchar;
+}
merge-ll.h +1 -0
index d038ee0c1e..b348aee15d 100644
@@ -109,6 +109,7 @@ enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
 	     const struct ll_merge_options *opts);
 
 int ll_merge_marker_size(struct index_state *istate, const char *path);
+int is_conflict_marker_line(const char *line, unsigned long len, int marker_size);
 void reset_merge_attributes(void);
 
 #endif
rerere.c +6 -32
index 216100925a..924a1f2e30 100644
@@ -331,33 +331,6 @@ static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
 	return strbuf_getwholeline(sb, io->input, '\n');
 }
 
-/*
- * Require the exact number of conflict marker letters, no more, no
- * less, followed by SP or any whitespace
- * (including LF).
- */
-static int is_cmarker(char *buf, int marker_char, int marker_size)
-{
-	int want_sp;
-
-	/*
-	 * The beginning of our version and the end of their version
-	 * always are labeled like "<<<<< ours" or ">>>>> theirs",
-	 * hence we set want_sp for them.  Note that the version from
-	 * the common ancestor in diff3-style output is not always
-	 * labelled (e.g. "||||| common" is often seen but "|||||"
-	 * alone is also valid), so we do not set want_sp.
-	 */
-	want_sp = (marker_char == '<') || (marker_char == '>');
-
-	while (marker_size--)
-		if (*buf++ != marker_char)
-			return 0;
-	if (want_sp && *buf != ' ')
-		return 0;
-	return isspace(*buf);
-}
-
 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
 {
 	strbuf_addchars(buf, ch, size);
@@ -375,7 +348,8 @@ static int handle_conflict(struct strbuf *out, struct rerere_io *io,
 	int has_conflicts = -1;
 
 	while (!io->getline(&buf, io)) {
-		if (is_cmarker(buf.buf, '<', marker_size)) {
+		int marker = is_conflict_marker_line(buf.buf, buf.len, marker_size);
+		if (marker == '<') {
 			if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
 				break;
 			if (hunk == RR_SIDE_1)
@@ -383,15 +357,15 @@ static int handle_conflict(struct strbuf *out, struct rerere_io *io,
 			else
 				strbuf_addbuf(&two, &conflict);
 			strbuf_release(&conflict);
-		} else if (is_cmarker(buf.buf, '|', marker_size)) {
+		} else if (marker == '|') {
 			if (hunk != RR_SIDE_1)
 				break;
 			hunk = RR_ORIGINAL;
-		} else if (is_cmarker(buf.buf, '=', marker_size)) {
+		} else if (marker == '=') {
 			if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
 				break;
 			hunk = RR_SIDE_2;
-		} else if (is_cmarker(buf.buf, '>', marker_size)) {
+		} else if (marker == '>') {
 			if (hunk != RR_SIDE_2)
 				break;
 			if (strbuf_cmp(&one, &two) > 0)
@@ -442,7 +416,7 @@ static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_siz
 		git_hash_init(&ctx, the_hash_algo);
 
 	while (!io->getline(&buf, io)) {
-		if (is_cmarker(buf.buf, '<', marker_size)) {
+		if (is_conflict_marker_line(buf.buf, buf.len, marker_size) == '<') {
 			has_conflicts = handle_conflict(&out, io, marker_size,
 							hash ? &ctx : NULL);
 			if (has_conflicts < 0)
Signature · 1 line
2.55.0-609-g9a17695db7
#16 lore raw

PATCH v2 3/4 read-cache: add remove_file_from_index_with_flags()

In reply to Junio C Hamano

add_file_to_index() takes flags such as ADD_CACHE_PRETEND and ADD_CACHE_VERBOSE and internally handles both reporting (e.g., "add 'path'") and suppressing index updates during dry runs.

In contrast, remove_file_from_index() takes only istate and path without flags. Callers that perform file removals (such as update_callback() in read-cache.c) are forced to manually inspect ADD_CACHE_PRETEND and ADD_CACHE_VERBOSE flags for removed files.

Introduce remove_file_from_index_with_flags() to encapsulate pretend mode and verbose reporting for index removals. Update update_callback() to use the new helper.

---
 read-cache-ll.h |  3 +++
 read-cache.c    | 19 +++++++++++++++----
 2 files changed, 18 insertions(+), 4 deletions(-)
read-cache-ll.h +3 -0
index 71b87615eb..8eb266cfd1 100644
@@ -391,11 +391,14 @@ int remove_index_entry_at(struct index_state *, int pos);
 
 void remove_marked_cache_entries(struct index_state *istate, int invalidate);
 int remove_file_from_index(struct index_state *, const char *path);
+int remove_file_from_index_with_flags(struct index_state *, const char *, int);
+
 #define ADD_CACHE_VERBOSE 1
 #define ADD_CACHE_PRETEND 2
 #define ADD_CACHE_IGNORE_ERRORS	4
 #define ADD_CACHE_IGNORE_REMOVAL 8
 #define ADD_CACHE_INTENT 16
+
 /*
  * These two are used to add the contents of the file at path
  * to the index, marking the working tree up-to-date by storing
read-cache.c +15 -4
index 58c378414a..ad77c0d5e2 100644
@@ -638,6 +638,20 @@ int remove_file_from_index(struct index_state *istate, const char *path)
 	return 0;
 }
 
+int remove_file_from_index_with_flags(struct index_state *istate,
+				      const char *path,
+				      int flags)
+{
+	int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
+	int pretend = flags & ADD_CACHE_PRETEND;
+
+	if (verbose)
+		printf(_("remove '%s'\n"), path);
+	if (pretend)
+		return 0;
+	return remove_file_from_index(istate, path);
+}
+
 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
 {
 	return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
@@ -4004,10 +4018,7 @@ static void update_callback(struct diff_queue_struct *q,
 		case DIFF_STATUS_DELETED:
 			if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
 				break;
-			if (!(data->flags & ADD_CACHE_PRETEND))
-				remove_file_from_index(data->index, path);
-			if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
-				printf(_("remove '%s'\n"), path);
+			remove_file_from_index_with_flags(data->index, path, data->flags);
 			break;
 		}
 	}
Signature · 1 line
2.55.0-609-g9a17695db7
#17 lore raw

PATCH v2 4/4 add: introduce '--resolved' option

In reply to Junio C Hamano

During a conflicted merge, rebase, or cherry-pick, 'git add -u' is a handy way to add modified paths to the index. However, '-u' indiscriminately adds all modified tracked paths, including unmerged paths that may still contain unresolved conflict markers. It also adds tracked files modified in the worktree that are not involved in the ongoing merge.

The latter is not a huge problem for "git rebase", which refuses to start with any local changes, but is a problem for "git merge", which is often run with local changes in maintainer workflows.

Introduce 'git add --resolved' to add only unmerged paths, limited by an optional pathspec, where no conflict markers remain in the working tree.

Before modifying the index, scan unmerged regular files for leftover conflict markers using a new helper, has_conflict_markers(), defined in merge-ll.c in terms of the is_conflict_marker_line() helper we introduced earlier. If any unmerged path still contains conflict markers, show an error listing the conflicted paths and abort without updating the index. Otherwise, add these unmerged paths that do not have conflict markers to the index.

Note that unmerged paths without conflict markers (such as binary files and deletions) are added as resolved using add_file_to_index() and remove_file_from_index_with_flags(). Tracked files that were not in a conflicted state are ignored by '--resolved'.

---
 Documentation/git-add.adoc |  10 +++-
 builtin/add.c              |  92 ++++++++++++++++++++++++++++---
 merge-ll.c                 |  25 +++++++++
 merge-ll.h                 |   1 +
 t/meson.build              |   1 +
 t/t2207-add-resolved.sh    | 108 +++++++++++++++++++++++++++++++++++++
 6 files changed, 230 insertions(+), 7 deletions(-)
 create mode 100755 t/t2207-add-resolved.sh
Documentation/git-add.adoc +9 -1
index 941135dc63..16b06e38e1 100644
@@ -11,7 +11,7 @@ SYNOPSIS
 git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p]
 	[--edit | -e] [--[no-]all | -A | --[no-]ignore-removal | [--update | -u]] [--sparse]
 	[--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize]
-	[--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
+	[--resolved] [--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
 	[--] [<pathspec>...]
 
 DESCRIPTION
@@ -195,6 +195,14 @@ for `git add --no-all <pathspec>...`, i.e. ignored removed files.
 	while a _CRLF_ cleans to _LF_, a _CRCRLF_ sequence is only partially
 	cleaned to _CRLF_.
 
+`--resolved`::
+	Update the index for unmerged paths matching _<pathspec>_ where
+	no conflict markers remain in the working tree. Unmerged paths
+	without conflict markers (including binary files and file
+	deletions) are staged as resolved, while any path with leftover
+	conflict markers causes the command to refuse to stage any files.
+	Cannot be combined with `-u` or `-A`.
+
 `--chmod=(+|-)x`::
 	Override the executable bit of the added files.  The executable
 	bit is only changed in the index, the files on disk are left
builtin/add.c +86 -6

140 lines not on this page · raw message

merge-ll.c +25 -0
index 41c97fb90a..ef5287dee8 100644
@@ -499,3 +499,28 @@ int is_conflict_marker_line(const char *line, unsigned long len, int marker_size
 
 	return firstchar;
 }
+
+int has_conflict_markers(struct index_state *istate, const char *path)
+{
+	FILE *f;
+	struct strbuf sb = STRBUF_INIT;
+	int marker_size = ll_merge_marker_size(istate, path);
+	int has_markers = 0;
+
+	f = fopen(path, "r");
+	if (!f)
+		return 0;
+
+	while (strbuf_getwholeline(&sb, f, '\n') != EOF) {
+		if (is_conflict_marker_line(sb.buf, sb.len, marker_size)) {
+			has_markers = 1;
+			break;
+		}
+		if (buffer_is_binary(sb.buf,
+				     ULONG_MAX <= sb.len ? ULONG_MAX : sb.len))
+			break;
+	}
+	fclose(f);
+	strbuf_release(&sb);
+	return has_markers;
+}
merge-ll.h +1 -0
index b348aee15d..f26aef238d 100644
@@ -110,6 +110,7 @@ enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
 
 int ll_merge_marker_size(struct index_state *istate, const char *path);
 int is_conflict_marker_line(const char *line, unsigned long len, int marker_size);
+int has_conflict_markers(struct index_state *istate, const char *path);
 void reset_merge_attributes(void);
 
 #endif
t/meson.build +1 -0
index 8ae6ab6c5f..e0f4b85ad5 100644
@@ -304,6 +304,7 @@ integration_tests = [
   't2204-add-ignored.sh',
   't2205-add-worktree-config.sh',
   't2206-add-submodule-ignored.sh',
+  't2207-add-resolved.sh',
   't2300-cd-to-toplevel.sh',
   't2400-worktree-add.sh',
   't2401-worktree-prune.sh',
t/t2207-add-resolved.sh new file +108 -0

108 lines not on this page · raw message

Signature · 1 line
2.55.0-609-g9a17695db7
#18 lore raw

Re: [PATCH v2 4/4] add: introduce '--resolved' option

Quoted 21 lines · Junio C Hamano
t/t2207-add-resolved.sh new file +14 -0
new file mode 100755
index 0000000000..f88e3f413e
@@ -0,0 +1,108 @@
+#!/bin/sh
+
+test_description='git add --resolved
+
+Test that "git add --resolved" stages conflict-resolved paths and
+refuses to stage when conflict markers remain.'
+
+. ./test-lib.sh
+
+test_expect_success 'setup repo' '
...
+	git branch topic &&
+	echo "ours 1" >file1.txt &&
+	echo "ours 2" >file2.txt &&
+	echo "ours 3" >file3.txt &&

t/t2207-add-resolved.sh line 31

Quoted 10 lines
t/t2207-add-resolved.sh new file +10 -0
+	git commit -a -m ours &&
+
+	git checkout topic &&
+	echo "theirs 1" >file1.txt &&
+	echo "theirs 2" >file2.txt &&
+	echo "theirs 3" >file3.txt &&
+	git commit -a -m theirs &&
+
+	git checkout master
+'

This will fail with breaking changes. The last step needs to be

	git checkout @{-1}

to go back to the original branch we were on before checking out the 'topic' branch.

#19 lore raw
In reply to Junio C Hamano
Quoted 11 lines · Junio C Hamano

When you are the maintainer of a project and make many merges day in, day out, a lot of your time is spent resolving conflicts and adding the results to the index. It is not unusual to have local changes in your working tree that are unrelated to any particular merge [*]. In such cases, 'git add -u', which adds all changes in the working tree to the index, does not help much.

Here is a new option for 'git add' that lets you add paths with resolved conflicts to the index, while keeping unrelated local changes out.

Please take this feedback with a grain of salt, as I am probably not the target audience for this feature and am still familiarizing myself with the concepts involved.

I wonder if it would make sense to separate the structural selection of unmerged paths from the conflict-marker safety policy.

For example, could the user-facing option be something like:

    git add --unmerged

with the same default behavior being proposed: select only unmerged index entries, and refuse the operation if any selected regular file contains standard Git conflict markers.

That would also potentially leave room for explicit policy escape hatches later, such as:

    git add --unmerged --allow-conflict-markers

for cases where marker-looking content is intentional; or something like:

    git add --unmerged --skip-conflict-markers

for a mode that stages marker-free unmerged paths while leaving marker-containing paths unmerged and returning non-zero.

I do see the argument for "--resolved" in terms of naming the option after the workflow the user is performing when resolving conflicts. My main feedback is that the implementation selects unmerged paths and applies a conflict-marker safety check, rather than determining semantic resolution, which a name like "--resolved" might imply more strongly.

#20 lore raw
Quoted 8 lines · Michael Montalbo

For example, could the user-facing option be something like:

    git add --unmerged

with the same default behavior being proposed: select only unmerged index entries, and refuse the operation if any selected regular file contains standard Git conflict markers.

Quoted 6 lines

That would also potentially leave room for explicit policy escape hatches later, such as:

    git add --unmerged --allow-conflict-markers

for cases where marker-looking content is intentional; or

Sure, but I do not think of a reason why the posted patches cannot later be extended in that direction if somebody wanted to (but because the option is called "--resolved", the command line would need to become "add --resolved --allow-conflict-markers"). I just did not feel the need for it myself, and because --allow would be a rare case, I would likely do "git add --resolved", see it fail due to conflict marker looking strings that are deliberately left in, and then do "git add $path" to cover these small exceptions, i.e., I do not think anybody would need "--allow-conflict-markers" option.

Quoted 6 lines

something like:

    git add --unmerged --skip-conflict-markers

for a mode that stages marker-free unmerged paths while leaving marker-containing paths unmerged and returning non-zero.

Have no idea how the user recovers after performing an operation like that.

The naming is very much deliberate. "git am --resolved" tells the command "I am done with them, so please continue". It is not like I want to add anything that are unmerged. I dealt with unmerged stuff and turned them into the resolved state, and the command is a request to record that fact. It is a regression to call it "--unmerged".

#21 lore raw
Quoted 4 lines · Junio C Hamano

Sure, but I do not think of a reason why the posted patches cannot later be extended in that direction if somebody wanted to...

Yes, that is fair.

Quoted 3 lines

Have no idea how the user recovers after performing an operation like that.

My thought was that a partial set of resolved files without markers would still be added and files with markers would be available for a subsequent add once they were resolved too. My understanding may be incorrect, though.

Quoted 6 lines

The naming is very much deliberate. "git am --resolved" tells the command "I am done with them, so please continue". It is not like I want to add anything that are unmerged. I dealt with unmerged stuff and turned them into the resolved state, and the command is a request to record that fact. It is a regression to call it "--unmerged".

Thank you for the pointer to "git am --resolved", the context helps me see what you mean that the naming is a regression in the workflow. The name makes sense to me, especially in relation to the existing --resolved flag.

#22 lore raw

v3 cover git add --resolved

In reply to Junio C Hamano

When you are the maintainer of a project and make many merges day in, day out, a lot of your time is spent resolving conflicts and adding the results to the index. It is not unusual to have local changes in your working tree that are unrelated to any particular merge [*]. In such cases, 'git add -u', which adds all changes in the working tree to the index, does not help much.

Here is a new option for 'git add' that lets you add paths with resolved conflicts to the index, while keeping unrelated local changes out.

The first three patches perform preliminary refactorings.

- [1/4] is a totally unrelated code cleanup that almost disappears when viewed with 'git show -w', but it was an eyesore to have so many lines with broken indentation while working in the vicinity.

- [2/4] consolidates a helper function to determine whether a line is a conflict marker (replacing two slightly different definitions).

- [3/4] introduces a helper that makes registering path removals from the index as easy as adding them, complete with automatic '--dry-run' and '--verbose' support.

The fourth patch implements the new feature.

1/4: read-cache: reindent
2/4: merge-ll: consolidate conflict marker scanning logic 3/4: read-cache: add remove_file_from_index_with_flags() 4/4: add: introduce '--resolved' option

The only change since v2 is to fix the test under BREAKING_CHANGES, where the tests are run with a future default initial branch name of 'main'. Instead of assuming that the initial branch is named 'master' when returning, we instruct 'checkout' to return to the previous branch, i.e., '@{-1}'.

[Footnote]

* This is not limited to my own workflow. An earlier message on this topic worth mentioning is:

https://lore.kernel.org/git/CA+55aFxP8j7YbYaRXt-8Y0n8cHafB=FPKMy8gKFYH5QsKX4S=Q@mail.gmail.com/

 Documentation/git-add.adoc |  10 +++-
 builtin/add.c              |  92 ++++++++++++++++++++++++++++---
 diff.c                     |  25 +--------
 merge-ll.c                 |  56 +++++++++++++++++++
 merge-ll.h                 |   2 +
 read-cache-ll.h            |   3 ++
 read-cache.c               |  89 +++++++++++++++++-------------
 rerere.c                   |  38 +++----------
 t/meson.build              |   1 +
 t/t2207-add-resolved.sh    | 108 +++++++++++++++++++++++++++++++++++++
 10 files changed, 323 insertions(+), 101 deletions(-)
 create mode 100755 t/t2207-add-resolved.sh

Range-diff against v2:

1:  b0643ed516 = 1:  414219a89a read-cache: reindent
2:  4533fa4da1 = 2:  f64ad26d1f merge-ll: consolidate conflict marker scanning logic
3:  dbf70c2d3a = 3:  1431d0bfdb read-cache: add remove_file_from_index_with_flags()
4:  033a3d2526 ! 4:  42fb33200a add: introduce '--resolved' option
    @@ t/t2207-add-resolved.sh (new)
     +	echo "theirs 3" >file3.txt &&
     +	git commit -a -m theirs &&
     +
    -+	git checkout master
    ++	git checkout @{-1}
     +'
     +
     +test_expect_success 'git add --resolved refuses files with conflict markers' '
Signature · 1 line
2.55.0-599-g5cacd2ad51
#23 lore raw

PATCH v3 1/4 read-cache: reindent

I do not know how this happened without anybody noticing, but a few months ago we added a16c4a245a (read-cache: submodule add need --force given ignore=all configuration, 2026-02-06), and almost all lines the patch added were incorrectly indented.

Reindent these lines so that they play better with surrounding lines in the same file.

---
 read-cache.c | 70 +++++++++++++++++++++++++++-------------------------
 1 file changed, 36 insertions(+), 34 deletions(-)
read-cache.c +36 -34
index 38b55323dd..58c378414a 100644
@@ -3910,32 +3910,33 @@ static int fix_unmerged_status(struct diff_filepair *p,
 }
 
 static int skip_submodule(const char *path,
-						struct repository *repo,
-						struct pathspec *pathspec,
-						int ignored_too)
-{
-    struct stat st;
-    const struct submodule *sub;
-    int pathspec_matches = 0;
-    int ps_i;
-    char *norm_pathspec = NULL;
-
-    /* Only consider if path is a directory */
-    if (lstat(path, &st) || !S_ISDIR(st.st_mode))
+			  struct repository *repo,
+			  struct pathspec *pathspec,
+			  int ignored_too)
+{
+	struct stat st;
+	const struct submodule *sub;
+	int pathspec_matches = 0;
+	int ps_i;
+	char *norm_pathspec = NULL;
+
+	/* Only consider if path is a directory */
+	if (lstat(path, &st) || !S_ISDIR(st.st_mode))
 		return 0;
 
-    /* Check if it's a submodule with ignore=all */
-    sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
-    if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
+	/* Check if it's a submodule with ignore=all */
+	sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
+	if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
 		return 0;
 
-    trace_printf("ignore=all: %s\n", path);
-    trace_printf("pathspec %s\n", (pathspec && pathspec->nr)
-									? "has pathspec"
-									: "no pathspec");
+	trace_printf("ignore=all: %s\n", path);
+	trace_printf("pathspec %s\n",
+		     ((pathspec && pathspec->nr)
+		      ? "has pathspec"
+		      : "no pathspec"));
 
-    /* Check if submodule path is explicitly mentioned in pathspec */
-    if (pathspec) {
+	/* Check if submodule path is explicitly mentioned in pathspec */
+	if (pathspec) {
 		for (ps_i = 0; ps_i < pathspec->nr; ps_i++) {
 			const char *m = pathspec->items[ps_i].match;
 			if (!m)
@@ -3949,28 +3950,29 @@ static int skip_submodule(const char *path,
 			}
 			FREE_AND_NULL(norm_pathspec);
 		}
-    }
+	}
 
-    /* If explicitly matched and forced, allow adding */
-    if (pathspec_matches) {
+	/* If explicitly matched and forced, allow adding */
+	if (pathspec_matches) {
 		if (ignored_too && ignored_too > 0) {
 			trace_printf("Add submodule due to --force: %s\n", path);
 			return 0;
 		} else {
 			advise_if_enabled(ADVICE_ADD_IGNORED_FILE,
-				_("Skipping submodule due to ignore=all: %s\n"
-					"Use --force if you really want to add the submodule."), path);
+				  _("Skipping submodule due to ignore=all: %s\n"
+				    "Use --force if you really want to "
+				    "add the submodule."), path);
 			return 1;
 		}
-    }
+	}
 
-    /* No explicit pathspec match -> skip silently */
-    trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
-    return 1;
+	/* No explicit pathspec match -> skip silently */
+	trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
+	return 1;
 }
 
 static void update_callback(struct diff_queue_struct *q,
-							struct diff_options *opt UNUSED, void *cbdata)
+			    struct diff_options *opt UNUSED, void *cbdata)
 {
 	int i;
 	struct update_callback_data *data = cbdata;
@@ -3980,7 +3982,7 @@ static void update_callback(struct diff_queue_struct *q,
 		const char *path = p->one->path;
 
 		if (!data->include_sparse &&
-			!path_in_sparse_checkout(path, data->index))
+		    !path_in_sparse_checkout(path, data->index))
 			continue;
 
 		switch (fix_unmerged_status(p, data)) {
@@ -3989,8 +3991,8 @@ static void update_callback(struct diff_queue_struct *q,
 		case DIFF_STATUS_MODIFIED:
 		case DIFF_STATUS_TYPE_CHANGED:
 			if (skip_submodule(path, data->repo,
-								data->pathspec,
-								data->ignored_too))
+					   data->pathspec,
+					   data->ignored_too))
 				continue;
 
 			if (add_file_to_index(data->index, path, data->flags)) {
Signature · 1 line
2.55.0-599-g5cacd2ad51
#24 lore raw

PATCH v3 2/4 merge-ll: consolidate conflict marker scanning logic

In reply to Junio C Hamano

The diff.c:is_conflict_marker() and rerere.c:is_cmarker() functions implement duplicate logic for identifying conflict marker lines (lines that begin with a run of '<', '=', '>', and '|' characters).

diff.c's original version from 049540435f (diff --check: detect leftover conflict markers, 2008-06-26) accepts any whitespace (such as a newline) immediately following '<<<<<<<' and '>>>>>>>', whereas rerere.c's version from 191f241717 (rerere: prepare for customizable conflict marker length, 2010-01-16) strictly requires a space character (' ') after them.

Implement is_conflict_marker_line() in merge-ll.c to serve as a replacement for both, and update diff.c and rerere.c to use the new helper. The unified helper intentionally adopts rerere's stricter rule, as the conflicts generated by Git always show the "ours" and "theirs" labels after these markers separated by a space.

---
 diff.c     | 25 +------------------------
 merge-ll.c | 31 +++++++++++++++++++++++++++++++
 merge-ll.h |  1 +
 rerere.c   | 38 ++++++--------------------------------
 4 files changed, 39 insertions(+), 56 deletions(-)
diff.c +1 -24
index 589c1969e4..cfe515af4e 100644
@@ -3519,29 +3519,6 @@ struct checkdiff_t {
 	int last_line_kind;
 };
 
-static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
-{
-	char firstchar;
-	int cnt;
-
-	if (len < marker_size + 1)
-		return 0;
-	firstchar = line[0];
-	switch (firstchar) {
-	case '=': case '>': case '<': case '|':
-		break;
-	default:
-		return 0;
-	}
-	for (cnt = 1; cnt < marker_size; cnt++)
-		if (line[cnt] != firstchar)
-			return 0;
-	/* line[1] through line[marker_size-1] are same as firstchar */
-	if (len < marker_size + 1 || !isspace(line[marker_size]))
-		return 0;
-	return 1;
-}
-
 static void checkdiff_consume_hunk(void *priv,
 				   long ob UNUSED, long on UNUSED,
 				   long nb, long nn UNUSED,
@@ -3571,7 +3548,7 @@ static int checkdiff_consume(void *priv, char *line, unsigned long len)
 	if (line[0] == '+') {
 		unsigned bad;
 		data->lineno++;
-		if (is_conflict_marker(line + 1, marker_size, len - 1)) {
+		if (is_conflict_marker_line(line + 1, len - 1, marker_size)) {
 			data->status |= 1;
 			fprintf(data->o->file,
 				"%s%s:%d: leftover conflict marker\n",
merge-ll.c +31 -0
index fafe2c9197..41c97fb90a 100644
@@ -468,3 +468,34 @@ int ll_merge_marker_size(struct index_state *istate, const char *path)
 	}
 	return marker_size;
 }
+
+int is_conflict_marker_line(const char *line, unsigned long len, int marker_size)
+{
+	char firstchar;
+	int cnt;
+
+	if (len < marker_size + 1)
+		return 0;
+
+	firstchar = line[0];
+	switch (firstchar) {
+	case '=': case '>': case '<': case '|':
+		break;
+	default:
+		return 0;
+	}
+
+	for (cnt = 1; cnt < marker_size; cnt++) {
+		if (line[cnt] != firstchar)
+			return 0;
+	}
+
+	if (((firstchar == '<') || (firstchar == '>')) &&
+	    line[marker_size] != ' ')
+		return 0;
+
+	if (!isspace((unsigned char)line[marker_size]))
+		return 0;
+
+	return firstchar;
+}
merge-ll.h +1 -0
index d038ee0c1e..b348aee15d 100644
@@ -109,6 +109,7 @@ enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
 	     const struct ll_merge_options *opts);
 
 int ll_merge_marker_size(struct index_state *istate, const char *path);
+int is_conflict_marker_line(const char *line, unsigned long len, int marker_size);
 void reset_merge_attributes(void);
 
 #endif
rerere.c +6 -32
index 216100925a..924a1f2e30 100644
@@ -331,33 +331,6 @@ static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
 	return strbuf_getwholeline(sb, io->input, '\n');
 }
 
-/*
- * Require the exact number of conflict marker letters, no more, no
- * less, followed by SP or any whitespace
- * (including LF).
- */
-static int is_cmarker(char *buf, int marker_char, int marker_size)
-{
-	int want_sp;
-
-	/*
-	 * The beginning of our version and the end of their version
-	 * always are labeled like "<<<<< ours" or ">>>>> theirs",
-	 * hence we set want_sp for them.  Note that the version from
-	 * the common ancestor in diff3-style output is not always
-	 * labelled (e.g. "||||| common" is often seen but "|||||"
-	 * alone is also valid), so we do not set want_sp.
-	 */
-	want_sp = (marker_char == '<') || (marker_char == '>');
-
-	while (marker_size--)
-		if (*buf++ != marker_char)
-			return 0;
-	if (want_sp && *buf != ' ')
-		return 0;
-	return isspace(*buf);
-}
-
 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
 {
 	strbuf_addchars(buf, ch, size);
@@ -375,7 +348,8 @@ static int handle_conflict(struct strbuf *out, struct rerere_io *io,
 	int has_conflicts = -1;
 
 	while (!io->getline(&buf, io)) {
-		if (is_cmarker(buf.buf, '<', marker_size)) {
+		int marker = is_conflict_marker_line(buf.buf, buf.len, marker_size);
+		if (marker == '<') {
 			if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
 				break;
 			if (hunk == RR_SIDE_1)
@@ -383,15 +357,15 @@ static int handle_conflict(struct strbuf *out, struct rerere_io *io,
 			else
 				strbuf_addbuf(&two, &conflict);
 			strbuf_release(&conflict);
-		} else if (is_cmarker(buf.buf, '|', marker_size)) {
+		} else if (marker == '|') {
 			if (hunk != RR_SIDE_1)
 				break;
 			hunk = RR_ORIGINAL;
-		} else if (is_cmarker(buf.buf, '=', marker_size)) {
+		} else if (marker == '=') {
 			if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
 				break;
 			hunk = RR_SIDE_2;
-		} else if (is_cmarker(buf.buf, '>', marker_size)) {
+		} else if (marker == '>') {
 			if (hunk != RR_SIDE_2)
 				break;
 			if (strbuf_cmp(&one, &two) > 0)
@@ -442,7 +416,7 @@ static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_siz
 		git_hash_init(&ctx, the_hash_algo);
 
 	while (!io->getline(&buf, io)) {
-		if (is_cmarker(buf.buf, '<', marker_size)) {
+		if (is_conflict_marker_line(buf.buf, buf.len, marker_size) == '<') {
 			has_conflicts = handle_conflict(&out, io, marker_size,
 							hash ? &ctx : NULL);
 			if (has_conflicts < 0)
Signature · 1 line
2.55.0-599-g5cacd2ad51
#25 lore raw

PATCH v3 3/4 read-cache: add remove_file_from_index_with_flags()

In reply to Junio C Hamano

add_file_to_index() takes flags such as ADD_CACHE_PRETEND and ADD_CACHE_VERBOSE and internally handles both reporting (e.g., "add 'path'") and suppressing index updates during dry runs.

In contrast, remove_file_from_index() takes only istate and path without flags. Callers that perform file removals (such as update_callback() in read-cache.c) are forced to manually inspect ADD_CACHE_PRETEND and ADD_CACHE_VERBOSE flags for removed files.

Introduce remove_file_from_index_with_flags() to encapsulate pretend mode and verbose reporting for index removals. Update update_callback() to use the new helper.

---
 read-cache-ll.h |  3 +++
 read-cache.c    | 19 +++++++++++++++----
 2 files changed, 18 insertions(+), 4 deletions(-)
read-cache-ll.h +3 -0
index 71b87615eb..8eb266cfd1 100644
@@ -391,11 +391,14 @@ int remove_index_entry_at(struct index_state *, int pos);
 
 void remove_marked_cache_entries(struct index_state *istate, int invalidate);
 int remove_file_from_index(struct index_state *, const char *path);
+int remove_file_from_index_with_flags(struct index_state *, const char *, int);
+
 #define ADD_CACHE_VERBOSE 1
 #define ADD_CACHE_PRETEND 2
 #define ADD_CACHE_IGNORE_ERRORS	4
 #define ADD_CACHE_IGNORE_REMOVAL 8
 #define ADD_CACHE_INTENT 16
+
 /*
  * These two are used to add the contents of the file at path
  * to the index, marking the working tree up-to-date by storing
read-cache.c +15 -4
index 58c378414a..ad77c0d5e2 100644
@@ -638,6 +638,20 @@ int remove_file_from_index(struct index_state *istate, const char *path)
 	return 0;
 }
 
+int remove_file_from_index_with_flags(struct index_state *istate,
+				      const char *path,
+				      int flags)
+{
+	int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
+	int pretend = flags & ADD_CACHE_PRETEND;
+
+	if (verbose)
+		printf(_("remove '%s'\n"), path);
+	if (pretend)
+		return 0;
+	return remove_file_from_index(istate, path);
+}
+
 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
 {
 	return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
@@ -4004,10 +4018,7 @@ static void update_callback(struct diff_queue_struct *q,
 		case DIFF_STATUS_DELETED:
 			if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
 				break;
-			if (!(data->flags & ADD_CACHE_PRETEND))
-				remove_file_from_index(data->index, path);
-			if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
-				printf(_("remove '%s'\n"), path);
+			remove_file_from_index_with_flags(data->index, path, data->flags);
 			break;
 		}
 	}
Signature · 1 line
2.55.0-599-g5cacd2ad51
#26 lore raw

PATCH v3 4/4 add: introduce '--resolved' option

In reply to Junio C Hamano

During a conflicted merge, rebase, or cherry-pick, 'git add -u' is a handy way to add modified paths to the index. However, '-u' indiscriminately adds all modified tracked paths, including unmerged paths that may still contain unresolved conflict markers. It also adds tracked files modified in the worktree that are not involved in the ongoing merge.

The latter is not a huge problem for "git rebase", which refuses to start with any local changes, but is a problem for "git merge", which is often run with local changes in maintainer workflows.

Introduce 'git add --resolved' to add only unmerged paths, limited by an optional pathspec, where no conflict markers remain in the working tree.

Before modifying the index, scan unmerged regular files for leftover conflict markers using a new helper, has_conflict_markers(), defined in merge-ll.c in terms of the is_conflict_marker_line() helper we introduced earlier. If any unmerged path still contains conflict markers, show an error listing the conflicted paths and abort without updating the index. Otherwise, add these unmerged paths that do not have conflict markers to the index.

Note that unmerged paths without conflict markers (such as binary files and deletions) are added as resolved using add_file_to_index() and remove_file_from_index_with_flags(). Tracked files that were not in a conflicted state are ignored by '--resolved'.

---
 Documentation/git-add.adoc |  10 +++-
 builtin/add.c              |  92 ++++++++++++++++++++++++++++---
 merge-ll.c                 |  25 +++++++++
 merge-ll.h                 |   1 +
 t/meson.build              |   1 +
 t/t2207-add-resolved.sh    | 108 +++++++++++++++++++++++++++++++++++++
 6 files changed, 230 insertions(+), 7 deletions(-)
 create mode 100755 t/t2207-add-resolved.sh
Documentation/git-add.adoc +9 -1
index 941135dc63..16b06e38e1 100644
@@ -11,7 +11,7 @@ SYNOPSIS
 git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p]
 	[--edit | -e] [--[no-]all | -A | --[no-]ignore-removal | [--update | -u]] [--sparse]
 	[--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize]
-	[--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
+	[--resolved] [--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
 	[--] [<pathspec>...]
 
 DESCRIPTION
@@ -195,6 +195,14 @@ for `git add --no-all <pathspec>...`, i.e. ignored removed files.
 	while a _CRLF_ cleans to _LF_, a _CRCRLF_ sequence is only partially
 	cleaned to _CRLF_.
 
+`--resolved`::
+	Update the index for unmerged paths matching _<pathspec>_ where
+	no conflict markers remain in the working tree. Unmerged paths
+	without conflict markers (including binary files and file
+	deletions) are staged as resolved, while any path with leftover
+	conflict markers causes the command to refuse to stage any files.
+	Cannot be combined with `-u` or `-A`.
+
 `--chmod=(+|-)x`::
 	Override the executable bit of the added files.  The executable
 	bit is only changed in the index, the files on disk are left
builtin/add.c +86 -6

140 lines not on this page · raw message

merge-ll.c +25 -0
index 41c97fb90a..ef5287dee8 100644
@@ -499,3 +499,28 @@ int is_conflict_marker_line(const char *line, unsigned long len, int marker_size
 
 	return firstchar;
 }
+
+int has_conflict_markers(struct index_state *istate, const char *path)
+{
+	FILE *f;
+	struct strbuf sb = STRBUF_INIT;
+	int marker_size = ll_merge_marker_size(istate, path);
+	int has_markers = 0;
+
+	f = fopen(path, "r");
+	if (!f)
+		return 0;
+
+	while (strbuf_getwholeline(&sb, f, '\n') != EOF) {
+		if (is_conflict_marker_line(sb.buf, sb.len, marker_size)) {
+			has_markers = 1;
+			break;
+		}
+		if (buffer_is_binary(sb.buf,
+				     ULONG_MAX <= sb.len ? ULONG_MAX : sb.len))
+			break;
+	}
+	fclose(f);
+	strbuf_release(&sb);
+	return has_markers;
+}
merge-ll.h +1 -0
index b348aee15d..f26aef238d 100644
@@ -110,6 +110,7 @@ enum ll_merge_result ll_merge(mmbuffer_t *result_buf,
 
 int ll_merge_marker_size(struct index_state *istate, const char *path);
 int is_conflict_marker_line(const char *line, unsigned long len, int marker_size);
+int has_conflict_markers(struct index_state *istate, const char *path);
 void reset_merge_attributes(void);
 
 #endif
t/meson.build +1 -0
index 8ae6ab6c5f..e0f4b85ad5 100644
@@ -304,6 +304,7 @@ integration_tests = [
   't2204-add-ignored.sh',
   't2205-add-worktree-config.sh',
   't2206-add-submodule-ignored.sh',
+  't2207-add-resolved.sh',
   't2300-cd-to-toplevel.sh',
   't2400-worktree-add.sh',
   't2401-worktree-prune.sh',
t/t2207-add-resolved.sh new file +108 -0

108 lines not on this page · raw message

Signature · 1 line
2.55.0-599-g5cacd2ad51
#27 lore raw
In reply to Junio C Hamano
Quoted 10 lines · Junio C Hamano

When you are the maintainer of a project and make many merges day in, day out, a lot of your time is spent resolving conflicts and adding the results to the index. It is not unusual to have local changes in your working tree that are unrelated to any particular merge [*]. In such cases, 'git add -u', which adds all changes in the working tree to the index, does not help much.

Here is a new option for 'git add' that lets you add paths with resolved conflicts to the index, while keeping unrelated local changes out.

I think this is a reasonable thing to want, but just playing devil's advocate for a moment: how big of a footgun might this be?

We have some changes in the working tree, we try a merge and get conflicts, do some resolving work and now we want to stage the resolution but nothing else. How close is --resolved to that? I can think of two corner cases:

1. There are non-merge changes in foo.c, which also had some conflicts. Because we stage the whole file, we accidentally stage those along with the merge resolution.

But maybe this is impossible, because merge would have refused to operate when one of the changed files is dirty? I think this is dependent on the strategy, but it should be true for most strategies. The exception is "ours", but that does not create conflicts in the first place. ;)

2. Your resolution required touching other files (e.g., updating the caller of a function), but we'll ignore them. Git has no idea that those changes are related to the merge and not just stray changes. You have to remember to stage them manually.

This is a problem even without --resolved, but I think it's easy for --resolved to lure you into a false sense of security that it is staging all of the important bits.

That doesn't seem too bad to me. I was mostly worried about (1), but after digging into it, I think I've convinced myself that it's a non-issue.

-Peff

#28 lore raw
Quoted 3 lines · Jeff King

That doesn't seem too bad to me. I was mostly worried about (1), but after digging into it, I think I've convinced myself that it's a non-issue.

Yeah, our merges that began with "read-tree -m -u" have never merged into a path with local modification in it, so I have blindly assuming that (1) is a given. I think "ort" did not change it, but quite honestly I do not know where the more recent invention that renames paths that existed only on one side to follow adjacent paths that were renamed from the same directory guarantees property (1), so in these new code paths my assumption truly is a blind faith X-<.

#29 lore raw
Quoted 6 lines · Junio C Hamano
Quoted 3 lines · Jeff King

That doesn't seem too bad to me. I was mostly worried about (1), but after digging into it, I think I've convinced myself that it's a non-issue.

Quoted 7 lines

Yeah, our merges that began with "read-tree -m -u" have never merged into a path with local modification in it, so I have blindly assuming that (1) is a given. I think "ort" did not change it, but quite honestly I do not know where the more recent invention that renames paths that existed only on one side to follow adjacent paths that were renamed from the same directory guarantees property (1), so in these new code paths my assumption truly is a blind faith X-<.

So I got curious, and found out that t6423 has a test labelled as "Testcase 11b" that covers this exact case. So it is a bit better than blind faith now ;-).