Skip to contentSkip to conversation

set remote/HEAD with fetch

RFC PATCH Superseded Bence Ferdinandy 11 participants 258 messages Sep 10, 2024 – Jan 6, 2025 Documentation Page 1 of 3

lore
Share & tools
lore
#0 lore raw

v2 cover set remote/HEAD with fetch

Sorry for the noise, I managed to badly mess up receipients in the previous thread so v2 is just fixing that ...

Hi,

these two patches attempt to solve the issue raised in
https://lore.kernel.org/git/[email protected]/

As a quick summary: clone sets refs/remotes/[remote]/HEAD while going init -> remote add -> fetch does not, one has to manually run remote set-head -a [remote].

The first patch adds a --set-head flag to fetch and remote update which runs remote set-head -a for us. Unfortunately, with the current behaviour of set-head this will always print a message, even though a no-op fetch doesn't print anything, and I think this is also confusing for people who do not care about remote/HEAD, so the second patch removes the print if set-head -a is a no-op (and actually makes it into a no-op, instead of just idempotent).

Another way could of course be duplicating some of the code from remote set-head in fetch.c instead of calling directly, but it didn't look like an anti-pattern in the code-base and it felt the best way to insure identical behaviour between a git fetch --all --set-head and a
git fetch --all && git remote | xargs -i git remote set-head -a {}.

What is missing for sure is:
- documentation
- tests (if needed)
- settings

For settings, my idea would be a fetch/remote.set_head that could take three values:
* never
* missing: run it only if the ref is missing, this setting would basically allow replicating the result of a clone
* always (with the other patch, this would still be a no-op if it didn't change)

This would probably also require a --no-set-head flag, to disable an always/missing setting. A --missing-set-head or something of the like also may or may not make sense. Alternatively, only two behaviours might be enough (missing and always) since clone already sort of does this.

I'm not sure if the general approach is fine or not, nor am I sure the code itself is any good, but it "works on my computer" :) I'm also hoping that I managed to read all the relevant parts for sending a patch.

Feedback would be highly appreciated!

Thanks,
Bence

Bence Ferdinandy (2):
fetch: set-head with --set-head option
set-head: do not update if there is no change

 builtin/fetch.c  | 29 ++++++++++++++++++++++++-----
 builtin/remote.c | 15 +++++++++++----
 2 files changed, 35 insertions(+), 9 deletions(-)
Signature · 1 line
2.46.0
#1 lore raw

RFC PATCH v2 1/2 fetch: set-head with --set-head option

When cloning a repository refs/remotes/origin/HEAD is set automatically. In contrast, when using init, remote add and fetch to set a remote, one needs to call remote set-head --auto to achieve the same result.

Add a --set-head option to git fetch to automatically set heads on remotes.

---
 builtin/fetch.c  | 29 ++++++++++++++++++++++++-----
 builtin/remote.c |  5 +++++
 2 files changed, 29 insertions(+), 5 deletions(-)
builtin/fetch.c +24 -5
index b2b5aee5bf..6392314c6a 100644
@@ -1961,8 +1961,19 @@ static int fetch_finished(int result, struct strbuf *out,
 	return 0;
 }
 
-static int fetch_multiple(struct string_list *list, int max_children,
-			  const struct fetch_config *config)
+static int run_set_head(const char *name)
+{
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	strvec_push(&cmd.args, "remote");
+	strvec_push(&cmd.args, "set-head");
+	strvec_push(&cmd.args, "--auto");
+	strvec_push(&cmd.args, name);
+	cmd.git_cmd = 1;
+	return run_command(&cmd);
+}
+
+static int fetch_multiple(struct string_list *list, int max_children, int set_head,
+			const struct fetch_config *config)
 {
 	int i, result = 0;
 	struct strvec argv = STRVEC_INIT;
@@ -2014,6 +2025,8 @@ static int fetch_multiple(struct string_list *list, int max_children,
 				error(_("could not fetch %s"), name);
 				result = 1;
 			}
+			if (set_head && run_set_head(name))
+				result = 1;
 		}
 
 	strvec_clear(&argv);
@@ -2062,7 +2075,7 @@ static inline void fetch_one_setup_partial(struct remote *remote)
 }
 
 static int fetch_one(struct remote *remote, int argc, const char **argv,
-		     int prune_tags_ok, int use_stdin_refspecs,
+		     int prune_tags_ok, int set_head, int use_stdin_refspecs,
 		     const struct fetch_config *config)
 {
 	struct refspec rs = REFSPEC_INIT_FETCH;
@@ -2135,9 +2148,12 @@ static int fetch_one(struct remote *remote, int argc, const char **argv,
 	refspec_clear(&rs);
 	transport_disconnect(gtransport);
 	gtransport = NULL;
+	if (set_head && run_set_head(remote -> name))
+		exit_code = 1;
 	return exit_code;
 }
 
+
 int cmd_fetch(int argc, const char **argv, const char *prefix)
 {
 	struct fetch_config config = {
@@ -2154,6 +2170,7 @@ int cmd_fetch(int argc, const char **argv, const char *prefix)
 	struct string_list list = STRING_LIST_INIT_DUP;
 	struct remote *remote = NULL;
 	int all = -1, multiple = 0;
+	int set_head = 0;
 	int result = 0;
 	int prune_tags_ok = 1;
 	int enable_auto_gc = 1;
@@ -2171,6 +2188,8 @@ int cmd_fetch(int argc, const char **argv, const char *prefix)
 		OPT__VERBOSITY(&verbosity),
 		OPT_BOOL(0, "all", &all,
 			 N_("fetch from all remotes")),
+		OPT_BOOL(0, "set-head", &set_head,
+			 N_("auto set remote HEAD")),
 		OPT_BOOL(0, "set-upstream", &set_upstream,
 			 N_("set upstream for git pull/fetch")),
 		OPT_BOOL('a', "append", &append,
@@ -2436,7 +2455,7 @@ int cmd_fetch(int argc, const char **argv, const char *prefix)
 			trace2_region_leave("fetch", "setup-partial", the_repository);
 		}
 		trace2_region_enter("fetch", "fetch-one", the_repository);
-		result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs,
+		result = fetch_one(remote, argc, argv, prune_tags_ok, set_head, stdin_refspecs,
 				   &config);
 		trace2_region_leave("fetch", "fetch-one", the_repository);
 	} else {
@@ -2459,7 +2478,7 @@ int cmd_fetch(int argc, const char **argv, const char *prefix)
 
 		/* TODO should this also die if we have a previous partial-clone? */
 		trace2_region_enter("fetch", "fetch-multiple", the_repository);
-		result = fetch_multiple(&list, max_children, &config);
+		result = fetch_multiple(&list, max_children, set_head, &config);
 		trace2_region_leave("fetch", "fetch-multiple", the_repository);
 	}
 
builtin/remote.c +5 -0
index 0acc547d69..35c54dd103 100644
@@ -1536,9 +1536,12 @@ static int get_remote_default(const char *key, const char *value UNUSED,
 static int update(int argc, const char **argv, const char *prefix)
 {
 	int i, prune = -1;
+	int set_head = 0;
 	struct option options[] = {
 		OPT_BOOL('p', "prune", &prune,
 			 N_("prune remotes after fetching")),
+		OPT_BOOL(0, "set-head", &set_head,
+			 N_("auto set remote HEAD")),
 		OPT_END()
 	};
 	struct child_process cmd = CHILD_PROCESS_INIT;
@@ -1552,6 +1555,8 @@ static int update(int argc, const char **argv, const char *prefix)
 
 	if (prune != -1)
 		strvec_push(&cmd.args, prune ? "--prune" : "--no-prune");
+	if (set_head)
+		strvec_push(&cmd.args, "--set-head");
 	if (verbose)
 		strvec_push(&cmd.args, "-v");
 	strvec_push(&cmd.args, "--multiple");
Signature · 1 line
2.46.0
#2 lore raw

Re: [RFC PATCH v2 1/2] fetch: set-head with --set-head option

Quoted 3 lines · Bence Ferdinandy

When cloning a repository refs/remotes/origin/HEAD is set automatically. In contrast, when using init, remote add and fetch to set a remote, one needs to call remote set-head --auto to achieve the same result.

In other words, "clone" is roughly equivalent to "init && remote add && fetch && remote set-head".

I do not see a problem with it. You'd do such a repository creation task only once per repository anyway.

Quoted 2 lines

Add a --set-head option to git fetch to automatically set heads on remotes.

This practically would help only those who want to blindly follow what the remote considers their primary branch. If the remote flip-flops that every day betweein 'master' and 'main', you'd want to either "fetch && remote set-head" or "fetch --set-head", but it would be weird to flip-flop the HEAD every day to begin with.

And the feature does not help those who want to inspect and then switch. When they say "--set-head", they will unconditionally switch whatever the remote uses and there is no opportunity for them to check.

Ideally, because every "git fetch" you do will automatically learn what their HEAD of the day points at, even without "--set-head", it may be nice to let the user know when their HEAD changed, so that the user can inspect the situation and decide.

If "fetch $repo", when it notices that refs/remotes/$repo/HEAD is missing, always unconditionally stores where their HEAD points at in refs/remotes/$repo/HEAD, and did nothing else, wouldn't that be sufficient?

The users have "remote set-head" to do this when needed. What is the true motivation that "fetch" (which presumably happens a lot more often) needs to be involved in this process? The *only* upside I can see with "fetch --set-head" to blindly follow every switch of HEAD on the remote end is that you can keep up with the remote that flips its HEAD very often, but is that really a realistic need? If we reject such a use case as invalid, I suspect that the end-user experience would be simplified quite a lot. Imagine that we teach "git fetch $repo" to notice refs/remotes/$repo/HEAD is missing, and create it from the remote HEAD information automatically. And we do NOTHING ELSE. What would the end-user experience look like?

* Usually, you start with "git clone" and 'origin' will know which branch 'origin/HEAD' points at.

* You may run "git remote add -f $repo $URL" to add one. Because this runs "git fetch $repo", the previous addition to the "git fetch" will make sure refs/remotes/$repo/HEAD would be there.

* You may run "git remote add $repo $URL" to add one, and then separately "git fetch $repo" yourself. The end result would be the same; refs/remotes/$repo/HEAD will be there.

Having said all that, the implementation here ...

builtin/fetch.c static int fetch_finished(int result, struct strbuf *out, · line 1973

Quoted 10 lines
builtin/fetch.c +10 -0
+static int run_set_head(const char *name)
+{
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	strvec_push(&cmd.args, "remote");
+	strvec_push(&cmd.args, "set-head");
+	strvec_push(&cmd.args, "--auto");
+	strvec_push(&cmd.args, name);
+	cmd.git_cmd = 1;
+	return run_command(&cmd);
+}

... does look quite straight-forward.

builtin/fetch.c static int fetch_multiple(struct string_list *list, int max_children, · line 2029

Quoted 11 lines
builtin/fetch.c +4 -0
+static int fetch_multiple(struct string_list *list, int max_children, int set_head,
+			const struct fetch_config *config)
 {
 	int i, result = 0;
 	struct strvec argv = STRVEC_INIT;
@@ -2014,6 +2025,8 @@ static int fetch_multiple(struct string_list *list, int max_children,
 				error(_("could not fetch %s"), name);
 				result = 1;
 			}
+			if (set_head && run_set_head(name))
+				result = 1;

This looked a bit questionable---I expected that we'd run the subfetches with "--set-head" option, but this makes us do the set-head step ourselves after the subfetches are done. What are pros-and-cons considered to reach the decision to do it this way?

Thanks.

#3 lore raw

Re: [RFC PATCH v2 1/2] fetch: set-head with --set-head option

Hey Junio,

thanks for the very speedy feedback!

On Wed Sep 11, 2024 at 00:19, Junio C Hamano <[email protected]> wrote:

[snip]

Quoted 5 lines

Ideally, because every "git fetch" you do will automatically learn what their HEAD of the day points at, even without "--set-head", it may be nice to let the user know when their HEAD changed, so that the user can inspect the situation and decide.

That would actually make sense, we could print a message saying HEAD has changed and I guess helpfully print the exact set-head command they would need to manually update should they wish to do so.

Quoted 22 lines

If "fetch $repo", when it notices that refs/remotes/$repo/HEAD is missing, always unconditionally stores where their HEAD points at in refs/remotes/$repo/HEAD, and did nothing else, wouldn't that be sufficient?

The users have "remote set-head" to do this when needed. What is the true motivation that "fetch" (which presumably happens a lot more often) needs to be involved in this process? The *only* upside I can see with "fetch --set-head" to blindly follow every switch of HEAD on the remote end is that you can keep up with the remote that flips its HEAD very often, but is that really a realistic need? If we reject such a use case as invalid, I suspect that the end-user experience would be simplified quite a lot. Imagine that we teach "git fetch $repo" to notice refs/remotes/$repo/HEAD is missing, and create it from the remote HEAD information automatically. And we do NOTHING ELSE. What would the end-user experience look like?

* Usually, you start with "git clone" and 'origin' will know which branch 'origin/HEAD' points at.

Quoted 7 lines

* You may run "git remote add -f $repo $URL" to add one. Because this runs "git fetch $repo", the previous addition to the "git fetch" will make sure refs/remotes/$repo/HEAD would be there.

* You may run "git remote add $repo $URL" to add one, and then separately "git fetch $repo" yourself. The end result would be the same; refs/remotes/$repo/HEAD will be there.

I'm convinced :) It also does drop a lot of complexity. So there will be no extra flag for fetch, rather:

- if the remote HEAD does not exist, we create it

- if it does exist, but has changed we print a message saying it was changed from X to Y and print the required command to update to this

- no configuration needed

The only place I can imagine this not being sufficient is in a CI/CD process that is fetching into a cached repo needs to be updated, but then those people can just always run remote set-head -a.

Quoted 15 lines

Having said all that, the implementation here ...

builtin/fetch.c static int fetch_finished(int result, struct strbuf *out, · line 1973

Quoted 10 lines
builtin/fetch.c +10 -0
+static int run_set_head(const char *name)
+{
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	strvec_push(&cmd.args, "remote");
+	strvec_push(&cmd.args, "set-head");
+	strvec_push(&cmd.args, "--auto");
+	strvec_push(&cmd.args, name);
+	cmd.git_cmd = 1;
+	return run_command(&cmd);
+}

... does look quite straight-forward.

Unfortunately, as Jeff has pointed out in the other thread, this implementation requires the user to authenticate twice ... Now, we could still rely on set-head to actually do the writing, since if you explicitly give it what to set to it will not do a network query, but considering all of the above, I think it would make more sense not to do this, rather just bring in the required logic here. This would also allow for the second patch to be a bit more explicit on what did or did not happen during a remote set-head.

Quoted 17 lines

builtin/fetch.c static int fetch_multiple(struct string_list *list, int max_children, · line 2029

Quoted 12 lines
builtin/fetch.c +4 -0
+static int fetch_multiple(struct string_list *list, int max_children, int set_head,
+			const struct fetch_config *config)
 {
 	int i, result = 0;
 	struct strvec argv = STRVEC_INIT;
@@ -2014,6 +2025,8 @@ static int fetch_multiple(struct string_list *list, int max_children,
 				error(_("could not fetch %s"), name);
 				result = 1;
 			}
+			if (set_head && run_set_head(name))
+				result = 1;

This looked a bit questionable---I expected that we'd run the subfetches with "--set-head" option, but this makes us do the set-head step ourselves after the subfetches are done. What are pros-and-cons considered to reach the decision to do it this way?

Just noobish oversight, I figured out how to do it in the subfetch, but with the above there will be no need for this anyway I guess.

I'll send a v2 soonish.

Best,
Bence

#4 lore raw

Re: [RFC PATCH v2 1/2] fetch: set-head with --set-head option

Quoted 8 lines · Bence Ferdinandy
Quoted 4 lines

Ideally, because every "git fetch" you do will automatically learn what their HEAD of the day points at, even without "--set-head", it may be nice to let the user know when their HEAD changed, so that the user can inspect the situation and decide.

That would actually make sense, we could print a message saying HEAD has changed and I guess helpfully print the exact set-head command they would need to manually update should they wish to do so.

We need to be careful if we were to do this, though. A user may see that their HEAD points at their 'main' branch, and they know the remote-tracking HEAD points at 'next' branch. But the only thing the latter tells us is that 'next' is, as far as this user is concerned, the primary branch they are interested in from this remote. It may have been set earlier with "git remtoe set-head" explicitly, or it may have been set back when "git clone" created this repository and back then the remote had 'next' marked as its primary branch. In other words, the HEAD we learned from remote while we are fetching from it may or may not be the same from the remote-tracking HEAD we have, but it does not mean that the remote recently flipped its HEAD if these two are different, but what we want to report is "their HEAD used to point at 'master' but now it is pointing at 'main'".

Quoted 8 lines

So there will be no
extra flag for fetch, rather:

- if the remote HEAD does not exist, we create it

- if it does exist, but has changed we print a message saying it was changed from X to Y and print the required command to update to this

- no configuration needed

Very good, with two reservations.

- if the remote HEAD does not exist, we may still not want to create it. Imagine

[remote "his"]
url = https://git.kernel.org/pub/scm/git/git
push = refs/heads/maint
push = refs/heads/master
push = refs/heads/next
push = +refs/heads/seen

without any refspec for the fetching side. "git fetch his master" may learn where the remote HEAD is, and it may even be pointing at their 'master' branch, but because we do not maintain any remote tracking information for their 'master' (in other words, refs/remotes/his/master is not updated by this 'fetch' and there is no configuration to make future 'fetch' to do so).

- it would be very nice to report when we notice that they changed their HEAD, but I do not think we have enough information to do so. Our existing refs/remotes/origin/HEAD may not have been set to match their HEAD in the first place.

Thanks.

#5 lore raw

v3 cover fetch: set remote/HEAD if missing

In reply to Bence Ferdinandy

This series is a complete rewrite of the RFC without using or touching the code of git remote set-head (that part of the RFC is being handled in a new thread of it's own).

Based on the previous discussions it does an atomic update of remote/HEAD if it doesn't exist and is able to. Since we have git remote set-head for manual handling of remote/HEAD, my idea was that it only outputs minimal information and in general send the user to use remote set-head for figuring out issues. If there is a simple, clear HEAD and is changed it will give the command to use for switching to this and if something went wrong it tells the user to check with remote set-head. I'm not sure if this is really needed to be honest.

A note on tests:

- the first patch changing refs_update_symref passes all tests

- the series in itself breaks many fetch tests currently, most of them seem to stem from the fact that we now have remote/HEAD refs as extra

I'm planning to add a test to fetch for testing not to overwrite existing refs, and of course I'll go and clean up all the tests, but it would be nice to know beforehand if the approach is good and to finalize all the outputs before changing 30 something tests.

Bence Ferdinandy (2):
update_symref: add REF_CREATE_ONLY option
fetch: set remote/HEAD if it does not exist

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  4 +--
 builtin/clone.c           |  6 ++--
 builtin/fetch.c           | 71 +++++++++++++++++++++++++++++++++++++++
 builtin/notes.c           |  2 +-
 builtin/remote.c          |  6 ++--
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    |  6 ++--
 refs.h                    | 12 +++++--
 refs/files-backend.c      |  8 +++++
 reset.c                   |  2 +-
 sequencer.c               |  2 +-
 setup.c                   |  2 +-
 t/helper/test-ref-store.c |  2 +-
 15 files changed, 108 insertions(+), 21 deletions(-)
Signature · 1 line
2.46.1.546.gaa0cd55cd3.dirty
#6 lore raw

PATCH v3 1/2 update_symref: add REF_CREATE_ONLY option

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

---

Notes:
v3: new patch, passes all tests on it's own

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  4 ++--
 builtin/clone.c           |  6 +++---
 builtin/notes.c           |  2 +-
 builtin/remote.c          |  6 +++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    |  6 +++---
 refs.h                    | 12 ++++++++++--
 refs/files-backend.c      |  8 ++++++++
 reset.c                   |  2 +-
 sequencer.c               |  2 +-
 setup.c                   |  2 +-
 t/helper/test-ref-store.c |  2 +-
 14 files changed, 37 insertions(+), 21 deletions(-)
builtin/branch.c +1 -1
index c98601c6fe..6025bca45e 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, 0, logmsg))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +2 -2
index 4cfe6fab50..23e28321d6 100644
@@ -1011,7 +1011,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, 0, msg.buf) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1475,7 +1475,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, 0, "checkout -b");
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index 269b6e18a4..43b7878a79 100644
@@ -659,7 +659,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, branch_top);
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
-				       remote_head_points_at->peer_ref->name,
+				       remote_head_points_at->peer_ref->name, 0,
 				       msg) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
@@ -672,7 +672,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, 0, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -701,7 +701,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, 0, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 04f9dfb7fb..6b42d1139f 100644
@@ -978,7 +978,7 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    default_notes_ref(), wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", default_notes_ref(), NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", default_notes_ref(), 0, NULL))
 			die(_("failed to store link to current notes ref (%s)"),
 			    default_notes_ref());
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 0acc547d69..d28c65599d 100644
@@ -243,7 +243,7 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, 0, "remote add"))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -863,7 +863,7 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, 0, buf3.buf))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1443,7 +1443,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, 0, "remote set-head"))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 81abdd170f..52de3e02af 100644
@@ -84,7 +84,7 @@ int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], 0, msg);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index 41e7f6a327..71434737e8 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, 0, NULL);
 	if (ret)
 		goto done;
 
refs.c +3 -3
index ceb72d4bd7..7afe46cadc 100644
@@ -2085,8 +2085,9 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 	return peel_object(r, base, peeled) ? -1 : 0;
 }
 
+
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const unsigned int extra_flags, const char *logmsg)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2095,7 +2096,7 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
 	    ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
+				   target, NULL, REF_NO_DEREF | extra_flags,
 				   logmsg, &err) ||
 	    ref_transaction_commit(transaction, &err)) {
 		ret = error("%s", err.buf);
@@ -2920,4 +2921,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +10 -2
index f8b919a138..d907451d13 100644
@@ -569,7 +569,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const unsigned int extra_flags, const char *logmsg);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
@@ -672,13 +672,21 @@ struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
  */
 #define REF_SKIP_CREATE_REFLOG (1 << 12)
 
+/*
+ * If the reference has already been created do not touch it.
+ */
+
+#define REF_CREATE_ONLY (1 << 13)
+
+
 /*
  * Bitmask of all of the flags that are allowed to be passed in to
  * ref_transaction_update() and friends:
  */
 #define REF_TRANSACTION_UPDATE_ALLOWED_FLAGS                                  \
 	(REF_NO_DEREF | REF_FORCE_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION | \
-	 REF_SKIP_REFNAME_VERIFICATION | REF_SKIP_CREATE_REFLOG)
+	 REF_SKIP_REFNAME_VERIFICATION | REF_SKIP_CREATE_REFLOG | \
+	 REF_CREATE_ONLY)
 
 /*
  * Add a reference update to transaction. `new_oid` is the value that
refs/files-backend.c +8 -0
index c7f3f4e591..1440b69b87 100644
@@ -2993,6 +2993,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
 		struct ref_update *update = transaction->updates[i];
 		struct ref_lock *lock = update->backend_data;
 
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
 		if (update->flags & REF_NEEDS_COMMIT ||
 		    update->flags & REF_LOG_ONLY) {
 			if (parse_and_write_reflog(refs, update, lock, err)) {
@@ -3031,6 +3033,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
 	 */
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
 		if (update->flags & REF_DELETING &&
 		    !(update->flags & REF_LOG_ONLY) &&
 		    !(update->flags & REF_IS_PRUNING)) {
@@ -3061,6 +3065,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
 		struct ref_lock *lock = update->backend_data;
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
 
 		if (update->flags & REF_DELETING &&
 		    !(update->flags & REF_LOG_ONLY)) {
@@ -3085,6 +3091,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
 
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
 
 		if (update->flags & REF_DELETED_RMDIR) {
 			/*
reset.c +1 -1
index b22b1be792..8dce5f2133 100644
@@ -75,7 +75,7 @@ static int update_refs(const struct reset_head_opts *opts,
 				      UPDATE_REFS_MSG_ON_ERR);
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
-						 "HEAD", switch_to_branch,
+						 "HEAD", switch_to_branch, 0,
 						 reflog_head);
 	}
 	if (!ret && run_hook)
sequencer.c +1 -1
index 8d01cd50ac..924a78dab8 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, 0, msg)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +1 -1
index 29f8673921..6a1fdef2c3 100644
@@ -2169,7 +2169,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, 0, NULL) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..90af41edce 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, 0, logmsg);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.46.1.546.gaa0cd55cd3.dirty
#7 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

Quoted 4 lines · Bence Ferdinandy

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

If I wanted to create a symref that points at A, there are three cases:

(1) the symref does not exist.
(2) the symref exists and points at A.
(3) the symref exists and points at B.

I'll see a symref that points at A at the end in the first two cases, and my request is silently ignored in the third case.

I'd expect that the caller can tell the failing case apart from the successful case with the return value or something. The caller might want to tell between the first two cases for reporting purposes, but I do not care as much as I would care about detecting true failures.

Nobody actually passes the flag yet, so we would not be able to tell if any of the added code is buggy from this step alone. Let's see what happens in the next patch ;-).

refs.c int peel_iterated_oid(struct repository *r, const struct object_id *base, struct · line 2090

Quoted 12 lines
refs.c +2 -1
index ceb72d4bd7..7afe46cadc 100644
@@ -2085,8 +2085,9 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 	return peel_object(r, base, peeled) ? -1 : 0;
 }
 
+
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const unsigned int extra_flags, const char *logmsg)

While it is not _wrong_ per-se to mark an "unsigned int" parameter as "const", it is a bit unusual in this code base. The only thing it prevents us from doing is to mutate it until this function returns, which does not help all that much in making the code safer, as opposed to marking a parameter of a pointer type as a const pointer.

#8 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

Quoted 1 line · Junio C Hamano

Bence Ferdinandy <[email protected]> writes:

[ snip]

Quoted 6 lines

If I wanted to create a symref that points at A, there are three cases:

(1) the symref does not exist.
(2) the symref exists and points at A.
(3) the symref exists and points at B.

Quoted 8 lines

I'll see a symref that points at A at the end in the first two cases, and my request is silently ignored in the third case.

I'd expect that the caller can tell the failing case apart from the successful case with the return value or something. The caller might want to tell between the first two cases for reporting purposes, but I do not care as much as I would care about detecting true failures.

Hmm. So in case I'm passing REF_CREATE_ONLY I would not expect the above cases to be error in the sense that transaction_finish should not report a failure and thus have all callers assume things went wrong. On the other hand it's a valid concern, that the caller may want to check what happened. Actually, the idea that I mentioned in

https://lore.kernel.org/git/[email protected]/

may actually be useful here as well. We could record the state of the reference atomically before the transaction in update, and then if the caller is interested, they can match this against what they requested. That way they can figure out which of the 3 cases they were in without raceconditions after the situation. Actually, this way any feedback could be given to the user post transaction here as well.

If this sounds sensible, then I guess it would make sense to rejoin the set-head patch into this thread as well ...

[snip]

Quoted 9 lines
Quoted 9 lines
refs.c +0 -0
index ceb72d4bd7..7afe46cadc 100644
@@ -2085,8 +2085,9 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 	return peel_object(r, base, peeled) ? -1 : 0;
 }
 
Quoted 11 lines

refs.c int peel_iterated_oid(struct repository *r, const struct object_id *base, struct · line 2090

Quoted 4 lines
refs.c +2 -1
+
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const unsigned int extra_flags, const char *logmsg)

While it is not _wrong_ per-se to mark an "unsigned int" parameter as "const", it is a bit unusual in this code base. The only thing it prevents us from doing is to mutate it until this function returns, which does not help all that much in making the code safer, as opposed to marking a parameter of a pointer type as a const pointer.

Makes sense, I'll drop it.

Thanks very much for your patience!

Best,
Bence

Signature · 1 line
bence.ferdinandy.com
#9 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

In reply to Bence Ferdinandy
Quoted 4 lines · Bence Ferdinandy

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

I'm not sure we need a new flag to do this as it is already supported by the ref transaction api.

	struct ref_transaction *t;
	struct strbuf err = STRBUF_INIT;
	struct ref_store refs = get_main_ref_store(the_repository);
	int ret = 0;

	t = ref_transaction_begin(refs, &err);
	if (!t ||
	    ref_transaction_create(t, b_head.buf, NULL, b_remote_head.buf,
				   REF_NO_DEREF, "fetch", &err) ||
	    ref_transaction_commit(t, &err))
		ret = error(_("%s", err.buf));

	ref_transaction_free(transaction);
	strbuf_release(&err);

	return ret;

Best Wishes

Phillip

Quoted 315 lines

---

Notes:
v3: new patch, passes all tests on it's own

  builtin/branch.c          |  2 +-
  builtin/checkout.c        |  4 ++--
  builtin/clone.c           |  6 +++---
  builtin/notes.c           |  2 +-
  builtin/remote.c          |  6 +++---
  builtin/symbolic-ref.c    |  2 +-
  builtin/worktree.c        |  2 +-
  refs.c                    |  6 +++---
  refs.h                    | 12 ++++++++++--
  refs/files-backend.c      |  8 ++++++++
  reset.c                   |  2 +-
  sequencer.c               |  2 +-
  setup.c                   |  2 +-
  t/helper/test-ref-store.c |  2 +-
  14 files changed, 37 insertions(+), 21 deletions(-)
builtin/branch.c +1 -1
index c98601c6fe..6025bca45e 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
  			continue;
 
  		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, 0, logmsg))
  			ret = error(_("HEAD of working tree %s is not updated"),
  				    worktrees[i]->path);
  	}
builtin/checkout.c +2 -2
index 4cfe6fab50..23e28321d6 100644
@@ -1011,7 +1011,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
  			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
  		}
  	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, 0, msg.buf) < 0)
  			die(_("unable to update HEAD"));
  		if (!opts->quiet) {
  			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1475,7 +1475,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
  		die(_("You are on a branch yet to be born"));
  	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
  	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, 0, "checkout -b");
  	strbuf_release(&branch_ref);
  	if (!opts->quiet)
  		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index 269b6e18a4..43b7878a79 100644
@@ -659,7 +659,7 @@ static void update_remote_refs(const struct ref *refs,
  		strbuf_addstr(&head_ref, branch_top);
  		strbuf_addstr(&head_ref, "HEAD");
  		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
-				       remote_head_points_at->peer_ref->name,
+				       remote_head_points_at->peer_ref->name, 0,
  				       msg) < 0)
  			die(_("unable to update %s"), head_ref.buf);
  		strbuf_release(&head_ref);
@@ -672,7 +672,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
  	const char *head;
  	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
  		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, 0, NULL) < 0)
  			die(_("unable to update HEAD"));
  		if (!option_bare) {
  			refs_update_ref(get_main_ref_store(the_repository),
@@ -701,7 +701,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
  		 * Unborn head from remote; same as "our" case above except
  		 * that we have no ref to update.
  		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, 0, NULL) < 0)
  			die(_("unable to update HEAD"));
  		if (!option_bare)
  			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 04f9dfb7fb..6b42d1139f 100644
@@ -978,7 +978,7 @@ static int merge(int argc, const char **argv, const char *prefix)
  			die(_("a notes merge into %s is already in-progress at %s"),
  			    default_notes_ref(), wt->path);
  		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", default_notes_ref(), NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", default_notes_ref(), 0, NULL))
  			die(_("failed to store link to current notes ref (%s)"),
  			    default_notes_ref());
  		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 0acc547d69..d28c65599d 100644
@@ -243,7 +243,7 @@ static int add(int argc, const char **argv, const char *prefix)
  		strbuf_reset(&buf2);
  		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, 0, "remote add"))
  			result = error(_("Could not setup master '%s'"), master);
  	}
 
@@ -863,7 +863,7 @@ static int mv(int argc, const char **argv, const char *prefix)
  		strbuf_reset(&buf3);
  		strbuf_addf(&buf3, "remote: renamed %s to %s",
  				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, 0, buf3.buf))
  			die(_("creating '%s' failed"), buf.buf);
  		display_progress(progress, ++refs_renamed_nr);
  	}
@@ -1443,7 +1443,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
  		/* make sure it's valid */
  		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
  			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, 0, "remote set-head"))
  			result |= error(_("Could not setup %s"), buf.buf);
  		else if (opt_a)
  			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 81abdd170f..52de3e02af 100644
@@ -84,7 +84,7 @@ int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
  		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
  			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
  		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], 0, msg);
  		break;
  	default:
  		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index 41e7f6a327..71434737e8 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
  		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
  				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
  	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, 0, NULL);
  	if (ret)
  		goto done;
 
refs.c +3 -3
index ceb72d4bd7..7afe46cadc 100644
@@ -2085,8 +2085,9 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
  	return peel_object(r, base, peeled) ? -1 : 0;
  }
 
+
  int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const unsigned int extra_flags, const char *logmsg)
  {
  	struct ref_transaction *transaction;
  	struct strbuf err = STRBUF_INIT;
@@ -2095,7 +2096,7 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
  	transaction = ref_store_transaction_begin(refs, &err);
  	if (!transaction ||
  	    ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
+				   target, NULL, REF_NO_DEREF | extra_flags,
  				   logmsg, &err) ||
  	    ref_transaction_commit(transaction, &err)) {
  		ret = error("%s", err.buf);
@@ -2920,4 +2921,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
  	return (update->flags & REF_HAVE_OLD) &&
  		(!is_null_oid(&update->old_oid) || update->old_target);
  }
-
refs.h +10 -2
index f8b919a138..d907451d13 100644
@@ -569,7 +569,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
  		    const char *newref, const char *logmsg);
 
  int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const unsigned int extra_flags, const char *logmsg);
 
  enum action_on_err {
  	UPDATE_REFS_MSG_ON_ERR,
@@ -672,13 +672,21 @@ struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
   */
  #define REF_SKIP_CREATE_REFLOG (1 << 12)
 
+/*
+ * If the reference has already been created do not touch it.
+ */
+
+#define REF_CREATE_ONLY (1 << 13)
+
+
  /*
   * Bitmask of all of the flags that are allowed to be passed in to
   * ref_transaction_update() and friends:
   */
  #define REF_TRANSACTION_UPDATE_ALLOWED_FLAGS                                  \
  	(REF_NO_DEREF | REF_FORCE_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION | \
-	 REF_SKIP_REFNAME_VERIFICATION | REF_SKIP_CREATE_REFLOG)
+	 REF_SKIP_REFNAME_VERIFICATION | REF_SKIP_CREATE_REFLOG | \
+	 REF_CREATE_ONLY)
 
  /*
   * Add a reference update to transaction. `new_oid` is the value that
refs/files-backend.c +8 -0
index c7f3f4e591..1440b69b87 100644
@@ -2993,6 +2993,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
  		struct ref_update *update = transaction->updates[i];
  		struct ref_lock *lock = update->backend_data;
 
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
  		if (update->flags & REF_NEEDS_COMMIT ||
  		    update->flags & REF_LOG_ONLY) {
  			if (parse_and_write_reflog(refs, update, lock, err)) {
@@ -3031,6 +3033,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
  	 */
  	for (i = 0; i < transaction->nr; i++) {
  		struct ref_update *update = transaction->updates[i];
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
  		if (update->flags & REF_DELETING &&
  		    !(update->flags & REF_LOG_ONLY) &&
  		    !(update->flags & REF_IS_PRUNING)) {
@@ -3061,6 +3065,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
  	for (i = 0; i < transaction->nr; i++) {
  		struct ref_update *update = transaction->updates[i];
  		struct ref_lock *lock = update->backend_data;
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
 
  		if (update->flags & REF_DELETING &&
  		    !(update->flags & REF_LOG_ONLY)) {
@@ -3085,6 +3091,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
 
  	for (i = 0; i < transaction->nr; i++) {
  		struct ref_update *update = transaction->updates[i];
+		if (update->flags & REF_CREATE_ONLY && refs_ref_exists(ref_store, update->refname))
+			continue;
 
  		if (update->flags & REF_DELETED_RMDIR) {
  			/*
reset.c +1 -1
index b22b1be792..8dce5f2133 100644
@@ -75,7 +75,7 @@ static int update_refs(const struct reset_head_opts *opts,
  				      UPDATE_REFS_MSG_ON_ERR);
  		if (!ret)
  			ret = refs_update_symref(get_main_ref_store(the_repository),
-						 "HEAD", switch_to_branch,
+						 "HEAD", switch_to_branch, 0,
  						 reflog_head);
  	}
  	if (!ret && run_hook)
sequencer.c +1 -1
index 8d01cd50ac..924a78dab8 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
  			}
  			msg = reflog_message(opts, "finish", "returning to %s",
  				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, 0, msg)) {
  				res = error(_("could not update HEAD to %s"),
  					head_ref.buf);
  				goto cleanup_head_ref;
setup.c +1 -1
index 29f8673921..6a1fdef2c3 100644
@@ -2169,7 +2169,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
  			die(_("invalid initial branch name: '%s'"),
  			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, 0, NULL) < 0)
  			exit(1);
  		free(ref);
  	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..90af41edce 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
  	const char *target = notnull(*argv++, "target");
  	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, 0, logmsg);
  }
 
  static struct flag_definition transaction_flags[] = {
#10 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

Quoted 8 lines · Phillip Wood
Quoted 4 lines · Bence Ferdinandy

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

I'm not sure we need a new flag to do this as it is already supported by the ref transaction api.

Thanks, I was not aware of ref_transaction_create. It also seems to return with TRANSACTION_NAME_CONFLICT so we should be able to see from the error code if indeed the existence was the problem or something else went wrong.

Best,
Bence

#11 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

Quoted 7 lines · Bence Ferdinandy
Quoted 6 lines · Phillip Wood
Quoted 4 lines · Bence Ferdinandy

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

Quoted 6 lines
Quoted 2 lines

I'm not sure we need a new flag to do this as it is already supported by the ref transaction api.

Thanks, I was not aware of ref_transaction_create. It also seems to return with TRANSACTION_NAME_CONFLICT so we should be able to see from the error code if indeed the existence was the problem or something else went wrong.

Thank you for working on this, and thanks, Phillip, for a useful suggestion.

#12 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

In reply to Bence Ferdinandy
Quoted 8 lines · Bence Ferdinandy
Quoted 6 lines · Phillip Wood
Quoted 4 lines · Bence Ferdinandy

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

Quoted 6 lines
Quoted 2 lines

I'm not sure we need a new flag to do this as it is already supported by the ref transaction api.

Thanks, I was not aware of ref_transaction_create. It also seems to return with TRANSACTION_NAME_CONFLICT so we should be able to see from the error code if indeed the existence was the problem or something else went wrong.

Unfortunately, it seems that my reading of the code did not pass practice. When using ref_transaction_create ref_transaction_commit will return with -2 if the reference already exists, but it also returns with -2 for various other issues, like if the lock file already exists. I could parse the error message to see what was the cause, but that doesn't feel like a robust solution. Since fetch should _not_ error out on this, I think the REF_CREATE_ONLY flag is warranted. As it stands, it would serve a different purpose than ref_transaction_create, i.e. a "silent" create-only.

I'll send a v4 tomorrow hopefully.

Best,
Bence

#13 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

Quoted 26 lines · Bence Ferdinandy
Quoted 8 lines · Bence Ferdinandy
Quoted 6 lines · Phillip Wood
Quoted 4 lines · Bence Ferdinandy

Add a new REF_CREATE_ONLY flag for use by the files backend which will only update the symref if it doesn't already exist. Add the possibility to pass extra flags to refs_update_symref so that it can utilize this new flag.

Quoted 6 lines
Quoted 2 lines

I'm not sure we need a new flag to do this as it is already supported by the ref transaction api.

Thanks, I was not aware of ref_transaction_create. It also seems to return with TRANSACTION_NAME_CONFLICT so we should be able to see from the error code if indeed the existence was the problem or something else went wrong.

Unfortunately, it seems that my reading of the code did not pass practice. When using ref_transaction_create ref_transaction_commit will return with -2 if the reference already exists, but it also returns with -2 for various other issues, like if the lock file already exists. I could parse the error message to see what was the cause, but that doesn't feel like a robust solution. Since fetch should _not_ error out on this, I think the REF_CREATE_ONLY flag is warranted. As it stands, it would serve a different purpose than ref_transaction_create, i.e. a "silent" create-only.

Quoted 1 line

I'll send a v4 tomorrow hopefully.

I don't think that is a good reason to introduce this new flag though. If we need to have a proper way to identify this specific failure case we should rather update the already-existing mechanism to give us useful signals, shouldn't we?

The problem with this flag is that it basically duplicates functionality that already exists, and it needs to be wired up by every ref backend that we have and that we're adding in the future. Your patch for example only implements the functionality for the "files" backend, but it must also be wired up for the "reftable" backend or otherwise it would be broken.

Another issue is that it gives you more ways to create nonsensical ref updates. With it you could for example create requests with a non-zero old object ID, and if it has REF_CREATE_ONLY set it would never be possible to fulfill the request. There's probably other cases where you can create nonsensical ref updates already, but we shouldn't add more ways of doing that.

Mind you, if we go the way I propose and improve the error reporting we'd also have to adapt both backends to do so. But that would be plugging a gap for which we have no proper solution right now instead of circumventing the current design by duplicating the functionality that we already have in a way that makes us able to handle this.

Patrick

#14 lore raw

Re: [PATCH v3 1/2] update_symref: add REF_CREATE_ONLY option

Quoted 19 lines · Patrick Steinhardt

I don't think that is a good reason to introduce this new flag though. If we need to have a proper way to identify this specific failure case we should rather update the already-existing mechanism to give us useful signals, shouldn't we?

The problem with this flag is that it basically duplicates functionality that already exists, and it needs to be wired up by every ref backend that we have and that we're adding in the future. Your patch for example only implements the functionality for the "files" backend, but it must also be wired up for the "reftable" backend or otherwise it would be broken.

Another issue is that it gives you more ways to create nonsensical ref updates. With it you could for example create requests with a non-zero old object ID, and if it has REF_CREATE_ONLY set it would never be possible to fulfill the request. There's probably other cases where you can create nonsensical ref updates already, but we shouldn't add more ways of doing that.

Quoted 7 lines

Mind you, if we go the way I propose and improve the error reporting we'd also have to adapt both backends to do so. But that would be plugging a gap for which we have no proper solution right now instead of circumventing the current design by duplicating the functionality that we already have in a way that makes us able to handle this.

Patrick

You make a convincing argument :) I'll try to see if I can add another transaction error code for when you only want to create not overwrite and the ref already exists and pass it up (for both files and reftables, you also don't mention it, but I think this would not concern packed after a quick glance at the code).

Best,
Bence

Signature · 1 line
bence.ferdinandy.com
#15 lore raw

v4 cover improve handling of remote/HEAD

This version has dropped some previous patches in favour of new ones. These solve the problem of atomically deciding what the head was before we updated it and also not reinventing the wheel for having an "create this ref, but if it already exists, fail silently" call.

Since now both changes to remote set-head and fetch utilize some common preceding patches I have again included in this series my changes to remote set-head. Sorry for the mess tangent there.

All tests (that run on my system) pass for the patches up to the last patch, which changes fetch. For the last patch I updated some of the test where it was trivial (lot of remote/HEAD -> something appeared as expected), but there is still work to be done there (i.e. figure out which tests need updating and which are actual bugs in the patch).

One specific thing I wanted to mention here. Junio asked earlier what happens on fetch, when we have a config like this:

Quoted 5 lines

If I am only fetching refs (or HEAD) in FETCH_HEAD for immediate consumtion by doing "git pull bence HEAD" with something like

[remote "bence"]
URL = http://github.com/bence/git

In this case setting head will error out with the generic error message I put at the end.

Bence Ferdinandy (5):
refs_update_symref: atomically record overwritten ref
set-head: better output for --auto
transaction: add TRANSACTION_CREATE_EXISTS error
refs_update_symref: add create_only option
fetch: set remote/HEAD if it does not exist

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 ++-
 builtin/clone.c           |  8 ++--
 builtin/fetch.c           | 83 +++++++++++++++++++++++++++++++++++++++
 builtin/notes.c           |  3 +-
 builtin/remote.c          | 43 ++++++++++++++++----
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 35 ++++++++++++-----
 refs.h                    |  7 +++-
 refs/files-backend.c      | 29 ++++++++++----
 refs/refs-internal.h      |  8 ++++
 refs/reftable-backend.c   |  6 ++-
 reset.c                   |  2 +-
 sequencer.c               |  3 +-
 setup.c                   |  3 +-
 t/helper/test-ref-store.c |  2 +-
 t/t5505-remote.sh         | 13 +++++-
 t/t5514-fetch-multiple.sh |  9 +++++
 19 files changed, 222 insertions(+), 43 deletions(-)
Signature · 1 line
2.47.0.rc0.5.gf1cffeb8df.dirty
#16 lore raw

PATCH v4 1/5 refs_update_symref: atomically record overwritten ref

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten. Make use of ref_transaction's atomicity and record the previous value there. Add a new variable to refs_update_symref's signature to be able to pass this information back up to callers.

---

Notes:
v4: new patch

 builtin/branch.c          | 2 +-
 builtin/checkout.c        | 4 ++--
 builtin/clone.c           | 6 +++---
 builtin/notes.c           | 2 +-
 builtin/remote.c          | 6 +++---
 builtin/symbolic-ref.c    | 2 +-
 builtin/worktree.c        | 2 +-
 refs.c                    | 8 ++++++--
 refs.h                    | 3 ++-
 refs/files-backend.c      | 1 +
 refs/refs-internal.h      | 8 ++++++++
 reset.c                   | 2 +-
 sequencer.c               | 2 +-
 setup.c                   | 2 +-
 t/helper/test-ref-store.c | 2 +-
 15 files changed, 33 insertions(+), 19 deletions(-)
builtin/branch.c +1 -1
index fd1611ebf5..6c87690b58 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +2 -2
index 9c30000d3a..356ee9bcde 100644
@@ -1015,7 +1015,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1479,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, "checkout -b", NULL);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index e77339c847..ead2af20ea 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg) < 0)
+				       msg, NULL) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +702,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 8c26e45526..ba646f06ff 100644
@@ -980,7 +980,7 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 76670ddd8b..d8ff440027 100644
@@ -244,7 +244,7 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +864,7 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1444,7 +1444,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 299d23d76a..7728fbc3c1 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], msg, NULL);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index fc31d072a6..a7ab4193c1 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
 	if (ret)
 		goto done;
 
refs.c +6 -2
index 5f729ed412..301db0dcdc 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2130,6 +2131,10 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 	}
 
 	strbuf_release(&err);
+
+	if (before_target && transaction->updates[0]->before_target)
+		strbuf_addstr(before_target, transaction->updates[0]->before_target);
+
 	if (transaction)
 		ref_transaction_free(transaction);
 
@@ -2948,4 +2953,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +2 -1
index 108dfc93b3..f38616db84 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
refs/files-backend.c +1 -0
index 0824c0b8a9..8415f2d020 100644
@@ -2577,6 +2577,7 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 	}
 
 	update->backend_data = lock;
+	update->before_target = xstrdup_or_null(referent.buf);
 
 	if (update->type & REF_ISSYMREF) {
 		if (update->flags & REF_NO_DEREF) {
refs/refs-internal.h +8 -0
index 2313c830d8..7df3e6271e 100644
@@ -104,6 +104,14 @@ struct ref_update {
 	 */
 	const char *old_target;
 
+	/*
+	 * The previous target before applying new_target will be
+	 * written here, to be used by callers when they do not want to
+	 * check old_target during the transaction, but do want to know
+	 * what it was.
+	 */
+	const char *before_target;
+
 	/*
 	 * One or more of REF_NO_DEREF, REF_FORCE_CREATE_REFLOG,
 	 * REF_HAVE_NEW, REF_HAVE_OLD, or backend-specific flags.
reset.c +1 -1
index b22b1be792..cc36a9ed56 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head);
+						 reflog_head, NULL);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +1 -1
index 8d01cd50ac..23b162924c 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +1 -1
index 94e79b2e48..d95f051465 100644
@@ -2275,7 +2275,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.rc0.5.gf1cffeb8df.dirty
#17 lore raw

Re: [PATCH v4 1/5] refs_update_symref: atomically record overwritten ref

refs.c int refs_update_symref(struct ref_store *refs, const char *ref,

Quoted 15 lines · Bence Ferdinandy
refs.c +2 -1
index 5f729ed412..301db0dcdc 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2130,6 +2131,10 @@ int refs_update_symref(struct ref_store *refs, const char *ref,

Let's extend the precontext of this hunk a bit. The function begins like this:

	transaction = ref_store_transaction_begin(refs, &err);
	if (!transaction ||
	    ref_transaction_update(transaction, ref, NULL, NULL,
				   target, NULL, REF_NO_DEREF,
				   logmsg, &err) ||
	    ref_transaction_commit(transaction, &err)) {
		ret = error("%s", err.buf);

refs.c int refs_update_symref(struct ref_store *refs, const char *ref, · line 2133

Quoted 2 lines
refs.c +0 -0
 	}
 	strbuf_release(&err);

We begin a transaction, update ref to point to target in the transaction, and commit the transaction. An error at any stage of this three-step process will bypass the rest and we give an error message.

refs.c int refs_update_symref(struct ref_store *refs, const char *ref, · line 2136

Quoted 3 lines
refs.c +3 -0
+
+	if (before_target && transaction->updates[0]->before_target)
+		strbuf_addstr(before_target, transaction->updates[0]->before_target);

What if ref_store_transaction_begin() failed?

If we want to say "we append the before_target recorded in the transaction to the caller-supplied strbuf only when we manage to do the update, and we leave before_target intact otherwise" We'd at least need

	if (transaction && before_target &&
            transaction->updates[0]->before_target)

wouldn't it? Like the code that frees it (below), this new call should be prepared to see !transaction.

refs.c int ref_update_expects_existing_old_ref(struct ref_update *update) · line 2951

Quoted 8 lines
refs.c +0 -1
 	if (transaction)
 		ref_transaction_free(transaction);
 
@@ -2948,4 +2953,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-

Good (even though it is unrelated to the topic of this series).

Quoted 19 lines
refs.h +2 -1
index 108dfc93b3..f38616db84 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
refs/files-backend.c +0 -0
index 0824c0b8a9..8415f2d020 100644

refs/files-backend.c static int lock_ref_for_update(struct files_ref_store *refs, · line 2580

Quoted 4 lines
refs/files-backend.c +1 -0
@@ -2577,6 +2577,7 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 	}
 
 	update->backend_data = lock;
+	update->before_target = xstrdup_or_null(referent.buf);

OK, so this comes from the backends, as they are the only thing that knows what the current value is (the caller can only indirectly infer if it has old_target, in which case the backend checks if the attempt is stale).

Do we need a corresponding change for the other, reftable, backend?

Quoted 13 lines
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
 }
 
 static struct flag_definition transaction_flags[] = {
#18 lore raw

PATCH v4 2/5 set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

 builtin/remote.c  | 36 ++++++++++++++++++++++++++++++------
 t/t5505-remote.sh | 13 ++++++++++++-
 2 files changed, 42 insertions(+), 7 deletions(-)
builtin/remote.c +30 -6
index d8ff440027..c61a7800ff 100644
@@ -1399,12 +1399,34 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
 			 N_("set refs/remotes/<name>/HEAD according to remote")),
@@ -1434,7 +1456,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
+		if (refs_delete_ref(refs, NULL, buf.buf, NULL, REF_NO_DEREF))
 			result |= error(_("Could not delete %s"), buf.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
@@ -1442,17 +1464,19 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	if (head_name) {
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
+		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
 			result |= error(_("Could not setup %s"), buf.buf);
-		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+		else if (opt_a) {
+			report_auto(argv[0], head_name, &buf_prev);
+		}
 		free(head_name);
 	}
 
 	strbuf_release(&buf);
 	strbuf_release(&buf2);
+	strbuf_release(&buf_prev);
 	return result;
 }
 
t/t5505-remote.sh +12 -1
index 532035933f..711d6e5598 100755
@@ -434,7 +434,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "two/HEAD set to main" >expect &&
+		echo "'\''two/HEAD'\'' is now created and points to '\''main'\''" >expect &&
 		test_cmp expect output
 	)
 '
@@ -453,6 +453,17 @@ test_expect_success 'set-head explicit' '
 	)
 '
 
+
+test_expect_success 'set-head --auto reports change' '
+	(
+		cd test &&
+		git remote set-head origin side2 &&
+		git remote set-head --auto origin >output 2>&1 &&
+		echo "'\''origin/HEAD'\'' has changed from '\''side2'\'' and now points to '\''main'\''" >expect &&
+		test_cmp expect output
+	)
+'
+
 cat >test/expect <<EOF
 Pruning origin
 URL: $(pwd)/one
Signature · 1 line
2.47.0.rc0.5.gf1cffeb8df.dirty
#19 lore raw

Re: [PATCH v4 2/5] set-head: better output for --auto

Quoted 8 lines · Bence Ferdinandy
builtin/remote.c +8 -0
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1419

Quoted 10 lines
builtin/remote.c +10 -0
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+}

OK.

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1429

Quoted 10 lines

static int set_head(int argc, const char **argv, const char *prefix) {

builtin/remote.c +4 -1
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 
+	struct ref_store *refs = get_main_ref_store(the_repository);
+

What does the blank line between "head_name" and "refs" declaration indicate? Is "refs" so special that it must stand separately from all others?

The primary purpose of this step is to pass a strbuf to refs_update_symref() so that we can learn what the original value of the HEAD was, so that report_auto() can give a more intelligent message. The introduction of "refs" to avoid repetitive calls to get_main_ref_store() is orthogonal to that. It is a good change, but it should stand on its own, as a separate "preparatory clean-up" patch.

Quoted 31 lines
t/t5505-remote.sh +12 -1
index 532035933f..711d6e5598 100755
@@ -434,7 +434,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "two/HEAD set to main" >expect &&
+		echo "'\''two/HEAD'\'' is now created and points to '\''main'\''" >expect &&
 		test_cmp expect output
 	)
 '
@@ -453,6 +453,17 @@ test_expect_success 'set-head explicit' '
 	)
 '
 
+
+test_expect_success 'set-head --auto reports change' '
+	(
+		cd test &&
+		git remote set-head origin side2 &&
+		git remote set-head --auto origin >output 2>&1 &&
+		echo "'\''origin/HEAD'\'' has changed from '\''side2'\'' and now points to '\''main'\''" >expect &&
+		test_cmp expect output
+	)
+'
+
 cat >test/expect <<EOF
 Pruning origin
 URL: $(pwd)/one
#20 lore raw

PATCH v4 3/5 transaction: add TRANSACTION_CREATE_EXISTS error

In reply to Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch

 refs.h                  |  4 +++-
 refs/files-backend.c    | 28 ++++++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 27 insertions(+), 11 deletions(-)
refs.h +3 -1
index f38616db84..166affbc89 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +20 -8
index 8415f2d020..272ad81315 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2603,9 +2607,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				int checkret;
+				checkret = check_old_oid(update, &lock->old_oid, err);
+				if  (checkret) {
+					ret = checkret;
+					goto out;
+				}
 			}
 		} else {
 			/*
@@ -2636,9 +2644,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			int checkret;
+			checkret = check_old_oid(update, &lock->old_oid, err);
+			if  (checkret) {
+				ret = checkret;
+				goto out;
+			}
 		}
 
 		/*
refs/reftable-backend.c +4 -2
index f5f957e6de..f66bbf5d49 100644
@@ -1197,10 +1197,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),
@@ -1212,7 +1215,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}
 
Signature · 1 line
2.47.0.rc0.5.gf1cffeb8df.dirty
#21 lore raw

PATCH v4 4/5 refs_update_symref: add create_only option

In reply to Bence Ferdinandy

Allow the caller to specify that it only wants to update the symref if it does not already exist. Silently ignore the error from the transaction API if the symref already exists.

---

Notes:
v4: new patch

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 +++--
 builtin/clone.c           |  8 +++++---
 builtin/notes.c           |  3 ++-
 builtin/remote.c          |  9 ++++++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 29 +++++++++++++++++++++--------
 refs.h                    |  2 +-
 reset.c                   |  2 +-
 sequencer.c               |  3 ++-
 setup.c                   |  3 ++-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 47 insertions(+), 25 deletions(-)
builtin/branch.c +1 -1
index 6c87690b58..3c9bc39800 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL, false))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +3 -2
index 356ee9bcde..d9514e9b7a 100644
@@ -1015,7 +1015,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, 
+					msg.buf, NULL, false) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1480,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b", NULL);
+				    "HEAD", branch_ref.buf, "checkout -b", NULL, false);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +5 -3
index ead2af20ea..25d0bcf3aa 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg, NULL) < 0)
+				       msg, NULL, false) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, 
+					NULL, NULL, false) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +703,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, 
+					NULL, NULL, false) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +2 -1
index ba646f06ff..fb49e491c3 100644
@@ -980,7 +980,8 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, 
+					NULL, NULL, false))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +6 -3
index c61a7800ff..a1cec6276d 100644
@@ -244,7 +244,8 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					"remote add", NULL, false))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +865,8 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					buf3.buf, NULL, false))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1466,7 +1468,8 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf,
+					"remote set-head", &buf_prev, false))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a) {
 			report_auto(argv[0], head_name, &buf_prev);
builtin/symbolic-ref.c +1 -1
index 7728fbc3c1..169f5f5340 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg, NULL);
+					   argv[0], argv[1], msg, NULL, false);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index a7ab4193c1..46b515a243 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL, false);
 	if (ret)
 		goto done;
 
refs.c +21 -8
index 301db0dcdc..e012b89ee9 100644
@@ -2115,19 +2115,32 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target)
+		       struct strbuf *before_target, bool create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
-	int ret = 0;
+	int ret = 0, create_ret = 0;
 
 	transaction = ref_store_transaction_begin(refs, &err);
-	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
-				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
-		ret = error("%s", err.buf);
+	if (create_only) {
+		if (!transaction ||
+		    ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err)) {
+			ret = error("%s", err.buf);
+		}
+		else {
+		    create_ret = ref_transaction_commit(transaction, &err);
+		    if (create_ret && create_ret != TRANSACTION_CREATE_EXISTS)
+			ret = error("%s", err.buf);
+		}
+	}
+	else
+		if (!transaction ||
+		    ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+		    ref_transaction_commit(transaction, &err)) {
+			ret = error("%s", err.buf);
 	}
 
 	strbuf_release(&err);
refs.h +1 -1
index 166affbc89..b64fd2318b 100644
@@ -572,7 +572,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target);
+		       struct strbuf *before_target, bool create_only);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index cc36a9ed56..674896fb61 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head, NULL);
+						 reflog_head, NULL, false);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +2 -1
index 23b162924c..1a46ef56ba 100644
@@ -5107,7 +5107,8 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, 
+						msg, NULL, false)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +2 -1
index d95f051465..67abbfaf3c 100644
@@ -2275,7 +2275,8 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, 
+					NULL, NULL, false) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index a911302bea..b6b06bb2e9 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg, NULL);
+	return refs_update_symref(refs, refname, target, logmsg, NULL, false);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.rc0.5.gf1cffeb8df.dirty
#22 lore raw

PATCH v4 5/5 fetch: set remote/HEAD if it does not exist

In reply to Bence Ferdinandy

If the user has remote/HEAD set already and it looks like it has changed on the server, then print a message, otherwise set it if we can. Silently pass if the user already has the same remote/HEAD set as reported by the server.

---

Notes:
v3: - does not rely on remote set-head anymore so it only authenticates
once
- uses the new REF_CREATE_ONLY to atomically check if the ref exists and only write it if it doesn't
- in all other cases the maximum it does is print a warning

v4: - instead of the discarded REF_CREATE_ONLY, it uses the existing,
but updated transaction api to request a silent create only
- it now uses the atomic before_target to determine reporting
- refactored for legibility

 builtin/fetch.c           | 83 +++++++++++++++++++++++++++++++++++++++
 t/t5514-fetch-multiple.sh |  9 +++++
 2 files changed, 92 insertions(+)
builtin/fetch.c +83 -0
index c900f57721..f10a9d5371 100644
@@ -1577,6 +1577,82 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		;
+	else if (prev_head) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}
+}
+
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1) {
+		result = 1;
+	} else
+		head_name = xstrdup(heads.items[0].string);
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head, true))
+			result |= error(_("Could not setup %s"), b_head.buf);
+		else {
+			report_set_head(remote, head_name, &b_local_head);
+		}
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)
@@ -1646,6 +1722,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes,"HEAD");
+
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1790,6 +1868,10 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		printf("Ran into issues with creating \'%s/HEAD\',\n"
+			"use \'git remote set-head -a %s\' to investigate.\n",
+			gtransport->remote->name,gtransport->remote->name);
 
 cleanup:
 	if (retcode) {
@@ -2020,6 +2102,7 @@ static int fetch_multiple(struct string_list *list, int max_children,
 	return !!result;
 }
 
+
 /*
  * Fetching from the promisor remote should use the given filter-spec
  * or inherit the default filter-spec from the config.
t/t5514-fetch-multiple.sh +9 -0
index 579872c258..ef5874b7b3 100755
@@ -45,14 +45,17 @@ test_expect_success setup '
 '
 
 cat > test/expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -97,6 +100,7 @@ cat > expect << EOF
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
@@ -112,8 +116,10 @@ test_expect_success 'git fetch --multiple (but only one remote)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -221,14 +227,17 @@ test_expect_success 'git fetch --multiple --jobs=0 picks a default' '
 
 create_fetch_all_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
 	  origin/main
 	  origin/side
+	  three/HEAD -> three/main
 	  three/another
 	  three/main
 	  three/side
+	  two/HEAD -> two/main
 	  two/another
 	  two/main
 	  two/side
Signature · 1 line
2.47.0.rc0.5.gf1cffeb8df.dirty
#23 lore raw

Re: [PATCH v4 0/5] improve handling of remote/HEAD

In reply to Bence Ferdinandy
Quoted 19 lines · Bence Ferdinandy

Bence Ferdinandy (5):
refs_update_symref: atomically record overwritten ref
set-head: better output for --auto
transaction: add TRANSACTION_CREATE_EXISTS error
refs_update_symref: add create_only option
fetch: set remote/HEAD if it does not exist

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 ++-
 builtin/clone.c           |  8 ++--
 builtin/fetch.c           | 83 +++++++++++++++++++++++++++++++++++++++
 builtin/notes.c           |  3 +-
 builtin/remote.c          | 43 ++++++++++++++++----
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 35 ++++++++++++-----
 refs.h                    |  7 +++-
 refs/files-backend.c      | 29 ++++++++++----
 refs/refs-internal.h      |  8 ++++
Quoted 8 lines
 refs/reftable-backend.c   |  6 ++-
 reset.c                   |  2 +-
 sequencer.c               |  3 +-
 setup.c                   |  3 +-
 t/helper/test-ref-store.c |  2 +-
 t/t5505-remote.sh         | 13 +++++-
 t/t5514-fetch-multiple.sh |  9 +++++
 19 files changed, 222 insertions(+), 43 deletions(-)

These seem to break some of the tests, either standalone or when merged to 'seen'.

I have the topic queued directly on top of e9356ba3 (another batch after 2.47-rc0, 2024-09-30); here is how the summary report looks like.

Thanks.

Test Summary Report
-------------------
t0410-partial-clone.sh (Wstat: 256 (exited 1) Tests: 38 Failed: 1)
Failed test: 32
Non-zero exit status: 1
t4207-log-decoration-colors.sh (Wstat: 256 (exited 1) Tests: 4 Failed: 1)
Failed test: 2
Non-zero exit status: 1
t5300-pack-object.sh (Wstat: 256 (exited 1) Tests: 56 Failed: 1)
Failed test: 51
Non-zero exit status: 1
t5512-ls-remote.sh (Wstat: 256 (exited 1) Tests: 40 Failed: 1)
Failed test: 32
Non-zero exit status: 1
t5527-fetch-odd-refs.sh (Wstat: 256 (exited 1) Tests: 5 Failed: 1)
Failed test: 4
Non-zero exit status: 1
t5514-fetch-multiple.sh (Wstat: 256 (exited 1) Tests: 25 Failed: 4)
Failed tests: 9-10, 18, 24
Non-zero exit status: 1
t5521-pull-options.sh (Wstat: 256 (exited 1) Tests: 22 Failed: 8)
Failed tests: 2-9
Non-zero exit status: 1
t5505-remote.sh (Wstat: 256 (exited 1) Tests: 114 Failed: 7)
Failed tests: 4, 31, 51-52, 54-56
Non-zero exit status: 1
t5574-fetch-output.sh (Wstat: 256 (exited 1) Tests: 14 Failed: 3)
Failed tests: 11-13
Non-zero exit status: 1
t5703-upload-pack-ref-in-want.sh (Wstat: 256 (exited 1) Tests: 26 Failed: 1)
Failed test: 12
Non-zero exit status: 1
t5616-partial-clone.sh (Wstat: 256 (exited 1) Tests: 46 Failed: 2)
Failed tests: 10, 22
Non-zero exit status: 1
t5516-fetch-push.sh (Wstat: 256 (exited 1) Tests: 120 Failed: 1)
Failed test: 102
Non-zero exit status: 1
t7814-grep-recurse-submodules.sh (Wstat: 256 (exited 1) Tests: 34 Failed: 1)
Failed test: 33
Non-zero exit status: 1
t7900-maintenance.sh (Wstat: 256 (exited 1) Tests: 53 Failed: 1)
Failed test: 23
Non-zero exit status: 1
t7406-submodule-update.sh (Wstat: 256 (exited 1) Tests: 68 Failed: 1)
Failed test: 59
Non-zero exit status: 1
t9211-scalar-clone.sh (Wstat: 256 (exited 1) Tests: 13 Failed: 2)
Failed tests: 8-9
Non-zero exit status: 1
t9210-scalar.sh (Wstat: 256 (exited 1) Tests: 21 Failed: 1)
Failed test: 11
Non-zero exit status: 1
t9902-completion.sh (Wstat: 256 (exited 1) Tests: 256 Failed: 56)
Failed tests: 54-55, 59, 61, 63, 71-75, 77, 86, 88-89

                92-93, 95, 101, 113, 116-117, 119-129, 138-141
                143-157, 162-163, 168, 170-171

Non-zero exit status: 1
Files=1029, Tests=31709, 371 wallclock secs (11.74 usr 4.74 sys + 853.87 cusr 6465.88 csys = 7336.23 CPU)
Result: FAIL

#24 lore raw

Re: [PATCH v4 0/5] improve handling of remote/HEAD

2024. okt. 3. 21:22:13 Junio C Hamano <[email protected]>:

Quoted 30 lines
Quoted 26 lines · Bence Ferdinandy

Bence Ferdinandy (5):
  refs_update_symref: atomically record overwritten ref
  set-head: better output for --auto
  transaction: add TRANSACTION_CREATE_EXISTS error
  refs_update_symref: add create_only option
  fetch: set remote/HEAD if it does not exist

builtin/branch.c          |  2 +-
builtin/checkout.c        |  5 ++-

builtin/clone.c           |  8 ++--
builtin/fetch.c           | 83 +++++++++++++++++++++++++++++++++++++++
builtin/notes.c           |  3 +-

builtin/remote.c          | 43 ++++++++++++++++---- builtin/symbolic-ref.c    |  2 +- builtin/worktree.c        |  2 +-
refs.c                    | 35 ++++++++++++----- refs.h                    |  7 +++- refs/files-backend.c      | 29 ++++++++++---- refs/refs-internal.h      |  8 ++++ refs/reftable-backend.c   |  6 ++-
reset.c                   |  2 +- sequencer.c               |  3 +-
setup.c                   |  3 +- t/helper/test-ref-store.c |  2 +- t/t5505-remote.sh         | 13 +++++- t/t5514-fetch-multiple.sh |  9 +++++

Quoted 1 line
19 files changed, 222 insertions(+), 43 deletions(-)
Quoted 8 lines

These seem to break some of the tests, either standalone or when merged to 'seen'.

I have the topic queued directly on top of e9356ba3 (another batch after 2.47-rc0, 2024-09-30); here is how the summary report looks like.

Thanks.

Sorry, I should have probably left in the RFC prefix to be more clear about this... As I noted in the cover letter, the first four patches pass the tests, the last one doesn't (yet), as I'm still not quite sure if even the approach is fine. If those look good I'll send a v5 and also fix the tests as well. Although based on your review of the first 2 patches there's already some changes needed there, so I can just do a v5 with that and tests fixed and see if that version looks good or not.

I'm currently on a holiday, so my ETA on this is early next week.

Thanks,
Bence

Quoted 61 lines

Test Summary Report
-------------------
t0410-partial-clone.sh                           (Wstat: 256 (exited 1) Tests: 38 Failed: 1) Failed test:  32
  Non-zero exit status: 1
t4207-log-decoration-colors.sh                   (Wstat: 256 (exited 1) Tests: 4 Failed: 1) Failed test:  2
  Non-zero exit status: 1
t5300-pack-object.sh                             (Wstat: 256 (exited 1) Tests: 56 Failed: 1) Failed test:  51
  Non-zero exit status: 1
t5512-ls-remote.sh                               (Wstat: 256 (exited 1) Tests: 40 Failed: 1) Failed test:  32
  Non-zero exit status: 1
t5527-fetch-odd-refs.sh                          (Wstat: 256 (exited 1) Tests: 5 Failed: 1) Failed test:  4
  Non-zero exit status: 1
t5514-fetch-multiple.sh                          (Wstat: 256 (exited 1) Tests: 25 Failed: 4) Failed tests:  9-10, 18, 24
  Non-zero exit status: 1
t5521-pull-options.sh                            (Wstat: 256 (exited 1) Tests: 22 Failed: 8) Failed tests:  2-9
  Non-zero exit status: 1
t5505-remote.sh                                  (Wstat: 256 (exited 1) Tests: 114 Failed: 7) Failed tests:  4, 31, 51-52, 54-56
  Non-zero exit status: 1
t5574-fetch-output.sh                            (Wstat: 256 (exited 1) Tests: 14 Failed: 3) Failed tests:  11-13
  Non-zero exit status: 1
t5703-upload-pack-ref-in-want.sh                 (Wstat: 256 (exited 1) Tests: 26 Failed: 1) Failed test:  12
  Non-zero exit status: 1
t5616-partial-clone.sh                           (Wstat: 256 (exited 1) Tests: 46 Failed: 2) Failed tests:  10, 22
  Non-zero exit status: 1
t5516-fetch-push.sh                              (Wstat: 256 (exited 1) Tests: 120 Failed: 1) Failed test:  102
  Non-zero exit status: 1
t7814-grep-recurse-submodules.sh                 (Wstat: 256 (exited 1) Tests: 34 Failed: 1) Failed test:  33
  Non-zero exit status: 1
t7900-maintenance.sh                             (Wstat: 256 (exited 1) Tests: 53 Failed: 1) Failed test:  23
  Non-zero exit status: 1
t7406-submodule-update.sh                        (Wstat: 256 (exited 1) Tests: 68 Failed: 1) Failed test:  59
  Non-zero exit status: 1
t9211-scalar-clone.sh                            (Wstat: 256 (exited 1) Tests: 13 Failed: 2) Failed tests:  8-9
  Non-zero exit status: 1
t9210-scalar.sh                                  (Wstat: 256 (exited 1) Tests: 21 Failed: 1) Failed test:  11
  Non-zero exit status: 1
t9902-completion.sh                              (Wstat: 256 (exited 1) Tests: 256 Failed: 56) Failed tests:  54-55, 59, 61, 63, 71-75, 77, 86, 88-89
                92-93, 95, 101, 113, 116-117, 119-129, 138-141
                143-157, 162-163, 168, 170-171
  Non-zero exit status: 1
Files=1029, Tests=31709, 371 wallclock secs (11.74 usr  4.74 sys + 853.87 cusr 6465.88 csys = 7336.23 CPU)
Result: FAIL

#25 lore raw

PATCH v5 1/6 refs_update_symref: atomically record overwritten ref

In reply to Junio C Hamano

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten. Make use of ref_transaction's atomicity and record the previous value there. Add a new variable to refs_update_symref's signature to be able to pass this information back up to callers.

---

Notes:
v4: new patch
v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

 builtin/branch.c          | 2 +-
 builtin/checkout.c        | 4 ++--
 builtin/clone.c           | 6 +++---
 builtin/notes.c           | 2 +-
 builtin/remote.c          | 6 +++---
 builtin/symbolic-ref.c    | 2 +-
 builtin/worktree.c        | 2 +-
 refs.c                    | 8 ++++++--
 refs.h                    | 3 ++-
 refs/files-backend.c      | 1 +
 refs/refs-internal.h      | 8 ++++++++
 refs/reftable-backend.c   | 1 +
 reset.c                   | 2 +-
 sequencer.c               | 2 +-
 setup.c                   | 2 +-
 t/helper/test-ref-store.c | 2 +-
 16 files changed, 34 insertions(+), 19 deletions(-)
builtin/branch.c +1 -1
index fd1611ebf5..6c87690b58 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +2 -2
index 9c30000d3a..356ee9bcde 100644
@@ -1015,7 +1015,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1479,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, "checkout -b", NULL);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index e77339c847..ead2af20ea 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg) < 0)
+				       msg, NULL) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +702,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 8c26e45526..ba646f06ff 100644
@@ -980,7 +980,7 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 76670ddd8b..d8ff440027 100644
@@ -244,7 +244,7 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +864,7 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1444,7 +1444,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 299d23d76a..7728fbc3c1 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], msg, NULL);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index fc31d072a6..a7ab4193c1 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
 	if (ret)
 		goto done;
 
refs.c +6 -2
index 5f729ed412..91cacee6f9 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2130,6 +2131,10 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 	}
 
 	strbuf_release(&err);
+
+	if (transaction && before_target && transaction->updates[0]->before_target)
+		strbuf_addstr(before_target, transaction->updates[0]->before_target);
+
 	if (transaction)
 		ref_transaction_free(transaction);
 
@@ -2948,4 +2953,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +2 -1
index 108dfc93b3..f38616db84 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
refs/files-backend.c +1 -0
index 0824c0b8a9..8415f2d020 100644
@@ -2577,6 +2577,7 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 	}
 
 	update->backend_data = lock;
+	update->before_target = xstrdup_or_null(referent.buf);
 
 	if (update->type & REF_ISSYMREF) {
 		if (update->flags & REF_NO_DEREF) {
refs/refs-internal.h +8 -0
index 2313c830d8..7df3e6271e 100644
@@ -104,6 +104,14 @@ struct ref_update {
 	 */
 	const char *old_target;
 
+	/*
+	 * The previous target before applying new_target will be
+	 * written here, to be used by callers when they do not want to
+	 * check old_target during the transaction, but do want to know
+	 * what it was.
+	 */
+	const char *before_target;
+
 	/*
 	 * One or more of REF_NO_DEREF, REF_FORCE_CREATE_REFLOG,
 	 * REF_HAVE_NEW, REF_HAVE_OLD, or backend-specific flags.
refs/reftable-backend.c +1 -0
index 3c96fbf66f..32330b6bc6 100644
@@ -1244,6 +1244,7 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 			if (ret)
 				goto done;
 		}
+		u->before_target = xstrdup_or_null(referent.buf);
 	}
 
 	transaction->backend_data = tx_data;
reset.c +1 -1
index b22b1be792..cc36a9ed56 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head);
+						 reflog_head, NULL);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +1 -1
index 8d01cd50ac..23b162924c 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +1 -1
index 94e79b2e48..d95f051465 100644
@@ -2275,7 +2275,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.6.g9542df9767
#26 lore raw

PATCH v5 2/6 set-head: add new variable for readability

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable for better readability.
---

Notes:
v5: new patch (split from the next patch as a preparatory step)

 builtin/remote.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
builtin/remote.c +4 -3
index d8ff440027..353ffd2c43 100644
@@ -1404,6 +1404,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	int i, opt_a = 0, opt_d = 0, result = 0;
 	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1434,7 +1435,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
+		if (refs_delete_ref(refs, NULL, buf.buf, NULL, REF_NO_DEREF))
 			result |= error(_("Could not delete %s"), buf.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
@@ -1442,9 +1443,9 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	if (head_name) {
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
+		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
Signature · 1 line
2.47.0.6.g9542df9767
#27 lore raw

Re: [PATCH v5 2/6] set-head: add new variable for readability

Quoted 9 lines · Bence Ferdinandy

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable for better readability.
---

Notes:
v5: new patch (split from the next patch as a preparatory step)

It is a good idea to help making it obvious that we are accessing the same ref store.

The patch needs to be signed-off, though.

Quoted 36 lines
 builtin/remote.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
builtin/remote.c +4 -3
index d8ff440027..353ffd2c43 100644
@@ -1404,6 +1404,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	int i, opt_a = 0, opt_d = 0, result = 0;
 	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1434,7 +1435,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
+		if (refs_delete_ref(refs, NULL, buf.buf, NULL, REF_NO_DEREF))
 			result |= error(_("Could not delete %s"), buf.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
@@ -1442,9 +1443,9 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	if (head_name) {
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
+		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
#28 lore raw

Re: [PATCH v5 2/6] set-head: add new variable for readability

Quoted 9 lines · Junio C Hamano
Quoted 7 lines · Bence Ferdinandy

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable for better readability.
---

Quoted 5 lines
Quoted 2 lines

Notes:
v5: new patch (split from the next patch as a preparatory step)

It is a good idea to help making it obvious that we are accessing the same ref store.

Indeed, although it was your idea ;)

Quoted 2 lines

The patch needs to be signed-off, though.

Damn :/ Sorry, another oversight ... Should I send a v6 for the series with this fixed now or wait a bit to see if there are other comments?

Thanks again for the patience!

Best,
Bence

#29 lore raw

PATCH v5 3/6 set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

v5: - the minor refactor has been split out into its own patch

 builtin/remote.c  | 30 ++++++++++++++++++++++++++----
 t/t5505-remote.sh | 13 ++++++++++++-
 2 files changed, 38 insertions(+), 5 deletions(-)
builtin/remote.c +26 -4
index 353ffd2c43..2480128b88 100644
@@ -1399,10 +1399,30 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1465,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
 			result |= error(_("Could not setup %s"), buf.buf);
-		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+		else if (opt_a) {
+			report_auto(argv[0], head_name, &buf_prev);
+		}
 		free(head_name);
 	}
 
 	strbuf_release(&buf);
 	strbuf_release(&buf2);
+	strbuf_release(&buf_prev);
 	return result;
 }
 
t/t5505-remote.sh +12 -1
index 532035933f..262a4de0aa 100755
@@ -434,7 +434,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "two/HEAD set to main" >expect &&
+		echo "'\''two/HEAD'\'' is unchanged and points to '\''main'\''" >expect &&
 		test_cmp expect output
 	)
 '
@@ -453,6 +453,17 @@ test_expect_success 'set-head explicit' '
 	)
 '
 
+
+test_expect_success 'set-head --auto reports change' '
+	(
+		cd test &&
+		git remote set-head origin side2 &&
+		git remote set-head --auto origin >output 2>&1 &&
+		echo "'\''origin/HEAD'\'' has changed from '\''side2'\'' and now points to '\''main'\''" >expect &&
+		test_cmp expect output
+	)
+'
+
 cat >test/expect <<EOF
 Pruning origin
 URL: $(pwd)/one
Signature · 1 line
2.47.0.6.g9542df9767
#30 lore raw

Re: [PATCH v5 3/6] set-head: better output for --auto

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1405

Quoted 4 lines · Bence Ferdinandy
builtin/remote.c +4 -0
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;

I think we need to initialize prev_head to NULL.

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1408

Quoted 2 lines
builtin/remote.c +2 -0
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);

If the symref was not pointing into the "refs/remotes/<remote>/" hierarchy previously, skip_prefix() comes back without touching prev_head (i.e. not starting with the prefix does not clear it).

Assuming that we fix the initialization, the rest of the function looks more or less correct.

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1418

Quoted 9 lines
builtin/remote.c +9 -0
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);

The "more or less" part is that the message does not let you tell between refs/remotes/<name>/HEAD that did not exist, and refs/remotes/<name>/HEAD that used to point at somewhere unexpected, outside refs/remotes/<name>/ hierarchy.

For that, we can check if buf_prev->len is 0 (in which case, the "now created and points at" applies) or non-zero (in which case, we say something like "used to point at '%s' (which is unusual), but now points at '%s' as requested").

#31 lore raw

Re: [PATCH v5 3/6] set-head: better output for --auto

Quoted 9 lines · Junio C Hamano

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1405

Quoted 4 lines · Bence Ferdinandy
builtin/remote.c +4 -0
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;

I think we need to initialize prev_head to NULL.

Quoted 6 lines

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1408

Quoted 2 lines
builtin/remote.c +2 -0
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);

If the symref was not pointing into the "refs/remotes/<remote>/" hierarchy previously, skip_prefix() comes back without touching prev_head (i.e. not starting with the prefix does not clear it).

The two uninitialized prev_head were also noticed by compilers in multiple jobs at GitHub CI.

https://github.com/git/git/actions/runs/11265515664

#32 lore raw

Re: [PATCH v5 3/6] set-head: better output for --auto

Quoted 18 lines · Junio C Hamano
Quoted 9 lines · Junio C Hamano

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1405

Quoted 4 lines · Bence Ferdinandy
builtin/remote.c +4 -0
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;

I think we need to initialize prev_head to NULL.

Quoted 6 lines

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1408

Quoted 2 lines
builtin/remote.c +2 -0
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);

If the symref was not pointing into the "refs/remotes/<remote>/" hierarchy previously, skip_prefix() comes back without touching prev_head (i.e. not starting with the prefix does not clear it).

Quoted 4 lines

The two uninitialized prev_head were also noticed by compilers in multiple jobs at GitHub CI.

https://github.com/git/git/actions/runs/11265515664

Heh, I was just about to send a patch to fix up these two warnings (errors with -Werror), so that I could build 'seen'. However, it seems to be well in hand, so I won't bother! :)

ATB,
Ramsay Jones

#33 lore raw

Re: [PATCH v5 3/6] set-head: better output for --auto

In reply to Junio C Hamano
Quoted 18 lines · Junio C Hamano
Quoted 9 lines · Junio C Hamano

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1405

Quoted 4 lines · Bence Ferdinandy
builtin/remote.c +4 -0
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;

I think we need to initialize prev_head to NULL.

Quoted 6 lines

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1408

Quoted 2 lines
builtin/remote.c +2 -0
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);

If the symref was not pointing into the "refs/remotes/<remote>/" hierarchy previously, skip_prefix() comes back without touching prev_head (i.e. not starting with the prefix does not clear it).

Quoted 4 lines

The two uninitialized prev_head were also noticed by compilers in multiple jobs at GitHub CI.

https://github.com/git/git/actions/runs/11265515664

I wonder why that didn't fail the build for me locally. I was running

make -j8 install PREFIX=$HOME/.local

for testing. Should I have added a flag or ENV variable somewhere?

Anyhow, the v6 I sent earlier today should fix this (and hopefully all your other comments as well).

Thanks,
Bence

Signature · 1 line
bence.ferdinandy.com
#34 lore raw

PATCH v5 4/6 transaction: add TRANSACTION_CREATE_EXISTS error

In reply to Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch
v5: no change

 refs.h                  |  4 +++-
 refs/files-backend.c    | 28 ++++++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 27 insertions(+), 11 deletions(-)
refs.h +3 -1
index f38616db84..166affbc89 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +20 -8
index 8415f2d020..272ad81315 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2603,9 +2607,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				int checkret;
+				checkret = check_old_oid(update, &lock->old_oid, err);
+				if  (checkret) {
+					ret = checkret;
+					goto out;
+				}
 			}
 		} else {
 			/*
@@ -2636,9 +2644,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			int checkret;
+			checkret = check_old_oid(update, &lock->old_oid, err);
+			if  (checkret) {
+				ret = checkret;
+				goto out;
+			}
 		}
 
 		/*
refs/reftable-backend.c +4 -2
index 32330b6bc6..c6b25ebac4 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}
 
Signature · 1 line
2.47.0.6.g9542df9767
#35 lore raw

Re: [PATCH v5 4/6] transaction: add TRANSACTION_CREATE_EXISTS error

refs.h int ref_transaction_verify(struct ref_transaction *transaction, · line 765

Quoted 7 lines · Bence Ferdinandy

/* Naming conflict (for example, the ref names A and A/B conflict). */ #define TRANSACTION_NAME_CONFLICT -1

refs.h +3 -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3

My initial knee-jerk reaction to the name "CREATE_EXISTS" was that the "CREATE" part is redundant, as the only case that the fact that something exists is a valid reason for an error is when we attempted to create it. EEXIST in errno(3) is not ECREATE_EXIST for the same reason.

But let's let it pass; contrasting with the fact that what ought to be named similarly to EISDIR is called NAME_CONFLICT, CREATE_EXISTS is fine.

Quoted 25 lines
refs/files-backend.c +5 -1
index 8415f2d020..272ad81315 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",

refs/files-backend.c static int check_old_oid(struct ref_update *update, struct object_id *oid, · line 2530

Quoted 6 lines
refs/files-backend.c +1 -1
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }

OK. So if a caller does not care which exact kind of error it got, they will keep working just the way they used to work, and a caller that cares can now check. A nice API enhancement.

Quoted 5 lines
refs/files-backend.c +0 -1
@@ -2603,9 +2607,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {

refs/files-backend.c static int lock_ref_for_update(struct files_ref_store *refs, · line 2617

Quoted 10 lines
refs/files-backend.c +7 -2
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				int checkret;
+				checkret = check_old_oid(update, &lock->old_oid, err);
+				if  (checkret) {
+					ret = checkret;
+					goto out;
+				}
 			}

Likewise; this code is just propagating what check_old_oid() did to its callers.

Quoted 4 lines
refs/files-backend.c +0 -0
@@ -2636,9 +2644,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;

refs/files-backend.c static int lock_ref_for_update(struct files_ref_store *refs, · line 2653

Quoted 10 lines
refs/files-backend.c +7 -3
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			int checkret;
+			checkret = check_old_oid(update, &lock->old_oid, err);
+			if  (checkret) {
+				ret = checkret;
+				goto out;
+			}

Ditto.

Quoted 20 lines
refs/reftable-backend.c +4 -1
index 32330b6bc6..c6b25ebac4 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),

refs/reftable-backend.c static int reftable_be_transaction_prepare(struct ref_store *ref_store, · line 1228

Quoted 6 lines
refs/reftable-backend.c +0 -1
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}

So it remains a little mystery how the ultimate caller uses this new bit of information.

Which is OK---the next step seems to have a new condition on the error status.

#36 lore raw

PATCH v5 5/6 refs_update_symref: add create_only option

In reply to Bence Ferdinandy

Allow the caller to specify that it only wants to update the symref if it does not already exist. Silently ignore the error from the transaction API if the symref already exists.

---

Notes:
v4: new patch
v5: no change

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 +++--
 builtin/clone.c           |  8 +++++---
 builtin/notes.c           |  3 ++-
 builtin/remote.c          |  9 ++++++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 29 +++++++++++++++++++++--------
 refs.h                    |  2 +-
 reset.c                   |  2 +-
 sequencer.c               |  3 ++-
 setup.c                   |  3 ++-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 47 insertions(+), 25 deletions(-)
builtin/branch.c +1 -1
index 6c87690b58..3c9bc39800 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL, false))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +3 -2
index 356ee9bcde..d9514e9b7a 100644
@@ -1015,7 +1015,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, 
+					msg.buf, NULL, false) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1480,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b", NULL);
+				    "HEAD", branch_ref.buf, "checkout -b", NULL, false);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +5 -3
index ead2af20ea..25d0bcf3aa 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg, NULL) < 0)
+				       msg, NULL, false) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, 
+					NULL, NULL, false) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +703,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, 
+					NULL, NULL, false) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +2 -1
index ba646f06ff..fb49e491c3 100644
@@ -980,7 +980,8 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, 
+					NULL, NULL, false))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +6 -3
index 2480128b88..79f22467f2 100644
@@ -244,7 +244,8 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					"remote add", NULL, false))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +865,8 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					buf3.buf, NULL, false))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1465,7 +1467,8 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf,
+					"remote set-head", &buf_prev, false))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a) {
 			report_auto(argv[0], head_name, &buf_prev);
builtin/symbolic-ref.c +1 -1
index 7728fbc3c1..169f5f5340 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg, NULL);
+					   argv[0], argv[1], msg, NULL, false);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index a7ab4193c1..46b515a243 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL, false);
 	if (ret)
 		goto done;
 
refs.c +21 -8
index 91cacee6f9..3d2c07dd67 100644
@@ -2115,19 +2115,32 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target)
+		       struct strbuf *before_target, bool create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
-	int ret = 0;
+	int ret = 0, create_ret = 0;
 
 	transaction = ref_store_transaction_begin(refs, &err);
-	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
-				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
-		ret = error("%s", err.buf);
+	if (create_only) {
+		if (!transaction ||
+		    ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err)) {
+			ret = error("%s", err.buf);
+		}
+		else {
+		    create_ret = ref_transaction_commit(transaction, &err);
+		    if (create_ret && create_ret != TRANSACTION_CREATE_EXISTS)
+			ret = error("%s", err.buf);
+		}
+	}
+	else
+		if (!transaction ||
+		    ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+		    ref_transaction_commit(transaction, &err)) {
+			ret = error("%s", err.buf);
 	}
 
 	strbuf_release(&err);
refs.h +1 -1
index 166affbc89..b64fd2318b 100644
@@ -572,7 +572,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target);
+		       struct strbuf *before_target, bool create_only);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index cc36a9ed56..674896fb61 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head, NULL);
+						 reflog_head, NULL, false);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +2 -1
index 23b162924c..1a46ef56ba 100644
@@ -5107,7 +5107,8 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, 
+						msg, NULL, false)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +2 -1
index d95f051465..67abbfaf3c 100644
@@ -2275,7 +2275,8 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, 
+					NULL, NULL, false) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index a911302bea..b6b06bb2e9 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg, NULL);
+	return refs_update_symref(refs, refname, target, logmsg, NULL, false);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.6.g9542df9767
#37 lore raw

Re: [PATCH v5 5/6] refs_update_symref: add create_only option

builtin/branch.c static int replace_each_worktree_head_symref(struct worktree **worktrees, · line 565

Quoted 13 lines · Bence Ferdinandy
builtin/branch.c +1 -1
index 6c87690b58..3c9bc39800 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL, false))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}

Didn't somebody tell you not to use "bool" in previous rounds of reviews?

We are still smoking out platforms that have trouble with the type by using it only in a tightly controlled weather balloon we raised in 8277dbe9 (git-compat-util: convert skip_{prefix,suffix}{,_mem} to bool, 2023-12-16), if I recall correctly.

Assuming either (1) I forgot that we are OK with bool everywhere, or
(2) the patch will be updated to use plain 0 for false and everything else for true, let's keep reading. I as a reader expect that some *.h file will tell us what the new parameter means.

Quoted 5 lines
refs.c +0 -0
index 91cacee6f9..3d2c07dd67 100644

refs.c int peel_iterated_oid(struct repository *r, const struct object_id *base, struct · line 2122

Quoted 10 lines
refs.c +2 -2
@@ -2115,19 +2115,32 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target)
+		       struct strbuf *before_target, bool create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
-	int ret = 0;
+	int ret = 0, create_ret = 0;

Isn't it sufficient for create_ret to be in the scope deep in the nested if/else where it is used?

Quoted 11 lines
refs.c +10 -0
 	transaction = ref_store_transaction_begin(refs, &err);
+	if (create_only) {
+		if (!transaction ||
+		    ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err)) {
+			ret = error("%s", err.buf);
+		}
+		else {
+		    create_ret = ref_transaction_commit(transaction, &err);
+		    if (create_ret && create_ret != TRANSACTION_CREATE_EXISTS)
+			ret = error("%s", err.buf);

refs.c int peel_iterated_oid(struct repository *r, const struct object_id *base, struct · line 2144

Quoted 10 lines
refs.c +9 -0
+		}
+	}
+	else
+		if (!transaction ||
+		    ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+		    ref_transaction_commit(transaction, &err)) {
+			ret = error("%s", err.buf);
 	}

Style: in if/else if/... cascade, opening and closing {braces} sit on the same line as these keywords, i.e.

	if (create_only) {
		if (...) {
			ret = error(...);
		} else {
			...
		}
	} else if (!transaction ||
			...) {
	}

But more importantly, I think it is much cleaner to handle failure from transaction_begin outside the if/else cascade. i.e.

	transaction = ref_store_transaction_begin(refs, &err);
	if (!transaction) {
        error_return:
		ret = error("%s", err.buf);
        	goto cleanup;
	}

        if (create_only) {
        	int create_ret;
		if (ref_transaction_create(...))
			goto error_return;
		create_ret = ref_transaction_commit(...);
                if (create_ret && create_ret != TRANSACTION_CREATE_EXISTS)
			goto error_return;
	} else {
		if (ref_transaction_update(...) ||
		    ref_transaction_commit(...))
			goto error_return;
	}

cleanup:

	strbuf_release(&err);

	if (transaction) {
		if (before_target && ...)
			strbuf_addstr(before_target, ...);
		ref_transaction_free(transaction);
	}
	return ret;

I didn't spot any caller that passes "true" to signal that it wants the create_only behaviour in this step.

Which is OK---let's keep reading to find such a caller in the next step.

#38 lore raw

PATCH v5 6/6 fetch: set remote/HEAD if it does not exist

In reply to Bence Ferdinandy

If the user has remote/HEAD set already and it looks like it has changed on the server, then print a message, otherwise set it if we can. Silently pass if the user already has the same remote/HEAD set as reported by the server.

---

Notes:
v3: - does not rely on remote set-head anymore so it only authenticates
once
- uses the new REF_CREATE_ONLY to atomically check if the ref exists and only write it if it doesn't
- in all other cases the maximum it does is print a warning

v4: - instead of the discarded REF_CREATE_ONLY, it uses the existing,
but updated transaction api to request a silent create only
- it now uses the atomic before_target to determine reporting
- refactored for legibility

v5: - instead of printing a not too useful message, it now fails
silently, this in line with the objective to only set up remote/HEAD automatically if the right thing is trivial, for everything else there is remote set-head
- fixed all failing tests
- added to new tests, one for checking if remote/HEAD is set to the correct one, and one to test that we do not override remote/HEAD if it has changed on the server from what we have locally

 builtin/fetch.c                  |  82 +++++++++++
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  11 +-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  67 ++++++++-
 12 files changed, 308 insertions(+), 123 deletions(-)
builtin/fetch.c +82 -0
index 80a64d0d26..c3d3c05950 100644
@@ -1578,6 +1578,82 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		;
+	else if (prev_head) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}
+}
+
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1) {
+		result = 1;
+	} else
+		head_name = xstrdup(heads.items[0].string);
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head, true))
+			result |= error(_("Could not setup %s"), b_head.buf);
+		else {
+			report_set_head(remote, head_name, &b_local_head);
+		}
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)
@@ -1647,6 +1723,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes,"HEAD");
+
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1791,6 +1869,9 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		; // Way too many cases where this can go wrong.
+		  // Just fail silently.
 
 cleanup:
 	if (retcode) {
@@ -2021,6 +2102,7 @@ static int fetch_multiple(struct string_list *list, int max_children,
 	return !!result;
 }
 
+
 /*
  * Fetching from the promisor remote should use the given filter-spec
  * or inherit the default filter-spec from the config.
t/t4207-log-decoration-colors.sh +2 -1
index 73ea9e5155..d55d22cb2f 100755
@@ -59,7 +59,8 @@ ${c_reset}${c_tag}tag: ${c_reset}${c_tag}v1.0${c_reset}${c_commit}, \
 ${c_reset}${c_tag}tag: ${c_reset}${c_tag}B${c_reset}${c_commit})${c_reset} B
 ${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_tag}tag: ${c_reset}${c_tag}A1${c_reset}${c_commit}, \
-${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit})${c_reset} A1
+${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit}, \
+${c_reset}${c_remoteBranch}other/HEAD${c_reset}${c_commit})${c_reset} A1
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_stash}refs/stash${c_reset}${c_commit})${c_reset} On main: Changes to A.t
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
t/t5505-remote.sh +7 -4
index 262a4de0aa..399a501740 100755
@@ -71,7 +71,7 @@ test_expect_success 'add another remote' '
 		cd test &&
 		git remote add -f second ../two &&
 		tokens_match "origin second" "$(git remote)" &&
-		check_tracking_branch second main side another &&
+		check_tracking_branch second main side another HEAD &&
 		git for-each-ref "--format=%(refname)" refs/remotes |
 		sed -e "/^refs\/remotes\/origin\//d" \
 		    -e "/^refs\/remotes\/second\//d" >actual &&
@@ -725,6 +725,7 @@ test_expect_success 'reject --no-no-tags' '
 cat >one/expect <<\EOF
   apis/main
   apis/side
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -742,6 +743,7 @@ test_expect_success 'update' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -754,7 +756,7 @@ EOF
 test_expect_success 'update with arguments' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -797,7 +799,7 @@ EOF
 test_expect_success 'update default' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -809,6 +811,7 @@ test_expect_success 'update default' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -831,7 +834,7 @@ test_expect_success 'update default (overridden, with funny whitespace)' '
 test_expect_success 'update (with remotes.default defined)' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
t/t5510-fetch.sh +122 -107

356 lines not on this page · raw message

t/t5512-ls-remote.sh +2 -0
index 64b3491e4e..1b3865e154 100755
@@ -293,6 +293,8 @@ test_expect_success 'ls-remote with filtered symref (refname)' '
 	cat >expect <<-EOF &&
 	ref: refs/heads/main	HEAD
 	$rev	HEAD
+	ref: refs/remotes/origin/main	refs/remotes/origin/HEAD
+	$rev	refs/remotes/origin/HEAD
 	EOF
 	git ls-remote --symref . HEAD >actual &&
 	test_cmp expect actual
t/t5514-fetch-multiple.sh +15 -2
index 579872c258..e3482b27b2 100755
@@ -45,14 +45,17 @@ test_expect_success setup '
 '
 
 cat > test/expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -97,6 +100,7 @@ cat > expect << EOF
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
@@ -112,8 +116,10 @@ test_expect_success 'git fetch --multiple (but only one remote)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -141,7 +147,7 @@ test_expect_success 'git fetch --multiple (bad remote names)' '
 
 test_expect_success 'git fetch --all (skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -153,11 +159,14 @@ test_expect_success 'git fetch --all (skipFetchAll)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -165,7 +174,7 @@ EOF
 
 test_expect_success 'git fetch --multiple (ignoring skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -221,14 +230,17 @@ test_expect_success 'git fetch --multiple --jobs=0 picks a default' '
 
 create_fetch_all_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
 	  origin/main
 	  origin/side
+	  three/HEAD -> three/main
 	  three/another
 	  three/main
 	  three/side
+	  two/HEAD -> two/main
 	  two/another
 	  two/main
 	  two/side
@@ -265,6 +277,7 @@ test_expect_success 'git fetch (fetch all remotes with fetch.all = true)' '
 
 create_fetch_one_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
t/t5516-fetch-push.sh +2 -1
index 331778bd42..5a051aa0c7 100755
@@ -1395,7 +1395,8 @@ test_expect_success 'fetch follows tags by default' '
 		git tag -m "annotated" tag &&
 		git for-each-ref >tmp1 &&
 		sed -n "p; s|refs/heads/main$|refs/remotes/origin/main|p" tmp1 |
-		sort -k 3 >../expect
+		sed -n "p; s|refs/heads/main$|refs/remotes/origin/HEAD|p"  |
+		sort -k 4 >../expect
 	) &&
 	test_when_finished "rm -rf dst" &&
 	git init dst &&
t/t5527-fetch-odd-refs.sh +2 -1
index 98ece27c6a..d3996af6ee 100755
@@ -52,7 +52,8 @@ test_expect_success LONG_REF 'fetch handles extremely long refname' '
 	long
 	main
 	EOF
-	git for-each-ref --format="%(subject)" refs/remotes/long >actual &&
+	git for-each-ref --format="%(subject)" refs/remotes/long \
+		--exclude=refs/remotes/long/HEAD >actual &&
 	test_cmp expect actual
 '
 
t/t7900-maintenance.sh +2 -1
index a66d0e089d..88331d1ceb 100755
@@ -329,7 +329,8 @@ test_expect_success 'incremental-repack task' '
 
 	# Delete refs that have not been repacked in these packs.
 	git for-each-ref --format="delete %(refname)" \
-		refs/prefetch refs/tags refs/remotes >refs &&
+		refs/prefetch refs/tags refs/remotes \
+		--exclude=refs/remotes/*/HEAD >refs &&
 	git update-ref --stdin <refs &&
 
 	# Replace the object directory with this pack layout.
t/t9210-scalar.sh +3 -2
index 027235d61a..a81662713e 100755
@@ -150,7 +150,8 @@ test_expect_success 'scalar clone' '
 			"$(pwd)" &&
 
 		git for-each-ref --format="%(refname)" refs/remotes/origin/ >actual &&
-		echo "refs/remotes/origin/parallel" >expect &&
+		echo "refs/remotes/origin/HEAD" >>expect &&
+		echo "refs/remotes/origin/parallel" >>expect &&
 		test_cmp expect actual &&
 
 		test_path_is_missing 1/2 &&
@@ -219,7 +220,7 @@ test_expect_success 'scalar reconfigure --all with includeIf.onbranch' '
 	done
 '
 
- test_expect_success 'scalar reconfigure --all with detached HEADs' '
+test_expect_success 'scalar reconfigure --all with detached HEADs' '
 	repos="two three four" &&
 	for num in $repos
 	do
t/t9211-scalar-clone.sh +3 -3
index 7869f45ee6..01f71910f5 100755
@@ -31,7 +31,7 @@ test_expect_success 'set up repository to clone' '
 	)
 '
 
-cleanup_clone () {
+cleanup_clone() {
 	rm -rf "$1"
 }
 
@@ -127,7 +127,7 @@ test_expect_success '--single-branch clones HEAD only' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 1 out &&
+		test_line_count = 2 out &&
 		grep "refs/remotes/origin/base" out
 	) &&
 
@@ -141,7 +141,7 @@ test_expect_success '--no-single-branch clones all branches' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 2 out &&
+		test_line_count = 3 out &&
 		grep "refs/remotes/origin/base" out &&
 		grep "refs/remotes/origin/parallel" out
 	) &&
t/t9902-completion.sh +66 -1

451 lines not on this page · raw message

Signature · 1 line
2.47.0.6.g9542df9767
#39 lore raw

Re: [PATCH v5 6/6] fetch: set remote/HEAD if it does not exist

Quoted 5 lines · Bence Ferdinandy
builtin/fetch.c +0 -0
index 80a64d0d26..c3d3c05950 100644

builtin/fetch.c static int backfill_tags(struct display_state *display_state, · line 1587

Quoted 10 lines
builtin/fetch.c +7 -0
@@ -1578,6 +1578,82 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);

The same "uninitialized prev_head" problem I discussed earlier for a separate patch is here, I think.

builtin/fetch.c static int backfill_tags(struct display_state *display_state, · line 1596

Quoted 8 lines
builtin/fetch.c +8 -0
+	if (prev_head && !strcmp(prev_head, head_name))
+		;
+	else if (prev_head) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}

If the condition is only for one arm, can't we do this without else/if? Would the condition become too contorted to read if we did so? Let's see.

	if (prev_head && strcmp(prev_head, head_name)) {
		HEAD has changed from prev_head to head_name;
	}

I guess it is a bit subjective, but as long as you are used to read "strcmp(a,b)" as "a and b are different", this should be easier to read than the original.

Quoted 24 lines
builtin/fetch.c +24 -0
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);

builtin/fetch.c static int backfill_tags(struct display_state *display_state, · line 1632

Quoted 10 lines
builtin/fetch.c +10 -0
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1) {

Curious use of extra {braces}. In this case we can just lose them.

Quoted 4 lines
builtin/fetch.c +3 -0
+		result = 1;
+	} else
+		head_name = xstrdup(heads.items[0].string);
 

builtin/fetch.c static int backfill_tags(struct display_state *display_state, · line 1644

Quoted 10 lines
builtin/fetch.c +9 -0
 
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head, true))
+			result |= error(_("Could not setup %s"), b_head.buf);

Two problems.

* we do not capitalize the beginning of the sentence in an error() message, i.e. "Could not" -> "could not" (or "cannot").

* "setup" is not a verb.

I know both were inherited from builtin/remote.c but existing breakage is not a good excuse to make new code worse.

builtin/fetch.c static int backfill_tags(struct display_state *display_state, · line 1645

Quoted 1 line
builtin/fetch.c +1 -0
+		else {

Curious use of extra {braces}. In this case we can just lose them.

Quoted 15 lines
builtin/fetch.c +11 -0
+			report_set_head(remote, head_name, &b_local_head);
+		}
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)

builtin/fetch.c static int do_fetch(struct transport *transport, · line 1726

Quoted 4 lines
builtin/fetch.c +1 -0
@@ -1647,6 +1723,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes,"HEAD");

Missing SP after ",".

builtin/fetch.c static int do_fetch(struct transport *transport, · line 1874

Quoted 10 lines
builtin/fetch.c +3 -0
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1791,6 +1869,9 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		; // Way too many cases where this can go wrong.
+		  // Just fail silently.
	/*
	 * our multi-line comments
	 * look like this.
	 */

More importantly, we are not failing silently. As we saw in the implementation of set_head() above, a non-zero return came from ret that was assigned the return value of error() in the function, so an error message is already given, no?

builtin/fetch.c static int fetch_multiple(struct string_list *list, int max_children, · line 2108

Quoted 8 lines
builtin/fetch.c +1 -0
@@ -2021,6 +2102,7 @@ static int fetch_multiple(struct string_list *list, int max_children,
 	return !!result;
 }
 
+
 /*
  * Fetching from the promisor remote should use the given filter-spec
  * or inherit the default filter-spec from the config.

An unintended change?

Thanks.

#40 lore raw

PATCH v6 1/6 refs_update_symref: atomically record overwritten ref

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten. Make use of ref_transaction's atomicity and record the previous value there. Add a new variable to refs_update_symref's signature to be able to pass this information back up to callers.

---

Notes:
v4: new patch

v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

v6: - no change

 builtin/branch.c          | 2 +-
 builtin/checkout.c        | 4 ++--
 builtin/clone.c           | 6 +++---
 builtin/notes.c           | 2 +-
 builtin/remote.c          | 6 +++---
 builtin/symbolic-ref.c    | 2 +-
 builtin/worktree.c        | 2 +-
 refs.c                    | 8 ++++++--
 refs.h                    | 3 ++-
 refs/files-backend.c      | 1 +
 refs/refs-internal.h      | 8 ++++++++
 refs/reftable-backend.c   | 1 +
 reset.c                   | 2 +-
 sequencer.c               | 2 +-
 setup.c                   | 2 +-
 t/helper/test-ref-store.c | 2 +-
 16 files changed, 34 insertions(+), 19 deletions(-)
builtin/branch.c +1 -1
index fd1611ebf5..6c87690b58 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +2 -2
index 9c30000d3a..356ee9bcde 100644
@@ -1015,7 +1015,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1479,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, "checkout -b", NULL);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index e77339c847..ead2af20ea 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg) < 0)
+				       msg, NULL) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +702,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 8c26e45526..ba646f06ff 100644
@@ -980,7 +980,7 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 76670ddd8b..d8ff440027 100644
@@ -244,7 +244,7 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +864,7 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1444,7 +1444,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 299d23d76a..7728fbc3c1 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], msg, NULL);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index fc31d072a6..a7ab4193c1 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
 	if (ret)
 		goto done;
 
refs.c +6 -2
index 5f729ed412..91cacee6f9 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2130,6 +2131,10 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 	}
 
 	strbuf_release(&err);
+
+	if (transaction && before_target && transaction->updates[0]->before_target)
+		strbuf_addstr(before_target, transaction->updates[0]->before_target);
+
 	if (transaction)
 		ref_transaction_free(transaction);
 
@@ -2948,4 +2953,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +2 -1
index 108dfc93b3..f38616db84 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *before_target);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
refs/files-backend.c +1 -0
index 0824c0b8a9..8415f2d020 100644
@@ -2577,6 +2577,7 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 	}
 
 	update->backend_data = lock;
+	update->before_target = xstrdup_or_null(referent.buf);
 
 	if (update->type & REF_ISSYMREF) {
 		if (update->flags & REF_NO_DEREF) {
refs/refs-internal.h +8 -0
index 2313c830d8..7df3e6271e 100644
@@ -104,6 +104,14 @@ struct ref_update {
 	 */
 	const char *old_target;
 
+	/*
+	 * The previous target before applying new_target will be
+	 * written here, to be used by callers when they do not want to
+	 * check old_target during the transaction, but do want to know
+	 * what it was.
+	 */
+	const char *before_target;
+
 	/*
 	 * One or more of REF_NO_DEREF, REF_FORCE_CREATE_REFLOG,
 	 * REF_HAVE_NEW, REF_HAVE_OLD, or backend-specific flags.
refs/reftable-backend.c +1 -0
index 3c96fbf66f..32330b6bc6 100644
@@ -1244,6 +1244,7 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 			if (ret)
 				goto done;
 		}
+		u->before_target = xstrdup_or_null(referent.buf);
 	}
 
 	transaction->backend_data = tx_data;
reset.c +1 -1
index b22b1be792..cc36a9ed56 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head);
+						 reflog_head, NULL);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +1 -1
index 8d01cd50ac..23b162924c 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +1 -1
index 94e79b2e48..d95f051465 100644
@@ -2275,7 +2275,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.6.g07cb02250a
#41 lore raw

PATCH v6 2/6 set-head: add new variable for readability

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable for better readability.

---

Notes:
v5: new patch (split from the next patch as a preparatory step)

v6: no change

 builtin/remote.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
builtin/remote.c +4 -3
index d8ff440027..353ffd2c43 100644
@@ -1404,6 +1404,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	int i, opt_a = 0, opt_d = 0, result = 0;
 	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1434,7 +1435,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
+		if (refs_delete_ref(refs, NULL, buf.buf, NULL, REF_NO_DEREF))
 			result |= error(_("Could not delete %s"), buf.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
@@ -1442,9 +1443,9 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	if (head_name) {
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
+		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
Signature · 1 line
2.47.0.6.g07cb02250a
#42 lore raw

PATCH v6 3/6 set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates. As a fourth output, if HEAD is changed from a previous value that was not a remote branch, explicitly call attention to this fact.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

v5: - the minor refactor has been split out into its own patch

v6: - fixed uninitialized prev_head
- fixed case of unusual previous target
- fixed a test that would have been actually broken at this patch (the output was only correct with the later update to fetch)
- added 4 tests for the 4 output cases

 builtin/remote.c  | 34 +++++++++++++++++++++++++++----
 t/t5505-remote.sh | 52 ++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 81 insertions(+), 5 deletions(-)
builtin/remote.c +30 -4
index 353ffd2c43..24f9caf149 100644
@@ -1399,10 +1399,34 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else if (buf_prev->len == 0)
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+	else
+		printf("'%s/HEAD' used to point to '%s' "
+			"(which is unusual), but now points to '%s'\n",
+			remote, buf_prev->buf, head_name);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1469,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
 			result |= error(_("Could not setup %s"), buf.buf);
-		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+		else if (opt_a) {
+			report_auto(argv[0], head_name, &buf_prev);
+		}
 		free(head_name);
 	}
 
 	strbuf_release(&buf);
 	strbuf_release(&buf2);
+	strbuf_release(&buf_prev);
 	return result;
 }
 
t/t5505-remote.sh +51 -1

69 lines not on this page · raw message

Signature · 1 line
2.47.0.6.g07cb02250a
#43 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Bence Ferdinandy <[email protected]> writes:
[snip]

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1403

Quoted 10 lines
builtin/remote.c +2 -0
index 353ffd2c43..24f9caf149 100644
@@ -1399,10 +1399,34 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {

Nit: would be nicer if this was called 'report_set_head_auto'

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1416

Quoted 13 lines
builtin/remote.c +13 -0
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else if (buf_prev->len == 0)

Nit: we tend to do if (!buf_prev->len) in this project

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1421

Quoted 5 lines
builtin/remote.c +5 -0
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+	else
+		printf("'%s/HEAD' used to point to '%s' "
+			"(which is unusual), but now points to '%s'\n",

Isn't "which is unusual" a bit vague? Wouldn't be nicer to say why it is unusual?

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1422

Quoted 1 line
builtin/remote.c +1 -0
+			remote, buf_prev->buf, head_name);

Let's clear up buf_prefix by calling strbuf_release here.

Quoted 37 lines
builtin/remote.c +9 -4
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1469,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
 			result |= error(_("Could not setup %s"), buf.buf);
-		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+		else if (opt_a) {
+			report_auto(argv[0], head_name, &buf_prev);
+		}
 		free(head_name);
 	}
 
 	strbuf_release(&buf);
 	strbuf_release(&buf2);
+	strbuf_release(&buf_prev);
 	return result;
 }
 
t/t5505-remote.sh +0 -0
index 532035933f..77c12b8709 100755

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 435

Quoted 7 lines
t/t5505-remote.sh +4 -0
@@ -429,12 +429,51 @@ test_expect_success 'set-head --auto' '
 	)
 '
 
+test_expect_success 'set-head --auto detects creation' '
+	(
+		cd test &&
+		rm .git/refs/remotes/origin/HEAD &&

does this work with reftables too?

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 437

Quoted 2 lines
t/t5505-remote.sh +2 -0
+		git remote set-head --auto origin >output &&
+		echo "'\''origin/HEAD'\'' is now created and points to '\''main'\''" >expect &&

Nit: might be cleaner to use ${SQ} here and below

[snip]

#44 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Thanks for the very helpful review on the series! Most of it is clear to me and I agree with, so for brevity I'll only comment where I have a question/comment.

On Thu Oct 10, 2024 at 23:05, karthik nayak <[email protected]> wrote:
[snip]

Quoted 8 lines
Quoted 8 lines
t/t5505-remote.sh +0 -0
index 532035933f..77c12b8709 100755
@@ -429,12 +429,51 @@ test_expect_success 'set-head --auto' '
 	)
 '
 
Quoted 6 lines

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 435

Quoted 4 lines
t/t5505-remote.sh +4 -0
+test_expect_success 'set-head --auto detects creation' '
+	(
+		cd test &&
+		rm .git/refs/remotes/origin/HEAD &&

does this work with reftables too?

You got me there, probably not. I'm guessing I should use git update-ref or something similar to set these values manually instead of editing the file.

On the other hand, is there a way to force the tests to run on a reftables backend? t/README does not mention anything about this and since in a previous round it already came up that I forgot to update the reftables backend, it would be nice if I could actually test everything with that as well.

Quoted 5 lines

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 437

Quoted 3 lines
t/t5505-remote.sh +2 -0
+		git remote set-head --auto origin >output &&
+		echo "'\''origin/HEAD'\'' is now created and points to '\''main'\''" >expect &&

Nit: might be cleaner to use ${SQ} here and below

You mean something like this?

	git remote set-head --auto origin >output &&
	HEAD="'\''origin/HEAD'\''" &&
	echo "${HEAD} is now created and points to '\''main'\''" >expect &&

I tried a few variations and this is what I could get working, but I may be simply missing something with the backtick.

Thanks,
Bence

Signature · 1 line
bence.ferdinandy.com
#45 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Quoted 21 lines · Bence Ferdinandy

Thanks for the very helpful review on the series! Most of it is clear to me and I agree with, so for brevity I'll only comment where I have a question/comment.

On Thu Oct 10, 2024 at 23:05, karthik nayak <[email protected]> wrote:
[snip]

Quoted 8 lines
Quoted 8 lines
t/t5505-remote.sh +0 -0
index 532035933f..77c12b8709 100755
@@ -429,12 +429,51 @@ test_expect_success 'set-head --auto' '
 	)
 '
 
Quoted 6 lines

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 435

Quoted 4 lines
t/t5505-remote.sh +4 -0
+test_expect_success 'set-head --auto detects creation' '
+	(
+		cd test &&
+		rm .git/refs/remotes/origin/HEAD &&

does this work with reftables too?

Quoted 2 lines

You got me there, probably not. I'm guessing I should use git update-ref or something similar to set these values manually instead of editing the file.

Yup, "git update-ref --no-deref -d refs/remotes/origin/HEAD"

Quoted 4 lines

On the other hand, is there a way to force the tests to run on a reftables backend? t/README does not mention anything about this and since in a previous round it already came up that I forgot to update the reftables backend, it would be nice if I could actually test everything with that as well.

$ git grep GIT_TEST_DEFAULT_REF_FORMAT t/README

Thanks.

#46 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

In reply to Bence Ferdinandy

"Bence Ferdinandy" <[email protected]> writes:

[snip]

Quoted 5 lines
Quoted 5 lines

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 437

Quoted 3 lines
t/t5505-remote.sh +2 -0
+		git remote set-head --auto origin >output &&
+		echo "'\''origin/HEAD'\'' is now created and points to '\''main'\''" >expect &&

Nit: might be cleaner to use ${SQ} here and below

Quoted 8 lines

You mean something like this?

	git remote set-head --auto origin >output &&
	HEAD="'\''origin/HEAD'\''" &&
	echo "${HEAD} is now created and points to '\''main'\''" >expect &&

I tried a few variations and this is what I could get working, but I may be simply missing something with the backtick.

I mean simply this

    git remote set-head --auto origin >output &&
    echo "${SQ}origin/HEAD${SQ} is now created and points to

${SQ}main${SQ}" >expect &&

- Karthik

#47 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Quoted 15 lines · karthik nayak

"Bence Ferdinandy" <[email protected]> writes:

[snip]

Quoted 11 lines
Quoted 5 lines

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 437

Quoted 3 lines
t/t5505-remote.sh +2 -0
+		git remote set-head --auto origin >output &&
+		echo "'\''origin/HEAD'\'' is now created and points to '\''main'\''" >expect &&

Nit: might be cleaner to use ${SQ} here and below

You mean something like this?

	git remote set-head --auto origin >output &&
	HEAD="'\''origin/HEAD'\''" &&
	echo "${HEAD} is now created and points to '\''main'\''" >expect &&
Quoted 8 lines
Quoted 2 lines

I tried a few variations and this is what I could get working, but I may be simply missing something with the backtick.

I mean simply this

    git remote set-head --auto origin >output &&
    echo "${SQ}origin/HEAD${SQ} is now created and points to

${SQ}main${SQ}" >expect &&

Ah, I see in other tests this is used, but not in this particular test file. It's a bit hard to decide which is more cryptic, but ${SQ} is nicer on the eyes. On the other hand I would either switch the entire file in a separate patch or leave in the '\'' here as well. Or I guess one could go through the entire test base and switch everything to either one or the other for consistency.

#48 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Quoted 25 lines · Bence Ferdinandy
Quoted 15 lines · karthik nayak

"Bence Ferdinandy" <[email protected]> writes:

[snip]

Quoted 11 lines
Quoted 5 lines

t/t5505-remote.sh test_expect_success 'set-head --auto' ' · line 437

Quoted 3 lines
t/t5505-remote.sh +2 -0
+		git remote set-head --auto origin >output &&
+		echo "'\''origin/HEAD'\'' is now created and points to '\''main'\''" >expect &&

Nit: might be cleaner to use ${SQ} here and below

You mean something like this?

	git remote set-head --auto origin >output &&
	HEAD="'\''origin/HEAD'\''" &&
	echo "${HEAD} is now created and points to '\''main'\''" >expect &&
Quoted 8 lines
Quoted 2 lines

I tried a few variations and this is what I could get working, but I may be simply missing something with the backtick.

I mean simply this

    git remote set-head --auto origin >output &&
    echo "${SQ}origin/HEAD${SQ} is now created and points to

${SQ}main${SQ}" >expect &&

Quoted 6 lines

Ah, I see in other tests this is used, but not in this particular test file. It's a bit hard to decide which is more cryptic, but ${SQ} is nicer on the eyes. On the other hand I would either switch the entire file in a separate patch or leave in the '\'' here as well. Or I guess one could go through the entire test base and switch everything to either one or the other for consistency.

I'm not sure I entirely agree with this sentiment. Consistency is a great goal to target, but it shouldn't hinder changes that are beneficial. In our case, if you make the first change, there is now reason for upcoming changes to the same file to also use '${SQ}' and eventually we can reach consistency of using '${SQ}' throughout the file.

- Karthik

#49 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Quoted 16 lines · karthik nayak
Quoted 8 lines · Bence Ferdinandy
Quoted 6 lines · karthik nayak

"Bence Ferdinandy" <[email protected]> writes:
I mean simply this

     git remote set-head --auto origin >output &&
     echo "${SQ}origin/HEAD${SQ} is now created and points to

${SQ}main${SQ}" >expect &&

Quoted 6 lines

Ah, I see in other tests this is used, but not in this particular test file. It's a bit hard to decide which is more cryptic, but ${SQ} is nicer on the eyes. On the other hand I would either switch the entire file in a separate patch or leave in the '\'' here as well. Or I guess one could go through the entire test base and switch everything to either one or the other for consistency.

Quoted 3 lines

I'm not sure I entirely agree with this sentiment. Consistency is a great goal to target, but it shouldn't hinder changes that are beneficial.

Exactly - if we wait for an entire test file to be modernized before using our modern test idioms in it we'll be waiting forever. It is much better to introduce the use of things like ${SQ} that improve readability as we add new tests or modify existing ones.

Best Wishes

Phillip

In our case, if you make the first change, there is now

Quoted 4 lines

reason for upcoming changes to the same file to also use '${SQ}' and eventually we can reach consistency of using '${SQ}' throughout the file.

- Karthik

#50 lore raw

Re: [PATCH v6 3/6] set-head: better output for --auto

Quoted 4 lines · Phillip Wood
Quoted 3 lines · karthik nayak
Quoted 1 line · Bence Ferdinandy

On Fri Oct 11, 2024 at 22:43, karthik nayak <[email protected]> wrote:

Quoted 8 lines
Quoted 3 lines

I'm not sure I entirely agree with this sentiment. Consistency is a great goal to target, but it shouldn't hinder changes that are beneficial.

Exactly - if we wait for an entire test file to be modernized before using our modern test idioms in it we'll be waiting forever. It is much better to introduce the use of things like ${SQ} that improve readability as we add new tests or modify existing ones.

Ok, I'll change the patch to use SQ. As I gather, it would be preferred if _all_ the tests would use ${SQ}? If this patch series is finally resolved I can send a patch for this style change, shouldn't be too complicated.

#51 lore raw

PATCH v6 4/6 transaction: add TRANSACTION_CREATE_EXISTS error

In reply to Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch
v5: no change
v6: no change

 refs.h                  |  4 +++-
 refs/files-backend.c    | 28 ++++++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 27 insertions(+), 11 deletions(-)
refs.h +3 -1
index f38616db84..166affbc89 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +20 -8
index 8415f2d020..272ad81315 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2603,9 +2607,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				int checkret;
+				checkret = check_old_oid(update, &lock->old_oid, err);
+				if  (checkret) {
+					ret = checkret;
+					goto out;
+				}
 			}
 		} else {
 			/*
@@ -2636,9 +2644,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			int checkret;
+			checkret = check_old_oid(update, &lock->old_oid, err);
+			if  (checkret) {
+				ret = checkret;
+				goto out;
+			}
 		}
 
 		/*
refs/reftable-backend.c +4 -2
index 32330b6bc6..c6b25ebac4 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}
 
Signature · 1 line
2.47.0.6.g07cb02250a
#52 lore raw

Re: [PATCH v6 4/6] transaction: add TRANSACTION_CREATE_EXISTS error

Quoted 1 line · Bence Ferdinandy

transaction: add TRANSACTION_CREATE_EXISTS error

Nit: but it would be nice to have s/transaction/refs here and similarly in other patches. Phrasing 'Documentation/SubmittingPatches':

It is also conventional in most cases to prefix the first line with "area: " where the area is a filename or identifier for the general area of the code being modified, e.g.

* doc: clarify distinction between sign-off and pgp-signing
* githooks.txt: improve the intro section

So in this sense, it would be the refs area, no?

Quoted 72 lines

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch
v5: no change
v6: no change

 refs.h                  |  4 +++-
 refs/files-backend.c    | 28 ++++++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 27 insertions(+), 11 deletions(-)
refs.h +3 -1
index f38616db84..166affbc89 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +6 -2
index 8415f2d020..272ad81315 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2603,9 +2607,13 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}

refs/files-backend.c static int lock_ref_for_update(struct files_ref_store *refs, · line 2616

Quoted 10 lines
refs/files-backend.c +7 -3
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				int checkret;
+				checkret = check_old_oid(update, &lock->old_oid, err);
+				if  (checkret) {
+					ret = checkret;
+					goto out;
+				}

Can't we simply do:

  ret = check_old_oid(update, &lock->old_oid, err);
  if (ret) {
     goto out
  }

if ret is '0', it shouldn't matter no?

[snip]

#53 lore raw

Re: [PATCH v6 4/6] transaction: add TRANSACTION_CREATE_EXISTS error

Quoted 10 lines · karthik nayak

refs/files-backend.c static int lock_ref_for_update(struct files_ref_store *refs, · line 2616

Quoted 7 lines
refs/files-backend.c +7 -0
+			} else {
+				int checkret;
+				checkret = check_old_oid(update, &lock->old_oid, err);
+				if  (checkret) {
+					ret = checkret;
+					goto out;
+				}

Can't we simply do:

Quoted 6 lines
  ret = check_old_oid(update, &lock->old_oid, err);
  if (ret) {
     goto out
  }

if ret is '0', it shouldn't matter no?

That's nice. Yes, as long as "ret" has no useful information when we enter this "else" block, reusing it like you did is just fine.

This is one of these moments I tell myself "oh, why didn't *I* think of that" ;-).

Thanks.

#54 lore raw

PATCH v6 5/6 refs_update_symref: add create_only option

In reply to Bence Ferdinandy

Allow the caller to specify that it only wants to update the symref if it does not already exist. Silently ignore the error from the transaction API if the symref already exists.

---

Notes:
v4: new patch
v5: no change

v6: - switched from bool to int for create_only
- refactored logic in refs_update_symref with goto as layed out by Junio

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 +++--
 builtin/clone.c           |  8 +++++---
 builtin/notes.c           |  3 ++-
 builtin/remote.c          |  9 ++++++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 36 +++++++++++++++++++++++++-----------
 refs.h                    |  2 +-
 reset.c                   |  2 +-
 sequencer.c               |  3 ++-
 setup.c                   |  3 ++-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 51 insertions(+), 28 deletions(-)
builtin/branch.c +1 -1
index 6c87690b58..2fcbcbfd59 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL, 0))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +3 -2
index 356ee9bcde..9abb71dc07 100644
@@ -1015,7 +1015,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path,
+					msg.buf, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1480,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b", NULL);
+				    "HEAD", branch_ref.buf, "checkout -b", NULL, 0);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +5 -3
index ead2af20ea..87e8f1421a 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg, NULL) < 0)
+				       msg, NULL, 0) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name,
+					NULL, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +703,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn,
+					NULL, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +2 -1
index ba646f06ff..7b3138e3c3 100644
@@ -980,7 +980,8 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref,
+					NULL, NULL, 0))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +6 -3
index 24f9caf149..9774d8ffe3 100644
@@ -244,7 +244,8 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					"remote add", NULL, 0))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +865,8 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					buf3.buf, NULL, 0))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1469,7 +1471,8 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf,
+					"remote set-head", &buf_prev, 0))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a) {
 			report_auto(argv[0], head_name, &buf_prev);
builtin/symbolic-ref.c +1 -1
index 7728fbc3c1..cfbb53b30c 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg, NULL);
+					   argv[0], argv[1], msg, NULL, 0);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index a7ab4193c1..2e95367235 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL, 0);
 	if (ret)
 		goto done;
 
refs.c +25 -11
index 91cacee6f9..e23288b817 100644
@@ -2115,29 +2115,43 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target)
+		       struct strbuf *before_target, int create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
 	int ret = 0;
 
 	transaction = ref_store_transaction_begin(refs, &err);
-	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
-				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+	if (!transaction) {
+	error_return:
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (create_only) {
+		int create_ret = 0;
+		if (ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err))
+			goto error_return;
+		create_ret = ref_transaction_commit(transaction, &err);
+		if (create_ret && create_ret != TRANSACTION_CREATE_EXISTS)
+			ret = error("%s", err.buf);
 
-	strbuf_release(&err);
+	} else {
+		if (ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+		    ref_transaction_commit(transaction, &err))
+			goto error_return;
+	}
 
-	if (transaction && before_target && transaction->updates[0]->before_target)
-		strbuf_addstr(before_target, transaction->updates[0]->before_target);
+cleanup:
+	strbuf_release(&err);
 
-	if (transaction)
+	if (transaction) {
+		if (before_target && transaction->updates[0]->before_target)
+			strbuf_addstr(before_target, transaction->updates[0]->before_target);
 		ref_transaction_free(transaction);
-
+	}
 	return ret;
 }
 
refs.h +1 -1
index 166affbc89..35f5439cd1 100644
@@ -572,7 +572,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg,
-		       struct strbuf *before_target);
+		       struct strbuf *before_target, int create_only);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index cc36a9ed56..919fb84f5f 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head, NULL);
+						 reflog_head, NULL, 0);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +2 -1
index 23b162924c..103d0ddfb2 100644
@@ -5107,7 +5107,8 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf,
+						msg, NULL, 0)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +2 -1
index d95f051465..9bbc655ee4 100644
@@ -2275,7 +2275,8 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref,
+					NULL, NULL, 0) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index a911302bea..f72b029e51 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg, NULL);
+	return refs_update_symref(refs, refname, target, logmsg, NULL, 0);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.6.g07cb02250a
#55 lore raw

PATCH v6 6/6 fetch: set remote/HEAD if it does not exist

In reply to Bence Ferdinandy

If the user has remote/HEAD set already and it looks like it has changed on the server, then print a message, otherwise set it if we can. Silently pass if the user already has the same remote/HEAD set as reported by the server or if we encounter any errors along the way.

---

Notes:
v3: - does not rely on remote set-head anymore so it only authenticates
once
- uses the new REF_CREATE_ONLY to atomically check if the ref exists and only write it if it doesn't
- in all other cases the maximum it does is print a warning

v4: - instead of the discarded REF_CREATE_ONLY, it uses the existing,
but updated transaction api to request a silent create only
- it now uses the atomic before_target to determine reporting
- refactored for legibility

v5: - instead of printing a not too useful message, it now fails
silently, this in line with the objective to only set up remote/HEAD automatically if the right thing is trivial, for everything else there is remote set-head
- fixed all failing tests
- added two new tests, one for checking if remote/HEAD is set to the correct one, and one to test that we do not override remote/HEAD if it has changed on the server from what we have locally

v6: - fixed style issues and unintended extra empty line
- updated function call with bool to int from previous patch's change
- removed calls to error(...) inherited from builtin/remote.c so we actually fail silently
- set the test for remote set-head --auto to the correct value here, which was previously erronously set in the remote set-head patch

 builtin/fetch.c                  |  82 +++++++++++
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  13 +-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 12 files changed, 308 insertions(+), 123 deletions(-)
builtin/fetch.c +82 -0
index 80a64d0d26..4c68f21be1 100644
@@ -1578,6 +1578,80 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && strcmp(prev_head, head_name)) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}
+}
+
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1)
+		result = 1;
+	else
+		head_name = xstrdup(heads.items[0].string);
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result = 1;
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head, 1))
+			result = 1;
+		else
+			report_set_head(remote, head_name, &b_local_head);
+
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)
@@ -1647,6 +1721,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
+
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1791,6 +1867,12 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		;
+		/*
+		 * Way too many cases where this can go wrong
+		 * so let's just fail silently for now.
+		 */
 
 cleanup:
 	if (retcode) {
t/t4207-log-decoration-colors.sh +2 -1
index 73ea9e5155..d55d22cb2f 100755
@@ -59,7 +59,8 @@ ${c_reset}${c_tag}tag: ${c_reset}${c_tag}v1.0${c_reset}${c_commit}, \
 ${c_reset}${c_tag}tag: ${c_reset}${c_tag}B${c_reset}${c_commit})${c_reset} B
 ${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_tag}tag: ${c_reset}${c_tag}A1${c_reset}${c_commit}, \
-${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit})${c_reset} A1
+${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit}, \
+${c_reset}${c_remoteBranch}other/HEAD${c_reset}${c_commit})${c_reset} A1
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_stash}refs/stash${c_reset}${c_commit})${c_reset} On main: Changes to A.t
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
t/t5505-remote.sh +8 -5
index 77c12b8709..4a62753af3 100755
@@ -71,7 +71,7 @@ test_expect_success 'add another remote' '
 		cd test &&
 		git remote add -f second ../two &&
 		tokens_match "origin second" "$(git remote)" &&
-		check_tracking_branch second main side another &&
+		check_tracking_branch second main side another HEAD &&
 		git for-each-ref "--format=%(refname)" refs/remotes |
 		sed -e "/^refs\/remotes\/origin\//d" \
 		    -e "/^refs\/remotes\/second\//d" >actual &&
@@ -473,7 +473,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "'\''two/HEAD'\'' is now created and points to '\''main'\''" >expect &&
+		echo "'\''two/HEAD'\'' is unchanged and points to '\''main'\''" >expect &&
 		test_cmp expect output
 	)
 '
@@ -764,6 +764,7 @@ test_expect_success 'reject --no-no-tags' '
 cat >one/expect <<\EOF
   apis/main
   apis/side
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -781,6 +782,7 @@ test_expect_success 'update' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -793,7 +795,7 @@ EOF
 test_expect_success 'update with arguments' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -836,7 +838,7 @@ EOF
 test_expect_success 'update default' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -848,6 +850,7 @@ test_expect_success 'update default' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -870,7 +873,7 @@ test_expect_success 'update default (overridden, with funny whitespace)' '
 test_expect_success 'update (with remotes.default defined)' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
t/t5510-fetch.sh +122 -107

356 lines not on this page · raw message

t/t5512-ls-remote.sh +2 -0
index 64b3491e4e..1b3865e154 100755
@@ -293,6 +293,8 @@ test_expect_success 'ls-remote with filtered symref (refname)' '
 	cat >expect <<-EOF &&
 	ref: refs/heads/main	HEAD
 	$rev	HEAD
+	ref: refs/remotes/origin/main	refs/remotes/origin/HEAD
+	$rev	refs/remotes/origin/HEAD
 	EOF
 	git ls-remote --symref . HEAD >actual &&
 	test_cmp expect actual
t/t5514-fetch-multiple.sh +15 -2
index 579872c258..e3482b27b2 100755
@@ -45,14 +45,17 @@ test_expect_success setup '
 '
 
 cat > test/expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -97,6 +100,7 @@ cat > expect << EOF
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
@@ -112,8 +116,10 @@ test_expect_success 'git fetch --multiple (but only one remote)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -141,7 +147,7 @@ test_expect_success 'git fetch --multiple (bad remote names)' '
 
 test_expect_success 'git fetch --all (skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -153,11 +159,14 @@ test_expect_success 'git fetch --all (skipFetchAll)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -165,7 +174,7 @@ EOF
 
 test_expect_success 'git fetch --multiple (ignoring skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -221,14 +230,17 @@ test_expect_success 'git fetch --multiple --jobs=0 picks a default' '
 
 create_fetch_all_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
 	  origin/main
 	  origin/side
+	  three/HEAD -> three/main
 	  three/another
 	  three/main
 	  three/side
+	  two/HEAD -> two/main
 	  two/another
 	  two/main
 	  two/side
@@ -265,6 +277,7 @@ test_expect_success 'git fetch (fetch all remotes with fetch.all = true)' '
 
 create_fetch_one_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
t/t5516-fetch-push.sh +2 -1
index 331778bd42..5a051aa0c7 100755
@@ -1395,7 +1395,8 @@ test_expect_success 'fetch follows tags by default' '
 		git tag -m "annotated" tag &&
 		git for-each-ref >tmp1 &&
 		sed -n "p; s|refs/heads/main$|refs/remotes/origin/main|p" tmp1 |
-		sort -k 3 >../expect
+		sed -n "p; s|refs/heads/main$|refs/remotes/origin/HEAD|p"  |
+		sort -k 4 >../expect
 	) &&
 	test_when_finished "rm -rf dst" &&
 	git init dst &&
t/t5527-fetch-odd-refs.sh +2 -1
index 98ece27c6a..d3996af6ee 100755
@@ -52,7 +52,8 @@ test_expect_success LONG_REF 'fetch handles extremely long refname' '
 	long
 	main
 	EOF
-	git for-each-ref --format="%(subject)" refs/remotes/long >actual &&
+	git for-each-ref --format="%(subject)" refs/remotes/long \
+		--exclude=refs/remotes/long/HEAD >actual &&
 	test_cmp expect actual
 '
 
t/t7900-maintenance.sh +2 -1
index a66d0e089d..88331d1ceb 100755
@@ -329,7 +329,8 @@ test_expect_success 'incremental-repack task' '
 
 	# Delete refs that have not been repacked in these packs.
 	git for-each-ref --format="delete %(refname)" \
-		refs/prefetch refs/tags refs/remotes >refs &&
+		refs/prefetch refs/tags refs/remotes \
+		--exclude=refs/remotes/*/HEAD >refs &&
 	git update-ref --stdin <refs &&
 
 	# Replace the object directory with this pack layout.
t/t9210-scalar.sh +3 -2
index 027235d61a..a81662713e 100755
@@ -150,7 +150,8 @@ test_expect_success 'scalar clone' '
 			"$(pwd)" &&
 
 		git for-each-ref --format="%(refname)" refs/remotes/origin/ >actual &&
-		echo "refs/remotes/origin/parallel" >expect &&
+		echo "refs/remotes/origin/HEAD" >>expect &&
+		echo "refs/remotes/origin/parallel" >>expect &&
 		test_cmp expect actual &&
 
 		test_path_is_missing 1/2 &&
@@ -219,7 +220,7 @@ test_expect_success 'scalar reconfigure --all with includeIf.onbranch' '
 	done
 '
 
- test_expect_success 'scalar reconfigure --all with detached HEADs' '
+test_expect_success 'scalar reconfigure --all with detached HEADs' '
 	repos="two three four" &&
 	for num in $repos
 	do
t/t9211-scalar-clone.sh +3 -3
index 7869f45ee6..01f71910f5 100755
@@ -31,7 +31,7 @@ test_expect_success 'set up repository to clone' '
 	)
 '
 
-cleanup_clone () {
+cleanup_clone() {
 	rm -rf "$1"
 }
 
@@ -127,7 +127,7 @@ test_expect_success '--single-branch clones HEAD only' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 1 out &&
+		test_line_count = 2 out &&
 		grep "refs/remotes/origin/base" out
 	) &&
 
@@ -141,7 +141,7 @@ test_expect_success '--no-single-branch clones all branches' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 2 out &&
+		test_line_count = 3 out &&
 		grep "refs/remotes/origin/base" out &&
 		grep "refs/remotes/origin/parallel" out
 	) &&
t/t9902-completion.sh +65 -0

443 lines not on this page · raw message

Signature · 1 line
2.47.0.6.g07cb02250a
#56 lore raw

PATCH v7 1/6 refs: atomically record overwritten ref in update_symref

In reply to Bence Ferdinandy

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten. Record the value after the ref has been locked if the caller of refs_update_symref requests it via a new variable in the function call.

---

Notes:
v4: new patch

v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

v6: - no change

v7: - remove the whole before_target concept from the backends and
handle checking it in refs.c instead (thanks Karthik)
- rename the before_target to referent which is how the same concept is called in the backends
- change commit prefix to be more in line with project standards

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  4 ++--
 builtin/clone.c           |  6 +++---
 builtin/notes.c           |  2 +-
 builtin/remote.c          |  6 +++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 16 +++++++++++-----
 refs.h                    |  3 ++-
 reset.c                   |  2 +-
 sequencer.c               |  2 +-
 setup.c                   |  2 +-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 29 insertions(+), 22 deletions(-)
builtin/branch.c +1 -1
index fd1611ebf5..6c87690b58 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +2 -2
index 9c30000d3a..356ee9bcde 100644
@@ -1015,7 +1015,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1479,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, "checkout -b", NULL);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index e77339c847..ead2af20ea 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg) < 0)
+				       msg, NULL) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +702,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 8c26e45526..ba646f06ff 100644
@@ -980,7 +980,7 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 76670ddd8b..d8ff440027 100644
@@ -244,7 +244,7 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +864,7 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1444,7 +1444,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 299d23d76a..7728fbc3c1 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], msg, NULL);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index fc31d072a6..a7ab4193c1 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
 	if (ret)
 		goto done;
 
refs.c +11 -5
index 5f729ed412..b964ac44d0 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2122,17 +2123,23 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
+		ref_transaction_update(transaction, ref, NULL, NULL,
 				   target, NULL, REF_NO_DEREF,
 				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);
+
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
 
+cleanup:
 	strbuf_release(&err);
 	if (transaction)
 		ref_transaction_free(transaction);
-
 	return ret;
 }
 
@@ -2948,4 +2955,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +2 -1
index 108dfc93b3..b09a3a4384 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index b22b1be792..cc36a9ed56 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head);
+						 reflog_head, NULL);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +1 -1
index 8d01cd50ac..23b162924c 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +1 -1
index 94e79b2e48..d95f051465 100644
@@ -2275,7 +2275,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#57 lore raw

PATCH v7 2/6 remote set-head: add new variable for readability

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable for better readability.

---

Notes:
v5: new patch (split from the next patch as a preparatory step)

v6: no change

v7: - change commit prefix to be more in line with project standards

 builtin/remote.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
builtin/remote.c +4 -3
index d8ff440027..353ffd2c43 100644
@@ -1404,6 +1404,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	int i, opt_a = 0, opt_d = 0, result = 0;
 	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1434,7 +1435,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
+		if (refs_delete_ref(refs, NULL, buf.buf, NULL, REF_NO_DEREF))
 			result |= error(_("Could not delete %s"), buf.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
@@ -1442,9 +1443,9 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	if (head_name) {
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
+		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#58 lore raw

PATCH v7 3/6 remote set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates. As a fourth output, if HEAD is changed from a previous value that was not a remote branch, explicitly call attention to this fact.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

v5: - the minor refactor has been split out into its own patch

v6: - fixed uninitialized prev_head
- fixed case of unusual previous target
- fixed a test that would have been actually broken at this patch (the output was only correct with the later update to fetch)
- added 4 tests for the 4 output cases

v7: - change commit prefix to be more in line with project standards
- fixed tests to also work with the reftable backend
- renamed report function, fixed style issue with checking buf len
- fixed not releasing an strbuf

 builtin/remote.c  | 35 ++++++++++++++++++++++++++++----
 t/t5505-remote.sh | 51 ++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 81 insertions(+), 5 deletions(-)
builtin/remote.c +31 -4
index 353ffd2c43..2b6948439f 100644
@@ -1399,10 +1399,35 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_set_head_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else if (!buf_prev->len)
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+	else
+		printf("'%s/HEAD' used to point to '%s' "
+			"(which is not a remote branch), but now points to '%s'\n",
+			remote, buf_prev->buf, head_name);
+	strbuf_release(&buf_prefix);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1470,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
 			result |= error(_("Could not setup %s"), buf.buf);
-		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+		else if (opt_a) {
+			report_set_head_auto(argv[0], head_name, &buf_prev);
+		}
 		free(head_name);
 	}
 
 	strbuf_release(&buf);
 	strbuf_release(&buf2);
+	strbuf_release(&buf_prev);
 	return result;
 }
 
t/t5505-remote.sh +50 -1

68 lines not on this page · raw message

Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#59 lore raw

PATCH v7 4/6 refs: add TRANSACTION_CREATE_EXISTS error

In reply to Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch
v5: no change
v6: no change

v7: - change commit prefix to be more in line with project standards
- changed error checking to Karthik's suggestion

 refs.h                  |  4 +++-
 refs/files-backend.c    | 24 ++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 23 insertions(+), 11 deletions(-)
refs.h +3 -1
index b09a3a4384..c83b1ec76e 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +16 -8
index 0824c0b8a9..e743ec44b5 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2602,9 +2606,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				ret = check_old_oid(update, &lock->old_oid, err);
+				if  (ret) {
+					goto out;
+				}
 			}
 		} else {
 			/*
@@ -2635,9 +2641,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			ret = check_old_oid(update, &lock->old_oid, err);
+			if  (ret) {
+				goto out;
+			}
 		}
 
 		/*
refs/reftable-backend.c +4 -2
index 3c96fbf66f..ebf8e57fbc 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}
 
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#60 lore raw

Re: [PATCH v7 4/6] refs: add TRANSACTION_CREATE_EXISTS error

Hi Bence

Quoted 5 lines · Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

This looks like useful improvement. Are the changes to reftable-backend.c correct - it looks like where it previously returned TRANSACTION_GENERIC_ERR it now returns TRANSACTION_NAME_CONFLICT which I think is used to indicate a file/directory conflict (e.g. trying to create refs/heads/topic/one when refs/heads/topic exists)

Best Wishes

Phillip

Quoted 122 lines

---

Notes:
v4: new patch
v5: no change
v6: no change

v7: - change commit prefix to be more in line with project standards
- changed error checking to Karthik's suggestion

  refs.h                  |  4 +++-
  refs/files-backend.c    | 24 ++++++++++++++++--------
  refs/reftable-backend.c |  6 ++++--
  3 files changed, 23 insertions(+), 11 deletions(-)
refs.h +3 -1
index b09a3a4384..c83b1ec76e 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
  /* Naming conflict (for example, the ref names A and A/B conflict). */
  #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
  /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
  /*
   * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +16 -8
index 0824c0b8a9..e743ec44b5 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
  static int check_old_oid(struct ref_update *update, struct object_id *oid,
  			 struct strbuf *err)
  {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
  	if (!(update->flags & REF_HAVE_OLD) ||
  		   oideq(oid, &update->old_oid))
  		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
  		strbuf_addf(err, "cannot lock ref '%s': "
  			    "reference already exists",
  			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
  	else if (is_null_oid(oid))
  		strbuf_addf(err, "cannot lock ref '%s': "
  			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
  			    oid_to_hex(oid),
  			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
  }
 
  /*
@@ -2602,9 +2606,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
  					ret = TRANSACTION_GENERIC_ERROR;
  					goto out;
  				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				ret = check_old_oid(update, &lock->old_oid, err);
+				if  (ret) {
+					goto out;
+				}
  			}
  		} else {
  			/*
@@ -2635,9 +2641,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
  				    update->old_target);
  			ret = TRANSACTION_GENERIC_ERROR;
  			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			ret = check_old_oid(update, &lock->old_oid, err);
+			if  (ret) {
+				goto out;
+			}
  		}
 
  		/*
refs/reftable-backend.c +4 -2
index 3c96fbf66f..ebf8e57fbc 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
  				goto done;
  			}
  		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
  				strbuf_addf(err, _("cannot lock ref '%s': "
  						   "reference already exists"),
  					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
  			else if (is_null_oid(&current_oid))
  				strbuf_addf(err, _("cannot lock ref '%s': "
  						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
  					    ref_update_original_update_refname(u),
  					    oid_to_hex(&current_oid),
  					    oid_to_hex(&u->old_oid));
-			ret = -1;
  			goto done;
  		}
 
#61 lore raw

Re: [PATCH v7 4/6] refs: add TRANSACTION_CREATE_EXISTS error

Quoted 9 lines · Phillip Wood

Hi Bence

Quoted 5 lines · Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

Quoted 5 lines

This looks like useful improvement. Are the changes to reftable-backend.c correct - it looks like where it previously returned TRANSACTION_GENERIC_ERR it now returns TRANSACTION_NAME_CONFLICT which I think is used to indicate a file/directory conflict (e.g. trying to create refs/heads/topic/one when refs/heads/topic exists)

This passes:
GIT_TEST_DEFAULT_REF_FORMAT=reftable prove --timer --jobs 8 ./t[0-9]*.sh so I'm hoping it's correct :)

[snip]

I guess you are referring to this part below:

Quoted 19 lines
Quoted 19 lines
refs/reftable-backend.c +4 -1
index 3c96fbf66f..ebf8e57fbc 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
  				goto done;
  			}
  		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
  				strbuf_addf(err, _("cannot lock ref '%s': "
  						   "reference already exists"),
  					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
  			else if (is_null_oid(&current_oid))
  				strbuf_addf(err, _("cannot lock ref '%s': "
  						   "reference is missing but expected %s"),
Quoted 8 lines

refs/reftable-backend.c static int reftable_be_transaction_prepare(struct ref_store *ref_store, · line 1229

Quoted 8 lines
refs/reftable-backend.c +0 -1
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
  					    ref_update_original_update_refname(u),
  					    oid_to_hex(&current_oid),
  					    oid_to_hex(&u->old_oid));
-			ret = -1;
  			goto done;
  		}
 

This originally returned -1, and it still returns that if it doesn't return -2, I just used the named variable instead of the integer itself. It might still be that this should be -3 GENERIC_ERROR, but if that is the case I think fixing that should be a different patch? I didn't check if changing that -1 to something else breaks anything or not.

Best,
Bence

Signature · 1 line
bence.ferdinandy.com
#62 lore raw

Re: [PATCH v7 4/6] refs: add TRANSACTION_CREATE_EXISTS error

Hi Bence

Quoted 27 lines · Bence Ferdinandy
Quoted 25 lines · Phillip Wood
Quoted 25 lines
refs/reftable-backend.c +4 -2
index 3c96fbf66f..ebf8e57fbc 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
   				goto done;
   			}
   		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
   				strbuf_addf(err, _("cannot lock ref '%s': "
   						   "reference already exists"),
   					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
   			else if (is_null_oid(&current_oid))
   				strbuf_addf(err, _("cannot lock ref '%s': "
   						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
   					    ref_update_original_update_refname(u),
   					    oid_to_hex(&current_oid),
   					    oid_to_hex(&u->old_oid));
-			ret = -1;
   			goto done;
Quoted 8 lines
Quoted 2 lines

refs/reftable-backend.c static int reftable_be_transaction_prepare(struct ref_store *ref_store, · line 1229

Quoted 2 lines
refs/reftable-backend.c +0 -0
   		}
 

This originally returned -1, and it still returns that if it doesn't return -2, I just used the named variable instead of the integer itself. It might still be that this should be -3 GENERIC_ERROR, but if that is the case I think fixing that should be a different patch? I didn't check if changing that -1 to something else breaks anything or not.

Oh sorry I was confused and thought TRANSACTION_GENERIC_ERROR was -1.

Best Wishes

Phillip

Quoted 3 lines

Best,
Bence

#63 lore raw

PATCH v7 5/6 refs: add create_only option to refs_update_symref

In reply to Bence Ferdinandy

Allow the caller to specify that it only wants to update the symref if it does not already exist. Silently ignore the error from the transaction API if the symref already exists.

---

Notes:
v4: new patch
v5: no change

v6: - switched from bool to int for create_only
- refactored logic in refs_update_symref with goto as layed out by Junio

v7: - change commit prefix to be more in line with project standards
- refactored code to accommodate changes in the first patch, but otherwise no change

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 +++--
 builtin/clone.c           |  8 +++++---
 builtin/notes.c           |  3 ++-
 builtin/remote.c          |  9 ++++++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 30 ++++++++++++++++++++++--------
 refs.h                    |  2 +-
 reset.c                   |  2 +-
 sequencer.c               |  3 ++-
 setup.c                   |  3 ++-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 48 insertions(+), 25 deletions(-)
builtin/branch.c +1 -1
index 6c87690b58..2fcbcbfd59 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL, 0))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +3 -2
index 356ee9bcde..9abb71dc07 100644
@@ -1015,7 +1015,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path,
+					msg.buf, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1480,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b", NULL);
+				    "HEAD", branch_ref.buf, "checkout -b", NULL, 0);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +5 -3
index ead2af20ea..87e8f1421a 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg, NULL) < 0)
+				       msg, NULL, 0) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name,
+					NULL, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +703,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn,
+					NULL, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +2 -1
index ba646f06ff..7b3138e3c3 100644
@@ -980,7 +980,8 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref,
+					NULL, NULL, 0))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +6 -3
index 2b6948439f..d60ec6e907 100644
@@ -244,7 +244,8 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					"remote add", NULL, 0))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +865,8 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					buf3.buf, NULL, 0))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1470,7 +1472,8 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf,
+					"remote set-head", &buf_prev, 0))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a) {
 			report_set_head_auto(argv[0], head_name, &buf_prev);
builtin/symbolic-ref.c +1 -1
index 7728fbc3c1..cfbb53b30c 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg, NULL);
+					   argv[0], argv[1], msg, NULL, 0);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index a7ab4193c1..2e95367235 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL, 0);
 	if (ret)
 		goto done;
 
refs.c +22 -8
index b964ac44d0..29c020e78e 100644
@@ -2115,26 +2115,40 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *referent)
+		       struct strbuf *referent, int create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
-	int ret = 0;
+	int ret = 0, prepret = 0;
 
 	transaction = ref_store_transaction_begin(refs, &err);
-	if (!transaction ||
-		ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
-				   logmsg, &err) ||
-		ref_transaction_prepare(transaction, &err)) {
+	if (!transaction) {
+	error_return:
 		ret = error("%s", err.buf);
 		goto cleanup;
 	}
+	if (create_only) {
+		if (ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err))
+			goto error_return;
+		prepret = ref_transaction_prepare(transaction, &err);
+		if (prepret && prepret != TRANSACTION_CREATE_EXISTS)
+			goto error_return;
+	} else {
+		if (ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+			ref_transaction_prepare(transaction, &err))
+			goto error_return;
+	}
+
 	if (referent)
 		refs_read_symbolic_ref(refs, ref, referent);
 
+	if (prepret == TRANSACTION_CREATE_EXISTS)
+		goto cleanup;
 	if (ref_transaction_commit(transaction, &err))
-		ret = error("%s", err.buf);
+		goto error_return;
 
 cleanup:
 	strbuf_release(&err);
refs.h +1 -1
index c83b1ec76e..41ae384f11 100644
@@ -572,7 +572,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg,
-		       struct strbuf *referent);
+		       struct strbuf *referent, int create_only);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index cc36a9ed56..919fb84f5f 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head, NULL);
+						 reflog_head, NULL, 0);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +2 -1
index 23b162924c..103d0ddfb2 100644
@@ -5107,7 +5107,8 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf,
+						msg, NULL, 0)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +2 -1
index d95f051465..9bbc655ee4 100644
@@ -2275,7 +2275,8 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref,
+					NULL, NULL, 0) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index a911302bea..f72b029e51 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg, NULL);
+	return refs_update_symref(refs, refname, target, logmsg, NULL, 0);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#64 lore raw

PATCH v7 6/6 fetch: set remote/HEAD if it does not exist

In reply to Bence Ferdinandy

If the user has remote/HEAD set already and it looks like it has changed on the server, then print a message, otherwise set it if we can. Silently pass if the user already has the same remote/HEAD set as reported by the server or if we encounter any errors along the way.

---

Notes:
v3: - does not rely on remote set-head anymore so it only authenticates
once
- uses the new REF_CREATE_ONLY to atomically check if the ref exists and only write it if it doesn't
- in all other cases the maximum it does is print a warning

v4: - instead of the discarded REF_CREATE_ONLY, it uses the existing,
but updated transaction api to request a silent create only
- it now uses the atomic before_target to determine reporting
- refactored for legibility

v5: - instead of printing a not too useful message, it now fails
silently, this in line with the objective to only set up remote/HEAD automatically if the right thing is trivial, for everything else there is remote set-head
- fixed all failing tests
- added two new tests, one for checking if remote/HEAD is set to the correct one, and one to test that we do not override remote/HEAD if it has changed on the server from what we have locally

v6: - fixed style issues and unintended extra empty line
- updated function call with bool to int from previous patch's change
- removed calls to error(...) inherited from builtin/remote.c so we actually fail silently
- set the test for remote set-head --auto to the correct value here, which was previously erronously set in the remote set-head patch

v7: - no change

 builtin/fetch.c                  |  82 +++++++++++
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  13 +-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 12 files changed, 308 insertions(+), 123 deletions(-)
builtin/fetch.c +82 -0
index 80a64d0d26..4c68f21be1 100644
@@ -1578,6 +1578,80 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && strcmp(prev_head, head_name)) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}
+}
+
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1)
+		result = 1;
+	else
+		head_name = xstrdup(heads.items[0].string);
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result = 1;
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head, 1))
+			result = 1;
+		else
+			report_set_head(remote, head_name, &b_local_head);
+
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)
@@ -1647,6 +1721,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
+
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1791,6 +1867,12 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		;
+		/*
+		 * Way too many cases where this can go wrong
+		 * so let's just fail silently for now.
+		 */
 
 cleanup:
 	if (retcode) {
t/t4207-log-decoration-colors.sh +2 -1
index 73ea9e5155..d55d22cb2f 100755
@@ -59,7 +59,8 @@ ${c_reset}${c_tag}tag: ${c_reset}${c_tag}v1.0${c_reset}${c_commit}, \
 ${c_reset}${c_tag}tag: ${c_reset}${c_tag}B${c_reset}${c_commit})${c_reset} B
 ${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_tag}tag: ${c_reset}${c_tag}A1${c_reset}${c_commit}, \
-${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit})${c_reset} A1
+${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit}, \
+${c_reset}${c_remoteBranch}other/HEAD${c_reset}${c_commit})${c_reset} A1
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_stash}refs/stash${c_reset}${c_commit})${c_reset} On main: Changes to A.t
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
t/t5505-remote.sh +8 -5
index d99cd1d0aa..cb45f22232 100755
@@ -71,7 +71,7 @@ test_expect_success 'add another remote' '
 		cd test &&
 		git remote add -f second ../two &&
 		tokens_match "origin second" "$(git remote)" &&
-		check_tracking_branch second main side another &&
+		check_tracking_branch second main side another HEAD &&
 		git for-each-ref "--format=%(refname)" refs/remotes |
 		sed -e "/^refs\/remotes\/origin\//d" \
 		    -e "/^refs\/remotes\/second\//d" >actual &&
@@ -473,7 +473,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "'\''two/HEAD'\'' is now created and points to '\''main'\''" >expect &&
+		echo "'\''two/HEAD'\'' is unchanged and points to '\''main'\''" >expect &&
 		test_cmp expect output
 	)
 '
@@ -763,6 +763,7 @@ test_expect_success 'reject --no-no-tags' '
 cat >one/expect <<\EOF
   apis/main
   apis/side
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -780,6 +781,7 @@ test_expect_success 'update' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -792,7 +794,7 @@ EOF
 test_expect_success 'update with arguments' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -835,7 +837,7 @@ EOF
 test_expect_success 'update default' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -847,6 +849,7 @@ test_expect_success 'update default' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -869,7 +872,7 @@ test_expect_success 'update default (overridden, with funny whitespace)' '
 test_expect_success 'update (with remotes.default defined)' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
t/t5510-fetch.sh +122 -107

356 lines not on this page · raw message

t/t5512-ls-remote.sh +2 -0
index 64b3491e4e..1b3865e154 100755
@@ -293,6 +293,8 @@ test_expect_success 'ls-remote with filtered symref (refname)' '
 	cat >expect <<-EOF &&
 	ref: refs/heads/main	HEAD
 	$rev	HEAD
+	ref: refs/remotes/origin/main	refs/remotes/origin/HEAD
+	$rev	refs/remotes/origin/HEAD
 	EOF
 	git ls-remote --symref . HEAD >actual &&
 	test_cmp expect actual
t/t5514-fetch-multiple.sh +15 -2
index 579872c258..e3482b27b2 100755
@@ -45,14 +45,17 @@ test_expect_success setup '
 '
 
 cat > test/expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -97,6 +100,7 @@ cat > expect << EOF
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
@@ -112,8 +116,10 @@ test_expect_success 'git fetch --multiple (but only one remote)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -141,7 +147,7 @@ test_expect_success 'git fetch --multiple (bad remote names)' '
 
 test_expect_success 'git fetch --all (skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -153,11 +159,14 @@ test_expect_success 'git fetch --all (skipFetchAll)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -165,7 +174,7 @@ EOF
 
 test_expect_success 'git fetch --multiple (ignoring skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -221,14 +230,17 @@ test_expect_success 'git fetch --multiple --jobs=0 picks a default' '
 
 create_fetch_all_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
 	  origin/main
 	  origin/side
+	  three/HEAD -> three/main
 	  three/another
 	  three/main
 	  three/side
+	  two/HEAD -> two/main
 	  two/another
 	  two/main
 	  two/side
@@ -265,6 +277,7 @@ test_expect_success 'git fetch (fetch all remotes with fetch.all = true)' '
 
 create_fetch_one_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
t/t5516-fetch-push.sh +2 -1
index 331778bd42..5a051aa0c7 100755
@@ -1395,7 +1395,8 @@ test_expect_success 'fetch follows tags by default' '
 		git tag -m "annotated" tag &&
 		git for-each-ref >tmp1 &&
 		sed -n "p; s|refs/heads/main$|refs/remotes/origin/main|p" tmp1 |
-		sort -k 3 >../expect
+		sed -n "p; s|refs/heads/main$|refs/remotes/origin/HEAD|p"  |
+		sort -k 4 >../expect
 	) &&
 	test_when_finished "rm -rf dst" &&
 	git init dst &&
t/t5527-fetch-odd-refs.sh +2 -1
index 98ece27c6a..d3996af6ee 100755
@@ -52,7 +52,8 @@ test_expect_success LONG_REF 'fetch handles extremely long refname' '
 	long
 	main
 	EOF
-	git for-each-ref --format="%(subject)" refs/remotes/long >actual &&
+	git for-each-ref --format="%(subject)" refs/remotes/long \
+		--exclude=refs/remotes/long/HEAD >actual &&
 	test_cmp expect actual
 '
 
t/t7900-maintenance.sh +2 -1
index a66d0e089d..88331d1ceb 100755
@@ -329,7 +329,8 @@ test_expect_success 'incremental-repack task' '
 
 	# Delete refs that have not been repacked in these packs.
 	git for-each-ref --format="delete %(refname)" \
-		refs/prefetch refs/tags refs/remotes >refs &&
+		refs/prefetch refs/tags refs/remotes \
+		--exclude=refs/remotes/*/HEAD >refs &&
 	git update-ref --stdin <refs &&
 
 	# Replace the object directory with this pack layout.
t/t9210-scalar.sh +3 -2
index 027235d61a..a81662713e 100755
@@ -150,7 +150,8 @@ test_expect_success 'scalar clone' '
 			"$(pwd)" &&
 
 		git for-each-ref --format="%(refname)" refs/remotes/origin/ >actual &&
-		echo "refs/remotes/origin/parallel" >expect &&
+		echo "refs/remotes/origin/HEAD" >>expect &&
+		echo "refs/remotes/origin/parallel" >>expect &&
 		test_cmp expect actual &&
 
 		test_path_is_missing 1/2 &&
@@ -219,7 +220,7 @@ test_expect_success 'scalar reconfigure --all with includeIf.onbranch' '
 	done
 '
 
- test_expect_success 'scalar reconfigure --all with detached HEADs' '
+test_expect_success 'scalar reconfigure --all with detached HEADs' '
 	repos="two three four" &&
 	for num in $repos
 	do
t/t9211-scalar-clone.sh +3 -3
index 7869f45ee6..01f71910f5 100755
@@ -31,7 +31,7 @@ test_expect_success 'set up repository to clone' '
 	)
 '
 
-cleanup_clone () {
+cleanup_clone() {
 	rm -rf "$1"
 }
 
@@ -127,7 +127,7 @@ test_expect_success '--single-branch clones HEAD only' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 1 out &&
+		test_line_count = 2 out &&
 		grep "refs/remotes/origin/base" out
 	) &&
 
@@ -141,7 +141,7 @@ test_expect_success '--no-single-branch clones all branches' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 2 out &&
+		test_line_count = 3 out &&
 		grep "refs/remotes/origin/base" out &&
 		grep "refs/remotes/origin/parallel" out
 	) &&
t/t9902-completion.sh +65 -0

443 lines not on this page · raw message

Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#65 lore raw

Re: [PATCH v7 1/6] refs: atomically record overwritten ref in update_symref

In reply to Bence Ferdinandy

Hi Bence

Quoted 2 lines · Bence Ferdinandy

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten.

It is if you use a ref transaction rather than call refs_update_symref() and query the ref after calling ref_transaction_prepare() and before calling ref_transaction_commit() which is what the code below does.

Quoted 3 lines

Record the value after the
ref has been locked if the caller of refs_update_symref requests it via a new variable in the function call.

To me this patch and patch 5 feel quite disruptive to all the existing callers which don't need this specialized functionality. I think it would be less disruptive over all if you used a ref transaction rather than calling refs_update_symref() in the final patch. That would enable us to keep the simpler interface for refs_update_symref().

I'm also not sure about the proposed interface I would have thought it would be simpler to take a "char**" rather than an "struct strbuf*" if we do decide that it is useful for callers of refs_update_symref() to query the old value.

Best Wishes

Phillip

Quoted 280 lines

---

Notes:
v4: new patch

v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

v6: - no change

v7: - remove the whole before_target concept from the backends and
handle checking it in refs.c instead (thanks Karthik)
- rename the before_target to referent which is how the same concept is called in the backends
- change commit prefix to be more in line with project standards

  builtin/branch.c          |  2 +-
  builtin/checkout.c        |  4 ++--
  builtin/clone.c           |  6 +++---
  builtin/notes.c           |  2 +-
  builtin/remote.c          |  6 +++---
  builtin/symbolic-ref.c    |  2 +-
  builtin/worktree.c        |  2 +-
  refs.c                    | 16 +++++++++++-----
  refs.h                    |  3 ++-
  reset.c                   |  2 +-
  sequencer.c               |  2 +-
  setup.c                   |  2 +-
  t/helper/test-ref-store.c |  2 +-
  13 files changed, 29 insertions(+), 22 deletions(-)
builtin/branch.c +1 -1
index fd1611ebf5..6c87690b58 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
  			continue;
 
  		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
  			ret = error(_("HEAD of working tree %s is not updated"),
  				    worktrees[i]->path);
  	}
builtin/checkout.c +2 -2
index 9c30000d3a..356ee9bcde 100644
@@ -1015,7 +1015,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
  			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
  		}
  	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
  			die(_("unable to update HEAD"));
  		if (!opts->quiet) {
  			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1479,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
  		die(_("You are on a branch yet to be born"));
  	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
  	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, "checkout -b", NULL);
  	strbuf_release(&branch_ref);
  	if (!opts->quiet)
  		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index e77339c847..ead2af20ea 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
  		strbuf_addstr(&head_ref, "HEAD");
  		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
  				       remote_head_points_at->peer_ref->name,
-				       msg) < 0)
+				       msg, NULL) < 0)
  			die(_("unable to update %s"), head_ref.buf);
  		strbuf_release(&head_ref);
  	}
@@ -673,7 +673,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
  	const char *head;
  	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
  		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
  			die(_("unable to update HEAD"));
  		if (!option_bare) {
  			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +702,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
  		 * Unborn head from remote; same as "our" case above except
  		 * that we have no ref to update.
  		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
  			die(_("unable to update HEAD"));
  		if (!option_bare)
  			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 8c26e45526..ba646f06ff 100644
@@ -980,7 +980,7 @@ static int merge(int argc, const char **argv, const char *prefix)
  			die(_("a notes merge into %s is already in-progress at %s"),
  			    notes_ref, wt->path);
  		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
  			die(_("failed to store link to current notes ref (%s)"),
  			    notes_ref);
  		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 76670ddd8b..d8ff440027 100644
@@ -244,7 +244,7 @@ static int add(int argc, const char **argv, const char *prefix)
  		strbuf_reset(&buf2);
  		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
  			result = error(_("Could not setup master '%s'"), master);
  	}
 
@@ -864,7 +864,7 @@ static int mv(int argc, const char **argv, const char *prefix)
  		strbuf_reset(&buf3);
  		strbuf_addf(&buf3, "remote: renamed %s to %s",
  				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
  			die(_("creating '%s' failed"), buf.buf);
  		display_progress(progress, ++refs_renamed_nr);
  	}
@@ -1444,7 +1444,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
  		/* make sure it's valid */
  		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
  			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
  			result |= error(_("Could not setup %s"), buf.buf);
  		else if (opt_a)
  			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 299d23d76a..7728fbc3c1 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
  		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
  			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
  		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], msg, NULL);
  		break;
  	default:
  		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index fc31d072a6..a7ab4193c1 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
  		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
  				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
  	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
  	if (ret)
  		goto done;
 
refs.c +11 -5
index 5f729ed412..b964ac44d0 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
  }
 
  int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
  {
  	struct ref_transaction *transaction;
  	struct strbuf err = STRBUF_INIT;
@@ -2122,17 +2123,23 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
  	transaction = ref_store_transaction_begin(refs, &err);
  	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
+		ref_transaction_update(transaction, ref, NULL, NULL,
  				   target, NULL, REF_NO_DEREF,
  				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
  		ret = error("%s", err.buf);
+		goto cleanup;
  	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);
+
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
 
+cleanup:
  	strbuf_release(&err);
  	if (transaction)
  		ref_transaction_free(transaction);
-
  	return ret;
  }
 
@@ -2948,4 +2955,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
  	return (update->flags & REF_HAVE_OLD) &&
  		(!is_null_oid(&update->old_oid) || update->old_target);
  }
-
refs.h +2 -1
index 108dfc93b3..b09a3a4384 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
  		    const char *newref, const char *logmsg);
 
  int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent);
 
  enum action_on_err {
  	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index b22b1be792..cc36a9ed56 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
  		if (!ret)
  			ret = refs_update_symref(get_main_ref_store(the_repository),
  						 "HEAD", switch_to_branch,
-						 reflog_head);
+						 reflog_head, NULL);
  	}
  	if (!ret && run_hook)
  		run_hooks_l(the_repository, "post-checkout",
sequencer.c +1 -1
index 8d01cd50ac..23b162924c 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
  			}
  			msg = reflog_message(opts, "finish", "returning to %s",
  				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
  				res = error(_("could not update HEAD to %s"),
  					head_ref.buf);
  				goto cleanup_head_ref;
setup.c +1 -1
index 94e79b2e48..d95f051465 100644
@@ -2275,7 +2275,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
  			die(_("invalid initial branch name: '%s'"),
  			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
  			exit(1);
  		free(ref);
  	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
  	const char *target = notnull(*argv++, "target");
  	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
  }
 
  static struct flag_definition transaction_flags[] = {
#66 lore raw

Re: [PATCH v7 1/6] refs: atomically record overwritten ref in update_symref

Quoted 9 lines · Phillip Wood

Hi Bence

Quoted 2 lines · Bence Ferdinandy

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten.

It is if you use a ref transaction rather than call refs_update_symref() and query the ref after calling ref_transaction_prepare() and before calling ref_transaction_commit() which is what the code below does.

Yeah, it would be more clear if that sentence would say "when using update_symref".

Quoted 10 lines
Quoted 4 lines

Record the value after the
ref has been locked if the caller of refs_update_symref requests it via a new variable in the function call.

To me this patch and patch 5 feel quite disruptive to all the existing callers which don't need this specialized functionality. I think it would be less disruptive over all if you used a ref transaction rather than calling refs_update_symref() in the final patch. That would enable us to keep the simpler interface for refs_update_symref().

The extra parameter introduced here is actually used in two places by the end of the series, in remote set-head and fetch (of course you could make a similar argument for the functionality added in 5/6 which is only used in fetch by the final patch). To avoid code duplication I think even if we did not touch refs_update_symref() it would make sense to create
a "refs_update_symref_extended()" and make refs_update_symref() a wrapper around that with a few less parameters. That would be similar to how refs_update_symref() and refs_update_ref() predetermine a couple of parameters to say transaction_update().

Currently there are 15 calls to refs_update_symref() in total, of these 5 do not use the complete functionality of the function (they pass NULL as logmsg), so the current implementation would not be completely unprecedented. (This tally did make me catch an error on my side: the logmsg in fetch's set_head should be "fetch" not "remote set-head", I'll fix that in a v8).

Imho, even if I manage to come up with a better name than "refs_update_symref_extended()" wouldn't it be more confusing to have two ways to update symrefs via a function call, rather than have one, where _usually_ you pass two NULL-s at the end?

Quoted 5 lines

I'm also not sure about the proposed interface I would have thought it would be simpler to take a "char**" rather than an "struct strbuf*" if we do decide that it is useful for callers of refs_update_symref() to query the old value.

refs_read_symbolic_ref requires a strbuf, so one would need to be created anyway and I also sort of got the feeling that the project likes to handle refs in strbufs (which may be wrong). Are there any downsides I'm not seeing?

Thanks,
Bence

#67 lore raw

Re: [PATCH v7 1/6] refs: atomically record overwritten ref in update_symref

Hi Bence

Quoted 23 lines · Bence Ferdinandy
Quoted 10 lines · Phillip Wood
Quoted 3 lines · Bence Ferdinandy

Record the value after the
ref has been locked if the caller of refs_update_symref requests it via a new variable in the function call.

To me this patch and patch 5 feel quite disruptive to all the existing callers which don't need this specialized functionality. I think it would be less disruptive over all if you used a ref transaction rather than calling refs_update_symref() in the final patch. That would enable us to keep the simpler interface for refs_update_symref().

The extra parameter introduced here is actually used in two places by the end of the series, in remote set-head and fetch (of course you could make a similar argument for the functionality added in 5/6 which is only used in fetch by the final patch). To avoid code duplication I think even if we did not touch refs_update_symref() it would make sense to create
a "refs_update_symref_extended()" and make refs_update_symref() a wrapper around that with a few less parameters. That would be similar to how refs_update_symref() and refs_update_ref() predetermine a couple of parameters to say transaction_update().

Quoted 3 lines

Currently there are 15 calls to refs_update_symref() in total, of these 5 do not use the complete functionality of the function (they pass NULL as logmsg), so the current implementation would not be completely unprecedented.

As those figures show it's pretty unusual not to pass a reflog message when updating a ref, on the other hand it is very unusual to want the old value so I don't think the two are comparable. At a high level the two callers that want to be able to check the old value are both doing essentially the same thing so can we create a specialized function that encapsulates the functionality needed by --set-head and uses a ref transaction?

Quoted 9 lines

(This tally did make me catch an error on my side: the logmsg in fetch's set_head should be "fetch" not "remote set-head", I'll fix that in a v8).

Imho, even if I manage to come up with a better name than "refs_update_symref_extended()" wouldn't it be more confusing to have two ways to update symrefs via a function call, rather than have one, where _usually_ you pass two NULL-s at the end?

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

I'm also not sure about the proposed interface I would have thought it would be simpler to take a "char**" rather than an "struct strbuf*" if we do decide that it is useful for callers of refs_update_symref() to query the old value.

refs_read_symbolic_ref requires a strbuf, so one would need to be created anyway and I also sort of got the feeling that the project likes to handle refs in strbufs (which may be wrong). Are there any downsides I'm not seeing?

It's true that refs_read_symbolic_ref takes and strbuf. I'd argue that's a mistake for a function that is just returning a string in an "out" parameter as I think it is more continent for the caller not to have to initialize an strbuf just to retrieve the target of a symbolic ref. I alse think that it is inconsistent with functions like refs_resolve_refdup() that return a string.

Best Wishes

Phillip

#68 lore raw

Re: [PATCH v7 1/6] refs: atomically record overwritten ref in update_symref

Quoted 30 lines · Phillip Wood

Hi Bence

Quoted 23 lines · Bence Ferdinandy
Quoted 10 lines · Phillip Wood
Quoted 3 lines · Bence Ferdinandy

Record the value after the
ref has been locked if the caller of refs_update_symref requests it via a new variable in the function call.

To me this patch and patch 5 feel quite disruptive to all the existing callers which don't need this specialized functionality. I think it would be less disruptive over all if you used a ref transaction rather than calling refs_update_symref() in the final patch. That would enable us to keep the simpler interface for refs_update_symref().

The extra parameter introduced here is actually used in two places by the end of the series, in remote set-head and fetch (of course you could make a similar argument for the functionality added in 5/6 which is only used in fetch by the final patch). To avoid code duplication I think even if we did not touch refs_update_symref() it would make sense to create
a "refs_update_symref_extended()" and make refs_update_symref() a wrapper around that with a few less parameters. That would be similar to how refs_update_symref() and refs_update_ref() predetermine a couple of parameters to say transaction_update().

Quoted 3 lines

Currently there are 15 calls to refs_update_symref() in total, of these 5 do not use the complete functionality of the function (they pass NULL as logmsg), so the current implementation would not be completely unprecedented.

Quoted 7 lines

As those figures show it's pretty unusual not to pass a reflog message when updating a ref, on the other hand it is very unusual to want the old value so I don't think the two are comparable. At a high level the two callers that want to be able to check the old value are both doing essentially the same thing so can we create a specialized function that encapsulates the functionality needed by --set-head and uses a ref transaction?

Ok, so let's not change the signature of refs_update_symref(). On the other hand the best approach here is still not quite clear to me. As it is now, the series added two extra parameters to refs_update_symref(), the referent and the create_only option. Obviously any new function would also take all the parameters refs_update_symref takes. Should I rename the current (v8) refs_update_symref to something else (name suggestion would be welcome, refs_update_symref_extended?, refs_update_symref_check_current? checking the currently existing symref is the common theme for the two new parameters) and leave refs_update_symref as it is? Or is this really about just not having to change all the already existing callers? Because in that case I'd just wrap the new function, something like

int refs_update_symref(struct ref_store *refs, const char *ref,

		       const char *target, const char *logmsg)
	
	return refs_update_symref_extended(*refs, *ref, *target, *logmsg, NULL, 0);

Let me know what you think, I'll hold off on a v9 until I see more clearly here on what would be preferred.

Quoted 19 lines
Quoted 10 lines

(This tally did make me catch an error on my side: the logmsg in fetch's set_head should be "fetch" not "remote set-head", I'll fix that in a v8).

Imho, even if I manage to come up with a better name than "refs_update_symref_extended()" wouldn't it be more confusing to have two ways to update symrefs via a function call, rather than have one, where _usually_ you pass two NULL-s at the end?

Quoted 1 line
Quoted 8 lines
Quoted 4 lines

I'm also not sure about the proposed interface I would have thought it would be simpler to take a "char**" rather than an "struct strbuf*" if we do decide that it is useful for callers of refs_update_symref() to query the old value.

refs_read_symbolic_ref requires a strbuf, so one would need to be created anyway and I also sort of got the feeling that the project likes to handle refs in strbufs (which may be wrong). Are there any downsides I'm not seeing?

Quoted 6 lines

It's true that refs_read_symbolic_ref takes and strbuf. I'd argue that's a mistake for a function that is just returning a string in an "out" parameter as I think it is more continent for the caller not to have to initialize an strbuf just to retrieve the target of a symbolic ref. I alse think that it is inconsistent with functions like refs_resolve_refdup() that return a string.

Ok, I'll change this to use **char. On the other hand, if refs_read_symbolic_ref is inconsistent would it make sense to change it to also use a **char instead of strbuf? There's only four calls to it including the one I just added. Although I might rather do that _after_ this series is resolved :)

Thanks (to everyone) for your time!

Best,
Bence

Signature · 1 line
bence.ferdinandy.com
#69 lore raw

Re: [PATCH v7 1/6] refs: atomically record overwritten ref in update_symref

Quoted 2 lines · Bence Ferdinandy

On Tue Oct 15, 2024 at 16:05, Phillip Wood <[email protected]> wrote:

[snip]

Quoted 17 lines
Quoted 10 lines
Quoted 9 lines
Quoted 5 lines

I'm also not sure about the proposed interface I would have thought it would be simpler to take a "char**" rather than an "struct strbuf*" if we do decide that it is useful for callers of refs_update_symref() to query the old value.

refs_read_symbolic_ref requires a strbuf, so one would need to be created anyway and I also sort of got the feeling that the project likes to handle refs in strbufs (which may be wrong). Are there any downsides I'm not seeing?

Quoted 6 lines

It's true that refs_read_symbolic_ref takes and strbuf. I'd argue that's a mistake for a function that is just returning a string in an "out" parameter as I think it is more continent for the caller not to have to initialize an strbuf just to retrieve the target of a symbolic ref. I alse think that it is inconsistent with functions like refs_resolve_refdup() that return a string.

Quoted 4 lines

Ok, I'll change this to use **char. On the other hand, if refs_read_symbolic_ref is inconsistent would it make sense to change it to also use a **char instead of strbuf? There's only four calls to it including the one I just added. Although I might rather do that _after_ this series is resolved :)

I started doing this change, but ran into two things which I would yet again, bring up in defence of strbuf. So not only refs_read_symbolic_ref makes use of strbuf, but

a) I also use it in refs_update_symref[_extended] to check if the caller actually wants that referent or not (passing a NULL or a strbuf).
b) the consumer, report_set_head_auto check for !buf->len

Both of these sound way more convenient with strbuf than with *char. Ofc I'm not exactly a C guru so ... Anyhow, v9 does not have this change.

Best,
Bence

#70 lore raw

v8 cover set-head/fetch remote/HEAD updates, small change from v7

In reply to Bence Ferdinandy

v8 is minor non-functional fix from v7

❯ git range-diff v7~6..v7 v8~6..v8

1:  e4a2d01bca = 1:  e4a2d01bca refs: atomically record overwritten ref in update_symref
2:  e6c40ef04c = 2:  e6c40ef04c remote set-head: add new variable for readability
3:  aefa49aa0d = 3:  aefa49aa0d remote set-head: better output for --auto
4:  ad8907c6a3 = 4:  ad8907c6a3 refs: add TRANSACTION_CREATE_EXISTS error
5:  ff616d8b77 = 5:  ff616d8b77 refs: add create_only option to refs_update_symref
6:  35b93f454c ! 6:  7b844b1dbb fetch: set remote/HEAD if it does not exist

@@ Notes

v7: - no change

+ v8: - changed logmsg in call to refs_update_symref from "remote
+ set-head" to "fetch"
+
## builtin/fetch.c ##
@@ builtin/fetch.c: static int backfill_tags(struct display_state *display_state,
return retcode;
@@ builtin/fetch.c: static int backfill_tags(struct display_state *display_state,
+ if (!refs_ref_exists(refs, b_remote_head.buf))
+ result = 1;
+ else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
-+ "remote set-head", &b_local_head, 1))
++ "fetch", &b_local_head, 1))
+ result = 1;
+ else
+ report_set_head(remote, head_name, &b_local_head);

Bence Ferdinandy (6):
refs: atomically record overwritten ref in update_symref remote set-head: add new variable for readability remote set-head: better output for --auto
refs: add TRANSACTION_CREATE_EXISTS error
refs: add create_only option to refs_update_symref
fetch: set remote/HEAD if it does not exist

 builtin/branch.c                 |   2 +-
 builtin/checkout.c               |   5 +-
 builtin/clone.c                  |   8 +-
 builtin/fetch.c                  |  82 +++++++++++
 builtin/notes.c                  |   3 +-
 builtin/remote.c                 |  47 +++++--
 builtin/symbolic-ref.c           |   2 +-
 builtin/worktree.c               |   2 +-
 refs.c                           |  38 +++--
 refs.h                           |   7 +-
 refs/files-backend.c             |  24 ++--
 refs/reftable-backend.c          |   6 +-
 reset.c                          |   2 +-
 sequencer.c                      |   3 +-
 setup.c                          |   3 +-
 t/helper/test-ref-store.c        |   2 +-
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  62 ++++++++-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 27 files changed, 469 insertions(+), 165 deletions(-)
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#71 lore raw

PATCH v8 1/6 refs: atomically record overwritten ref in update_symref

When updating a symref it's currently not possible to know for sure what was the previous value that was overwritten. Record the value after the ref has been locked if the caller of refs_update_symref requests it via a new variable in the function call.

---

Notes:
v4: new patch

v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

v6: - no change

v7: - remove the whole before_target concept from the backends and
handle checking it in refs.c instead (thanks Karthik)
- rename the before_target to referent which is how the same concept is called in the backends
- change commit prefix to be more in line with project standards

v8: no change

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  4 ++--
 builtin/clone.c           |  6 +++---
 builtin/notes.c           |  2 +-
 builtin/remote.c          |  6 +++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 16 +++++++++++-----
 refs.h                    |  3 ++-
 reset.c                   |  2 +-
 sequencer.c               |  2 +-
 setup.c                   |  2 +-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 29 insertions(+), 22 deletions(-)
builtin/branch.c +1 -1
index fd1611ebf5..6c87690b58 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +2 -2
index 9c30000d3a..356ee9bcde 100644
@@ -1015,7 +1015,7 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1479,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b");
+				    "HEAD", branch_ref.buf, "checkout -b", NULL);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +3 -3
index e77339c847..ead2af20ea 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg) < 0)
+				       msg, NULL) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +702,7 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +1 -1
index 8c26e45526..ba646f06ff 100644
@@ -980,7 +980,7 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +3 -3
index 76670ddd8b..d8ff440027 100644
@@ -244,7 +244,7 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add"))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +864,7 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1444,7 +1444,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
+		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
builtin/symbolic-ref.c +1 -1
index 299d23d76a..7728fbc3c1 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg);
+					   argv[0], argv[1], msg, NULL);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index fc31d072a6..a7ab4193c1 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
 	if (ret)
 		goto done;
 
refs.c +11 -5
index 5f729ed412..b964ac44d0 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2122,17 +2123,23 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
+		ref_transaction_update(transaction, ref, NULL, NULL,
 				   target, NULL, REF_NO_DEREF,
 				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);
+
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
 
+cleanup:
 	strbuf_release(&err);
 	if (transaction)
 		ref_transaction_free(transaction);
-
 	return ret;
 }
 
@@ -2948,4 +2955,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +2 -1
index 108dfc93b3..b09a3a4384 100644
@@ -571,7 +571,8 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg);
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
-		       const char *target, const char *logmsg);
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index b22b1be792..cc36a9ed56 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head);
+						 reflog_head, NULL);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +1 -1
index 8d01cd50ac..23b162924c 100644
@@ -5107,7 +5107,7 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +1 -1
index 94e79b2e48..d95f051465 100644
@@ -2275,7 +2275,7 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index 65346dee55..a911302bea 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg);
+	return refs_update_symref(refs, refname, target, logmsg, NULL);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#72 lore raw

Re: [PATCH v8 1/6] refs: atomically record overwritten ref in update_symref

Bence Ferdinandy <[email protected]> writes:

[snip]

Quoted 19 lines
refs.c +2 -2
index 5f729ed412..b964ac44d0 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2122,17 +2123,23 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,

refs.c int refs_update_symref(struct ref_store *refs, const char *ref, · line 2134

Quoted 10 lines
refs.c +5 -1
+		ref_transaction_update(transaction, ref, NULL, NULL,
 				   target, NULL, REF_NO_DEREF,
 				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);

Shouldn't we also check the return value here?

refs.c int refs_update_symref(struct ref_store *refs, const char *ref, · line 2145

Quoted 10 lines
refs.c +4 -1
+
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
 
+cleanup:
 	strbuf_release(&err);
 	if (transaction)
 		ref_transaction_free(transaction);
-
 

Why remove this whiteline?

Quoted 3 lines
refs.c +0 -0
 	return ret;
 }

[snip]

#73 lore raw

Re: [PATCH v8 1/6] refs: atomically record overwritten ref in update_symref

Quoted 20 lines · karthik nayak

Bence Ferdinandy <[email protected]> writes:

[snip]

Quoted 16 lines
refs.c +2 -1
index 5f729ed412..b964ac44d0 100644
@@ -2114,7 +2114,8 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 }
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
-		       const char *target, const char *logmsg)
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2122,17 +2123,23 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
Quoted 15 lines

refs.c int refs_update_symref(struct ref_store *refs, const char *ref, · line 2134

Quoted 13 lines
refs.c +5 -2
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
+		ref_transaction_update(transaction, ref, NULL, NULL,
 				   target, NULL, REF_NO_DEREF,
 				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);

Shouldn't we also check the return value here?

My reasoning was that if this fails referent will just look like as if it did not exist. Since this is an addition to set-head and fetch failing to set the HEAD in a case which would have previously worked I did not think it prudent to now fail on this for any reason.

Quoted 5 lines
Quoted 5 lines
refs.c +3 -0
+
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
 
Quoted 8 lines

refs.c int refs_update_symref(struct ref_store *refs, const char *ref, · line 2145

Quoted 6 lines
refs.c +1 -1
+cleanup:
 	strbuf_release(&err);
 	if (transaction)
 		ref_transaction_free(transaction);
-
 

Why remove this whiteline?

Looks like a mistake made during rebase.

Signature · 1 line
bence.ferdinandy.com
#74 lore raw

PATCH v8 2/6 remote set-head: add new variable for readability

In reply to Bence Ferdinandy

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable for better readability.

---

Notes:
v5: new patch (split from the next patch as a preparatory step)

v6: no change

v7: - change commit prefix to be more in line with project standards

v8: no change

 builtin/remote.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
builtin/remote.c +4 -3
index d8ff440027..353ffd2c43 100644
@@ -1404,6 +1404,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	int i, opt_a = 0, opt_d = 0, result = 0;
 	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1434,7 +1435,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
+		if (refs_delete_ref(refs, NULL, buf.buf, NULL, REF_NO_DEREF))
 			result |= error(_("Could not delete %s"), buf.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
@@ -1442,9 +1443,9 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	if (head_name) {
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
+		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#75 lore raw

PATCH v8 3/6 remote set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates. As a fourth output, if HEAD is changed from a previous value that was not a remote branch, explicitly call attention to this fact.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

v5: - the minor refactor has been split out into its own patch

v6: - fixed uninitialized prev_head
- fixed case of unusual previous target
- fixed a test that would have been actually broken at this patch (the output was only correct with the later update to fetch)
- added 4 tests for the 4 output cases

v7: - change commit prefix to be more in line with project standards
- fixed tests to also work with the reftable backend
- renamed report function, fixed style issue with checking buf len
- fixed not releasing an strbuf

v8: no change

 builtin/remote.c  | 35 ++++++++++++++++++++++++++++----
 t/t5505-remote.sh | 51 ++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 81 insertions(+), 5 deletions(-)
builtin/remote.c +31 -4
index 353ffd2c43..2b6948439f 100644
@@ -1399,10 +1399,35 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_set_head_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else if (!buf_prev->len)
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+	else
+		printf("'%s/HEAD' used to point to '%s' "
+			"(which is not a remote branch), but now points to '%s'\n",
+			remote, buf_prev->buf, head_name);
+	strbuf_release(&buf_prefix);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1470,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", NULL))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
 			result |= error(_("Could not setup %s"), buf.buf);
-		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+		else if (opt_a) {
+			report_set_head_auto(argv[0], head_name, &buf_prev);
+		}
 		free(head_name);
 	}
 
 	strbuf_release(&buf);
 	strbuf_release(&buf2);
+	strbuf_release(&buf_prev);
 	return result;
 }
 
t/t5505-remote.sh +50 -1

68 lines not on this page · raw message

Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#76 lore raw

Re: [PATCH v8 3/6] remote set-head: better output for --auto

Bence Ferdinandy <[email protected]> writes:

[snip]

Quoted 14 lines
builtin/remote.c +14 -0
+static void report_set_head_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1425

Quoted 10 lines
builtin/remote.c +10 -0
+	else if (!buf_prev->len)
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+	else
+		printf("'%s/HEAD' used to point to '%s' "
+			"(which is not a remote branch), but now points to '%s'\n",
+			remote, buf_prev->buf, head_name);
+	strbuf_release(&buf_prefix);
+}
+

Shouldn't the messages above be marked for translation too? using _()?

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1430

Quoted 6 lines

static int set_head(int argc, const char **argv, const char *prefix) {

builtin/remote.c +2 -1
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;

Nit: these names could definitely be better.

[snip]

#77 lore raw

Re: [PATCH v8 3/6] remote set-head: better output for --auto

Quoted 22 lines · karthik nayak

Bence Ferdinandy <[email protected]> writes:

[snip]

Quoted 18 lines
builtin/remote.c +18 -0
+static void report_set_head_auto(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf("'%s/HEAD' is unchanged and points to '%s'\n",
+			remote, head_name);
+	else if (prev_head)
+		printf("'%s/HEAD' has changed from '%s' and now points to '%s'\n",
+			remote, prev_head, head_name);
+	else if (!buf_prev->len)
+		printf("'%s/HEAD' is now created and points to '%s'\n",
+			remote, head_name);
+	else
Quoted 8 lines

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1425

Quoted 6 lines
builtin/remote.c +6 -0
+		printf("'%s/HEAD' used to point to '%s' "
+			"(which is not a remote branch), but now points to '%s'\n",
+			remote, buf_prev->buf, head_name);
+	strbuf_release(&buf_prefix);
+}
+

Shouldn't the messages above be marked for translation too? using _()?

I guess it is unlikely to fall under the "should be machine readable" category. I'll fix that up as well.

Quoted 9 lines

builtin/remote.c static int show(int argc, const char **argv, const char *prefix) · line 1430

Quoted 7 lines

static int set_head(int argc, const char **argv, const char *prefix) {

builtin/remote.c +2 -1
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT,
+		buf_prev = STRBUF_INIT;

Nit: these names could definitely be better.

Indeed ... The second patch is a refactor of remote set-head, I could include a variable rename refactor there as well, and use the same names I used in the last patch when adding the similar calls to fetch's set_head.

#78 lore raw

PATCH v8 4/6 refs: add TRANSACTION_CREATE_EXISTS error

In reply to Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch
v5: no change
v6: no change

v7: - change commit prefix to be more in line with project standards
- changed error checking to Karthik's suggestion

v8: no change

 refs.h                  |  4 +++-
 refs/files-backend.c    | 24 ++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 23 insertions(+), 11 deletions(-)
refs.h +3 -1
index b09a3a4384..c83b1ec76e 100644
@@ -759,8 +759,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +16 -8
index 0824c0b8a9..e743ec44b5 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2602,9 +2606,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				ret = check_old_oid(update, &lock->old_oid, err);
+				if  (ret) {
+					goto out;
+				}
 			}
 		} else {
 			/*
@@ -2635,9 +2641,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			ret = check_old_oid(update, &lock->old_oid, err);
+			if  (ret) {
+				goto out;
+			}
 		}
 
 		/*
refs/reftable-backend.c +4 -2
index 3c96fbf66f..ebf8e57fbc 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}
 
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#79 lore raw

PATCH v8 5/6 refs: add create_only option to refs_update_symref

In reply to Bence Ferdinandy

Allow the caller to specify that it only wants to update the symref if it does not already exist. Silently ignore the error from the transaction API if the symref already exists.

---

Notes:
v4: new patch
v5: no change

v6: - switched from bool to int for create_only
- refactored logic in refs_update_symref with goto as layed out by Junio

v7: - change commit prefix to be more in line with project standards
- refactored code to accommodate changes in the first patch, but otherwise no change

v8: no change

 builtin/branch.c          |  2 +-
 builtin/checkout.c        |  5 +++--
 builtin/clone.c           |  8 +++++---
 builtin/notes.c           |  3 ++-
 builtin/remote.c          |  9 ++++++---
 builtin/symbolic-ref.c    |  2 +-
 builtin/worktree.c        |  2 +-
 refs.c                    | 30 ++++++++++++++++++++++--------
 refs.h                    |  2 +-
 reset.c                   |  2 +-
 sequencer.c               |  3 ++-
 setup.c                   |  3 ++-
 t/helper/test-ref-store.c |  2 +-
 13 files changed, 48 insertions(+), 25 deletions(-)
builtin/branch.c +1 -1
index 6c87690b58..2fcbcbfd59 100644
@@ -559,7 +559,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 			continue;
 
 		refs = get_worktree_ref_store(worktrees[i]);
-		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL))
+		if (refs_update_symref(refs, "HEAD", newref, logmsg, NULL, 0))
 			ret = error(_("HEAD of working tree %s is not updated"),
 				    worktrees[i]->path);
 	}
builtin/checkout.c +3 -2
index 356ee9bcde..9abb71dc07 100644
@@ -1015,7 +1015,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 			describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
 		}
 	} else if (new_branch_info->path) {	/* Switch branches. */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path,
+					msg.buf, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!opts->quiet) {
 			if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
@@ -1479,7 +1480,7 @@ static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
 		die(_("You are on a branch yet to be born"));
 	strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
 	status = refs_update_symref(get_main_ref_store(the_repository),
-				    "HEAD", branch_ref.buf, "checkout -b", NULL);
+				    "HEAD", branch_ref.buf, "checkout -b", NULL, 0);
 	strbuf_release(&branch_ref);
 	if (!opts->quiet)
 		fprintf(stderr, _("Switched to a new branch '%s'\n"),
builtin/clone.c +5 -3
index ead2af20ea..87e8f1421a 100644
@@ -661,7 +661,7 @@ static void update_remote_refs(const struct ref *refs,
 		strbuf_addstr(&head_ref, "HEAD");
 		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
 				       remote_head_points_at->peer_ref->name,
-				       msg, NULL) < 0)
+				       msg, NULL, 0) < 0)
 			die(_("unable to update %s"), head_ref.buf);
 		strbuf_release(&head_ref);
 	}
@@ -673,7 +673,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 	const char *head;
 	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 		/* Local default branch link */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name,
+					NULL, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare) {
 			refs_update_ref(get_main_ref_store(the_repository),
@@ -702,7 +703,8 @@ static void update_head(const struct ref *our, const struct ref *remote,
 		 * Unborn head from remote; same as "our" case above except
 		 * that we have no ref to update.
 		 */
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn,
+					NULL, NULL, 0) < 0)
 			die(_("unable to update HEAD"));
 		if (!option_bare)
 			install_branch_config(0, head, remote_name, unborn);
builtin/notes.c +2 -1
index ba646f06ff..7b3138e3c3 100644
@@ -980,7 +980,8 @@ static int merge(int argc, const char **argv, const char *prefix)
 			die(_("a notes merge into %s is already in-progress at %s"),
 			    notes_ref, wt->path);
 		free_worktrees(worktrees);
-		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref, NULL, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), "NOTES_MERGE_REF", notes_ref,
+					NULL, NULL, 0))
 			die(_("failed to store link to current notes ref (%s)"),
 			    notes_ref);
 		fprintf(stderr, _("Automatic notes merge failed. Fix conflicts in %s "
builtin/remote.c +6 -3
index 2b6948439f..d60ec6e907 100644
@@ -244,7 +244,8 @@ static int add(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf2);
 		strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote add", NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					"remote add", NULL, 0))
 			result = error(_("Could not setup master '%s'"), master);
 	}
 
@@ -864,7 +865,8 @@ static int mv(int argc, const char **argv, const char *prefix)
 		strbuf_reset(&buf3);
 		strbuf_addf(&buf3, "remote: renamed %s to %s",
 				item->string, buf.buf);
-		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, buf3.buf, NULL))
+		if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf,
+					buf3.buf, NULL, 0))
 			die(_("creating '%s' failed"), buf.buf);
 		display_progress(progress, ++refs_renamed_nr);
 	}
@@ -1470,7 +1472,8 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, buf2.buf))
 			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(refs, buf.buf, buf2.buf, "remote set-head", &buf_prev))
+		else if (refs_update_symref(refs, buf.buf, buf2.buf,
+					"remote set-head", &buf_prev, 0))
 			result |= error(_("Could not setup %s"), buf.buf);
 		else if (opt_a) {
 			report_set_head_auto(argv[0], head_name, &buf_prev);
builtin/symbolic-ref.c +1 -1
index 7728fbc3c1..cfbb53b30c 100644
@@ -88,7 +88,7 @@ int cmd_symbolic_ref(int argc,
 		if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
 			die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
 		ret = !!refs_update_symref(get_main_ref_store(the_repository),
-					   argv[0], argv[1], msg, NULL);
+					   argv[0], argv[1], msg, NULL, 0);
 		break;
 	default:
 		usage_with_options(git_symbolic_ref_usage, options);
builtin/worktree.c +1 -1
index a7ab4193c1..2e95367235 100644
@@ -517,7 +517,7 @@ static int add_worktree(const char *path, const char *refname,
 		ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
 				      NULL, 0, UPDATE_REFS_MSG_ON_ERR);
 	else
-		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL);
+		ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL, NULL, 0);
 	if (ret)
 		goto done;
 
refs.c +22 -8
index b964ac44d0..29c020e78e 100644
@@ -2115,26 +2115,40 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *referent)
+		       struct strbuf *referent, int create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
-	int ret = 0;
+	int ret = 0, prepret = 0;
 
 	transaction = ref_store_transaction_begin(refs, &err);
-	if (!transaction ||
-		ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
-				   logmsg, &err) ||
-		ref_transaction_prepare(transaction, &err)) {
+	if (!transaction) {
+	error_return:
 		ret = error("%s", err.buf);
 		goto cleanup;
 	}
+	if (create_only) {
+		if (ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err))
+			goto error_return;
+		prepret = ref_transaction_prepare(transaction, &err);
+		if (prepret && prepret != TRANSACTION_CREATE_EXISTS)
+			goto error_return;
+	} else {
+		if (ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+			ref_transaction_prepare(transaction, &err))
+			goto error_return;
+	}
+
 	if (referent)
 		refs_read_symbolic_ref(refs, ref, referent);
 
+	if (prepret == TRANSACTION_CREATE_EXISTS)
+		goto cleanup;
 	if (ref_transaction_commit(transaction, &err))
-		ret = error("%s", err.buf);
+		goto error_return;
 
 cleanup:
 	strbuf_release(&err);
refs.h +1 -1
index c83b1ec76e..41ae384f11 100644
@@ -572,7 +572,7 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg,
-		       struct strbuf *referent);
+		       struct strbuf *referent, int create_only);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
reset.c +1 -1
index cc36a9ed56..919fb84f5f 100644
@@ -76,7 +76,7 @@ static int update_refs(const struct reset_head_opts *opts,
 		if (!ret)
 			ret = refs_update_symref(get_main_ref_store(the_repository),
 						 "HEAD", switch_to_branch,
-						 reflog_head, NULL);
+						 reflog_head, NULL, 0);
 	}
 	if (!ret && run_hook)
 		run_hooks_l(the_repository, "post-checkout",
sequencer.c +2 -1
index 23b162924c..103d0ddfb2 100644
@@ -5107,7 +5107,8 @@ static int pick_commits(struct repository *r,
 			}
 			msg = reflog_message(opts, "finish", "returning to %s",
 				head_ref.buf);
-			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg, NULL)) {
+			if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf,
+						msg, NULL, 0)) {
 				res = error(_("could not update HEAD to %s"),
 					head_ref.buf);
 				goto cleanup_head_ref;
setup.c +2 -1
index d95f051465..9bbc655ee4 100644
@@ -2275,7 +2275,8 @@ void create_reference_database(enum ref_storage_format ref_storage_format,
 			die(_("invalid initial branch name: '%s'"),
 			    initial_branch);
 
-		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL, NULL) < 0)
+		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref,
+					NULL, NULL, 0) < 0)
 			exit(1);
 		free(ref);
 	}
t/helper/test-ref-store.c +1 -1
index a911302bea..f72b029e51 100644
@@ -120,7 +120,7 @@ static int cmd_create_symref(struct ref_store *refs, const char **argv)
 	const char *target = notnull(*argv++, "target");
 	const char *logmsg = *argv++;
 
-	return refs_update_symref(refs, refname, target, logmsg, NULL);
+	return refs_update_symref(refs, refname, target, logmsg, NULL, 0);
 }
 
 static struct flag_definition transaction_flags[] = {
Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#80 lore raw

PATCH v8 6/6 fetch: set remote/HEAD if it does not exist

In reply to Bence Ferdinandy

If the user has remote/HEAD set already and it looks like it has changed on the server, then print a message, otherwise set it if we can. Silently pass if the user already has the same remote/HEAD set as reported by the server or if we encounter any errors along the way.

---

Notes:
v3: - does not rely on remote set-head anymore so it only authenticates
once
- uses the new REF_CREATE_ONLY to atomically check if the ref exists and only write it if it doesn't
- in all other cases the maximum it does is print a warning

v4: - instead of the discarded REF_CREATE_ONLY, it uses the existing,
but updated transaction api to request a silent create only
- it now uses the atomic before_target to determine reporting
- refactored for legibility

v5: - instead of printing a not too useful message, it now fails
silently, this in line with the objective to only set up remote/HEAD automatically if the right thing is trivial, for everything else there is remote set-head
- fixed all failing tests
- added two new tests, one for checking if remote/HEAD is set to the correct one, and one to test that we do not override remote/HEAD if it has changed on the server from what we have locally

v6: - fixed style issues and unintended extra empty line
- updated function call with bool to int from previous patch's change
- removed calls to error(...) inherited from builtin/remote.c so we actually fail silently
- set the test for remote set-head --auto to the correct value here, which was previously erronously set in the remote set-head patch

v7: - no change

v8: - changed logmsg in call to refs_update_symref from "remote
set-head" to "fetch"

 builtin/fetch.c                  |  82 +++++++++++
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  13 +-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 12 files changed, 308 insertions(+), 123 deletions(-)
builtin/fetch.c +82 -0
index 80a64d0d26..88ebca8294 100644
@@ -1578,6 +1578,80 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && strcmp(prev_head, head_name)) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}
+}
+
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1)
+		result = 1;
+	else
+		head_name = xstrdup(heads.items[0].string);
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result = 1;
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf,
+					"fetch", &b_local_head, 1))
+			result = 1;
+		else
+			report_set_head(remote, head_name, &b_local_head);
+
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)
@@ -1647,6 +1721,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
+
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1791,6 +1867,12 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		;
+		/*
+		 * Way too many cases where this can go wrong
+		 * so let's just fail silently for now.
+		 */
 
 cleanup:
 	if (retcode) {
t/t4207-log-decoration-colors.sh +2 -1
index 73ea9e5155..d55d22cb2f 100755
@@ -59,7 +59,8 @@ ${c_reset}${c_tag}tag: ${c_reset}${c_tag}v1.0${c_reset}${c_commit}, \
 ${c_reset}${c_tag}tag: ${c_reset}${c_tag}B${c_reset}${c_commit})${c_reset} B
 ${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_tag}tag: ${c_reset}${c_tag}A1${c_reset}${c_commit}, \
-${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit})${c_reset} A1
+${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit}, \
+${c_reset}${c_remoteBranch}other/HEAD${c_reset}${c_commit})${c_reset} A1
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_stash}refs/stash${c_reset}${c_commit})${c_reset} On main: Changes to A.t
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
t/t5505-remote.sh +8 -5
index d99cd1d0aa..cb45f22232 100755
@@ -71,7 +71,7 @@ test_expect_success 'add another remote' '
 		cd test &&
 		git remote add -f second ../two &&
 		tokens_match "origin second" "$(git remote)" &&
-		check_tracking_branch second main side another &&
+		check_tracking_branch second main side another HEAD &&
 		git for-each-ref "--format=%(refname)" refs/remotes |
 		sed -e "/^refs\/remotes\/origin\//d" \
 		    -e "/^refs\/remotes\/second\//d" >actual &&
@@ -473,7 +473,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "'\''two/HEAD'\'' is now created and points to '\''main'\''" >expect &&
+		echo "'\''two/HEAD'\'' is unchanged and points to '\''main'\''" >expect &&
 		test_cmp expect output
 	)
 '
@@ -763,6 +763,7 @@ test_expect_success 'reject --no-no-tags' '
 cat >one/expect <<\EOF
   apis/main
   apis/side
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -780,6 +781,7 @@ test_expect_success 'update' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -792,7 +794,7 @@ EOF
 test_expect_success 'update with arguments' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -835,7 +837,7 @@ EOF
 test_expect_success 'update default' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -847,6 +849,7 @@ test_expect_success 'update default' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -869,7 +872,7 @@ test_expect_success 'update default (overridden, with funny whitespace)' '
 test_expect_success 'update (with remotes.default defined)' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
t/t5510-fetch.sh +122 -107

356 lines not on this page · raw message

t/t5512-ls-remote.sh +2 -0
index 64b3491e4e..1b3865e154 100755
@@ -293,6 +293,8 @@ test_expect_success 'ls-remote with filtered symref (refname)' '
 	cat >expect <<-EOF &&
 	ref: refs/heads/main	HEAD
 	$rev	HEAD
+	ref: refs/remotes/origin/main	refs/remotes/origin/HEAD
+	$rev	refs/remotes/origin/HEAD
 	EOF
 	git ls-remote --symref . HEAD >actual &&
 	test_cmp expect actual
t/t5514-fetch-multiple.sh +15 -2
index 579872c258..e3482b27b2 100755
@@ -45,14 +45,17 @@ test_expect_success setup '
 '
 
 cat > test/expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -97,6 +100,7 @@ cat > expect << EOF
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
@@ -112,8 +116,10 @@ test_expect_success 'git fetch --multiple (but only one remote)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -141,7 +147,7 @@ test_expect_success 'git fetch --multiple (bad remote names)' '
 
 test_expect_success 'git fetch --all (skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -153,11 +159,14 @@ test_expect_success 'git fetch --all (skipFetchAll)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -165,7 +174,7 @@ EOF
 
 test_expect_success 'git fetch --multiple (ignoring skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -221,14 +230,17 @@ test_expect_success 'git fetch --multiple --jobs=0 picks a default' '
 
 create_fetch_all_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
 	  origin/main
 	  origin/side
+	  three/HEAD -> three/main
 	  three/another
 	  three/main
 	  three/side
+	  two/HEAD -> two/main
 	  two/another
 	  two/main
 	  two/side
@@ -265,6 +277,7 @@ test_expect_success 'git fetch (fetch all remotes with fetch.all = true)' '
 
 create_fetch_one_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
t/t5516-fetch-push.sh +2 -1
index 331778bd42..5a051aa0c7 100755
@@ -1395,7 +1395,8 @@ test_expect_success 'fetch follows tags by default' '
 		git tag -m "annotated" tag &&
 		git for-each-ref >tmp1 &&
 		sed -n "p; s|refs/heads/main$|refs/remotes/origin/main|p" tmp1 |
-		sort -k 3 >../expect
+		sed -n "p; s|refs/heads/main$|refs/remotes/origin/HEAD|p"  |
+		sort -k 4 >../expect
 	) &&
 	test_when_finished "rm -rf dst" &&
 	git init dst &&
t/t5527-fetch-odd-refs.sh +2 -1
index 98ece27c6a..d3996af6ee 100755
@@ -52,7 +52,8 @@ test_expect_success LONG_REF 'fetch handles extremely long refname' '
 	long
 	main
 	EOF
-	git for-each-ref --format="%(subject)" refs/remotes/long >actual &&
+	git for-each-ref --format="%(subject)" refs/remotes/long \
+		--exclude=refs/remotes/long/HEAD >actual &&
 	test_cmp expect actual
 '
 
t/t7900-maintenance.sh +2 -1
index a66d0e089d..88331d1ceb 100755
@@ -329,7 +329,8 @@ test_expect_success 'incremental-repack task' '
 
 	# Delete refs that have not been repacked in these packs.
 	git for-each-ref --format="delete %(refname)" \
-		refs/prefetch refs/tags refs/remotes >refs &&
+		refs/prefetch refs/tags refs/remotes \
+		--exclude=refs/remotes/*/HEAD >refs &&
 	git update-ref --stdin <refs &&
 
 	# Replace the object directory with this pack layout.
t/t9210-scalar.sh +3 -2
index 027235d61a..a81662713e 100755
@@ -150,7 +150,8 @@ test_expect_success 'scalar clone' '
 			"$(pwd)" &&
 
 		git for-each-ref --format="%(refname)" refs/remotes/origin/ >actual &&
-		echo "refs/remotes/origin/parallel" >expect &&
+		echo "refs/remotes/origin/HEAD" >>expect &&
+		echo "refs/remotes/origin/parallel" >>expect &&
 		test_cmp expect actual &&
 
 		test_path_is_missing 1/2 &&
@@ -219,7 +220,7 @@ test_expect_success 'scalar reconfigure --all with includeIf.onbranch' '
 	done
 '
 
- test_expect_success 'scalar reconfigure --all with detached HEADs' '
+test_expect_success 'scalar reconfigure --all with detached HEADs' '
 	repos="two three four" &&
 	for num in $repos
 	do
t/t9211-scalar-clone.sh +3 -3
index 7869f45ee6..01f71910f5 100755
@@ -31,7 +31,7 @@ test_expect_success 'set up repository to clone' '
 	)
 '
 
-cleanup_clone () {
+cleanup_clone() {
 	rm -rf "$1"
 }
 
@@ -127,7 +127,7 @@ test_expect_success '--single-branch clones HEAD only' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 1 out &&
+		test_line_count = 2 out &&
 		grep "refs/remotes/origin/base" out
 	) &&
 
@@ -141,7 +141,7 @@ test_expect_success '--no-single-branch clones all branches' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 2 out &&
+		test_line_count = 3 out &&
 		grep "refs/remotes/origin/base" out &&
 		grep "refs/remotes/origin/parallel" out
 	) &&
t/t9902-completion.sh +65 -0

443 lines not on this page · raw message

Signature · 1 line
2.47.0.7.g072c39eddb.dirty
#81 lore raw

Re: [PATCH v8 0/6] set-head/fetch remote/HEAD updates, small change from v7

In reply to Bence Ferdinandy
Quoted 7 lines · Bence Ferdinandy

Bence Ferdinandy (6):
refs: atomically record overwritten ref in update_symref remote set-head: add new variable for readability remote set-head: better output for --auto
refs: add TRANSACTION_CREATE_EXISTS error
refs: add create_only option to refs_update_symref
fetch: set remote/HEAD if it does not exist

I integrated this new round into my copy of 'seen' today and noticed some test breakage in t5505 here:

    https://github.com/ttaylorr/git/actions/runs/11356267070

I'm going to temporarily eject this topic out of 'seen' until we can get an analysis of what's going on here.

Thanks,
Taylor

#82 lore raw

Re: [PATCH v8 0/6] set-head/fetch remote/HEAD updates, small change from v7

Quoted 9 lines · Taylor Blau
Quoted 7 lines · Bence Ferdinandy

Bence Ferdinandy (6):
refs: atomically record overwritten ref in update_symref remote set-head: add new variable for readability remote set-head: better output for --auto
refs: add TRANSACTION_CREATE_EXISTS error
refs: add create_only option to refs_update_symref
fetch: set remote/HEAD if it does not exist

Quoted 7 lines

I integrated this new round into my copy of 'seen' today and noticed some test breakage in t5505 here:

    https://github.com/ttaylorr/git/actions/runs/11356267070

I'm going to temporarily eject this topic out of 'seen' until we can get an analysis of what's going on here.

Thanks for the heads up! I see that indeed the failing output is different than what I have locally (e.g. no "apis/HEAD -> apis/main" in any of the test files I have). On the other hand I can't reproduce it so I will need some help with this I think.

I tested with both a rebase on master and a rebase on your seen branch. I'm using these to commands in t/ to run tests:

prove --timer --jobs 15 ./t[0-9]*.sh GIT_TEST_DEFAULT_REF_FORMAT=reftable prove --timer --jobs 15 ./t[0-9]*.sh

Everything passes. Should I be running this differently? I'm assuming the test do not use any global or local git config I may have?

I'm testing on Ubuntu 22.04 natively and in WSL, but the nature of the error doesn't seem like it could or should be related to the OS.

Thanks,
Bence

#83 lore raw

Re: [PATCH v8 0/6] set-head/fetch remote/HEAD updates, small change from v7

Quoted 16 lines · Bence Ferdinandy
Quoted 14 lines · Taylor Blau
Quoted 7 lines · Bence Ferdinandy

Bence Ferdinandy (6):
refs: atomically record overwritten ref in update_symref remote set-head: add new variable for readability remote set-head: better output for --auto
refs: add TRANSACTION_CREATE_EXISTS error
refs: add create_only option to refs_update_symref
fetch: set remote/HEAD if it does not exist

I integrated this new round into my copy of 'seen' today and noticed some test breakage in t5505 here:

    https://github.com/ttaylorr/git/actions/runs/11356267070
Quoted 7 lines
Quoted 2 lines

I'm going to temporarily eject this topic out of 'seen' until we can get an analysis of what's going on here.

Thanks for the heads up! I see that indeed the failing output is different than what I have locally (e.g. no "apis/HEAD -> apis/main" in any of the test files I have). On the other hand I can't reproduce it so I will need some help with this I think.

I similarly could not reproduce it (I ran 'make test' on this topic before integrating it into 'seen', and it passed, otherwise I wouldn't have picked it up).

I am not sure what the differences are. The 'ci' directory has some more bits on how the various suites are run, and the '.github/workflows' directory has some more bits still.

Thanks,
Taylor

#84 lore raw

Re: [PATCH v8 0/6] set-head/fetch remote/HEAD updates, small change from v7

Quoted 6 lines · Taylor Blau
Quoted 4 lines · Bence Ferdinandy

Thanks for the heads up! I see that indeed the failing output is different than what I have locally (e.g. no "apis/HEAD -> apis/main" in any of the test files I have). On the other hand I can't reproduce it so I will need some help with this I think.

Quoted 7 lines

I similarly could not reproduce it (I ran 'make test' on this topic before integrating it into 'seen', and it passed, otherwise I wouldn't have picked it up).

I am not sure what the differences are. The 'ci' directory has some more bits on how the various suites are run, and the '.github/workflows' directory has some more bits still.

I managed to reproduce it in docker once, but I'm not sure how and I wasn't able to do it again ... On the other hand (using some printf) I managed to figure out that fetch --multiple --all is running both in the CI and locally and the difference is actually what we see in the output (so no error per se). E.g. in t5505.55 update, if you run it locally refs/remotes/apis/HEAD does not exist, while in the CI it does.

I'm not sure why this difference exists yet, so I'm hoping someone might have an idea. I'll keep poking around in the meanwhile.

Thanks,
Bence

#85 lore raw

v9 cover set-head/fetch remote/HEAD updates

In reply to Taylor Blau

Hi,

the two most notable changes are
- the new patch 1/7 which address
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/, but see
https://lore.kernel.org/git/[email protected]/
- the refs_update_symref -> refs_update_symref_extended change in 2/7, reflecting on Phillip's comments (see
https://lore.kernel.org/git/[email protected]/)

Hopefully with 1/7 the series is ready to move back to seen :)

Best,
Bence

Bence Ferdinandy (7):
t/t5505-remote: set default branch to main
refs: atomically record overwritten ref in update_symref remote set-head: refactor for readability
remote set-head: better output for --auto
refs: add TRANSACTION_CREATE_EXISTS error
refs: add create_only option to refs_update_symref_extended
fetch: set remote/HEAD if it does not exist

 builtin/fetch.c                  |  82 +++++++++++
 builtin/remote.c                 |  52 +++++--
 refs.c                           |  41 +++++-
 refs.h                           |   8 +-
 refs/files-backend.c             |  24 ++--
 refs/reftable-backend.c          |   6 +-
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  73 +++++++++-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 17 files changed, 468 insertions(+), 154 deletions(-)
Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#86 lore raw

PATCH v9 1/7 t/t5505-remote: set default branch to main

Consider the bare repository called "mirror" in the test. Running git remote add --mirror -f origin ../one will not change HEAD, consequently if init.defaultBranch is not the same as what HEAD in the remote ("one"), HEAD in "mirror" will be pointing to a non-existent reference. Hence if "mirror" is used as a remote by yet another repository, ls-remote will not show HEAD. On the other hand, if init.defaultBranch happens to match HEAD in "one", then ls-remote will show HEAD.

Since the CI globally exports GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main, there's a drift between how the test repositories are set up in the CI and during local testing. This issue does not manifest currently, as the test does not do any remote HEAD manipulation where this would come up, but should such things be added, a locally passing test would break the CI vice-versa.

Set GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main in the test to be consistent with the CI.
---

Notes:
v9: - new patch
- a bandaid for the CI issue noticed by Taylor (cf:
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/), but
see
https://lore.kernel.org/git/[email protected]/ for the root cause in detail

 t/t5505-remote.sh | 3 +++
 1 file changed, 3 insertions(+)
t/t5505-remote.sh +3 -0
index 532035933f..9b50276646 100755
@@ -2,6 +2,9 @@
 
 test_description='git remote porcelain-ish'
 
+GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main
+export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
+
 TEST_PASSES_SANITIZE_LEAK=true
 . ./test-lib.sh
 
Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#87 lore raw

PATCH v9 2/7 refs: atomically record overwritten ref in update_symref

In reply to Bence Ferdinandy

When updating a symref with update_symref it's currently not possible to know for sure what was the previous value that was overwritten. Extend refs_update_symref under a new function name, to record the value after the ref has been locked if the caller of refs_update_symref_extended requests it via a new variable in the function call. Keep the original refs_update_symref function with the same signature, but now as a wrapper around refs_update_symref_extended.

---

Notes:
v4: new patch

v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

v6: - no change

v7: - remove the whole before_target concept from the backends and
handle checking it in refs.c instead (thanks Karthik)
- rename the before_target to referent which is how the same concept is called in the backends
- change commit prefix to be more in line with project standards

v8: no change

v9: - instead of adding parameters to refs_update_symref, rename what
was in v8 as refs_update_symref_extended and make refs_update_symref a wrapper for that. This significantly reduces the number of files that need to be touched, and avoids adding a lot of dummy NULL-s in unrelated places.

 refs.c | 19 ++++++++++++++++---
 refs.h |  4 ++++
 2 files changed, 20 insertions(+), 3 deletions(-)
refs.c +16 -3
index 5f729ed412..24a4172cd2 100644
@@ -2115,6 +2115,13 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg)
+{
+	return refs_update_symref_extended(refs, ref, target, logmsg, NULL);
+}
+
+int refs_update_symref_extended(struct ref_store *refs, const char *ref,
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2122,13 +2129,20 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
+		ref_transaction_update(transaction, ref, NULL, NULL,
 				   target, NULL, REF_NO_DEREF,
 				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);
 
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
+
+cleanup:
 	strbuf_release(&err);
 	if (transaction)
 		ref_transaction_free(transaction);
@@ -2948,4 +2962,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +4 -0
index 108dfc93b3..259191a485 100644
@@ -573,6 +573,10 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg);
 
+int refs_update_symref_extended(struct ref_store *refs, const char *refname,
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent);
+
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
 	UPDATE_REFS_DIE_ON_ERR,
Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#88 lore raw

PATCH v9 3/7 remote set-head: refactor for readability

In reply to Bence Ferdinandy

Rename buf and buf2 to something more explanatory.

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable.

---

Notes:
v5: new patch (split from the next patch as a preparatory step)

v6: no change

v7: - change commit prefix to be more in line with project standards

v8: no change

v9: - further improve readability by renaming buf, and buf2 consistently
with how patch 6 was already done

 builtin/remote.c | 23 ++++++++++++-----------
 1 file changed, 12 insertions(+), 11 deletions(-)
builtin/remote.c +12 -11
index 76670ddd8b..1d68c5b2ba 100644
@@ -1402,8 +1402,9 @@ static int show(int argc, const char **argv, const char *prefix)
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1415,7 +1416,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	argc = parse_options(argc, argv, prefix, options,
 			     builtin_remote_sethead_usage, 0);
 	if (argc)
-		strbuf_addf(&buf, "refs/remotes/%s/HEAD", argv[0]);
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", argv[0]);
 
 	if (!opt_a && !opt_d && argc == 2) {
 		head_name = xstrdup(argv[1]);
@@ -1434,25 +1435,25 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
-			result |= error(_("Could not delete %s"), buf.buf);
+		if (refs_delete_ref(refs, NULL, b_head.buf, NULL, REF_NO_DEREF))
+			result |= error(_("Could not delete %s"), b_head.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
 
 	if (head_name) {
-		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
-			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
-			result |= error(_("Could not setup %s"), buf.buf);
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf, "remote set-head"))
+			result |= error(_("Could not setup %s"), b_head.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
 		free(head_name);
 	}
 
-	strbuf_release(&buf);
-	strbuf_release(&buf2);
+	strbuf_release(&b_head);
+	strbuf_release(&b_remote_head);
 	return result;
 }
 
Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#89 lore raw

PATCH v9 4/7 remote set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates. As a fourth output, if HEAD is changed from a previous value that was not a remote branch, explicitly call attention to this fact.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

v5: - the minor refactor has been split out into its own patch

v6: - fixed uninitialized prev_head
- fixed case of unusual previous target
- fixed a test that would have been actually broken at this patch (the output was only correct with the later update to fetch)
- added 4 tests for the 4 output cases

v7: - change commit prefix to be more in line with project standards
- fixed tests to also work with the reftable backend
- renamed report function, fixed style issue with checking buf len
- fixed not releasing an strbuf

v8: no change

v9: - mark output strings in report_set_head_auto as translatable
- rename buf_prev to b_local_head for consistency
- use ${SQ} in tests instead of '\''

 builtin/remote.c  | 33 +++++++++++++++++++++++++++---
 t/t5505-remote.sh | 51 ++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 80 insertions(+), 4 deletions(-)
builtin/remote.c +30 -3
index 1d68c5b2ba..108f1271d3 100644
@@ -1399,10 +1399,35 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_set_head_auto(const char *remote, const char *head_name,
+			struct strbuf *b_local_head) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(b_local_head->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf(_("'%s/HEAD' is unchanged and points to '%s'\n"),
+			remote, head_name);
+	else if (prev_head)
+		printf(_("'%s/HEAD' has changed from '%s' and now points to '%s'\n"),
+			remote, prev_head, head_name);
+	else if (!b_local_head->len)
+		printf(_("'%s/HEAD' is now created and points to '%s'\n"),
+			remote, head_name);
+	else
+		printf(_("'%s/HEAD' used to point to '%s' "
+			"(which is not a remote branch), but now points to '%s'\n"),
+			remote, b_local_head->buf, head_name);
+	strbuf_release(&buf_prefix);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1470,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, b_remote_head.buf))
 			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
-		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf, "remote set-head"))
+		else if (refs_update_symref_extended(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head))
 			result |= error(_("Could not setup %s"), b_head.buf);
 		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+			report_set_head_auto(argv[0], head_name, &b_local_head);
 		free(head_name);
 	}
 
 	strbuf_release(&b_head);
 	strbuf_release(&b_remote_head);
+	strbuf_release(&b_local_head);
 	return result;
 }
 
t/t5505-remote.sh +50 -1

68 lines not on this page · raw message

Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#90 lore raw

PATCH v9 5/7 refs: add TRANSACTION_CREATE_EXISTS error

In reply to Bence Ferdinandy

Currently there is only one special error for transaction, for when there is a naming conflict, all other errors are dumped under a generic error. Add a new special error case for when the caller requests the reference to be updated only when it does not yet exist and the reference actually does exist.

---

Notes:
v4: new patch
v5: no change
v6: no change

v7: - change commit prefix to be more in line with project standards
- changed error checking to Karthik's suggestion

v8: no change

v9: - no change

 refs.h                  |  4 +++-
 refs/files-backend.c    | 24 ++++++++++++++++--------
 refs/reftable-backend.c |  6 ++++--
 3 files changed, 23 insertions(+), 11 deletions(-)
refs.h +3 -1
index 259191a485..a5bc25442b 100644
@@ -762,8 +762,10 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 
 /* Naming conflict (for example, the ref names A and A/B conflict). */
 #define TRANSACTION_NAME_CONFLICT -1
+/* When only creation was requested, but the ref already exists. */
+#define TRANSACTION_CREATE_EXISTS -2
 /* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -2
+#define TRANSACTION_GENERIC_ERROR -3
 
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
refs/files-backend.c +16 -8
index 0824c0b8a9..e743ec44b5 100644
@@ -2502,14 +2502,18 @@ static int split_symref_update(struct ref_update *update,
 static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			 struct strbuf *err)
 {
+	int ret = TRANSACTION_GENERIC_ERROR;
+
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
 		return 0;
 
-	if (is_null_oid(&update->old_oid))
+	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
+		ret = TRANSACTION_CREATE_EXISTS;
+	}
 	else if (is_null_oid(oid))
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
@@ -2522,7 +2526,7 @@ static int check_old_oid(struct ref_update *update, struct object_id *oid,
 			    oid_to_hex(oid),
 			    oid_to_hex(&update->old_oid));
 
-	return -1;
+	return ret;
 }
 
 /*
@@ -2602,9 +2606,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					ret = TRANSACTION_GENERIC_ERROR;
 					goto out;
 				}
-			} else if  (check_old_oid(update, &lock->old_oid, err)) {
-				ret = TRANSACTION_GENERIC_ERROR;
-				goto out;
+			} else {
+				ret = check_old_oid(update, &lock->old_oid, err);
+				if  (ret) {
+					goto out;
+				}
 			}
 		} else {
 			/*
@@ -2635,9 +2641,11 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				    update->old_target);
 			ret = TRANSACTION_GENERIC_ERROR;
 			goto out;
-		} else if  (check_old_oid(update, &lock->old_oid, err)) {
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
+		} else {
+			ret = check_old_oid(update, &lock->old_oid, err);
+			if  (ret) {
+				goto out;
+			}
 		}
 
 		/*
refs/reftable-backend.c +4 -2
index 3c6107c7ce..b3b5ce77dd 100644
@@ -1206,10 +1206,13 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			if (is_null_oid(&u->old_oid))
+			ret = TRANSACTION_NAME_CONFLICT;
+			if (is_null_oid(&u->old_oid)) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference already exists"),
 					    ref_update_original_update_refname(u));
+				ret = TRANSACTION_CREATE_EXISTS;
+			}
 			else if (is_null_oid(&current_oid))
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "reference is missing but expected %s"),
@@ -1221,7 +1224,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    ref_update_original_update_refname(u),
 					    oid_to_hex(&current_oid),
 					    oid_to_hex(&u->old_oid));
-			ret = -1;
 			goto done;
 		}
 
Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#91 lore raw

PATCH v9 6/7 refs: add create_only option to refs_update_symref_extended

In reply to Bence Ferdinandy

Allow the caller to specify that it only wants to update the symref if it does not already exist. Silently ignore the error from the transaction API if the symref already exists.

---

Notes:
v4: new patch
v5: no change

v6: - switched from bool to int for create_only
- refactored logic in refs_update_symref with goto as layed out by Junio

v7: - change commit prefix to be more in line with project standards
- refactored code to accommodate changes in the first patch, but otherwise no change

v8: no change

v9: - no change (except for following through the
refs_update_symref_extended refactoring)

 builtin/remote.c |  2 +-
 refs.c           | 32 +++++++++++++++++++++++---------
 refs.h           |  2 +-
 3 files changed, 25 insertions(+), 11 deletions(-)
builtin/remote.c +1 -1
index 108f1271d3..b1eba75a2b 100644
@@ -1471,7 +1471,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		if (!refs_ref_exists(refs, b_remote_head.buf))
 			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
 		else if (refs_update_symref_extended(refs, b_head.buf, b_remote_head.buf,
-					"remote set-head", &b_local_head))
+					"remote set-head", &b_local_head, 0))
 			result |= error(_("Could not setup %s"), b_head.buf);
 		else if (opt_a)
 			report_set_head_auto(argv[0], head_name, &b_local_head);
refs.c +23 -9
index 24a4172cd2..093ee11ab0 100644
@@ -2116,31 +2116,45 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg)
 {
-	return refs_update_symref_extended(refs, ref, target, logmsg, NULL);
+	return refs_update_symref_extended(refs, ref, target, logmsg, NULL, 0);
 }
 
 int refs_update_symref_extended(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg,
-		       struct strbuf *referent)
+		       struct strbuf *referent, int create_only)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
-	int ret = 0;
+	int ret = 0, prepret = 0;
 
 	transaction = ref_store_transaction_begin(refs, &err);
-	if (!transaction ||
-		ref_transaction_update(transaction, ref, NULL, NULL,
-				   target, NULL, REF_NO_DEREF,
-				   logmsg, &err) ||
-		ref_transaction_prepare(transaction, &err)) {
+	if (!transaction) {
+	error_return:
 		ret = error("%s", err.buf);
 		goto cleanup;
 	}
+	if (create_only) {
+		if (ref_transaction_create(transaction, ref, NULL, target,
+					   REF_NO_DEREF, logmsg, &err))
+			goto error_return;
+		prepret = ref_transaction_prepare(transaction, &err);
+		if (prepret && prepret != TRANSACTION_CREATE_EXISTS)
+			goto error_return;
+	} else {
+		if (ref_transaction_update(transaction, ref, NULL, NULL,
+					   target, NULL, REF_NO_DEREF,
+					   logmsg, &err) ||
+			ref_transaction_prepare(transaction, &err))
+			goto error_return;
+	}
+
 	if (referent)
 		refs_read_symbolic_ref(refs, ref, referent);
 
+	if (prepret == TRANSACTION_CREATE_EXISTS)
+		goto cleanup;
 	if (ref_transaction_commit(transaction, &err))
-		ret = error("%s", err.buf);
+		goto error_return;
 
 cleanup:
 	strbuf_release(&err);
refs.h +1 -1
index a5bc25442b..458582ebcf 100644
@@ -575,7 +575,7 @@ int refs_update_symref(struct ref_store *refs, const char *refname,
 
 int refs_update_symref_extended(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg,
-		       struct strbuf *referent);
+		       struct strbuf *referent, int create_only);
 
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#92 lore raw

PATCH v9 7/7 fetch: set remote/HEAD if it does not exist

In reply to Bence Ferdinandy

If the user has remote/HEAD set already and it looks like it has changed on the server, then print a message, otherwise set it if we can. Silently pass if the user already has the same remote/HEAD set as reported by the server or if we encounter any errors along the way.

---

Notes:
v3: - does not rely on remote set-head anymore so it only authenticates
once
- uses the new REF_CREATE_ONLY to atomically check if the ref exists and only write it if it doesn't
- in all other cases the maximum it does is print a warning

v4: - instead of the discarded REF_CREATE_ONLY, it uses the existing,
but updated transaction api to request a silent create only
- it now uses the atomic before_target to determine reporting
- refactored for legibility

v5: - instead of printing a not too useful message, it now fails
silently, this in line with the objective to only set up remote/HEAD automatically if the right thing is trivial, for everything else there is remote set-head
- fixed all failing tests
- added two new tests, one for checking if remote/HEAD is set to the correct one, and one to test that we do not override remote/HEAD if it has changed on the server from what we have locally

v6: - fixed style issues and unintended extra empty line
- updated function call with bool to int from previous patch's change
- removed calls to error(...) inherited from builtin/remote.c so we actually fail silently
- set the test for remote set-head --auto to the correct value here, which was previously erronously set in the remote set-head patch

v7: - no change

v8: - changed logmsg in call to refs_update_symref from "remote
set-head" to "fetch"

v9: - follow through with refs_update_symref_extended
- fix test errors uncovered by the new patch

 builtin/fetch.c                  |  82 +++++++++++
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  21 ++-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 12 files changed, 315 insertions(+), 124 deletions(-)
builtin/fetch.c +82 -0
index d9027e4dc9..31edc67447 100644
@@ -1578,6 +1578,80 @@ static int backfill_tags(struct display_state *display_state,
 	return retcode;
 }
 
+static void report_set_head(const char *remote, const char *head_name,
+			struct strbuf *buf_prev) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && strcmp(prev_head, head_name)) {
+		printf("'HEAD' at '%s' has changed from '%s' to '%s'\n",
+			remote, prev_head, head_name);
+		printf("Run 'git remote set-head %s %s' to follow the change.\n",
+			remote, head_name);
+	}
+}
+
+static const char *strip_refshead(const char *name){
+	skip_prefix(name, "refs/heads/", &name);
+	return name;
+}
+
+static int set_head(const struct ref *remote_refs)
+{
+	int result = 0;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
+	const char *remote = gtransport->remote->name;
+	char *head_name = NULL;
+	struct ref *ref, *matches;
+	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
+	struct refspec_item refspec = {
+		.force = 0,
+		.pattern = 1,
+		.src = (char *) "refs/heads/*",
+		.dst = (char *) "refs/heads/*",
+	};
+	struct string_list heads = STRING_LIST_INIT_DUP;
+	struct ref_store *refs = get_main_ref_store(the_repository);
+
+	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
+	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
+				    fetch_map, 1);
+	for (ref = matches; ref; ref = ref->next) {
+		string_list_append(&heads, strip_refshead(ref->name));
+	}
+
+
+	if (!heads.nr)
+		result = 1;
+	else if (heads.nr > 1)
+		result = 1;
+	else
+		head_name = xstrdup(heads.items[0].string);
+	if (head_name) {
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote, head_name);
+		/* make sure it's valid */
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result = 1;
+		else if (refs_update_symref_extended(refs, b_head.buf, b_remote_head.buf,
+					"fetch", &b_local_head, 1))
+			result = 1;
+		else
+			report_set_head(remote, head_name, &b_local_head);
+
+		free(head_name);
+	}
+
+	strbuf_release(&b_head);
+	strbuf_release(&b_local_head);
+	strbuf_release(&b_remote_head);
+	return result;
+}
+
 static int do_fetch(struct transport *transport,
 		    struct refspec *rs,
 		    const struct fetch_config *config)
@@ -1647,6 +1721,8 @@ static int do_fetch(struct transport *transport,
 				    "refs/tags/");
 	}
 
+	strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
+
 	if (must_list_refs) {
 		trace2_region_enter("fetch", "remote_refs", the_repository);
 		remote_refs = transport_get_remote_refs(transport,
@@ -1791,6 +1867,12 @@ static int do_fetch(struct transport *transport,
 				  "you need to specify exactly one branch with the --set-upstream option"));
 		}
 	}
+	if (set_head(remote_refs))
+		;
+		/*
+		 * Way too many cases where this can go wrong
+		 * so let's just fail silently for now.
+		 */
 
 cleanup:
 	if (retcode) {
t/t4207-log-decoration-colors.sh +2 -1
index 73ea9e5155..d55d22cb2f 100755
@@ -59,7 +59,8 @@ ${c_reset}${c_tag}tag: ${c_reset}${c_tag}v1.0${c_reset}${c_commit}, \
 ${c_reset}${c_tag}tag: ${c_reset}${c_tag}B${c_reset}${c_commit})${c_reset} B
 ${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_tag}tag: ${c_reset}${c_tag}A1${c_reset}${c_commit}, \
-${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit})${c_reset} A1
+${c_reset}${c_remoteBranch}other/main${c_reset}${c_commit}, \
+${c_reset}${c_remoteBranch}other/HEAD${c_reset}${c_commit})${c_reset} A1
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
 ${c_stash}refs/stash${c_reset}${c_commit})${c_reset} On main: Changes to A.t
 	${c_commit}COMMIT_ID${c_reset}${c_commit} (${c_reset}\
t/t5505-remote.sh +15 -6
index 0ea86d51a4..4990d00209 100755
@@ -74,7 +74,7 @@ test_expect_success 'add another remote' '
 		cd test &&
 		git remote add -f second ../two &&
 		tokens_match "origin second" "$(git remote)" &&
-		check_tracking_branch second main side another &&
+		check_tracking_branch second main side another HEAD &&
 		git for-each-ref "--format=%(refname)" refs/remotes |
 		sed -e "/^refs\/remotes\/origin\//d" \
 		    -e "/^refs\/remotes\/second\//d" >actual &&
@@ -476,7 +476,7 @@ test_expect_success 'set-head --auto has no problem w/multiple HEADs' '
 		cd test &&
 		git fetch two "refs/heads/*:refs/remotes/two/*" &&
 		git remote set-head --auto two >output 2>&1 &&
-		echo "${SQ}two/HEAD${SQ} is now created and points to ${SQ}main${SQ}" >expect &&
+		echo "${SQ}two/HEAD${SQ} is unchanged and points to ${SQ}main${SQ}" >expect &&
 		test_cmp expect output
 	)
 '
@@ -764,8 +764,10 @@ test_expect_success 'reject --no-no-tags' '
 '
 
 cat >one/expect <<\EOF
+  apis/HEAD -> apis/main
   apis/main
   apis/side
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -783,11 +785,14 @@ test_expect_success 'update' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
+  manduca/HEAD -> manduca/main
   manduca/main
   manduca/side
+  megaloprepus/HEAD -> megaloprepus/main
   megaloprepus/main
   megaloprepus/side
 EOF
@@ -795,7 +800,7 @@ EOF
 test_expect_success 'update with arguments' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -827,10 +832,13 @@ test_expect_success 'update --prune' '
 '
 
 cat >one/expect <<-\EOF
+  apis/HEAD -> apis/main
   apis/main
   apis/side
+  manduca/HEAD -> manduca/main
   manduca/main
   manduca/side
+  megaloprepus/HEAD -> megaloprepus/main
   megaloprepus/main
   megaloprepus/side
 EOF
@@ -838,7 +846,7 @@ EOF
 test_expect_success 'update default' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -850,6 +858,7 @@ test_expect_success 'update default' '
 '
 
 cat >one/expect <<\EOF
+  drosophila/HEAD -> drosophila/main
   drosophila/another
   drosophila/main
   drosophila/side
@@ -858,7 +867,7 @@ EOF
 test_expect_success 'update default (overridden, with funny whitespace)' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
@@ -872,7 +881,7 @@ test_expect_success 'update default (overridden, with funny whitespace)' '
 test_expect_success 'update (with remotes.default defined)' '
 	(
 		cd one &&
-		for b in $(git branch -r)
+		for b in $(git branch -r | grep -v HEAD)
 		do
 		git branch -r -d $b || exit 1
 		done &&
t/t5510-fetch.sh +122 -107

356 lines not on this page · raw message

t/t5512-ls-remote.sh +2 -0
index 64b3491e4e..1b3865e154 100755
@@ -293,6 +293,8 @@ test_expect_success 'ls-remote with filtered symref (refname)' '
 	cat >expect <<-EOF &&
 	ref: refs/heads/main	HEAD
 	$rev	HEAD
+	ref: refs/remotes/origin/main	refs/remotes/origin/HEAD
+	$rev	refs/remotes/origin/HEAD
 	EOF
 	git ls-remote --symref . HEAD >actual &&
 	test_cmp expect actual
t/t5514-fetch-multiple.sh +15 -2
index 579872c258..e3482b27b2 100755
@@ -45,14 +45,17 @@ test_expect_success setup '
 '
 
 cat > test/expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -97,6 +100,7 @@ cat > expect << EOF
   origin/HEAD -> origin/main
   origin/main
   origin/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
@@ -112,8 +116,10 @@ test_expect_success 'git fetch --multiple (but only one remote)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -141,7 +147,7 @@ test_expect_success 'git fetch --multiple (bad remote names)' '
 
 test_expect_success 'git fetch --all (skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -153,11 +159,14 @@ test_expect_success 'git fetch --all (skipFetchAll)' '
 '
 
 cat > expect << EOF
+  one/HEAD -> one/main
   one/main
   one/side
+  three/HEAD -> three/main
   three/another
   three/main
   three/side
+  two/HEAD -> two/main
   two/another
   two/main
   two/side
@@ -165,7 +174,7 @@ EOF
 
 test_expect_success 'git fetch --multiple (ignoring skipFetchAll)' '
 	(cd test4 &&
-	 for b in $(git branch -r)
+	 for b in $(git branch -r | grep -v HEAD)
 	 do
 		git branch -r -d $b || exit 1
 	 done &&
@@ -221,14 +230,17 @@ test_expect_success 'git fetch --multiple --jobs=0 picks a default' '
 
 create_fetch_all_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
 	  origin/main
 	  origin/side
+	  three/HEAD -> three/main
 	  three/another
 	  three/main
 	  three/side
+	  two/HEAD -> two/main
 	  two/another
 	  two/main
 	  two/side
@@ -265,6 +277,7 @@ test_expect_success 'git fetch (fetch all remotes with fetch.all = true)' '
 
 create_fetch_one_expect () {
 	cat >expect <<-\EOF
+	  one/HEAD -> one/main
 	  one/main
 	  one/side
 	  origin/HEAD -> origin/main
t/t5516-fetch-push.sh +2 -1
index 331778bd42..5a051aa0c7 100755
@@ -1395,7 +1395,8 @@ test_expect_success 'fetch follows tags by default' '
 		git tag -m "annotated" tag &&
 		git for-each-ref >tmp1 &&
 		sed -n "p; s|refs/heads/main$|refs/remotes/origin/main|p" tmp1 |
-		sort -k 3 >../expect
+		sed -n "p; s|refs/heads/main$|refs/remotes/origin/HEAD|p"  |
+		sort -k 4 >../expect
 	) &&
 	test_when_finished "rm -rf dst" &&
 	git init dst &&
t/t5527-fetch-odd-refs.sh +2 -1
index 98ece27c6a..d3996af6ee 100755
@@ -52,7 +52,8 @@ test_expect_success LONG_REF 'fetch handles extremely long refname' '
 	long
 	main
 	EOF
-	git for-each-ref --format="%(subject)" refs/remotes/long >actual &&
+	git for-each-ref --format="%(subject)" refs/remotes/long \
+		--exclude=refs/remotes/long/HEAD >actual &&
 	test_cmp expect actual
 '
 
t/t7900-maintenance.sh +2 -1
index a66d0e089d..88331d1ceb 100755
@@ -329,7 +329,8 @@ test_expect_success 'incremental-repack task' '
 
 	# Delete refs that have not been repacked in these packs.
 	git for-each-ref --format="delete %(refname)" \
-		refs/prefetch refs/tags refs/remotes >refs &&
+		refs/prefetch refs/tags refs/remotes \
+		--exclude=refs/remotes/*/HEAD >refs &&
 	git update-ref --stdin <refs &&
 
 	# Replace the object directory with this pack layout.
t/t9210-scalar.sh +3 -2
index a30b2c9f70..2237844550 100755
@@ -151,7 +151,8 @@ test_expect_success 'scalar clone' '
 			"$(pwd)" &&
 
 		git for-each-ref --format="%(refname)" refs/remotes/origin/ >actual &&
-		echo "refs/remotes/origin/parallel" >expect &&
+		echo "refs/remotes/origin/HEAD" >>expect &&
+		echo "refs/remotes/origin/parallel" >>expect &&
 		test_cmp expect actual &&
 
 		test_path_is_missing 1/2 &&
@@ -220,7 +221,7 @@ test_expect_success 'scalar reconfigure --all with includeIf.onbranch' '
 	done
 '
 
- test_expect_success 'scalar reconfigure --all with detached HEADs' '
+test_expect_success 'scalar reconfigure --all with detached HEADs' '
 	repos="two three four" &&
 	for num in $repos
 	do
t/t9211-scalar-clone.sh +3 -3
index c16ea67c1d..d9cb6b9a3e 100755
@@ -32,7 +32,7 @@ test_expect_success 'set up repository to clone' '
 	)
 '
 
-cleanup_clone () {
+cleanup_clone() {
 	rm -rf "$1"
 }
 
@@ -128,7 +128,7 @@ test_expect_success '--single-branch clones HEAD only' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 1 out &&
+		test_line_count = 2 out &&
 		grep "refs/remotes/origin/base" out
 	) &&
 
@@ -142,7 +142,7 @@ test_expect_success '--no-single-branch clones all branches' '
 	(
 		cd $enlistment/src &&
 		git for-each-ref refs/remotes/origin >out &&
-		test_line_count = 2 out &&
+		test_line_count = 3 out &&
 		grep "refs/remotes/origin/base" out &&
 		grep "refs/remotes/origin/parallel" out
 	) &&
t/t9902-completion.sh +65 -0

443 lines not on this page · raw message

Signature · 1 line
2.47.0.92.g83fdbe24c3.dirty
#94 lore raw

v11 cover set-head/fetch remote/HEAD updates

v11: fixed leaks found by running tests after make SANITIZE=leak

    green pipeline:
    https://github.com/ferdinandyb/git/actions/runs/11466803523

v10: added a new patch (8/8) on top of v9 to handle HEAD in mirrored bare repositories, rest of the patches are unchanged

v9:
the two most notable changes are
- the new patch 1/7 which address
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/, but see
https://lore.kernel.org/git/[email protected]/
- the refs_update_symref -> refs_update_symref_extended change in 2/7, reflecting on Phillip's comments (see
https://lore.kernel.org/git/[email protected]/)

Bence Ferdinandy (8):
t/t5505-remote: set default branch to main
refs: atomically record overwritten ref in update_symref remote set-head: refactor for readability
remote set-head: better output for --auto
refs: add TRANSACTION_CREATE_EXISTS error
refs: add create_only option to refs_update_symref_extended
fetch: set remote/HEAD if it does not exist
fetch set_head: handle mirrored bare repositories

 builtin/fetch.c                  |  94 +++++++++++++
 builtin/remote.c                 |  52 +++++--
 refs.c                           |  41 +++++-
 refs.h                           |   8 +-
 refs/files-backend.c             |  24 ++--
 refs/reftable-backend.c          |   6 +-
 t/t4207-log-decoration-colors.sh |   3 +-
 t/t5505-remote.sh                |  83 ++++++++++-
 t/t5510-fetch.sh                 | 229 ++++++++++++++++---------------
 t/t5512-ls-remote.sh             |   2 +
 t/t5514-fetch-multiple.sh        |  17 ++-
 t/t5516-fetch-push.sh            |   3 +-
 t/t5527-fetch-odd-refs.sh        |   3 +-
 t/t7900-maintenance.sh           |   3 +-
 t/t9210-scalar.sh                |   5 +-
 t/t9211-scalar-clone.sh          |   6 +-
 t/t9902-completion.sh            |  65 +++++++++
 17 files changed, 490 insertions(+), 154 deletions(-)
Signature · 1 line
2.47.0.94.gb64850d498
#95 lore raw

PATCH v11 1/8 t/t5505-remote: set default branch to main

Consider the bare repository called "mirror" in the test. Running git remote add --mirror -f origin ../one will not change HEAD, consequently if init.defaultBranch is not the same as what HEAD in the remote ("one"), HEAD in "mirror" will be pointing to a non-existent reference. Hence if "mirror" is used as a remote by yet another repository, ls-remote will not show HEAD. On the other hand, if init.defaultBranch happens to match HEAD in "one", then ls-remote will show HEAD.

Since the CI globally exports GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main, there's a drift between how the test repositories are set up in the CI and during local testing. This issue does not manifest currently, as the test does not do any remote HEAD manipulation where this would come up, but should such things be added, a locally passing test would break the CI vice-versa.

Set GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main in the test to be consistent with the CI.
---

Notes:
v9: - new patch
- a bandaid for the CI issue noticed by Taylor (cf:
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/), but
see
https://lore.kernel.org/git/[email protected]/ for the root cause in detail

v10: no change

v11: no change

 t/t5505-remote.sh | 3 +++
 1 file changed, 3 insertions(+)
t/t5505-remote.sh +3 -0
index 532035933f..9b50276646 100755
@@ -2,6 +2,9 @@
 
 test_description='git remote porcelain-ish'
 
+GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main
+export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
+
 TEST_PASSES_SANITIZE_LEAK=true
 . ./test-lib.sh
 
Signature · 1 line
2.47.0.94.gb64850d498
#96 lore raw

Re: [PATCH v11 1/8] t/t5505-remote: set default branch to main

Quoted 26 lines · Bence Ferdinandy

Consider the bare repository called "mirror" in the test. Running git remote add --mirror -f origin ../one will not change HEAD, consequently if init.defaultBranch is not the same as what HEAD in the remote ("one"), HEAD in "mirror" will be pointing to a non-existent reference. Hence if "mirror" is used as a remote by yet another repository, ls-remote will not show HEAD. On the other hand, if init.defaultBranch happens to match HEAD in "one", then ls-remote will show HEAD.

Since the CI globally exports GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main, there's a drift between how the test repositories are set up in the CI and during local testing. This issue does not manifest currently, as the test does not do any remote HEAD manipulation where this would come up, but should such things be added, a locally passing test would break the CI vice-versa.

Set GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main in the test to be consistent with the CI.
---

Notes:
v9: - new patch
- a bandaid for the CI issue noticed by Taylor (cf:
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/),
but
see

Quoted 2 lines

https://lore.kernel.org/git/[email protected]/
for the root cause in detail

Why no signoff?

Signature · 1 line
Kristoffer Haugsbakk
#97 lore raw

Re: [PATCH v11 1/8] t/t5505-remote: set default branch to main

Quoted 27 lines · Kristoffer Haugsbakk
Quoted 26 lines · Bence Ferdinandy

Consider the bare repository called "mirror" in the test. Running git remote add --mirror -f origin ../one will not change HEAD, consequently if init.defaultBranch is not the same as what HEAD in the remote ("one"), HEAD in "mirror" will be pointing to a non-existent reference. Hence if "mirror" is used as a remote by yet another repository, ls-remote will not show HEAD. On the other hand, if init.defaultBranch happens to match HEAD in "one", then ls-remote will show HEAD.

Since the CI globally exports GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main, there's a drift between how the test repositories are set up in the CI and during local testing. This issue does not manifest currently, as the test does not do any remote HEAD manipulation where this would come up, but should such things be added, a locally passing test would break the CI vice-versa.

Set GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main in the test to be consistent with the CI.
---

Notes:
v9: - new patch
- a bandaid for the CI issue noticed by Taylor (cf:
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/),
but
see

Quoted 4 lines
Quoted 2 lines

https://lore.kernel.org/git/[email protected]/
for the root cause in detail

Why no signoff?

Because I always forget :( I've been thinking on making it by default, but I didn't want to add it to all the work related commits, where I'd be the only one doing it, but I just found the format.signoff setting, so I should be covered for future patches.

I'll wait some time before sending a fix for this :)

Thanks,
Bence

Signature · 1 line
bence.ferdinandy.com
#98 lore raw

Re: [PATCH v11 1/8] t/t5505-remote: set default branch to main

Quoted 32 lines · Bence Ferdinandy
Quoted 30 lines · Kristoffer Haugsbakk
Quoted 28 lines · Bence Ferdinandy

Consider the bare repository called "mirror" in the test. Running git remote add --mirror -f origin ../one will not change HEAD, consequently if init.defaultBranch is not the same as what HEAD in the remote ("one"), HEAD in "mirror" will be pointing to a non-existent reference. Hence if "mirror" is used as a remote by yet another repository, ls-remote will not show HEAD. On the other hand, if init.defaultBranch happens to match HEAD in "one", then ls-remote will show HEAD.

Since the CI globally exports GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main, there's a drift between how the test repositories are set up in the CI and during local testing. This issue does not manifest currently, as the test does not do any remote HEAD manipulation where this would come up, but should such things be added, a locally passing test would break the CI vice-versa.

Set GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main in the test to be consistent with the CI.
---

Notes:
v9: - new patch
- a bandaid for the CI issue noticed by Taylor (cf:
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/),
but
see

https://lore.kernel.org/git/[email protected]/
for the root cause in detail

Quoted 8 lines
Quoted 1 line

Why no signoff?

Because I always forget :( I've been thinking on making it by default, but I didn't want to add it to all the work related commits, where I'd be the only one doing it, but I just found the format.signoff setting, so I should be covered for future patches.

I'll wait some time before sending a fix for this :)

Yeah, I was going to suggest format.signOff as well. If you don't want to add your S-o-b to work commits but do want to add it to patches you send to the Git list, you could just stop there (assuming that you don't use format-patch for work-related patches).

Alternatively, you could set it in your copy of git.git's own configuration in $GIT_DIR/config, so that it doesn't apply to work you do outside of that repository.

Either way, I'm going to avoid queueing this round since it is missing the required Signed-off-by line.

Thanks,
Taylor

#99 lore raw

Re: [PATCH v11 1/8] t/t5505-remote: set default branch to main

Quoted 40 lines · Taylor Blau
Quoted 39 lines · Bence Ferdinandy
Quoted 27 lines · Kristoffer Haugsbakk
Quoted 26 lines · Bence Ferdinandy

Consider the bare repository called "mirror" in the test. Running git remote add --mirror -f origin ../one will not change HEAD, consequently if init.defaultBranch is not the same as what HEAD in the remote ("one"), HEAD in "mirror" will be pointing to a non-existent reference. Hence if "mirror" is used as a remote by yet another repository, ls-remote will not show HEAD. On the other hand, if init.defaultBranch happens to match HEAD in "one", then ls-remote will show HEAD.

Since the CI globally exports GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main, there's a drift between how the test repositories are set up in the CI and during local testing. This issue does not manifest currently, as the test does not do any remote HEAD manipulation where this would come up, but should such things be added, a locally passing test would break the CI vice-versa.

Set GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main in the test to be consistent with the CI.
---

Notes:
v9: - new patch
- a bandaid for the CI issue noticed by Taylor (cf:
https://lore.kernel.org/git/Zw8IKyPkG0Hr6%[email protected]/),
but
see

Quoted 4 lines
Quoted 2 lines

https://lore.kernel.org/git/[email protected]/
for the root cause in detail

Why no signoff?

Because I always forget :( I've been thinking on making it by default, but I didn't want to add it to all the work related commits, where I'd be the only one doing it, but I just found the format.signoff setting, so I should be covered for future patches.

Quoted 6 lines
Quoted 1 line

I'll wait some time before sending a fix for this :)

Yeah, I was going to suggest format.signOff as well. If you don't want to add your S-o-b to work commits but do want to add it to patches you send to the Git list, you could just stop there (assuming that you don't use format-patch for work-related patches).

The projects I contribute to seem to have a bidirectional mapping of requiring S-o-b and format patch so I should be good with this :)

Quoted 7 lines

Alternatively, you could set it in your copy of git.git's own configuration in $GIT_DIR/config, so that it doesn't apply to work you do outside of that repository.

Either way, I'm going to avoid queueing this round since it is missing the required Signed-off-by line.

In that case I'll send a v12 with the S-o-b so the series can get back into circulation.

Best,
Bence

Quoted 3 lines

Thanks,
Taylor

Signature · 1 line
bence.ferdinandy.com
#100 lore raw

Re: [PATCH v11 1/8] t/t5505-remote: set default branch to main

Quoted 9 lines · Bence Ferdinandy
Quoted 6 lines

Alternatively, you could set it in your copy of git.git's own configuration in $GIT_DIR/config, so that it doesn't apply to work you do outside of that repository.

Either way, I'm going to avoid queueing this round since it is missing the required Signed-off-by line.

In that case I'll send a v12 with the S-o-b so the series can get back into circulation.

Thanks, will queue.

Thanks,
Taylor

#101 lore raw

PATCH v11 2/8 refs: atomically record overwritten ref in update_symref

In reply to Bence Ferdinandy

When updating a symref with update_symref it's currently not possible to know for sure what was the previous value that was overwritten. Extend refs_update_symref under a new function name, to record the value after the ref has been locked if the caller of refs_update_symref_extended requests it via a new variable in the function call. Keep the original refs_update_symref function with the same signature, but now as a wrapper around refs_update_symref_extended.

---

Notes:
v4: new patch

v5: - added before_target to reftables backend
- added an extra safety check for transaction's existence in refs.c

v6: - no change

v7: - remove the whole before_target concept from the backends and
handle checking it in refs.c instead (thanks Karthik)
- rename the before_target to referent which is how the same concept is called in the backends
- change commit prefix to be more in line with project standards

v8: no change

v9: - instead of adding parameters to refs_update_symref, rename what
was in v8 as refs_update_symref_extended and make refs_update_symref a wrapper for that. This significantly reduces the number of files that need to be touched, and avoids adding a lot of dummy NULL-s in unrelated places.

v10: no change

v11: no change

 refs.c | 19 ++++++++++++++++---
 refs.h |  4 ++++
 2 files changed, 20 insertions(+), 3 deletions(-)
refs.c +16 -3
index 5f729ed412..24a4172cd2 100644
@@ -2115,6 +2115,13 @@ int peel_iterated_oid(struct repository *r, const struct object_id *base, struct
 
 int refs_update_symref(struct ref_store *refs, const char *ref,
 		       const char *target, const char *logmsg)
+{
+	return refs_update_symref_extended(refs, ref, target, logmsg, NULL);
+}
+
+int refs_update_symref_extended(struct ref_store *refs, const char *ref,
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent)
 {
 	struct ref_transaction *transaction;
 	struct strbuf err = STRBUF_INIT;
@@ -2122,13 +2129,20 @@ int refs_update_symref(struct ref_store *refs, const char *ref,
 
 	transaction = ref_store_transaction_begin(refs, &err);
 	if (!transaction ||
-	    ref_transaction_update(transaction, ref, NULL, NULL,
+		ref_transaction_update(transaction, ref, NULL, NULL,
 				   target, NULL, REF_NO_DEREF,
 				   logmsg, &err) ||
-	    ref_transaction_commit(transaction, &err)) {
+		ref_transaction_prepare(transaction, &err)) {
 		ret = error("%s", err.buf);
+		goto cleanup;
 	}
+	if (referent)
+		refs_read_symbolic_ref(refs, ref, referent);
 
+	if (ref_transaction_commit(transaction, &err))
+		ret = error("%s", err.buf);
+
+cleanup:
 	strbuf_release(&err);
 	if (transaction)
 		ref_transaction_free(transaction);
@@ -2948,4 +2962,3 @@ int ref_update_expects_existing_old_ref(struct ref_update *update)
 	return (update->flags & REF_HAVE_OLD) &&
 		(!is_null_oid(&update->old_oid) || update->old_target);
 }
-
refs.h +4 -0
index 108dfc93b3..259191a485 100644
@@ -573,6 +573,10 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
 int refs_update_symref(struct ref_store *refs, const char *refname,
 		       const char *target, const char *logmsg);
 
+int refs_update_symref_extended(struct ref_store *refs, const char *refname,
+		       const char *target, const char *logmsg,
+		       struct strbuf *referent);
+
 enum action_on_err {
 	UPDATE_REFS_MSG_ON_ERR,
 	UPDATE_REFS_DIE_ON_ERR,
Signature · 1 line
2.47.0.94.gb64850d498
#102 lore raw

PATCH v11 3/8 remote set-head: refactor for readability

In reply to Bence Ferdinandy

Rename buf and buf2 to something more explanatory.

Instead of calling get_main_ref_store(the_repository) multiple times, call it once and store in a new refs variable. Although this change probably offers some performance benefits, the main purpose is to shorten the line lengths of function calls using this variable.

---

Notes:
v5: new patch (split from the next patch as a preparatory step)

v6: no change

v7: - change commit prefix to be more in line with project standards

v8: no change

v9: - further improve readability by renaming buf, and buf2 consistently
with how patch 6 was already done

v10: no change

v11: no change

 builtin/remote.c | 23 ++++++++++++-----------
 1 file changed, 12 insertions(+), 11 deletions(-)
builtin/remote.c +12 -11
index 76670ddd8b..1d68c5b2ba 100644
@@ -1402,8 +1402,9 @@ static int show(int argc, const char **argv, const char *prefix)
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT;
 	char *head_name = NULL;
+	struct ref_store *refs = get_main_ref_store(the_repository);
 
 	struct option options[] = {
 		OPT_BOOL('a', "auto", &opt_a,
@@ -1415,7 +1416,7 @@ static int set_head(int argc, const char **argv, const char *prefix)
 	argc = parse_options(argc, argv, prefix, options,
 			     builtin_remote_sethead_usage, 0);
 	if (argc)
-		strbuf_addf(&buf, "refs/remotes/%s/HEAD", argv[0]);
+		strbuf_addf(&b_head, "refs/remotes/%s/HEAD", argv[0]);
 
 	if (!opt_a && !opt_d && argc == 2) {
 		head_name = xstrdup(argv[1]);
@@ -1434,25 +1435,25 @@ static int set_head(int argc, const char **argv, const char *prefix)
 			head_name = xstrdup(states.heads.items[0].string);
 		free_remote_ref_states(&states);
 	} else if (opt_d && !opt_a && argc == 1) {
-		if (refs_delete_ref(get_main_ref_store(the_repository), NULL, buf.buf, NULL, REF_NO_DEREF))
-			result |= error(_("Could not delete %s"), buf.buf);
+		if (refs_delete_ref(refs, NULL, b_head.buf, NULL, REF_NO_DEREF))
+			result |= error(_("Could not delete %s"), b_head.buf);
 	} else
 		usage_with_options(builtin_remote_sethead_usage, options);
 
 	if (head_name) {
-		strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
+		strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", argv[0], head_name);
 		/* make sure it's valid */
-		if (!refs_ref_exists(get_main_ref_store(the_repository), buf2.buf))
-			result |= error(_("Not a valid ref: %s"), buf2.buf);
-		else if (refs_update_symref(get_main_ref_store(the_repository), buf.buf, buf2.buf, "remote set-head"))
-			result |= error(_("Could not setup %s"), buf.buf);
+		if (!refs_ref_exists(refs, b_remote_head.buf))
+			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
+		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf, "remote set-head"))
+			result |= error(_("Could not setup %s"), b_head.buf);
 		else if (opt_a)
 			printf("%s/HEAD set to %s\n", argv[0], head_name);
 		free(head_name);
 	}
 
-	strbuf_release(&buf);
-	strbuf_release(&buf2);
+	strbuf_release(&b_head);
+	strbuf_release(&b_remote_head);
 	return result;
 }
 
Signature · 1 line
2.47.0.94.gb64850d498
#103 lore raw

PATCH v11 4/8 remote set-head: better output for --auto

In reply to Bence Ferdinandy

Currently, set-head --auto will print a message saying "remote/HEAD set to branch", which implies something was changed.

Change the output of --auto, so the output actually reflects what was
done: a) set a previously unset HEAD, b) change HEAD because remote changed or c) no updates. As a fourth output, if HEAD is changed from a previous value that was not a remote branch, explicitly call attention to this fact.

---

Notes:
v1-v2:

was RFC in https://lore.kernel.org/git/[email protected]/

v3:

This patch was originally sent along when I thought set-head was going to be invoked by fetch, but the discussion on the RFC concluded that it should be not. This opened the possibility to make it more explicit.

Note: although I feel both things the patch does are really just cosmetic, an argument could be made for breaking it into two, one for the no-op part and one for the --auto print update.

Was sent in:
https://lore.kernel.org/git/[email protected]/

v4:
- changes are now handled atomically via the ref update transaction
- outputs have changed along the lines of Junio's suggestion
- minor refactor to set_head for improved legibility

v5: - the minor refactor has been split out into its own patch

v6: - fixed uninitialized prev_head
- fixed case of unusual previous target
- fixed a test that would have been actually broken at this patch (the output was only correct with the later update to fetch)
- added 4 tests for the 4 output cases

v7: - change commit prefix to be more in line with project standards
- fixed tests to also work with the reftable backend
- renamed report function, fixed style issue with checking buf len
- fixed not releasing an strbuf

v8: no change

v9: - mark output strings in report_set_head_auto as translatable
- rename buf_prev to b_local_head for consistency
- use ${SQ} in tests instead of '\''

v10: no change

v11: no change

 builtin/remote.c  | 33 +++++++++++++++++++++++++++---
 t/t5505-remote.sh | 51 ++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 80 insertions(+), 4 deletions(-)
builtin/remote.c +30 -3
index 1d68c5b2ba..108f1271d3 100644
@@ -1399,10 +1399,35 @@ static int show(int argc, const char **argv, const char *prefix)
 	return result;
 }
 
+static void report_set_head_auto(const char *remote, const char *head_name,
+			struct strbuf *b_local_head) {
+	struct strbuf buf_prefix = STRBUF_INIT;
+	const char *prev_head = NULL;
+
+	strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
+	skip_prefix(b_local_head->buf, buf_prefix.buf, &prev_head);
+
+	if (prev_head && !strcmp(prev_head, head_name))
+		printf(_("'%s/HEAD' is unchanged and points to '%s'\n"),
+			remote, head_name);
+	else if (prev_head)
+		printf(_("'%s/HEAD' has changed from '%s' and now points to '%s'\n"),
+			remote, prev_head, head_name);
+	else if (!b_local_head->len)
+		printf(_("'%s/HEAD' is now created and points to '%s'\n"),
+			remote, head_name);
+	else
+		printf(_("'%s/HEAD' used to point to '%s' "
+			"(which is not a remote branch), but now points to '%s'\n"),
+			remote, b_local_head->buf, head_name);
+	strbuf_release(&buf_prefix);
+}
+
 static int set_head(int argc, const char **argv, const char *prefix)
 {
 	int i, opt_a = 0, opt_d = 0, result = 0;
-	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT;
+	struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
+		b_local_head = STRBUF_INIT;
 	char *head_name = NULL;
 	struct ref_store *refs = get_main_ref_store(the_repository);
 
@@ -1445,15 +1470,17 @@ static int set_head(int argc, const char **argv, const char *prefix)
 		/* make sure it's valid */
 		if (!refs_ref_exists(refs, b_remote_head.buf))
 			result |= error(_("Not a valid ref: %s"), b_remote_head.buf);
-		else if (refs_update_symref(refs, b_head.buf, b_remote_head.buf, "remote set-head"))
+		else if (refs_update_symref_extended(refs, b_head.buf, b_remote_head.buf,
+					"remote set-head", &b_local_head))
 			result |= error(_("Could not setup %s"), b_head.buf);
 		else if (opt_a)
-			printf("%s/HEAD set to %s\n", argv[0], head_name);
+			report_set_head_auto(argv[0], head_name, &b_local_head);
 		free(head_name);
 	}
 
 	strbuf_release(&b_head);
 	strbuf_release(&b_remote_head);
+	strbuf_release(&b_local_head);
 	return result;
 }
 
t/t5505-remote.sh +50 -1

68 lines not on this page · raw message

Signature · 1 line
2.47.0.94.gb64850d498