worktree: extract checkout_worktree()

The ability to add the --no-checkout flag to 'git worktree' was added in ef2a0ac9a0 (worktree: add: introduce --checkout option, 2016-03-29). Recently, we noticed that add_worktree() is rather complicated, so extract the logic for this checkout process to simplify the method. Signed-off-by: Derrick Stolee <derrickstolee@github.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Derrick Stolee committed Feb 23, 2022 at 14:29 UTC 23f832e29ec20ddbded431fdf55f49dc0f54e794
1 file changed +15 -11
builtin/worktree.c
+15 -11
@@ -292,6 +292,18 @@ worktree_copy_cleanup:
292 free(to_file);
293 }
294
295 +static int checkout_worktree(const struct add_opts *opts,
296 + struct strvec *child_env)
297 +{
298 + struct child_process cp = CHILD_PROCESS_INIT;
299 + cp.git_cmd = 1;
300 + strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
301 + if (opts->quiet)
302 + strvec_push(&cp.args, "--quiet");
303 + strvec_pushv(&cp.env_array, child_env->v);
304 + return run_command(&cp);
305 +}
306 +
307 static int add_worktree(const char *path, const char *refname,
308 const struct add_opts *opts)
309 {
@@ -425,17 +437,9 @@ static int add_worktree(const char *path, const char *refname,
437 if (ret)
438 goto done;
439
428 - if (opts->checkout) {
429 - struct child_process cp = CHILD_PROCESS_INIT;
430 - cp.git_cmd = 1;
431 - strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
432 - if (opts->quiet)
433 - strvec_push(&cp.args, "--quiet");
434 - strvec_pushv(&cp.env_array, child_env.v);
435 - ret = run_command(&cp);
436 - if (ret)
437 - goto done;
438 - }
440 + if (opts->checkout &&
441 + (ret = checkout_worktree(opts, &child_env)))
442 + goto done;
443
444 is_junk = 0;
445 FREE_AND_NULL(junk_work_tree);