Skip to contentSkip to conversation

implement branch --recurse-submodules

PATCH Superseded Glen Choo 5 participants 110 messages Nov 22, 2021 – Feb 4, 2022 Documentation Page 2 of 2

lore
Share & tools
lore
author
#88 lore raw

PATCH v7 2/6 branch: make create_branch() always create a branch

In reply to Glen Choo

With the previous commit, there are no more invocations of create_branch() that do not create a branch because:

* BRANCH_TRACK_OVERRIDE is no longer passed
* clobber_head_ok = true and force = false is never passed

Assert these situations, delete dead code and ensure that we're handling clobber_head_ok and force correctly by introducing tests for git branch --force. As a result, create_branch() now always creates a branch.

---
 branch.c          | 57 ++++++++++++++++++++++-------------------------
 branch.h          |  4 ++--
 t/t3200-branch.sh | 17 ++++++++++++++
 3 files changed, 46 insertions(+), 32 deletions(-)
branch.c +27 -30
index f3a31930fb..df24021f27 100644
@@ -429,15 +429,19 @@ void create_branch(struct repository *r,
 	char *real_ref;
 	struct strbuf ref = STRBUF_INIT;
 	int forcing = 0;
-	int dont_change_ref = 0;
-
-	if ((track == BRANCH_TRACK_OVERRIDE || clobber_head_ok)
-	    ? validate_branchname(name, &ref)
-	    : validate_new_branchname(name, &ref, force)) {
-		if (!force)
-			dont_change_ref = 1;
-		else
-			forcing = 1;
+	struct ref_transaction *transaction;
+	struct strbuf err = STRBUF_INIT;
+	char *msg;
+
+	if (track == BRANCH_TRACK_OVERRIDE)
+		BUG("'track' cannot be BRANCH_TRACK_OVERRIDE. Did you mean to call dwim_and_setup_tracking()?");
+	if (clobber_head_ok && !force)
+		BUG("'clobber_head_ok' can only be used with 'force'");
+
+	if (clobber_head_ok ?
+			  validate_branchname(name, &ref) :
+			  validate_new_branchname(name, &ref, force)) {
+		forcing = 1;
 	}
 
 	dwim_branch_start(r, start_name, track, &real_ref, &oid);
@@ -445,27 +449,20 @@ void create_branch(struct repository *r,
 	if (reflog)
 		log_all_ref_updates = LOG_REFS_NORMAL;
 
-	if (!dont_change_ref) {
-		struct ref_transaction *transaction;
-		struct strbuf err = STRBUF_INIT;
-		char *msg;
-
-		if (forcing)
-			msg = xstrfmt("branch: Reset to %s", start_name);
-		else
-			msg = xstrfmt("branch: Created from %s", start_name);
-
-		transaction = ref_transaction_begin(&err);
-		if (!transaction ||
-		    ref_transaction_update(transaction, ref.buf,
-					   &oid, forcing ? NULL : null_oid(),
-					   0, msg, &err) ||
-		    ref_transaction_commit(transaction, &err))
-			die("%s", err.buf);
-		ref_transaction_free(transaction);
-		strbuf_release(&err);
-		free(msg);
-	}
+	if (forcing)
+		msg = xstrfmt("branch: Reset to %s", start_name);
+	else
+		msg = xstrfmt("branch: Created from %s", start_name);
+	transaction = ref_transaction_begin(&err);
+	if (!transaction ||
+		ref_transaction_update(transaction, ref.buf,
+					&oid, forcing ? NULL : null_oid(),
+					0, msg, &err) ||
+		ref_transaction_commit(transaction, &err))
+		die("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_release(&err);
+	free(msg);
 
 	if (real_ref && track)
 		setup_tracking(ref.buf + 11, real_ref, track, quiet);
branch.h +2 -2
index ab2315c611..cf3a4d3ff3 100644
@@ -52,8 +52,8 @@ void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
  *
  *   - force enables overwriting an existing (non-head) branch
  *
- *   - clobber_head_ok allows the currently checked out (hence existing)
- *     branch to be overwritten; without 'force', it has no effect.
+ *   - clobber_head_ok, when enabled with 'force', allows the currently
+ *     checked out (head) branch to be overwritten
  *
  *   - reflog creates a reflog for the branch
  *
t/t3200-branch.sh +17 -0
index a74b2e06a1..9157382ad0 100755
@@ -42,6 +42,23 @@ test_expect_success 'git branch abc should create a branch' '
 	git branch abc && test_path_is_file .git/refs/heads/abc
 '
 
+test_expect_success 'git branch abc should fail when abc exists' '
+	test_must_fail git branch abc
+'
+
+test_expect_success 'git branch --force abc should fail when abc is checked out' '
+	test_when_finished git switch main &&
+	git switch abc &&
+	test_must_fail git branch --force abc HEAD~1
+'
+
+test_expect_success 'git branch --force abc should succeed when abc exists' '
+	git rev-parse HEAD~1 >expect &&
+	git branch --force abc HEAD~1 &&
+	git rev-parse abc >actual &&
+	test_cmp expect actual
+'
+
 test_expect_success 'git branch a/b/c should create a branch' '
 	git branch a/b/c && test_path_is_file .git/refs/heads/a/b/c
 '
Signature · 1 line
2.33.GIT
author
#89 lore raw

PATCH v7 3/6 branch: add a dry_run parameter to create_branch()

In reply to Glen Choo

Add a dry_run parameter to create_branch() such that dry_run = 1 will validate a new branch without trying to create it. This will be used in git branch --recurse-submodules to ensure that the new branch can be created in all submodules.

---
 branch.c           | 5 ++++-
 branch.h           | 5 ++++-
 builtin/branch.c   | 2 +-
 builtin/checkout.c | 3 ++-
 4 files changed, 11 insertions(+), 4 deletions(-)
branch.c +4 -1
index df24021f27..02d46a69b8 100644
@@ -423,7 +423,7 @@ static void dwim_branch_start(struct repository *r, const char *start_name,
 void create_branch(struct repository *r,
 		   const char *name, const char *start_name,
 		   int force, int clobber_head_ok, int reflog,
-		   int quiet, enum branch_track track)
+		   int quiet, enum branch_track track, int dry_run)
 {
 	struct object_id oid;
 	char *real_ref;
@@ -445,6 +445,8 @@ void create_branch(struct repository *r,
 	}
 
 	dwim_branch_start(r, start_name, track, &real_ref, &oid);
+	if (dry_run)
+		goto cleanup;
 
 	if (reflog)
 		log_all_ref_updates = LOG_REFS_NORMAL;
@@ -467,6 +469,7 @@ void create_branch(struct repository *r,
 	if (real_ref && track)
 		setup_tracking(ref.buf + 11, real_ref, track, quiet);
 
+cleanup:
 	strbuf_release(&ref);
 	free(real_ref);
 }
branch.h +4 -1
index cf3a4d3ff3..509cfcc34e 100644
@@ -62,11 +62,14 @@ void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
  *   - track causes the new branch to be configured to merge the remote branch
  *     that start_name is a tracking branch for (if any).
  *
+ *   - dry_run causes the branch to be validated but not created.
+ *
  */
 void create_branch(struct repository *r,
 		   const char *name, const char *start_name,
 		   int force, int clobber_head_ok,
-		   int reflog, int quiet, enum branch_track track);
+		   int reflog, int quiet, enum branch_track track,
+		   int dry_run);
 
 /*
  * Check if 'name' can be a valid name for a branch; die otherwise.
builtin/branch.c +1 -1
index 59768a3f67..d1e3ad6ebf 100644
@@ -858,7 +858,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 
 		create_branch(the_repository,
 			      argv[0], (argc == 2) ? argv[1] : head,
-			      force, 0, reflog, quiet, track);
+			      force, 0, reflog, quiet, track, 0);
 
 	} else
 		usage_with_options(builtin_branch_usage, options);
builtin/checkout.c +2 -1
index 8d511aa6b7..fb4323dfca 100644
@@ -893,7 +893,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 				      opts->new_branch_force ? 1 : 0,
 				      opts->new_branch_log,
 				      opts->quiet,
-				      opts->track);
+				      opts->track,
+				      0);
 		new_branch_info->name = opts->new_branch;
 		setup_branch_path(new_branch_info);
 	}
Signature · 1 line
2.33.GIT
author
#90 lore raw

PATCH v7 4/6 builtin/branch: consolidate action-picking logic in cmd_branch()

In reply to Glen Choo

Consolidate the logic for deciding when to create a new branch in cmd_branch(), and save the result for reuse. Besides making the function more explicit, this allows us to validate options that can only be used when creating a branch. Such an option does not exist yet, but one will be introduced in a subsequent commit.

---
 builtin/branch.c | 19 +++++++++++--------
 1 file changed, 11 insertions(+), 8 deletions(-)
builtin/branch.c +11 -8
index d1e3ad6ebf..c274fbdfcf 100644
@@ -616,14 +616,15 @@ static int edit_branch_description(const char *branch_name)
 
 int cmd_branch(int argc, const char **argv, const char *prefix)
 {
-	int delete = 0, rename = 0, copy = 0, force = 0, list = 0;
-	int show_current = 0;
-	int reflog = 0, edit_description = 0;
-	int quiet = 0, unset_upstream = 0;
+	/* possible actions */
+	int delete = 0, rename = 0, copy = 0, list = 0,
+	    unset_upstream = 0, show_current = 0, edit_description = 0;
 	const char *new_upstream = NULL;
+	int noncreate_actions = 0;
+	/* possible options */
+	int reflog = 0, quiet = 0, icase = 0, force = 0;
 	enum branch_track track;
 	struct ref_filter filter;
-	int icase = 0;
 	static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
 	struct ref_format format = REF_FORMAT_INIT;
 
@@ -707,8 +708,10 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 	    filter.reachable_from || filter.unreachable_from || filter.points_at.nr)
 		list = 1;
 
-	if (!!delete + !!rename + !!copy + !!new_upstream + !!show_current +
-	    list + edit_description + unset_upstream > 1)
+	noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
+			    !!show_current + !!list + !!edit_description +
+			    !!unset_upstream;
+	if (noncreate_actions > 1)
 		usage_with_options(builtin_branch_usage, options);
 
 	if (filter.abbrev == -1)
@@ -848,7 +851,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 		strbuf_addf(&buf, "branch.%s.merge", branch->name);
 		git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
 		strbuf_release(&buf);
-	} else if (argc > 0 && argc <= 2) {
+	} else if (!noncreate_actions && argc > 0 && argc <= 2) {
 		if (filter.kind != FILTER_REFS_BRANCHES)
 			die(_("The -a, and -r, options to 'git branch' do not take a branch name.\n"
 				  "Did you mean to use: -a|-r --list <pattern>?"));
Signature · 1 line
2.33.GIT
author
#91 lore raw

PATCH v7 5/6 branch: add --recurse-submodules option for branch creation

In reply to Glen Choo

To improve the submodules UX, we would like to teach Git to handle branches in submodules. Start this process by teaching "git branch" the --recurse-submodules option so that "git branch --recurse-submodules topic" will create the topic branch in the superproject and its submodules.

Although this commit does not introduce breaking changes, it is incompatible with existing --recurse-submodules commands because "git branch --recurse-submodules" writes to the submodule ref store, but most commands only consider the superproject gitlink and ignore the submodule ref store. For example, "git checkout --recurse-submodules" will check out the commits in the superproject gitlinks (and put the submodules in detached HEAD) instead of checking out the submodule branches.

Because of this, this commit introduces a new configuration value, submodule.propagateBranches. The plan is for Git commands to prioritize submodule ref store information over superproject gitlinks if this value is true. Because "git branch --recurse-submodules" writes to submodule ref stores, for the sake of clarity, it will not function unless this configuration value is set.

This commit also includes changes that support working with submodules from a superproject commit because "branch --recurse-submodules" (and future commands) need to read .gitmodules and gitlinks from the superproject commit, but submodules are typically read from the filesystem's .gitmodules and the index's gitlinks. These changes are:

* add a submodules_of_tree() helper that gives the relevant information of an in-tree submodule (e.g. path and oid) and initializes the repository
* add is_tree_submodule_active() by adding a treeish_name parameter to is_submodule_active()
* add the "submoduleNotUpdated" advice to advise users to update the submodules in their trees

Incidentally, fix an incorrect usage string that combined the 'list' usage of git branch (-l) with the 'create' usage; this string has been incorrect since its inception, a8dfd5eac4 (Make builtin-branch.c use parse_options., 2007-10-07).

---
To Jonathan: When describing the differences between "git branch" and "git checkout", I opted to emphasize the fact that "git checkout" checks out the gitlink in detached HEAD and not the branches themselves (vs your suggestion of mentioning that checkout would check out the wrong version if the branch is subsequently updated).

 Documentation/config/advice.txt    |   3 +
 Documentation/config/submodule.txt |  37 ++--
 Documentation/git-branch.txt       |  11 +-
 advice.c                           |   1 +
 advice.h                           |   1 +
 branch.c                           | 137 ++++++++++++++
 branch.h                           |  22 +++
 builtin/branch.c                   |  44 ++++-
 builtin/submodule--helper.c        |  38 ++++
 submodule-config.c                 |  60 ++++++
 submodule-config.h                 |  34 ++++
 submodule.c                        |  11 +-
 submodule.h                        |   3 +
 t/t3207-branch-submodule.sh        | 282 +++++++++++++++++++++++++++++
 14 files changed, 664 insertions(+), 20 deletions(-)
 create mode 100755 t/t3207-branch-submodule.sh
Documentation/config/advice.txt +3 -0
index 063eec2511..adee26fbbb 100644
@@ -116,6 +116,9 @@ advice.*::
 	submoduleAlternateErrorStrategyDie::
 		Advice shown when a submodule.alternateErrorStrategy option
 		configured to "die" causes a fatal error.
+	submodulesNotUpdated::
+		Advice shown when a user runs a submodule command that fails
+		because `git submodule update --init` was not run.
 	addIgnoredFile::
 		Advice shown if a user attempts to add an ignored file to
 		the index.
Documentation/config/submodule.txt +26 -11
index ee454f8126..6490527b45 100644
@@ -59,18 +59,33 @@ submodule.active::
 
 submodule.recurse::
 	A boolean indicating if commands should enable the `--recurse-submodules`
-	option by default.
-	Applies to all commands that support this option
-	(`checkout`, `fetch`, `grep`, `pull`, `push`, `read-tree`, `reset`,
-	`restore` and `switch`) except `clone` and `ls-files`.
+	option by default. Defaults to false.
++
+When set to true, it can be deactivated via the
+`--no-recurse-submodules` option. Note that some Git commands
+lacking this option may call some of the above commands affected by
+`submodule.recurse`; for instance `git remote update` will call
+`git fetch` but does not have a `--no-recurse-submodules` option.
+For these commands a workaround is to temporarily change the
+configuration value by using `git -c submodule.recurse=0`.
++
+The following list shows the commands that accept
+`--recurse-submodules` and whether they are supported by this
+setting.
+
+* `checkout`, `fetch`, `grep`, `pull`, `push`, `read-tree`,
+`reset`, `restore` and `switch` are always supported.
+* `clone` and `ls-files` are not supported.
+* `branch` is supported only if `submodule.propagateBranches` is
+enabled
+
+submodule.propagateBranches::
+	[EXPERIMENTAL] A boolean that enables branching support when
+	using `--recurse-submodules` or `submodule.recurse=true`.
+	Enabling this will allow certain commands to accept
+	`--recurse-submodules` and certain commands that already accept
+	`--recurse-submodules` will now consider branches.
 	Defaults to false.
-	When set to true, it can be deactivated via the
-	`--no-recurse-submodules` option. Note that some Git commands
-	lacking this option may call some of the above commands affected by
-	`submodule.recurse`; for instance `git remote update` will call
-	`git fetch` but does not have a `--no-recurse-submodules` option.
-	For these commands a workaround is to temporarily change the
-	configuration value by using `git -c submodule.recurse=0`.
 
 submodule.fetchJobs::
 	Specifies how many submodules are fetched/cloned at the same time.
Documentation/git-branch.txt +10 -1
index 75beea7bac..871ca3c3eb 100644
@@ -16,7 +16,8 @@ SYNOPSIS
 	[--points-at <object>] [--format=<format>]
 	[(-r | --remotes) | (-a | --all)]
 	[--list] [<pattern>...]
-'git branch' [--track [direct|inherit] | --no-track] [-f] <branchname> [<start-point>]
+'git branch' [--track [direct|inherit] | --no-track] [-f]
+	[--recurse-submodules] <branchname> [<start-point>]
 'git branch' (--set-upstream-to=<upstream> | -u <upstream>) [<branchname>]
 'git branch' --unset-upstream [<branchname>]
 'git branch' (-m | -M) [<oldbranch>] <newbranch>
@@ -235,6 +236,14 @@ how the `branch.<name>.remote` and `branch.<name>.merge` options are used.
 	Do not set up "upstream" configuration, even if the
 	branch.autoSetupMerge configuration variable is set.
 
+--recurse-submodules::
+	THIS OPTION IS EXPERIMENTAL! Causes the current command to
+	recurse into submodules if `submodule.propagateBranches` is
+	enabled. See `submodule.propagateBranches` in
+	linkgit:git-config[1].
+	+
+	Currently, only branch creation is supported.
+
 --set-upstream::
 	As this option had confusing syntax, it is no longer supported.
 	Please use `--track` or `--set-upstream-to` instead.
advice.c +1 -0
index 1dfc91d176..e00d30254c 100644
@@ -70,6 +70,7 @@ static struct {
 	[ADVICE_STATUS_HINTS]				= { "statusHints", 1 },
 	[ADVICE_STATUS_U_OPTION]			= { "statusUoption", 1 },
 	[ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE] = { "submoduleAlternateErrorStrategyDie", 1 },
+	[ADVICE_SUBMODULES_NOT_UPDATED] 		= { "submodulesNotUpdated", 1 },
 	[ADVICE_UPDATE_SPARSE_PATH]			= { "updateSparsePath", 1 },
 	[ADVICE_WAITING_FOR_EDITOR]			= { "waitingForEditor", 1 },
 };
advice.h +1 -0
index 601265fd10..a7521d6087 100644
@@ -44,6 +44,7 @@ struct string_list;
 	ADVICE_STATUS_HINTS,
 	ADVICE_STATUS_U_OPTION,
 	ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE,
+	ADVICE_SUBMODULES_NOT_UPDATED,
 	ADVICE_UPDATE_SPARSE_PATH,
 	ADVICE_WAITING_FOR_EDITOR,
 	ADVICE_SKIPPED_CHERRY_PICKS,
branch.c +137 -0

149 lines not on this page · raw message

branch.h +22 -0
index 509cfcc34e..a59905a211 100644
@@ -71,6 +71,28 @@ void create_branch(struct repository *r,
 		   int reflog, int quiet, enum branch_track track,
 		   int dry_run);
 
+/*
+ * Creates a new branch in repository and its submodules (and its
+ * submodules, recursively). Besides these exceptions, the parameters
+ * function identically to create_branch():
+ *
+ * - start_name is the name of the ref, in repository r, that the new
+ *   branch should start from. In submodules, branches will start from
+ *   the respective gitlink commit ids in start_name's tree.
+ *
+ * - tracking_name is the name used of the ref that will be used to set
+ *   up tracking, e.g. origin/main. This is propagated to submodules so
+ *   that tracking information will appear as if the branch branched off
+ *   tracking_name instead of start_name (which is a plain commit id for
+ *   submodules). If omitted, start_name is used for tracking (just like
+ *   create_branch()).
+ *
+ */
+void create_branches_recursively(struct repository *r, const char *name,
+				 const char *start_name,
+				 const char *tracking_name, int force,
+				 int reflog, int quiet, enum branch_track track,
+				 int dry_run);
 /*
  * Check if 'name' can be a valid name for a branch; die otherwise.
  * Return 1 if the named branch already exists; return 0 otherwise.
builtin/branch.c +38 -6

92 lines not on this page · raw message

builtin/submodule--helper.c +38 -0
index 6298cbdd4e..eba2a6e9b0 100644
@@ -20,6 +20,7 @@
 #include "diff.h"
 #include "object-store.h"
 #include "advice.h"
+#include "branch.h"
 
 #define OPT_QUIET (1 << 0)
 #define OPT_CACHED (1 << 1)
@@ -2983,6 +2984,42 @@ static int module_set_branch(int argc, const char **argv, const char *prefix)
 	return !!ret;
 }
 
+static int module_create_branch(int argc, const char **argv, const char *prefix)
+{
+	enum branch_track track;
+	int quiet = 0, force = 0, reflog = 0, dry_run = 0;
+
+	struct option options[] = {
+		OPT__QUIET(&quiet, N_("print only error messages")),
+		OPT__FORCE(&force, N_("force creation"), 0),
+		OPT_BOOL(0, "create-reflog", &reflog,
+			 N_("create the branch's reflog")),
+		OPT_SET_INT('t', "track", &track,
+			    N_("set up tracking mode (see git-pull(1))"),
+			    BRANCH_TRACK_EXPLICIT),
+		OPT__DRY_RUN(&dry_run,
+			     N_("show whether the branch would be created")),
+		OPT_END()
+	};
+	const char *const usage[] = {
+		N_("git submodule--helper create-branch [-f|--force] [--create-reflog] [-q|--quiet] [-t|--track] [-n|--dry-run] <name> <start_oid> <start_name>"),
+		NULL
+	};
+
+	git_config(git_default_config, NULL);
+	track = git_branch_track;
+	argc = parse_options(argc, argv, prefix, options, usage, 0);
+
+	if (argc != 3)
+		usage_with_options(usage, options);
+
+	if (!quiet && !dry_run)
+		printf_ln(_("creating branch '%s'"), argv[0]);
+
+	create_branches_recursively(the_repository, argv[0], argv[1], argv[2],
+				    force, reflog, quiet, track, dry_run);
+	return 0;
+}
 struct add_data {
 	const char *prefix;
 	const char *branch;
@@ -3379,6 +3416,7 @@ static struct cmd_struct commands[] = {
 	{"config", module_config, 0},
 	{"set-url", module_set_url, 0},
 	{"set-branch", module_set_branch, 0},
+	{"create-branch", module_create_branch, 0},
 };
 
 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
submodule-config.c +60 -0

72 lines not on this page · raw message

submodule-config.h +34 -0
index 65875b94ea..fa229a8b97 100644
@@ -6,6 +6,7 @@
 #include "hashmap.h"
 #include "submodule.h"
 #include "strbuf.h"
+#include "tree-walk.h"
 
 /**
  * The submodule config cache API allows to read submodule
@@ -101,4 +102,37 @@ int check_submodule_name(const char *name);
 void fetch_config_from_gitmodules(int *max_children, int *recurse_submodules);
 void update_clone_config_from_gitmodules(int *max_jobs);
 
+/*
+ * Submodule entry that contains relevant information about a
+ * submodule in a tree.
+ */
+struct submodule_tree_entry {
+	/* The submodule's tree entry. */
+	struct name_entry *name_entry;
+	/*
+	 * A struct repository corresponding to the submodule. May be
+	 * NULL if the submodule has not been updated.
+	 */
+	struct repository *repo;
+	/*
+	 * A struct submodule containing the submodule config in the
+	 * tree's .gitmodules.
+	 */
+	const struct submodule *submodule;
+};
+
+struct submodule_entry_list {
+	struct submodule_tree_entry *entries;
+	int entry_nr;
+	int entry_alloc;
+};
+
+/**
+ * Given a treeish, return all submodules in the tree and its subtrees,
+ * but excluding nested submodules. Callers that require nested
+ * submodules are expected to recurse into the submodules themselves.
+ */
+void submodules_of_tree(struct repository *r,
+			const struct object_id *treeish_name,
+			struct submodule_entry_list *ret);
 #endif /* SUBMODULE_CONFIG_H */
submodule.c +9 -2
index f3c99634a9..07ae7c266e 100644
@@ -265,7 +265,9 @@ int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
  * ie, the config looks like: "[submodule] active\n".
  * Since that is an invalid pathspec, we should inform the user.
  */
-int is_submodule_active(struct repository *repo, const char *path)
+int is_tree_submodule_active(struct repository *repo,
+			     const struct object_id *treeish_name,
+			     const char *path)
 {
 	int ret = 0;
 	char *key = NULL;
@@ -273,7 +275,7 @@ int is_submodule_active(struct repository *repo, const char *path)
 	const struct string_list *sl;
 	const struct submodule *module;
 
-	module = submodule_from_path(repo, null_oid(), path);
+	module = submodule_from_path(repo, treeish_name, path);
 
 	/* early return if there isn't a path->module mapping */
 	if (!module)
@@ -315,6 +317,11 @@ int is_submodule_active(struct repository *repo, const char *path)
 	return ret;
 }
 
+int is_submodule_active(struct repository *repo, const char *path)
+{
+	return is_tree_submodule_active(repo, null_oid(), path);
+}
+
 int is_submodule_populated_gently(const char *path, int *return_error_code)
 {
 	int ret = 0;
submodule.h +3 -0
index 6bd2c99fd9..784ceffc0e 100644
@@ -54,6 +54,9 @@ int git_default_submodule_config(const char *var, const char *value, void *cb);
 struct option;
 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
 						     const char *arg, int unset);
+int is_tree_submodule_active(struct repository *repo,
+			     const struct object_id *treeish_name,
+			     const char *path);
 int is_submodule_active(struct repository *repo, const char *path);
 /*
  * Determine if a submodule has been populated at a given 'path' by checking if
t/t3207-branch-submodule.sh new file +282 -0

282 lines not on this page · raw message

Signature · 1 line
2.33.GIT
#92 lore raw

Re: [PATCH v7 5/6] branch: add --recurse-submodules option for branch creation

Patches up to this one look good, and the implementation looks good too. I just have minor comments on some of the text and tests.

Quoted 7 lines · Glen Choo

Although this commit does not introduce breaking changes, it is incompatible with existing --recurse-submodules commands because "git branch --recurse-submodules" writes to the submodule ref store, but most commands only consider the superproject gitlink and ignore the submodule ref store. For example, "git checkout --recurse-submodules" will check out the commits in the superproject gitlinks (and put the submodules in detached HEAD) instead of checking out the submodule branches.

The usual meaning of "incompatible" is "cannot be used together", I think, which is not what's happening here - it's just that the user would expect them to work together in a specific way but they don't do that.

Quoted 5 lines

To Jonathan: When describing the differences between "git branch" and "git checkout", I opted to emphasize the fact that "git checkout" checks out the gitlink in detached HEAD and not the branches themselves (vs your suggestion of mentioning that checkout would check out the wrong version if the branch is subsequently updated).

OK - makes sense.

Quoted 6 lines

+/**
+ * Creates a branch in a submodule by calling
+ * create_branches_recursively() in a child process. The child process
+ * is necessary because install_branch_config_multiple_remotes() (which
+ * is called by setup_tracking()) does not support writing configs to
+ * submodules.

OK, good explanation for why a child process is needed.

Quoted 13 lines

+ */

branch.c +12 -0
+static int submodule_create_branch(struct repository *r,
+				   const struct submodule *submodule,
+				   const char *name, const char *start_oid,
+				   const char *start_name, int force,
+				   int reflog, int quiet,
+				   enum branch_track track, int dry_run)
+{
+	int ret = 0;
+	struct child_process child = CHILD_PROCESS_INIT;
+	struct strbuf child_err = STRBUF_INIT;
+	struct strbuf out_buf = STRBUF_INIT;
+	char *out_prefix = xstrfmt("submodule '%s': ", submodule->name);

branch.c void dwim_and_setup_tracking(struct repository *r, const char *new_ref, · line 516

Quoted 10 lines
branch.c +10 -0
+	child.git_cmd = 1;
+	child.err = -1;
+	child.stdout_to_stderr = 1;
+
+	prepare_other_repo_env(&child.env_array, r->gitdir);
+	/*
+	 * submodule_create_branch() is indirectly invoked by "git
+	 * branch", but we cannot invoke "git branch" in the child
+	 * process because it does not let us set start_name and
+	 * start_oid separately (see create_branches_recursively()).

Probably clearer to enumerate the 3 different pieces of information
needed: the name of the branch to be created, the OID, and the name of the branch that would be used for tracking purposes.

An argument could be made that "git branch" should be extended to be able to take in these 3 different pieces of information, but it also makes sense to put this functionality in submodule--helper for now, since the whole thing is marked as experimental.

Quoted 12 lines
branch.h +12 -0
+/*
+ * Creates a new branch in repository and its submodules (and its
+ * submodules, recursively). Besides these exceptions, the parameters
+ * function identically to create_branch():
+ *
+ * - start_name is the name of the ref, in repository r, that the new
+ *   branch should start from. In submodules, branches will start from
+ *   the respective gitlink commit ids in start_name's tree.
+ *
+ * - tracking_name is the name used of the ref that will be used to set
+ *   up tracking, e.g. origin/main. This is propagated to submodules so
+ *   that tracking information will appear as if the branch branched off

branch.h void create_branch(struct repository *r, · line 95

Quoted 10 lines
branch.h +10 -0
+ *   tracking_name instead of start_name (which is a plain commit id for
+ *   submodules). If omitted, start_name is used for tracking (just like
+ *   create_branch()).
+ *
+ */
+void create_branches_recursively(struct repository *r, const char *name,
+				 const char *start_name,
+				 const char *tracking_name, int force,
+				 int reflog, int quiet, enum branch_track track,
+				 int dry_run);

Instead of taking in "name", "start_name", and "tracking_name", could we take in "name", "oid", and "tracking_name"? That way, it's clearer what each parameter is used for.

t/t3207-branch-submodule.sh line 178

Quoted 10 lines
t/t3207-branch-submodule.sh new file +10 -0
+test_expect_success 'should not create branches in inactive submodules' '
+	test_when_finished "reset_test" &&
+	test_config -C super submodule.sub.active false &&
+	(
+		cd super &&
+		git branch --recurse-submodules branch-a &&
+		git rev-parse branch-a &&
+		test_must_fail git -C sub branch-a
+	)
+'

The "test_must_fail" line doesn't make sense - there is no such command branch-a. To avoid errors like this, maybe make sure that all test_must_fail invocations are accompanied by assertions on the error message. (And for "test_must_fail git rev-parse", we could have a helper function here that asserts the "object not found".)

t/t3207-branch-submodule.sh line 189

Quoted 10 lines
t/t3207-branch-submodule.sh new file +10 -0
+test_expect_success 'should set up tracking of local branches with track=always' '
+	test_when_finished "reset_test" &&
+	(
+		cd super &&
+		git -c branch.autoSetupMerge=always branch --recurse-submodules branch-a main &&
+		git -C sub rev-parse main &&
+		test "$(git -C sub config branch.branch-a.remote)" = . &&
+		test "$(git -C sub config branch.branch-a.merge)" = refs/heads/main
+	)
+'

As described in t/README line 671, this means that the inner command could silently fail. You can do REMOTE=$(...) && <newline> test .... Same comment throughout this file.

author
#93 lore raw

Re: [PATCH v7 5/6] branch: add --recurse-submodules option for branch creation

Quoted 8 lines · Jonathan Tan
Quoted 7 lines

Although this commit does not introduce breaking changes, it is incompatible with existing --recurse-submodules commands because "git branch --recurse-submodules" writes to the submodule ref store, but most commands only consider the superproject gitlink and ignore the submodule ref store. For example, "git checkout --recurse-submodules" will check out the commits in the superproject gitlinks (and put the submodules in detached HEAD) instead of checking out the submodule branches.

Quoted 4 lines

The usual meaning of "incompatible" is "cannot be used together", I think, which is not what's happening here - it's just that the user would expect them to work together in a specific way but they don't do that.

Ok, I'll replace "incompatible with" with "does not interact well with".

Quoted 19 lines
Quoted 19 lines

+ */

branch.c +18 -0
+static int submodule_create_branch(struct repository *r,
+				   const struct submodule *submodule,
+				   const char *name, const char *start_oid,
+				   const char *start_name, int force,
+				   int reflog, int quiet,
+				   enum branch_track track, int dry_run)
+{
+	int ret = 0;
+	struct child_process child = CHILD_PROCESS_INIT;
+	struct strbuf child_err = STRBUF_INIT;
+	struct strbuf out_buf = STRBUF_INIT;
+	char *out_prefix = xstrfmt("submodule '%s': ", submodule->name);
+	child.git_cmd = 1;
+	child.err = -1;
+	child.stdout_to_stderr = 1;
+
+	prepare_other_repo_env(&child.env_array, r->gitdir);
+	/*
Quoted 8 lines

branch.c void dwim_and_setup_tracking(struct repository *r, const char *new_ref, · line 516

Quoted 4 lines
branch.c +4 -0
+	 * submodule_create_branch() is indirectly invoked by "git
+	 * branch", but we cannot invoke "git branch" in the child
+	 * process because it does not let us set start_name and
+	 * start_oid separately (see create_branches_recursively()).

Probably clearer to enumerate the 3 different pieces of information
needed: the name of the branch to be created, the OID, and the name of the branch that would be used for tracking purposes.

Makes sense. Also the comment on create_branches_recursively() doesn't do a great job of explaining why we need the additional piece of information (tracking name), so I'll tidy them up together.

Quoted 4 lines

An argument could be made that "git branch" should be extended to be able to take in these 3 different pieces of information, but it also makes sense to put this functionality in submodule--helper for now, since the whole thing is marked as experimental.

Yes, I considered this, but I can't think of a good reason to expose this functionality to users - users can set their upstream with the more intuitive "git branch --set-upstream-to".

Quoted 18 lines
Quoted 18 lines
branch.h +18 -0
+/*
+ * Creates a new branch in repository and its submodules (and its
+ * submodules, recursively). Besides these exceptions, the parameters
+ * function identically to create_branch():
+ *
+ * - start_name is the name of the ref, in repository r, that the new
+ *   branch should start from. In submodules, branches will start from
+ *   the respective gitlink commit ids in start_name's tree.
+ *
+ * - tracking_name is the name used of the ref that will be used to set
+ *   up tracking, e.g. origin/main. This is propagated to submodules so
+ *   that tracking information will appear as if the branch branched off
+ *   tracking_name instead of start_name (which is a plain commit id for
+ *   submodules). If omitted, start_name is used for tracking (just like
+ *   create_branch()).
+ *
+ */
+void create_branches_recursively(struct repository *r, const char *name,
Quoted 8 lines

branch.h void create_branch(struct repository *r, · line 95

Quoted 4 lines
branch.h +4 -0
+				 const char *start_name,
+				 const char *tracking_name, int force,
+				 int reflog, int quiet, enum branch_track track,
+				 int dry_run);

Instead of taking in "name", "start_name", and "tracking_name", could we take in "name", "oid", and "tracking_name"? That way, it's clearer what each parameter is used for.

I used start_name to mirror create_branches(), but start_name makes less sense here because it's ambiguous.

Since the start_name is always an oid or NULL, this makes sense. I'll do this.

Quoted 8 lines
Quoted 8 lines
t/t3207-branch-submodule.sh new file +8 -0
+test_expect_success 'should not create branches in inactive submodules' '
+	test_when_finished "reset_test" &&
+	test_config -C super submodule.sub.active false &&
+	(
+		cd super &&
+		git branch --recurse-submodules branch-a &&
+		git rev-parse branch-a &&
+		test_must_fail git -C sub branch-a
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+	)
+'

The "test_must_fail" line doesn't make sense - there is no such command branch-a. To avoid errors like this, maybe make sure that all test_must_fail invocations are accompanied by assertions on the error message. (And for "test_must_fail git rev-parse", we could have a helper function here that asserts the "object not found".)

Ah good catch. I'll make the test helper.

Quoted 15 lines

t/t3207-branch-submodule.sh line 189

Quoted 11 lines
t/t3207-branch-submodule.sh new file +10 -0
+test_expect_success 'should set up tracking of local branches with track=always' '
+	test_when_finished "reset_test" &&
+	(
+		cd super &&
+		git -c branch.autoSetupMerge=always branch --recurse-submodules branch-a main &&
+		git -C sub rev-parse main &&
+		test "$(git -C sub config branch.branch-a.remote)" = . &&
+		test "$(git -C sub config branch.branch-a.merge)" = refs/heads/main
+	)
+'

As described in t/README line 671, this means that the inner command could silently fail. You can do REMOTE=$(...) && <newline> test .... Same comment throughout this file.

Thanks for the catch and double thanks for the recommended fix.

Will reroll soon.

author
#94 lore raw

Re: [PATCH v7 5/6] branch: add --recurse-submodules option for branch creation

Quoted 29 lines · Glen Choo
Quoted 18 lines · Jonathan Tan
Quoted 18 lines
branch.h +18 -0
+/*
+ * Creates a new branch in repository and its submodules (and its
+ * submodules, recursively). Besides these exceptions, the parameters
+ * function identically to create_branch():
+ *
+ * - start_name is the name of the ref, in repository r, that the new
+ *   branch should start from. In submodules, branches will start from
+ *   the respective gitlink commit ids in start_name's tree.
+ *
+ * - tracking_name is the name used of the ref that will be used to set
+ *   up tracking, e.g. origin/main. This is propagated to submodules so
+ *   that tracking information will appear as if the branch branched off
+ *   tracking_name instead of start_name (which is a plain commit id for
+ *   submodules). If omitted, start_name is used for tracking (just like
+ *   create_branch()).
+ *
+ */
+void create_branches_recursively(struct repository *r, const char *name,
Quoted 8 lines

branch.h void create_branch(struct repository *r, · line 95

Quoted 4 lines
branch.h +4 -0
+				 const char *start_name,
+				 const char *tracking_name, int force,
+				 int reflog, int quiet, enum branch_track track,
+				 int dry_run);

Instead of taking in "name", "start_name", and "tracking_name", could we take in "name", "oid", and "tracking_name"? That way, it's clearer what each parameter is used for.

Quoted 5 lines

I used start_name to mirror create_branches(), but start_name makes less sense here because it's ambiguous.

Since the start_name is always an oid or NULL, this makes sense. I'll do this.

Rereading the code, I realise that start_name isn't guaranteed to be an oid or NULL. When create_branches_recursively() is called at the root level i.e. cmd_branch(), start_name is a user-given revision which may or may not be an object id. In that scenario, tracking_name is NULL to indicate that we would like to track start_name.

I can still pass only oids, but that would require parsing the revision in cmd_branch() itself, and that seems like a violation of the layering we have set up.

Instead, I'll try to find an accurate, but more descriptive name than start_name.

author
#95 lore raw

PATCH v7 6/6 branch.c: use 'goto cleanup' in setup_tracking() to fix memory leaks

In reply to Glen Choo
---
 branch.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
branch.c +3 -2
index be33fe09fa..1e9a585633 100644
@@ -239,7 +239,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (track != BRANCH_TRACK_INHERIT)
 		for_each_remote(find_tracked_branch, &tracking);
 	else if (inherit_tracking(&tracking, orig_ref))
-		return;
+		goto cleanup;
 
 	if (!tracking.matches)
 		switch (track) {
@@ -249,7 +249,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 		case BRANCH_TRACK_INHERIT:
 			break;
 		default:
-			return;
+			goto cleanup;
 		}
 
 	if (tracking.matches > 1)
@@ -262,6 +262,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 				tracking.remote, tracking.srcs) < 0)
 		exit(-1);
 
+cleanup:
 	string_list_clear(tracking.srcs, 0);
 }
 
Signature · 1 line
2.33.GIT
#96 lore raw

Re: [PATCH v7 6/6] branch.c: use 'goto cleanup' in setup_tracking() to fix memory leaks

Quoted 28 lines · Glen Choo
---
 branch.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
branch.c +2 -2
index be33fe09fa..1e9a585633 100644
@@ -239,7 +239,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (track != BRANCH_TRACK_INHERIT)
 		for_each_remote(find_tracked_branch, &tracking);
 	else if (inherit_tracking(&tracking, orig_ref))
-		return;
+		goto cleanup;
 
 	if (!tracking.matches)
 		switch (track) {
@@ -249,7 +249,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 		case BRANCH_TRACK_INHERIT:
 			break;
 		default:
-			return;
+			goto cleanup;
 		}
 
 	if (tracking.matches > 1)

branch.c static void setup_tracking(const char *new_ref, const char *orig_ref, · line 266

Quoted 5 lines
branch.c +1 -0
@@ -262,6 +262,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 				tracking.remote, tracking.srcs) < 0)
 		exit(-1);
 
+cleanup:
 	string_list_clear(tracking.srcs, 0);

Makes sense. There is no other exit paths out of the function after the tracking_srcs variable gets initialized, so this should be covering everything.

Two tangential findings:

* I see exit(-1) in the precontext of the final hunk. We probably would want to fix it, as negative argument to exit(3) is misleading (the standard makes it clear that only the least significant 8 bits matter, so it is not that bad).

* At the end, what is cleared is tracking.srcs, but because it is a pointer to the real resource we allocated on our stack, it would be cleaner to pass &tracking_srcs instead.

Both are not what this patch introduces, and are outside the scope of this series.

Thanks.

author
#97 lore raw

Re: [PATCH v7 6/6] branch.c: use 'goto cleanup' in setup_tracking() to fix memory leaks

Quoted 40 lines · Junio C Hamano
Quoted 28 lines · Glen Choo
---
 branch.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
branch.c +2 -2
index be33fe09fa..1e9a585633 100644
@@ -239,7 +239,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (track != BRANCH_TRACK_INHERIT)
 		for_each_remote(find_tracked_branch, &tracking);
 	else if (inherit_tracking(&tracking, orig_ref))
-		return;
+		goto cleanup;
 
 	if (!tracking.matches)
 		switch (track) {
@@ -249,7 +249,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 		case BRANCH_TRACK_INHERIT:
 			break;
 		default:
-			return;
+			goto cleanup;
 		}
 
 	if (tracking.matches > 1)

branch.c static void setup_tracking(const char *new_ref, const char *orig_ref, · line 266

Quoted 5 lines
branch.c +1 -0
@@ -262,6 +262,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 				tracking.remote, tracking.srcs) < 0)
 		exit(-1);
 
+cleanup:
 	string_list_clear(tracking.srcs, 0);

Makes sense. There is no other exit paths out of the function after the tracking_srcs variable gets initialized, so this should be covering everything.

Quoted 6 lines

Two tangential findings:

* I see exit(-1) in the precontext of the final hunk. We probably would want to fix it, as negative argument to exit(3) is misleading (the standard makes it clear that only the least significant 8 bits matter, so it is not that bad).

Thanks for the reminder. We had this discussion previously and the conclusion was that I would send this cleanup as a separate series [1]. Unlike this relatively obvious cleanup, I think exit codes might spark a more involved discussion.

Quoted 4 lines

* At the end, what is cleared is tracking.srcs, but because it is a pointer to the real resource we allocated on our stack, it would be cleaner to pass &tracking_srcs instead.

Ah yes, that is true. I'll do that. If you (or others) prefer, I can move this patch to its own series, or possibly as part of a grab bag with the exit code fix.

Quoted 5 lines

Both are not what this patch introduces, and are outside the scope of this series.

Thanks.

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

author
#98 lore raw

v8 cover implement branch --recurse-submodules

In reply to Glen Choo

Thanks again for the feedback, Jonathan!

This version is rebased onto the updated js/branch-track-inherit, from 44f14a9d24 (config: require lowercase for branch.*.autosetupmerge, 2021-12-20) to 6327f0efed (branch,checkout: fix --track documentation, 2022-01-20). As such, the range-diff for patch 5 shows some additional changes in the usage string lines.

Junio spotted some issues in the context that are worth fixing, but out of scope for this series (https://lore.kernel.org/git/[email protected]). I plan to send fixes for them after this series is merged. Patch 6 arguably fits in better with that fixup series than this one, but I'll leave the decision to keep/drop it to Junio.

= Description

This series implements "git branch --recurse-submodules", which is part of the submodule branching RFC (see "See also"). "git branch" (and some other features in that RFC) are incompatible with existing "--recurse-submodules" commands; patch 5 describes this incompatibility in more detail and how we plan to introduce this new functionality in a manner.

This series is based off js/branch-track-inherit.

Patches 1-4 are preparation for the implementation of "branch --recurse-submodules" in patch 5. Patch 6 cleans up a memory leak that I encountered on js/branch-track-inherit as I was moving code around; it isn't neeeded by "branch --recurse-submodules".

See the previous cover letter
(https://lore.kernel.org/git/[email protected])
for discussions of future work.

= See also

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

Original Submodule UX RFC/Discussion:
https://lore.kernel.org/git/[email protected]/

Contributor Summit submodules Notes:
https://lore.kernel.org/git/[email protected]/

Submodule UX overhaul updates:
https://lore.kernel.org/git/?q=Submodule+UX+overhaul+update

= Changes

Changes since v7:
* Reword patch 5's commit message
* In comments and Documentation/git-branch.txt, clarify how branch --recurse-submodules behaves and rename a parameter to better reflect this behavior
* In t3207, always assert on error messages when using test_must_fail
* In t3207, assert on config values using test_cmp_config. This avoids the silent failures discouraged by t/README:671.
* In patch 6, be more explicit about freeing the stack-allocated variable.

Changes since v6:
* Move memory leak fix into its own patch (patch 6)
* Eliminate unnecessary rewrapping and small style fixes
* In branch --recurse-submodules tests, setup test repo anew instead of deleting the unused branches
* Numerous commit message wording changes

Changes since v5:
* Rebase onto v7 of js/branch-track-inherit
(https://lore.kernel.org/git/[email protected])

Changes since v4:
* Rebase correctly onto 'gitster/seen^{/^Merge branch .js/branch-track-inherit.}' (see base-commit) as suggested in [1] (thanks Junio!)
* These patches were also verified on top of 'next'.

Changes since v3:
* Split up the old patch 1. Patch 1 had a big diff because it used to move lines, remove dead code and introduce repo_* functions (thanks Jonathan!)
** repo_* functions have been dropped; they added noise and are not
necessary for correctness.
* Use a new, harder-to-misuse function in --set-upstream-to, dwim_and_setup_tracking(). Now, setup_tracking() never does DWIM and dwim_and_setup_tracking() always does DWIM.
* Move create_branch() dry_run to its own patch.
* Fix an oversight where submodules in subtrees were ignored. This was because submodules_of_tree() and tree_entry() didn't recurse into subtrees. Test this accordingly (thanks Jonathan!).
* cmd_branch() possible actions are more consistently ordered.
* Documentation fixes (thanks Philippe!).
* Additional comments and explanation.
* Drop patch 5 (optional cleanup).
* Rebase onto js/branch-track-inherit v6.

Changes since v2:
* Rebase onto js/branch-track-inherit. This series should continue to be the case going forward.
* Patch 1 has a smaller diff because the introduction of validate_branch_start() no longer changes the function order thanks to a forward declaration. This artificial forward declaration is removed in a patch 2 (which can just be squashed into patch 1).
* Optional cleanup: fix questionable exit codes in patch 5.

Changes since v1:
* Move the functionality of "git branch --dry-run" into "git submodule-helper create-branch --dry-run"
* Add more fields to the submodules_of_tree() struct to reduce the
number of allocations made by the caller. Move this functionality
to patch 3 (formerly patch 4) and drop patch 1.
* Make submodules_of_tree() ignore inactive submodules
* Structure the output of the submodules a bit better by adding prefixes
to the child process' output (instead of inconsistently indenting the
output).
** I wasn't able to find a good way to interleave stdout/stderr
correctly, so a less-than-desirable workaround was to route the child
process output to stdout/stderr depending on the exit code.
** Eventually, I would like to structure the output of submodules in a
report, as Ævar suggested. But at this stage, I think that it's
better to spend time getting user feedback on the submodules
branching UX and it'll be easier to standardize the output when we've
implemented more of the UX :)

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

Glen Choo (6):
branch: move --set-upstream-to behavior to dwim_and_setup_tracking()
branch: make create_branch() always create a branch
branch: add a dry_run parameter to create_branch() builtin/branch: consolidate action-picking logic in cmd_branch()
branch: add --recurse-submodules option for branch creation branch.c: use 'goto cleanup' in setup_tracking() to fix memory leaks

 Documentation/config/advice.txt    |   3 +
 Documentation/config/submodule.txt |  37 ++--
 Documentation/git-branch.txt       |  19 +-
 advice.c                           |   1 +
 advice.h                           |   1 +
 branch.c                           | 277 ++++++++++++++++++++++-----
 branch.h                           |  60 +++++-
 builtin/branch.c                   |  70 +++++--
 builtin/checkout.c                 |   3 +-
 builtin/submodule--helper.c        |  38 ++++
 submodule-config.c                 |  60 ++++++
 submodule-config.h                 |  34 ++++
 submodule.c                        |  11 +-
 submodule.h                        |   3 +
 t/t3200-branch.sh                  |  17 ++
 t/t3207-branch-submodule.sh        | 292 +++++++++++++++++++++++++++++
 16 files changed, 845 insertions(+), 81 deletions(-)
 create mode 100755 t/t3207-branch-submodule.sh

Range-diff against v7:

1:  206175cfb3 = 1:  547055d55e branch: move --set-upstream-to behavior to dwim_and_setup_tracking()
2:  2e02885eb3 = 2:  016f62681d branch: make create_branch() always create a branch
3:  cd43a9aaaa = 3:  a459a030f6 branch: add a dry_run parameter to create_branch()
4:  8e5f750162 = 4:  4903f8eb4b builtin/branch: consolidate action-picking logic in cmd_branch()
5:  c59de1fd9c ! 5:  b95b77b7c1 branch: add --recurse-submodules option for branch creation
    @@ Commit message
         topic" will create the `topic` branch in the superproject and its
         submodules.
     
    -    Although this commit does not introduce breaking changes, it is
    -    incompatible with existing --recurse-submodules commands because "git
    +    Although this commit does not introduce breaking changes, it does not
    +    work well with existing --recurse-submodules commands because "git
         branch --recurse-submodules" writes to the submodule ref store, but most
         commands only consider the superproject gitlink and ignore the submodule
         ref store. For example, "git checkout --recurse-submodules" will check
    @@ Documentation/git-branch.txt: SYNOPSIS
      	[--points-at <object>] [--format=<format>]
      	[(-r | --remotes) | (-a | --all)]
      	[--list] [<pattern>...]
    --'git branch' [--track [direct|inherit] | --no-track] [-f] <branchname> [<start-point>]
    -+'git branch' [--track [direct|inherit] | --no-track] [-f]
    +-'git branch' [--track[=(direct|inherit)] | --no-track] [-f] <branchname> [<start-point>]
    ++'git branch' [--track[=(direct|inherit)] | --no-track] [-f]
     +	[--recurse-submodules] <branchname> [<start-point>]
      'git branch' (--set-upstream-to=<upstream> | -u <upstream>) [<branchname>]
      'git branch' --unset-upstream [<branchname>]
    @@ Documentation/git-branch.txt: how the `branch.<name>.remote` and `branch.<name>.
     +	THIS OPTION IS EXPERIMENTAL! Causes the current command to
     +	recurse into submodules if `submodule.propagateBranches` is
     +	enabled. See `submodule.propagateBranches` in
    -+	linkgit:git-config[1].
    -+	+
    -+	Currently, only branch creation is supported.
    ++	linkgit:git-config[1]. Currently, only branch creation is
    ++	supported.
    +++
    ++When used in branch creation, a new branch <branchname> will be created
    ++in the superproject and all of the submodules in the superproject's
    ++<start-point>. In submodules, the branch will point to the submodule
    ++commit in the superproject's <start-point> but the branch's tracking
    ++information will be set up based on the submodule's branches and remotes
    ++e.g. `git branch --recurse-submodules topic origin/main` will create the
    ++submodule branch "topic" that points to the submodule commit in the
    ++superproject's "origin/main", but tracks the submodule's "origin/main".
     +
      --set-upstream::
      	As this option had confusing syntax, it is no longer supported.
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +static int submodule_create_branch(struct repository *r,
     +				   const struct submodule *submodule,
     +				   const char *name, const char *start_oid,
    -+				   const char *start_name, int force,
    ++				   const char *tracking_name, int force,
     +				   int reflog, int quiet,
     +				   enum branch_track track, int dry_run)
     +{
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +	/*
     +	 * submodule_create_branch() is indirectly invoked by "git
     +	 * branch", but we cannot invoke "git branch" in the child
    -+	 * process because it does not let us set start_name and
    -+	 * start_oid separately (see create_branches_recursively()).
    ++	 * process. "git branch" accepts a branch name and start point,
    ++	 * where the start point is assumed to provide both the OID
    ++	 * (start_oid) and the branch to use for tracking
    ++	 * (tracking_name). But when recursing through submodules,
    ++	 * start_oid and tracking name need to be specified separately
    ++	 * (see create_branches_recursively()).
     +	 */
     +	strvec_pushl(&child.args, "submodule--helper", "create-branch", NULL);
     +	if (dry_run)
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +	if (track == BRANCH_TRACK_ALWAYS || track == BRANCH_TRACK_EXPLICIT)
     +		strvec_push(&child.args, "--track");
     +
    -+	strvec_pushl(&child.args, name, start_oid, start_name, NULL);
    ++	strvec_pushl(&child.args, name, start_oid, tracking_name, NULL);
     +
     +	if ((ret = start_command(&child)))
     +		return ret;
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +}
     +
     +void create_branches_recursively(struct repository *r, const char *name,
    -+				 const char *start_name,
    ++				 const char *start_commitish,
     +				 const char *tracking_name, int force,
     +				 int reflog, int quiet, enum branch_track track,
     +				 int dry_run)
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +	struct object_id super_oid;
     +	struct submodule_entry_list submodule_entry_list;
     +
    -+	/* Perform dwim on start_name to get super_oid and branch_point. */
    -+	dwim_branch_start(r, start_name, BRANCH_TRACK_NEVER, &branch_point,
    -+			  &super_oid);
    ++	/* Perform dwim on start_commitish to get super_oid and branch_point. */
    ++	dwim_branch_start(r, start_commitish, BRANCH_TRACK_NEVER,
    ++			  &branch_point, &super_oid);
     +
     +	/*
     +	 * If we were not given an explicit name to track, then assume we are at
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +		if (submodule_entry_list.entries[i].repo == NULL) {
     +			if (advice_enabled(ADVICE_SUBMODULES_NOT_UPDATED))
     +				advise(_("You may try updating the submodules using 'git checkout %s && git submodule update --init'"),
    -+				       start_name);
    ++				       start_commitish);
     +			die(_("submodule '%s': unable to find submodule"),
     +			    submodule_entry_list.entries[i].submodule->name);
     +		}
    @@ branch.c: void dwim_and_setup_tracking(struct repository *r, const char *new_ref
     +			    name);
     +	}
     +
    -+	create_branch(the_repository, name, start_name, force, 0, reflog, quiet,
    ++	create_branch(the_repository, name, start_commitish, force, 0, reflog, quiet,
     +		      BRANCH_TRACK_NEVER, dry_run);
     +	if (dry_run)
     +		return;
    @@ branch.h: void create_branch(struct repository *r,
      		   int dry_run);
      
     +/*
    -+ * Creates a new branch in repository and its submodules (and its
    -+ * submodules, recursively). Besides these exceptions, the parameters
    -+ * function identically to create_branch():
    ++ * Creates a new branch in a repository and its submodules (and its
    ++ * submodules, recursively). The parameters are mostly analogous to
    ++ * those of create_branch() except for start_name, which is represented
    ++ * by two different parameters:
     + *
    -+ * - start_name is the name of the ref, in repository r, that the new
    -+ *   branch should start from. In submodules, branches will start from
    -+ *   the respective gitlink commit ids in start_name's tree.
    ++ * - start_commitish is the commit-ish, in repository r, that determines
    ++ *   which commits the branches will point to. The superproject branch
    ++ *   will point to the commit of start_commitish and the submodule
    ++ *   branches will point to the gitlink commit oids in start_commitish's
    ++ *   tree.
     + *
    -+ * - tracking_name is the name used of the ref that will be used to set
    -+ *   up tracking, e.g. origin/main. This is propagated to submodules so
    -+ *   that tracking information will appear as if the branch branched off
    -+ *   tracking_name instead of start_name (which is a plain commit id for
    -+ *   submodules). If omitted, start_name is used for tracking (just like
    -+ *   create_branch()).
    ++ * - tracking_name is the name of the ref, in repository r, that will be
    ++ *   used to set up tracking information. This value is propagated to
    ++ *   all submodules, which will evaluate the ref using their own ref
    ++ *   stores. If NULL, this defaults to start_commitish.
     + *
    ++ * When this function is called on the superproject, start_commitish
    ++ * can be any user-provided ref and tracking_name can be NULL (similar
    ++ * to create_branches()). But when recursing through submodules,
    ++ * start_commitish is the plain gitlink commit oid. Since the oid cannot
    ++ * be used for tracking information, tracking_name is propagated and
    ++ * used for tracking instead.
     + */
     +void create_branches_recursively(struct repository *r, const char *name,
    -+				 const char *start_name,
    ++				 const char *start_commitish,
     +				 const char *tracking_name, int force,
     +				 int reflog, int quiet, enum branch_track track,
     +				 int dry_run);
    @@ t/t3207-branch-submodule.sh (new)
     +	cp -r test_dirs/* .
     +}
     +
    ++# Tests that the expected branch does not exist
    ++test_no_branch () {
    ++	DIR=$1 &&
    ++	BRANCH_NAME=$2 &&
    ++	test_must_fail git -C "$DIR" rev-parse "$BRANCH_NAME" 2>err &&
    ++	grep "ambiguous argument .$BRANCH_NAME." err
    ++}
    ++
     +test_expect_success 'setup superproject and submodule' '
     +	mkdir test_dirs &&
     +	(
    @@ t/t3207-branch-submodule.sh (new)
     +	(
     +		cd super &&
     +		git branch --recurse-submodules branch-a &&
    -+		test_must_fail git branch --recurse-submodules -D branch-a &&
    ++		echo "fatal: --recurse-submodules can only be used to create branches" >expected &&
    ++		test_must_fail git branch --recurse-submodules -D branch-a 2>actual &&
    ++		test_cmp expected actual &&
     +		# Assert that the branches were not deleted
     +		git rev-parse branch-a &&
     +		git -C sub rev-parse branch-a
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super &&
     +		git branch --recurse-submodules branch-a &&
     +		git -c submodule.recurse=true branch -D branch-a &&
    -+		test_must_fail git rev-parse branch-a &&
    ++		test_no_branch . branch-a &&
     +		git -C sub rev-parse branch-a
     +	)
     +'
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super &&
     +		git -C sub branch branch-a &&
     +		test_must_fail git branch --recurse-submodules branch-a 2>actual &&
    -+		test_must_fail git rev-parse branch-a &&
    ++		test_no_branch . branch-a &&
     +		grep "submodule .sub.: fatal: A branch named .branch-a. already exists" actual
     +	)
     +'
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super &&
     +		git branch --recurse-submodules branch-a &&
     +		git rev-parse branch-a &&
    -+		test_must_fail git -C sub branch-a
    ++		test_no_branch sub branch-a
     +	)
     +'
     +
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super &&
     +		git -c branch.autoSetupMerge=always branch --recurse-submodules branch-a main &&
     +		git -C sub rev-parse main &&
    -+		test "$(git -C sub config branch.branch-a.remote)" = . &&
    -+		test "$(git -C sub config branch.branch-a.merge)" = refs/heads/main
    ++		test_cmp_config -C sub . branch.branch-a.remote &&
    ++		test_cmp_config -C sub refs/heads/main branch.branch-a.merge
     +	)
     +'
     +
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super &&
     +		git branch --track --recurse-submodules branch-a main &&
     +		git -C sub rev-parse main &&
    -+		test "$(git -C sub config branch.branch-a.remote)" = . &&
    -+		test "$(git -C sub config branch.branch-a.merge)" = refs/heads/main
    ++		test_cmp_config -C sub . branch.branch-a.remote &&
    ++		test_cmp_config -C sub refs/heads/main branch.branch-a.merge
     +	)
     +'
     +
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super &&
     +		git branch --recurse-submodules branch-a main &&
     +		git -C sub rev-parse main &&
    -+		test "$(git -C sub config branch.branch-a.remote)" = "" &&
    -+		test "$(git -C sub config branch.branch-a.merge)" = ""
    ++		test_cmp_config -C sub "" --default "" branch.branch-a.remote &&
    ++		test_cmp_config -C sub "" --default "" branch.branch-a.merge
     +	)
     +'
     +
    @@ t/t3207-branch-submodule.sh (new)
     +		# This should fail because super-clone does not have sub2 .git/modules
     +		test_must_fail git branch --recurse-submodules branch-b origin/branch-b 2>actual &&
     +		grep "fatal: submodule .sub2.: unable to find submodule" actual &&
    -+		test_must_fail git rev-parse branch-b &&
    -+		test_must_fail git -C sub rev-parse branch-b &&
    ++		test_no_branch . branch-b &&
    ++		test_no_branch sub branch-b &&
     +		# User can fix themselves by initializing the submodule
     +		git checkout origin/branch-b &&
     +		git submodule update --init --recursive &&
    @@ t/t3207-branch-submodule.sh (new)
     +	(
     +		cd super-clone &&
     +		git branch --recurse-submodules branch-a origin/branch-a &&
    -+		test "$(git config branch.branch-a.remote)" = origin &&
    -+		test "$(git config branch.branch-a.merge)" = refs/heads/branch-a &&
    ++		test_cmp_config origin branch.branch-a.remote &&
    ++		test_cmp_config refs/heads/branch-a branch.branch-a.merge &&
     +		# "origin/branch-a" does not exist for "sub", but it matches the refspec
     +		# so tracking should be set up
    -+		test "$(git -C sub config branch.branch-a.remote)" = origin &&
    -+		test "$(git -C sub config branch.branch-a.merge)" = refs/heads/branch-a &&
    -+		test "$(git -C sub/sub-sub config branch.branch-a.remote)" = origin &&
    -+		test "$(git -C sub/sub-sub config branch.branch-a.merge)" = refs/heads/branch-a
    ++		test_cmp_config -C sub origin branch.branch-a.remote &&
    ++		test_cmp_config -C sub refs/heads/branch-a branch.branch-a.merge &&
    ++		test_cmp_config -C sub/sub-sub origin branch.branch-a.remote &&
    ++		test_cmp_config -C sub/sub-sub refs/heads/branch-a branch.branch-a.merge
     +	)
     +'
     +
    @@ t/t3207-branch-submodule.sh (new)
     +		cd super-clone &&
     +		git remote rename origin ex-origin &&
     +		git branch --recurse-submodules branch-a ex-origin/branch-a &&
    -+		test "$(git config branch.branch-a.remote)" = ex-origin &&
    -+		test "$(git config branch.branch-a.merge)" = refs/heads/branch-a &&
    -+		test "$(git -C sub config branch.branch-a.remote)" = "" &&
    -+		test "$(git -C sub config branch.branch-a.merge)" = ""
    ++		test_cmp_config ex-origin branch.branch-a.remote &&
    ++		test_cmp_config refs/heads/branch-a branch.branch-a.merge &&
    ++		test_cmp_config -C sub "" --default "" branch.branch-a.remote &&
    ++		test_cmp_config -C sub "" --default "" branch.branch-a.merge
     +	)
     +'
     +

6: a4634f0493 ! 6: bdf7be52be branch.c: use 'goto cleanup' in setup_tracking() to fix memory leaks
@@ branch.c: static void setup_tracking(const char *new_ref, const char *orig_ref,
tracking.remote, tracking.srcs) < 0)
exit(-1);

+- string_list_clear(tracking.srcs, 0);
+cleanup:
- string_list_clear(tracking.srcs, 0);
++ string_list_clear(&tracking_srcs, 0);
}

+ int read_branch_desc(struct strbuf *buf, const char *branch_name)

base-commit: 6327f0efed36c64d98a140110171362b7cb75a52

Signature · 1 line
2.33.GIT
author
#99 lore raw

PATCH v8 1/6 branch: move --set-upstream-to behavior to dwim_and_setup_tracking()

This commit is preparation for a future commit that will simplify create_branch() so that it always creates a branch. This will allow create_branch() to accept a dry_run parameter (which is needed for "git branch --recurse-submodules").

create_branch() used to always create a branch, but 4fc5006676 (Add branch --set-upstream, 2010-01-18) changed it to also be able to set tracking information without creating a branch.

Refactor the code that sets tracking information into its own functions dwim_branch_start() and dwim_and_setup_tracking(). Also change an invocation of create_branch() in cmd_branch() in builtin/branch.c to use dwim_and_setup_tracking(), since that invocation is only for setting tracking information (in "git branch --set-upstream-to").

As of this commit, create_branch() is no longer invoked in a way that does not create branches.

---
 branch.c         | 87 +++++++++++++++++++++++++++++++++++++-----------
 branch.h         | 22 ++++++++++++
 builtin/branch.c |  9 ++---
 3 files changed, 92 insertions(+), 26 deletions(-)
branch.c +67 -20
index a4e4631ef1..f3a31930fb 100644
@@ -218,9 +218,11 @@ static int inherit_tracking(struct tracking *tracking, const char *orig_ref)
 }
 
 /*
- * This is called when new_ref is branched off of orig_ref, and tries
- * to infer the settings for branch.<new_ref>.{remote,merge} from the
- * config.
+ * Used internally to set the branch.<new_ref>.{remote,merge} config
+ * settings so that branch 'new_ref' tracks 'orig_ref'. Unlike
+ * dwim_and_setup_tracking(), this does not do DWIM, i.e. "origin/main"
+ * will not be expanded to "refs/remotes/origin/main", so it is not safe
+ * for 'orig_ref' to be raw user input.
  */
 static void setup_tracking(const char *new_ref, const char *orig_ref,
 			   enum branch_track track, int quiet)
@@ -341,31 +343,37 @@ N_("\n"
 "will track its remote counterpart, you may want to use\n"
 "\"git push -u\" to set the upstream config as you push.");
 
-void create_branch(struct repository *r,
-		   const char *name, const char *start_name,
-		   int force, int clobber_head_ok, int reflog,
-		   int quiet, enum branch_track track)
+/**
+ * DWIMs a user-provided ref to determine the starting point for a
+ * branch and validates it, where:
+ *
+ *   - r is the repository to validate the branch for
+ *
+ *   - start_name is the ref that we would like to test. This is
+ *     expanded with DWIM and assigned to out_real_ref.
+ *
+ *   - track is the tracking mode of the new branch. If tracking is
+ *     explicitly requested, start_name must be a branch (because
+ *     otherwise start_name cannot be tracked)
+ *
+ *   - out_oid is an out parameter containing the object_id of start_name
+ *
+ *   - out_real_ref is an out parameter containing the full, 'real' form
+ *     of start_name e.g. refs/heads/main instead of main
+ *
+ */
+static void dwim_branch_start(struct repository *r, const char *start_name,
+			   enum branch_track track, char **out_real_ref,
+			   struct object_id *out_oid)
 {
 	struct commit *commit;
 	struct object_id oid;
 	char *real_ref;
-	struct strbuf ref = STRBUF_INIT;
-	int forcing = 0;
-	int dont_change_ref = 0;
 	int explicit_tracking = 0;
 
 	if (track == BRANCH_TRACK_EXPLICIT || track == BRANCH_TRACK_OVERRIDE)
 		explicit_tracking = 1;
 
-	if ((track == BRANCH_TRACK_OVERRIDE || clobber_head_ok)
-	    ? validate_branchname(name, &ref)
-	    : validate_new_branchname(name, &ref, force)) {
-		if (!force)
-			dont_change_ref = 1;
-		else
-			forcing = 1;
-	}
-
 	real_ref = NULL;
 	if (get_oid_mb(start_name, &oid)) {
 		if (explicit_tracking) {
@@ -402,7 +410,37 @@ void create_branch(struct repository *r,
 
 	if ((commit = lookup_commit_reference(r, &oid)) == NULL)
 		die(_("Not a valid branch point: '%s'."), start_name);
-	oidcpy(&oid, &commit->object.oid);
+	if (out_real_ref) {
+		*out_real_ref = real_ref;
+		real_ref = NULL;
+	}
+	if (out_oid)
+		oidcpy(out_oid, &commit->object.oid);
+
+	FREE_AND_NULL(real_ref);
+}
+
+void create_branch(struct repository *r,
+		   const char *name, const char *start_name,
+		   int force, int clobber_head_ok, int reflog,
+		   int quiet, enum branch_track track)
+{
+	struct object_id oid;
+	char *real_ref;
+	struct strbuf ref = STRBUF_INIT;
+	int forcing = 0;
+	int dont_change_ref = 0;
+
+	if ((track == BRANCH_TRACK_OVERRIDE || clobber_head_ok)
+	    ? validate_branchname(name, &ref)
+	    : validate_new_branchname(name, &ref, force)) {
+		if (!force)
+			dont_change_ref = 1;
+		else
+			forcing = 1;
+	}
+
+	dwim_branch_start(r, start_name, track, &real_ref, &oid);
 
 	if (reflog)
 		log_all_ref_updates = LOG_REFS_NORMAL;
@@ -436,6 +474,15 @@ void create_branch(struct repository *r,
 	free(real_ref);
 }
 
+void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
+			     const char *orig_ref, enum branch_track track,
+			     int quiet)
+{
+	char *real_orig_ref;
+	dwim_branch_start(r, orig_ref, track, &real_orig_ref, NULL);
+	setup_tracking(new_ref, real_orig_ref, track, quiet);
+}
+
 void remove_merge_branch_state(struct repository *r)
 {
 	unlink(git_path_merge_head(r));
branch.h +22 -0
index 815dcd40c0..ab2315c611 100644
@@ -18,6 +18,28 @@ extern enum branch_track git_branch_track;
 
 /* Functions for acting on the information about branches. */
 
+/**
+ * Sets branch.<new_ref>.{remote,merge} config settings such that
+ * new_ref tracks orig_ref according to the specified tracking mode.
+ *
+ *   - new_ref is the name of the branch that we are setting tracking
+ *     for.
+ *
+ *   - orig_ref is the name of the ref that is 'upstream' of new_ref.
+ *     orig_ref will be expanded with DWIM so that the config settings
+ *     are in the correct format e.g. "refs/remotes/origin/main" instead
+ *     of "origin/main".
+ *
+ *   - track is the tracking mode e.g. BRANCH_TRACK_REMOTE causes
+ *     new_ref to track orig_ref directly, whereas BRANCH_TRACK_INHERIT
+ *     causes new_ref to track whatever orig_ref tracks.
+ *
+ *   - quiet suppresses tracking information.
+ */
+void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
+			     const char *orig_ref, enum branch_track track,
+			     int quiet);
+
 /*
  * Creates a new branch, where:
  *
builtin/branch.c +3 -6
index c5de1207e4..62b1a70b05 100644
@@ -822,12 +822,9 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 		if (!ref_exists(branch->refname))
 			die(_("branch '%s' does not exist"), branch->name);
 
-		/*
-		 * create_branch takes care of setting up the tracking
-		 * info and making sure new_upstream is correct
-		 */
-		create_branch(the_repository, branch->name, new_upstream,
-			      0, 0, 0, quiet, BRANCH_TRACK_OVERRIDE);
+		dwim_and_setup_tracking(the_repository, branch->name,
+					new_upstream, BRANCH_TRACK_OVERRIDE,
+					quiet);
 	} else if (unset_upstream) {
 		struct branch *branch = branch_get(argv[0]);
 		struct strbuf buf = STRBUF_INIT;
Signature · 1 line
2.33.GIT
author
#100 lore raw

PATCH v8 2/6 branch: make create_branch() always create a branch

In reply to Glen Choo

With the previous commit, there are no more invocations of create_branch() that do not create a branch because:

* BRANCH_TRACK_OVERRIDE is no longer passed
* clobber_head_ok = true and force = false is never passed

Assert these situations, delete dead code and ensure that we're handling clobber_head_ok and force correctly by introducing tests for git branch --force. As a result, create_branch() now always creates a branch.

---
 branch.c          | 57 ++++++++++++++++++++++-------------------------
 branch.h          |  4 ++--
 t/t3200-branch.sh | 17 ++++++++++++++
 3 files changed, 46 insertions(+), 32 deletions(-)
branch.c +27 -30
index f3a31930fb..df24021f27 100644
@@ -429,15 +429,19 @@ void create_branch(struct repository *r,
 	char *real_ref;
 	struct strbuf ref = STRBUF_INIT;
 	int forcing = 0;
-	int dont_change_ref = 0;
-
-	if ((track == BRANCH_TRACK_OVERRIDE || clobber_head_ok)
-	    ? validate_branchname(name, &ref)
-	    : validate_new_branchname(name, &ref, force)) {
-		if (!force)
-			dont_change_ref = 1;
-		else
-			forcing = 1;
+	struct ref_transaction *transaction;
+	struct strbuf err = STRBUF_INIT;
+	char *msg;
+
+	if (track == BRANCH_TRACK_OVERRIDE)
+		BUG("'track' cannot be BRANCH_TRACK_OVERRIDE. Did you mean to call dwim_and_setup_tracking()?");
+	if (clobber_head_ok && !force)
+		BUG("'clobber_head_ok' can only be used with 'force'");
+
+	if (clobber_head_ok ?
+			  validate_branchname(name, &ref) :
+			  validate_new_branchname(name, &ref, force)) {
+		forcing = 1;
 	}
 
 	dwim_branch_start(r, start_name, track, &real_ref, &oid);
@@ -445,27 +449,20 @@ void create_branch(struct repository *r,
 	if (reflog)
 		log_all_ref_updates = LOG_REFS_NORMAL;
 
-	if (!dont_change_ref) {
-		struct ref_transaction *transaction;
-		struct strbuf err = STRBUF_INIT;
-		char *msg;
-
-		if (forcing)
-			msg = xstrfmt("branch: Reset to %s", start_name);
-		else
-			msg = xstrfmt("branch: Created from %s", start_name);
-
-		transaction = ref_transaction_begin(&err);
-		if (!transaction ||
-		    ref_transaction_update(transaction, ref.buf,
-					   &oid, forcing ? NULL : null_oid(),
-					   0, msg, &err) ||
-		    ref_transaction_commit(transaction, &err))
-			die("%s", err.buf);
-		ref_transaction_free(transaction);
-		strbuf_release(&err);
-		free(msg);
-	}
+	if (forcing)
+		msg = xstrfmt("branch: Reset to %s", start_name);
+	else
+		msg = xstrfmt("branch: Created from %s", start_name);
+	transaction = ref_transaction_begin(&err);
+	if (!transaction ||
+		ref_transaction_update(transaction, ref.buf,
+					&oid, forcing ? NULL : null_oid(),
+					0, msg, &err) ||
+		ref_transaction_commit(transaction, &err))
+		die("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_release(&err);
+	free(msg);
 
 	if (real_ref && track)
 		setup_tracking(ref.buf + 11, real_ref, track, quiet);
branch.h +2 -2
index ab2315c611..cf3a4d3ff3 100644
@@ -52,8 +52,8 @@ void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
  *
  *   - force enables overwriting an existing (non-head) branch
  *
- *   - clobber_head_ok allows the currently checked out (hence existing)
- *     branch to be overwritten; without 'force', it has no effect.
+ *   - clobber_head_ok, when enabled with 'force', allows the currently
+ *     checked out (head) branch to be overwritten
  *
  *   - reflog creates a reflog for the branch
  *
t/t3200-branch.sh +17 -0
index a74b2e06a1..9157382ad0 100755
@@ -42,6 +42,23 @@ test_expect_success 'git branch abc should create a branch' '
 	git branch abc && test_path_is_file .git/refs/heads/abc
 '
 
+test_expect_success 'git branch abc should fail when abc exists' '
+	test_must_fail git branch abc
+'
+
+test_expect_success 'git branch --force abc should fail when abc is checked out' '
+	test_when_finished git switch main &&
+	git switch abc &&
+	test_must_fail git branch --force abc HEAD~1
+'
+
+test_expect_success 'git branch --force abc should succeed when abc exists' '
+	git rev-parse HEAD~1 >expect &&
+	git branch --force abc HEAD~1 &&
+	git rev-parse abc >actual &&
+	test_cmp expect actual
+'
+
 test_expect_success 'git branch a/b/c should create a branch' '
 	git branch a/b/c && test_path_is_file .git/refs/heads/a/b/c
 '
Signature · 1 line
2.33.GIT
#101 lore raw

Re: [PATCH v8 2/6] branch: make create_branch() always create a branch

Quoted 9 lines · Glen Choo

With the previous commit, there are no more invocations of create_branch() that do not create a branch because:

* BRANCH_TRACK_OVERRIDE is no longer passed
* clobber_head_ok = true and force = false is never passed

Assert these situations, delete dead code and ensure that we're handling clobber_head_ok and force correctly by introducing tests for git branch --force. As a result, create_branch() now always creates a branch.

A very nice simplifiation of semantics.

author
#102 lore raw

PATCH v8 3/6 branch: add a dry_run parameter to create_branch()

In reply to Glen Choo

Add a dry_run parameter to create_branch() such that dry_run = 1 will validate a new branch without trying to create it. This will be used in git branch --recurse-submodules to ensure that the new branch can be created in all submodules.

---
 branch.c           | 5 ++++-
 branch.h           | 5 ++++-
 builtin/branch.c   | 2 +-
 builtin/checkout.c | 3 ++-
 4 files changed, 11 insertions(+), 4 deletions(-)
branch.c +4 -1
index df24021f27..02d46a69b8 100644
@@ -423,7 +423,7 @@ static void dwim_branch_start(struct repository *r, const char *start_name,
 void create_branch(struct repository *r,
 		   const char *name, const char *start_name,
 		   int force, int clobber_head_ok, int reflog,
-		   int quiet, enum branch_track track)
+		   int quiet, enum branch_track track, int dry_run)
 {
 	struct object_id oid;
 	char *real_ref;
@@ -445,6 +445,8 @@ void create_branch(struct repository *r,
 	}
 
 	dwim_branch_start(r, start_name, track, &real_ref, &oid);
+	if (dry_run)
+		goto cleanup;
 
 	if (reflog)
 		log_all_ref_updates = LOG_REFS_NORMAL;
@@ -467,6 +469,7 @@ void create_branch(struct repository *r,
 	if (real_ref && track)
 		setup_tracking(ref.buf + 11, real_ref, track, quiet);
 
+cleanup:
 	strbuf_release(&ref);
 	free(real_ref);
 }
branch.h +4 -1
index cf3a4d3ff3..509cfcc34e 100644
@@ -62,11 +62,14 @@ void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
  *   - track causes the new branch to be configured to merge the remote branch
  *     that start_name is a tracking branch for (if any).
  *
+ *   - dry_run causes the branch to be validated but not created.
+ *
  */
 void create_branch(struct repository *r,
 		   const char *name, const char *start_name,
 		   int force, int clobber_head_ok,
-		   int reflog, int quiet, enum branch_track track);
+		   int reflog, int quiet, enum branch_track track,
+		   int dry_run);
 
 /*
  * Check if 'name' can be a valid name for a branch; die otherwise.
builtin/branch.c +1 -1
index 62b1a70b05..c6fffb99ab 100644
@@ -858,7 +858,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 
 		create_branch(the_repository,
 			      argv[0], (argc == 2) ? argv[1] : head,
-			      force, 0, reflog, quiet, track);
+			      force, 0, reflog, quiet, track, 0);
 
 	} else
 		usage_with_options(builtin_branch_usage, options);
builtin/checkout.c +2 -1
index 1809ac12df..8600860629 100644
@@ -893,7 +893,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
 				      opts->new_branch_force ? 1 : 0,
 				      opts->new_branch_log,
 				      opts->quiet,
-				      opts->track);
+				      opts->track,
+				      0);
 		new_branch_info->name = opts->new_branch;
 		setup_branch_path(new_branch_info);
 	}
Signature · 1 line
2.33.GIT
author
#103 lore raw

PATCH v8 4/6 builtin/branch: consolidate action-picking logic in cmd_branch()

In reply to Glen Choo

Consolidate the logic for deciding when to create a new branch in cmd_branch(), and save the result for reuse. Besides making the function more explicit, this allows us to validate options that can only be used when creating a branch. Such an option does not exist yet, but one will be introduced in a subsequent commit.

---
 builtin/branch.c | 19 +++++++++++--------
 1 file changed, 11 insertions(+), 8 deletions(-)
builtin/branch.c +11 -8
index c6fffb99ab..b352cc789a 100644
@@ -616,14 +616,15 @@ static int edit_branch_description(const char *branch_name)
 
 int cmd_branch(int argc, const char **argv, const char *prefix)
 {
-	int delete = 0, rename = 0, copy = 0, force = 0, list = 0;
-	int show_current = 0;
-	int reflog = 0, edit_description = 0;
-	int quiet = 0, unset_upstream = 0;
+	/* possible actions */
+	int delete = 0, rename = 0, copy = 0, list = 0,
+	    unset_upstream = 0, show_current = 0, edit_description = 0;
 	const char *new_upstream = NULL;
+	int noncreate_actions = 0;
+	/* possible options */
+	int reflog = 0, quiet = 0, icase = 0, force = 0;
 	enum branch_track track;
 	struct ref_filter filter;
-	int icase = 0;
 	static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
 	struct ref_format format = REF_FORMAT_INIT;
 
@@ -707,8 +708,10 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 	    filter.reachable_from || filter.unreachable_from || filter.points_at.nr)
 		list = 1;
 
-	if (!!delete + !!rename + !!copy + !!new_upstream + !!show_current +
-	    list + edit_description + unset_upstream > 1)
+	noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
+			    !!show_current + !!list + !!edit_description +
+			    !!unset_upstream;
+	if (noncreate_actions > 1)
 		usage_with_options(builtin_branch_usage, options);
 
 	if (filter.abbrev == -1)
@@ -848,7 +851,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
 		strbuf_addf(&buf, "branch.%s.merge", branch->name);
 		git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
 		strbuf_release(&buf);
-	} else if (argc > 0 && argc <= 2) {
+	} else if (!noncreate_actions && argc > 0 && argc <= 2) {
 		if (filter.kind != FILTER_REFS_BRANCHES)
 			die(_("The -a, and -r, options to 'git branch' do not take a branch name.\n"
 				  "Did you mean to use: -a|-r --list <pattern>?"));
Signature · 1 line
2.33.GIT
author
#104 lore raw

PATCH v8 5/6 branch: add --recurse-submodules option for branch creation

In reply to Glen Choo

To improve the submodules UX, we would like to teach Git to handle branches in submodules. Start this process by teaching "git branch" the --recurse-submodules option so that "git branch --recurse-submodules topic" will create the topic branch in the superproject and its submodules.

Although this commit does not introduce breaking changes, it does not work well with existing --recurse-submodules commands because "git branch --recurse-submodules" writes to the submodule ref store, but most commands only consider the superproject gitlink and ignore the submodule ref store. For example, "git checkout --recurse-submodules" will check out the commits in the superproject gitlinks (and put the submodules in detached HEAD) instead of checking out the submodule branches.

Because of this, this commit introduces a new configuration value, submodule.propagateBranches. The plan is for Git commands to prioritize submodule ref store information over superproject gitlinks if this value is true. Because "git branch --recurse-submodules" writes to submodule ref stores, for the sake of clarity, it will not function unless this configuration value is set.

This commit also includes changes that support working with submodules from a superproject commit because "branch --recurse-submodules" (and future commands) need to read .gitmodules and gitlinks from the superproject commit, but submodules are typically read from the filesystem's .gitmodules and the index's gitlinks. These changes are:

* add a submodules_of_tree() helper that gives the relevant information of an in-tree submodule (e.g. path and oid) and initializes the repository
* add is_tree_submodule_active() by adding a treeish_name parameter to is_submodule_active()
* add the "submoduleNotUpdated" advice to advise users to update the submodules in their trees

Incidentally, fix an incorrect usage string that combined the 'list' usage of git branch (-l) with the 'create' usage; this string has been incorrect since its inception, a8dfd5eac4 (Make builtin-branch.c use parse_options., 2007-10-07).

---
 Documentation/config/advice.txt    |   3 +
 Documentation/config/submodule.txt |  37 ++--
 Documentation/git-branch.txt       |  19 +-
 advice.c                           |   1 +
 advice.h                           |   1 +
 branch.c                           | 141 ++++++++++++++
 branch.h                           |  29 +++
 builtin/branch.c                   |  44 ++++-
 builtin/submodule--helper.c        |  38 ++++
 submodule-config.c                 |  60 ++++++
 submodule-config.h                 |  34 ++++
 submodule.c                        |  11 +-
 submodule.h                        |   3 +
 t/t3207-branch-submodule.sh        | 292 +++++++++++++++++++++++++++++
 14 files changed, 693 insertions(+), 20 deletions(-)
 create mode 100755 t/t3207-branch-submodule.sh
Documentation/config/advice.txt +3 -0
index 063eec2511..adee26fbbb 100644
@@ -116,6 +116,9 @@ advice.*::
 	submoduleAlternateErrorStrategyDie::
 		Advice shown when a submodule.alternateErrorStrategy option
 		configured to "die" causes a fatal error.
+	submodulesNotUpdated::
+		Advice shown when a user runs a submodule command that fails
+		because `git submodule update --init` was not run.
 	addIgnoredFile::
 		Advice shown if a user attempts to add an ignored file to
 		the index.
Documentation/config/submodule.txt +26 -11
index ee454f8126..6490527b45 100644
@@ -59,18 +59,33 @@ submodule.active::
 
 submodule.recurse::
 	A boolean indicating if commands should enable the `--recurse-submodules`
-	option by default.
-	Applies to all commands that support this option
-	(`checkout`, `fetch`, `grep`, `pull`, `push`, `read-tree`, `reset`,
-	`restore` and `switch`) except `clone` and `ls-files`.
+	option by default. Defaults to false.
++
+When set to true, it can be deactivated via the
+`--no-recurse-submodules` option. Note that some Git commands
+lacking this option may call some of the above commands affected by
+`submodule.recurse`; for instance `git remote update` will call
+`git fetch` but does not have a `--no-recurse-submodules` option.
+For these commands a workaround is to temporarily change the
+configuration value by using `git -c submodule.recurse=0`.
++
+The following list shows the commands that accept
+`--recurse-submodules` and whether they are supported by this
+setting.
+
+* `checkout`, `fetch`, `grep`, `pull`, `push`, `read-tree`,
+`reset`, `restore` and `switch` are always supported.
+* `clone` and `ls-files` are not supported.
+* `branch` is supported only if `submodule.propagateBranches` is
+enabled
+
+submodule.propagateBranches::
+	[EXPERIMENTAL] A boolean that enables branching support when
+	using `--recurse-submodules` or `submodule.recurse=true`.
+	Enabling this will allow certain commands to accept
+	`--recurse-submodules` and certain commands that already accept
+	`--recurse-submodules` will now consider branches.
 	Defaults to false.
-	When set to true, it can be deactivated via the
-	`--no-recurse-submodules` option. Note that some Git commands
-	lacking this option may call some of the above commands affected by
-	`submodule.recurse`; for instance `git remote update` will call
-	`git fetch` but does not have a `--no-recurse-submodules` option.
-	For these commands a workaround is to temporarily change the
-	configuration value by using `git -c submodule.recurse=0`.
 
 submodule.fetchJobs::
 	Specifies how many submodules are fetched/cloned at the same time.
Documentation/git-branch.txt +18 -1
index c59687a4d9..f526573951 100644
@@ -16,7 +16,8 @@ SYNOPSIS
 	[--points-at <object>] [--format=<format>]
 	[(-r | --remotes) | (-a | --all)]
 	[--list] [<pattern>...]
-'git branch' [--track[=(direct|inherit)] | --no-track] [-f] <branchname> [<start-point>]
+'git branch' [--track[=(direct|inherit)] | --no-track] [-f]
+	[--recurse-submodules] <branchname> [<start-point>]
 'git branch' (--set-upstream-to=<upstream> | -u <upstream>) [<branchname>]
 'git branch' --unset-upstream [<branchname>]
 'git branch' (-m | -M) [<oldbranch>] <newbranch>
@@ -235,6 +236,22 @@ how the `branch.<name>.remote` and `branch.<name>.merge` options are used.
 	Do not set up "upstream" configuration, even if the
 	branch.autoSetupMerge configuration variable is set.
 
+--recurse-submodules::
+	THIS OPTION IS EXPERIMENTAL! Causes the current command to
+	recurse into submodules if `submodule.propagateBranches` is
+	enabled. See `submodule.propagateBranches` in
+	linkgit:git-config[1]. Currently, only branch creation is
+	supported.
++
+When used in branch creation, a new branch <branchname> will be created
+in the superproject and all of the submodules in the superproject's
+<start-point>. In submodules, the branch will point to the submodule
+commit in the superproject's <start-point> but the branch's tracking
+information will be set up based on the submodule's branches and remotes
+e.g. `git branch --recurse-submodules topic origin/main` will create the
+submodule branch "topic" that points to the submodule commit in the
+superproject's "origin/main", but tracks the submodule's "origin/main".
+
 --set-upstream::
 	As this option had confusing syntax, it is no longer supported.
 	Please use `--track` or `--set-upstream-to` instead.
advice.c +1 -0
index 1dfc91d176..e00d30254c 100644
@@ -70,6 +70,7 @@ static struct {
 	[ADVICE_STATUS_HINTS]				= { "statusHints", 1 },
 	[ADVICE_STATUS_U_OPTION]			= { "statusUoption", 1 },
 	[ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE] = { "submoduleAlternateErrorStrategyDie", 1 },
+	[ADVICE_SUBMODULES_NOT_UPDATED] 		= { "submodulesNotUpdated", 1 },
 	[ADVICE_UPDATE_SPARSE_PATH]			= { "updateSparsePath", 1 },
 	[ADVICE_WAITING_FOR_EDITOR]			= { "waitingForEditor", 1 },
 };
advice.h +1 -0
index 601265fd10..a7521d6087 100644
@@ -44,6 +44,7 @@ struct string_list;
 	ADVICE_STATUS_HINTS,
 	ADVICE_STATUS_U_OPTION,
 	ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE,
+	ADVICE_SUBMODULES_NOT_UPDATED,
 	ADVICE_UPDATE_SPARSE_PATH,
 	ADVICE_WAITING_FOR_EDITOR,
 	ADVICE_SKIPPED_CHERRY_PICKS,
branch.c +141 -0

153 lines not on this page · raw message

branch.h +29 -0
index 509cfcc34e..04df2aa5b5 100644
@@ -71,6 +71,35 @@ void create_branch(struct repository *r,
 		   int reflog, int quiet, enum branch_track track,
 		   int dry_run);
 
+/*
+ * Creates a new branch in a repository and its submodules (and its
+ * submodules, recursively). The parameters are mostly analogous to
+ * those of create_branch() except for start_name, which is represented
+ * by two different parameters:
+ *
+ * - start_commitish is the commit-ish, in repository r, that determines
+ *   which commits the branches will point to. The superproject branch
+ *   will point to the commit of start_commitish and the submodule
+ *   branches will point to the gitlink commit oids in start_commitish's
+ *   tree.
+ *
+ * - tracking_name is the name of the ref, in repository r, that will be
+ *   used to set up tracking information. This value is propagated to
+ *   all submodules, which will evaluate the ref using their own ref
+ *   stores. If NULL, this defaults to start_commitish.
+ *
+ * When this function is called on the superproject, start_commitish
+ * can be any user-provided ref and tracking_name can be NULL (similar
+ * to create_branches()). But when recursing through submodules,
+ * start_commitish is the plain gitlink commit oid. Since the oid cannot
+ * be used for tracking information, tracking_name is propagated and
+ * used for tracking instead.
+ */
+void create_branches_recursively(struct repository *r, const char *name,
+				 const char *start_commitish,
+				 const char *tracking_name, int force,
+				 int reflog, int quiet, enum branch_track track,
+				 int dry_run);
 /*
  * Check if 'name' can be a valid name for a branch; die otherwise.
  * Return 1 if the named branch already exists; return 0 otherwise.
builtin/branch.c +38 -6

92 lines not on this page · raw message

builtin/submodule--helper.c +38 -0
index 6298cbdd4e..eba2a6e9b0 100644
@@ -20,6 +20,7 @@
 #include "diff.h"
 #include "object-store.h"
 #include "advice.h"
+#include "branch.h"
 
 #define OPT_QUIET (1 << 0)
 #define OPT_CACHED (1 << 1)
@@ -2983,6 +2984,42 @@ static int module_set_branch(int argc, const char **argv, const char *prefix)
 	return !!ret;
 }
 
+static int module_create_branch(int argc, const char **argv, const char *prefix)
+{
+	enum branch_track track;
+	int quiet = 0, force = 0, reflog = 0, dry_run = 0;
+
+	struct option options[] = {
+		OPT__QUIET(&quiet, N_("print only error messages")),
+		OPT__FORCE(&force, N_("force creation"), 0),
+		OPT_BOOL(0, "create-reflog", &reflog,
+			 N_("create the branch's reflog")),
+		OPT_SET_INT('t', "track", &track,
+			    N_("set up tracking mode (see git-pull(1))"),
+			    BRANCH_TRACK_EXPLICIT),
+		OPT__DRY_RUN(&dry_run,
+			     N_("show whether the branch would be created")),
+		OPT_END()
+	};
+	const char *const usage[] = {
+		N_("git submodule--helper create-branch [-f|--force] [--create-reflog] [-q|--quiet] [-t|--track] [-n|--dry-run] <name> <start_oid> <start_name>"),
+		NULL
+	};
+
+	git_config(git_default_config, NULL);
+	track = git_branch_track;
+	argc = parse_options(argc, argv, prefix, options, usage, 0);
+
+	if (argc != 3)
+		usage_with_options(usage, options);
+
+	if (!quiet && !dry_run)
+		printf_ln(_("creating branch '%s'"), argv[0]);
+
+	create_branches_recursively(the_repository, argv[0], argv[1], argv[2],
+				    force, reflog, quiet, track, dry_run);
+	return 0;
+}
 struct add_data {
 	const char *prefix;
 	const char *branch;
@@ -3379,6 +3416,7 @@ static struct cmd_struct commands[] = {
 	{"config", module_config, 0},
 	{"set-url", module_set_url, 0},
 	{"set-branch", module_set_branch, 0},
+	{"create-branch", module_create_branch, 0},
 };
 
 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
submodule-config.c +60 -0

72 lines not on this page · raw message

submodule-config.h +34 -0
index 65875b94ea..fa229a8b97 100644
@@ -6,6 +6,7 @@
 #include "hashmap.h"
 #include "submodule.h"
 #include "strbuf.h"
+#include "tree-walk.h"
 
 /**
  * The submodule config cache API allows to read submodule
@@ -101,4 +102,37 @@ int check_submodule_name(const char *name);
 void fetch_config_from_gitmodules(int *max_children, int *recurse_submodules);
 void update_clone_config_from_gitmodules(int *max_jobs);
 
+/*
+ * Submodule entry that contains relevant information about a
+ * submodule in a tree.
+ */
+struct submodule_tree_entry {
+	/* The submodule's tree entry. */
+	struct name_entry *name_entry;
+	/*
+	 * A struct repository corresponding to the submodule. May be
+	 * NULL if the submodule has not been updated.
+	 */
+	struct repository *repo;
+	/*
+	 * A struct submodule containing the submodule config in the
+	 * tree's .gitmodules.
+	 */
+	const struct submodule *submodule;
+};
+
+struct submodule_entry_list {
+	struct submodule_tree_entry *entries;
+	int entry_nr;
+	int entry_alloc;
+};
+
+/**
+ * Given a treeish, return all submodules in the tree and its subtrees,
+ * but excluding nested submodules. Callers that require nested
+ * submodules are expected to recurse into the submodules themselves.
+ */
+void submodules_of_tree(struct repository *r,
+			const struct object_id *treeish_name,
+			struct submodule_entry_list *ret);
 #endif /* SUBMODULE_CONFIG_H */
submodule.c +9 -2
index f3c99634a9..07ae7c266e 100644
@@ -265,7 +265,9 @@ int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
  * ie, the config looks like: "[submodule] active\n".
  * Since that is an invalid pathspec, we should inform the user.
  */
-int is_submodule_active(struct repository *repo, const char *path)
+int is_tree_submodule_active(struct repository *repo,
+			     const struct object_id *treeish_name,
+			     const char *path)
 {
 	int ret = 0;
 	char *key = NULL;
@@ -273,7 +275,7 @@ int is_submodule_active(struct repository *repo, const char *path)
 	const struct string_list *sl;
 	const struct submodule *module;
 
-	module = submodule_from_path(repo, null_oid(), path);
+	module = submodule_from_path(repo, treeish_name, path);
 
 	/* early return if there isn't a path->module mapping */
 	if (!module)
@@ -315,6 +317,11 @@ int is_submodule_active(struct repository *repo, const char *path)
 	return ret;
 }
 
+int is_submodule_active(struct repository *repo, const char *path)
+{
+	return is_tree_submodule_active(repo, null_oid(), path);
+}
+
 int is_submodule_populated_gently(const char *path, int *return_error_code)
 {
 	int ret = 0;
submodule.h +3 -0
index 6bd2c99fd9..784ceffc0e 100644
@@ -54,6 +54,9 @@ int git_default_submodule_config(const char *var, const char *value, void *cb);
 struct option;
 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
 						     const char *arg, int unset);
+int is_tree_submodule_active(struct repository *repo,
+			     const struct object_id *treeish_name,
+			     const char *path);
 int is_submodule_active(struct repository *repo, const char *path);
 /*
  * Determine if a submodule has been populated at a given 'path' by checking if
t/t3207-branch-submodule.sh new file +292 -0

292 lines not on this page · raw message

Signature · 1 line
2.33.GIT
author
#105 lore raw

Re: [PATCH v8 5/6] branch: add --recurse-submodules option for branch creation

I tested this series some more and found a silly bug. Let me know if I should just send v9 instead.

----- >8 --------- >8 --------- >8 --------- >8 --------- >8 ----

Subject: [PATCH] submodule-config.c: remove accidental pointer reuse

List entries allocated by traverse_tree_submodules() are sharing the .name_entry pointer, but each of them needs their own pointer. Fix this.

---
 submodule-config.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
submodule-config.c +2 -1
index 24b8d1a700..c9f54bc72d 100644
@@ -757,7 +757,8 @@ static void traverse_tree_submodules(struct repository *r,
 		if (S_ISGITLINK(name_entry->mode) &&
 		    is_tree_submodule_active(r, root_tree, tree_path)) {
 			st_entry = xmalloc(sizeof(*st_entry));
-			st_entry->name_entry = name_entry;
+			st_entry->name_entry = xmalloc(sizeof(*st_entry->name_entry));
+			*st_entry->name_entry = *name_entry;
 			st_entry->submodule =
 				submodule_from_path(r, root_tree, tree_path);
 			st_entry->repo = xmalloc(sizeof(*st_entry->repo));
Signature · 1 line
2.35.0.263.gb82422642f-goog
#106 lore raw

Re: [PATCH v8 5/6] branch: add --recurse-submodules option for branch creation

Quoted 2 lines · Glen Choo

I tested this series some more and found a silly bug. Let me know if I should just send v9 instead.

As long as the log message of this new thing does not have to be retained, I can squash it in for you.

And in this case, we can lose the message below---it just talks about a mistake in the version that was submitted, and will become irrelevant once the change is squashed in.

Thanks.

Quoted 26 lines

----- >8 --------- >8 --------- >8 --------- >8 --------- >8 ----

Subject: [PATCH] submodule-config.c: remove accidental pointer reuse

List entries allocated by traverse_tree_submodules() are sharing the .name_entry pointer, but each of them needs their own pointer. Fix this.

---
 submodule-config.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
submodule-config.c +2 -1
index 24b8d1a700..c9f54bc72d 100644
@@ -757,7 +757,8 @@ static void traverse_tree_submodules(struct repository *r,
 		if (S_ISGITLINK(name_entry->mode) &&
 		    is_tree_submodule_active(r, root_tree, tree_path)) {
 			st_entry = xmalloc(sizeof(*st_entry));
-			st_entry->name_entry = name_entry;
+			st_entry->name_entry = xmalloc(sizeof(*st_entry->name_entry));
+			*st_entry->name_entry = *name_entry;
 			st_entry->submodule =
 				submodule_from_path(r, root_tree, tree_path);
 			st_entry->repo = xmalloc(sizeof(*st_entry->repo));
author
#107 lore raw

Re: [PATCH v8 5/6] branch: add --recurse-submodules option for branch creation

Quoted 9 lines · Junio C Hamano

Glen Choo <[email protected]> writes:

As long as the log message of this new thing does not have to be retained, I can squash it in for you.

And in this case, we can lose the message below---it just talks about a mistake in the version that was submitted, and will become irrelevant once the change is squashed in.

Yes, the intention was to lose the message.

Thanks so much for being accommodating :)

author
#108 lore raw

PATCH v8 6/6 branch.c: use 'goto cleanup' in setup_tracking() to fix memory leaks

In reply to Glen Choo
---
 branch.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
branch.c +4 -3
index 70026b3c79..47251669e1 100644
@@ -239,7 +239,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (track != BRANCH_TRACK_INHERIT)
 		for_each_remote(find_tracked_branch, &tracking);
 	else if (inherit_tracking(&tracking, orig_ref))
-		return;
+		goto cleanup;
 
 	if (!tracking.matches)
 		switch (track) {
@@ -249,7 +249,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 		case BRANCH_TRACK_INHERIT:
 			break;
 		default:
-			return;
+			goto cleanup;
 		}
 
 	if (tracking.matches > 1)
@@ -262,7 +262,8 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 				tracking.remote, tracking.srcs) < 0)
 		exit(-1);
 
-	string_list_clear(tracking.srcs, 0);
+cleanup:
+	string_list_clear(&tracking_srcs, 0);
 }
 
 int read_branch_desc(struct strbuf *buf, const char *branch_name)
Signature · 1 line
2.33.GIT
Reviewed-by on the v8 series
#109 lore raw
In reply to Glen Choo
Quoted 10 lines · Glen Choo

Changes since v7:
* Reword patch 5's commit message
* In comments and Documentation/git-branch.txt, clarify how branch --recurse-submodules behaves and rename a parameter to better reflect this behavior
* In t3207, always assert on error messages when using test_must_fail
* In t3207, assert on config values using test_cmp_config. This avoids the silent failures discouraged by t/README:671.
* In patch 6, be more explicit about freeing the stack-allocated variable.

I had minor comments [1] which have been addressed, so:

I'm OK with 6/6 being included or not being included.