branch: add a dry_run parameter to create_branch()

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. Signed-off-by: Glen Choo <chooglen@google.com> Reviewed-by: Jonathan Tan <jonathantanmy@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Glen Choo committed Jan 28, 2022 at 16:04 UTC 3f3e76082bc29ff647dff16de9f0145a4d582825
4 files changed +11 -4
branch.c
+4 -1
@@ -423,7 +423,7 @@ static void dwim_branch_start(struct repository *r, const char *start_name,
423 void create_branch(struct repository *r,
424 const char *name, const char *start_name,
425 int force, int clobber_head_ok, int reflog,
426 - int quiet, enum branch_track track)
426 + int quiet, enum branch_track track, int dry_run)
427 {
428 struct object_id oid;
429 char *real_ref;
@@ -445,6 +445,8 @@ void create_branch(struct repository *r,
445 }
446
447 dwim_branch_start(r, start_name, track, &real_ref, &oid);
448 + if (dry_run)
449 + goto cleanup;
450
451 if (reflog)
452 log_all_ref_updates = LOG_REFS_NORMAL;
@@ -467,6 +469,7 @@ void create_branch(struct repository *r,
469 if (real_ref && track)
470 setup_tracking(ref.buf + 11, real_ref, track, quiet);
471
472 +cleanup:
473 strbuf_release(&ref);
474 free(real_ref);
475 }
branch.h
+4 -1
@@ -62,11 +62,14 @@ void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
62 * - track causes the new branch to be configured to merge the remote branch
63 * that start_name is a tracking branch for (if any).
64 *
65 + * - dry_run causes the branch to be validated but not created.
66 + *
67 */
68 void create_branch(struct repository *r,
69 const char *name, const char *start_name,
70 int force, int clobber_head_ok,
69 - int reflog, int quiet, enum branch_track track);
71 + int reflog, int quiet, enum branch_track track,
72 + int dry_run);
73
74 /*
75 * Check if 'name' can be a valid name for a branch; die otherwise.
builtin/branch.c
+1 -1
@@ -859,7 +859,7 @@ int cmd_branch(int argc, const char **argv, const char *prefix)
859
860 create_branch(the_repository,
861 argv[0], (argc == 2) ? argv[1] : head,
862 - force, 0, reflog, quiet, track);
862 + force, 0, reflog, quiet, track, 0);
863
864 } else
865 usage_with_options(builtin_branch_usage, options);
builtin/checkout.c
+2 -1
@@ -893,7 +893,8 @@ static void update_refs_for_switch(const struct checkout_opts *opts,
893 opts->new_branch_force ? 1 : 0,
894 opts->new_branch_log,
895 opts->quiet,
896 - opts->track);
896 + opts->track,
897 + 0);
898 new_branch_info->name = opts->new_branch;
899 setup_branch_path(new_branch_info);
900 }