0affcb476c15ff6baf2b4c2b4ca73d7a38fb5175
   1#include "cache.h"
   2#include "checkout.h"
   3#include "config.h"
   4#include "builtin.h"
   5#include "dir.h"
   6#include "parse-options.h"
   7#include "argv-array.h"
   8#include "branch.h"
   9#include "refs.h"
  10#include "run-command.h"
  11#include "sigchain.h"
  12#include "refs.h"
  13#include "utf8.h"
  14#include "worktree.h"
  15
  16static const char * const worktree_usage[] = {
  17        N_("git worktree add [<options>] <path> [<commit-ish>]"),
  18        N_("git worktree list [<options>]"),
  19        N_("git worktree lock [<options>] <path>"),
  20        N_("git worktree move <worktree> <new-path>"),
  21        N_("git worktree prune [<options>]"),
  22        N_("git worktree remove [<options>] <worktree>"),
  23        N_("git worktree unlock <path>"),
  24        NULL
  25};
  26
  27struct add_opts {
  28        int force;
  29        int detach;
  30        int quiet;
  31        int checkout;
  32        int keep_locked;
  33};
  34
  35static int show_only;
  36static int verbose;
  37static int guess_remote;
  38static timestamp_t expire;
  39
  40static int git_worktree_config(const char *var, const char *value, void *cb)
  41{
  42        if (!strcmp(var, "worktree.guessremote")) {
  43                guess_remote = git_config_bool(var, value);
  44                return 0;
  45        }
  46
  47        return git_default_config(var, value, cb);
  48}
  49
  50static int delete_git_dir(const char *id)
  51{
  52        struct strbuf sb = STRBUF_INIT;
  53        int ret;
  54
  55        strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
  56        ret = remove_dir_recursively(&sb, 0);
  57        if (ret < 0 && errno == ENOTDIR)
  58                ret = unlink(sb.buf);
  59        if (ret)
  60                error_errno(_("failed to delete '%s'"), sb.buf);
  61        strbuf_release(&sb);
  62        return ret;
  63}
  64
  65static int prune_worktree(const char *id, struct strbuf *reason)
  66{
  67        struct stat st;
  68        char *path;
  69        int fd;
  70        size_t len;
  71        ssize_t read_result;
  72
  73        if (!is_directory(git_path("worktrees/%s", id))) {
  74                strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
  75                return 1;
  76        }
  77        if (file_exists(git_path("worktrees/%s/locked", id)))
  78                return 0;
  79        if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
  80                strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
  81                return 1;
  82        }
  83        fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
  84        if (fd < 0) {
  85                strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
  86                            id, strerror(errno));
  87                return 1;
  88        }
  89        len = xsize_t(st.st_size);
  90        path = xmallocz(len);
  91
  92        read_result = read_in_full(fd, path, len);
  93        if (read_result < 0) {
  94                strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
  95                            id, strerror(errno));
  96                close(fd);
  97                free(path);
  98                return 1;
  99        }
 100        close(fd);
 101
 102        if (read_result != len) {
 103                strbuf_addf(reason,
 104                            _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
 105                            id, (uintmax_t)len, (uintmax_t)read_result);
 106                free(path);
 107                return 1;
 108        }
 109        while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
 110                len--;
 111        if (!len) {
 112                strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
 113                free(path);
 114                return 1;
 115        }
 116        path[len] = '\0';
 117        if (!file_exists(path)) {
 118                free(path);
 119                if (stat(git_path("worktrees/%s/index", id), &st) ||
 120                    st.st_mtime <= expire) {
 121                        strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
 122                        return 1;
 123                } else {
 124                        return 0;
 125                }
 126        }
 127        free(path);
 128        return 0;
 129}
 130
 131static void prune_worktrees(void)
 132{
 133        struct strbuf reason = STRBUF_INIT;
 134        DIR *dir = opendir(git_path("worktrees"));
 135        struct dirent *d;
 136        if (!dir)
 137                return;
 138        while ((d = readdir(dir)) != NULL) {
 139                if (is_dot_or_dotdot(d->d_name))
 140                        continue;
 141                strbuf_reset(&reason);
 142                if (!prune_worktree(d->d_name, &reason))
 143                        continue;
 144                if (show_only || verbose)
 145                        printf("%s\n", reason.buf);
 146                if (show_only)
 147                        continue;
 148                delete_git_dir(d->d_name);
 149        }
 150        closedir(dir);
 151        if (!show_only)
 152                rmdir(git_path("worktrees"));
 153        strbuf_release(&reason);
 154}
 155
 156static int prune(int ac, const char **av, const char *prefix)
 157{
 158        struct option options[] = {
 159                OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
 160                OPT__VERBOSE(&verbose, N_("report pruned working trees")),
 161                OPT_EXPIRY_DATE(0, "expire", &expire,
 162                                N_("expire working trees older than <time>")),
 163                OPT_END()
 164        };
 165
 166        expire = TIME_MAX;
 167        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 168        if (ac)
 169                usage_with_options(worktree_usage, options);
 170        prune_worktrees();
 171        return 0;
 172}
 173
 174static char *junk_work_tree;
 175static char *junk_git_dir;
 176static int is_junk;
 177static pid_t junk_pid;
 178
 179static void remove_junk(void)
 180{
 181        struct strbuf sb = STRBUF_INIT;
 182        if (!is_junk || getpid() != junk_pid)
 183                return;
 184        if (junk_git_dir) {
 185                strbuf_addstr(&sb, junk_git_dir);
 186                remove_dir_recursively(&sb, 0);
 187                strbuf_reset(&sb);
 188        }
 189        if (junk_work_tree) {
 190                strbuf_addstr(&sb, junk_work_tree);
 191                remove_dir_recursively(&sb, 0);
 192        }
 193        strbuf_release(&sb);
 194}
 195
 196static void remove_junk_on_signal(int signo)
 197{
 198        remove_junk();
 199        sigchain_pop(signo);
 200        raise(signo);
 201}
 202
 203static const char *worktree_basename(const char *path, int *olen)
 204{
 205        const char *name;
 206        int len;
 207
 208        len = strlen(path);
 209        while (len && is_dir_sep(path[len - 1]))
 210                len--;
 211
 212        for (name = path + len - 1; name > path; name--)
 213                if (is_dir_sep(*name)) {
 214                        name++;
 215                        break;
 216                }
 217
 218        *olen = len;
 219        return name;
 220}
 221
 222static int add_worktree(const char *path, const char *refname,
 223                        const struct add_opts *opts)
 224{
 225        struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
 226        struct strbuf sb = STRBUF_INIT;
 227        const char *name;
 228        struct stat st;
 229        struct child_process cp = CHILD_PROCESS_INIT;
 230        struct argv_array child_env = ARGV_ARRAY_INIT;
 231        int counter = 0, len, ret;
 232        struct strbuf symref = STRBUF_INIT;
 233        struct commit *commit = NULL;
 234        int is_branch = 0;
 235
 236        if (file_exists(path) && !is_empty_dir(path))
 237                die(_("'%s' already exists"), path);
 238
 239        /* is 'refname' a branch or commit? */
 240        if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
 241            ref_exists(symref.buf)) {
 242                is_branch = 1;
 243                if (!opts->force)
 244                        die_if_checked_out(symref.buf, 0);
 245        }
 246        commit = lookup_commit_reference_by_name(refname);
 247        if (!commit)
 248                die(_("invalid reference: %s"), refname);
 249
 250        name = worktree_basename(path, &len);
 251        git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
 252        len = sb_repo.len;
 253        if (safe_create_leading_directories_const(sb_repo.buf))
 254                die_errno(_("could not create leading directories of '%s'"),
 255                          sb_repo.buf);
 256        while (!stat(sb_repo.buf, &st)) {
 257                counter++;
 258                strbuf_setlen(&sb_repo, len);
 259                strbuf_addf(&sb_repo, "%d", counter);
 260        }
 261        name = strrchr(sb_repo.buf, '/') + 1;
 262
 263        junk_pid = getpid();
 264        atexit(remove_junk);
 265        sigchain_push_common(remove_junk_on_signal);
 266
 267        if (mkdir(sb_repo.buf, 0777))
 268                die_errno(_("could not create directory of '%s'"), sb_repo.buf);
 269        junk_git_dir = xstrdup(sb_repo.buf);
 270        is_junk = 1;
 271
 272        /*
 273         * lock the incomplete repo so prune won't delete it, unlock
 274         * after the preparation is over.
 275         */
 276        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 277        if (!opts->keep_locked)
 278                write_file(sb.buf, "initializing");
 279        else
 280                write_file(sb.buf, "added with --lock");
 281
 282        strbuf_addf(&sb_git, "%s/.git", path);
 283        if (safe_create_leading_directories_const(sb_git.buf))
 284                die_errno(_("could not create leading directories of '%s'"),
 285                          sb_git.buf);
 286        junk_work_tree = xstrdup(path);
 287
 288        strbuf_reset(&sb);
 289        strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
 290        write_file(sb.buf, "%s", real_path(sb_git.buf));
 291        write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
 292                   real_path(get_git_common_dir()), name);
 293        /*
 294         * This is to keep resolve_ref() happy. We need a valid HEAD
 295         * or is_git_directory() will reject the directory. Any value which
 296         * looks like an object ID will do since it will be immediately
 297         * replaced by the symbolic-ref or update-ref invocation in the new
 298         * worktree.
 299         */
 300        strbuf_reset(&sb);
 301        strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
 302        write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
 303        strbuf_reset(&sb);
 304        strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
 305        write_file(sb.buf, "../..");
 306
 307        argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
 308        argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
 309        cp.git_cmd = 1;
 310
 311        if (!is_branch)
 312                argv_array_pushl(&cp.args, "update-ref", "HEAD",
 313                                 oid_to_hex(&commit->object.oid), NULL);
 314        else {
 315                argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
 316                                 symref.buf, NULL);
 317                if (opts->quiet)
 318                        argv_array_push(&cp.args, "--quiet");
 319        }
 320
 321        cp.env = child_env.argv;
 322        ret = run_command(&cp);
 323        if (ret)
 324                goto done;
 325
 326        if (opts->checkout) {
 327                cp.argv = NULL;
 328                argv_array_clear(&cp.args);
 329                argv_array_pushl(&cp.args, "reset", "--hard", NULL);
 330                if (opts->quiet)
 331                        argv_array_push(&cp.args, "--quiet");
 332                cp.env = child_env.argv;
 333                ret = run_command(&cp);
 334                if (ret)
 335                        goto done;
 336        }
 337
 338        is_junk = 0;
 339        FREE_AND_NULL(junk_work_tree);
 340        FREE_AND_NULL(junk_git_dir);
 341
 342done:
 343        if (ret || !opts->keep_locked) {
 344                strbuf_reset(&sb);
 345                strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 346                unlink_or_warn(sb.buf);
 347        }
 348
 349        /*
 350         * Hook failure does not warrant worktree deletion, so run hook after
 351         * is_junk is cleared, but do return appropriate code when hook fails.
 352         */
 353        if (!ret && opts->checkout) {
 354                const char *hook = find_hook("post-checkout");
 355                if (hook) {
 356                        const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
 357                        cp.git_cmd = 0;
 358                        cp.no_stdin = 1;
 359                        cp.stdout_to_stderr = 1;
 360                        cp.dir = path;
 361                        cp.env = env;
 362                        cp.argv = NULL;
 363                        argv_array_pushl(&cp.args, absolute_path(hook),
 364                                         oid_to_hex(&null_oid),
 365                                         oid_to_hex(&commit->object.oid),
 366                                         "1", NULL);
 367                        ret = run_command(&cp);
 368                }
 369        }
 370
 371        argv_array_clear(&child_env);
 372        strbuf_release(&sb);
 373        strbuf_release(&symref);
 374        strbuf_release(&sb_repo);
 375        strbuf_release(&sb_git);
 376        return ret;
 377}
 378
 379static void print_preparing_worktree_line(int detach,
 380                                          const char *branch,
 381                                          const char *new_branch,
 382                                          int force_new_branch)
 383{
 384        if (force_new_branch) {
 385                struct commit *commit = lookup_commit_reference_by_name(new_branch);
 386                if (!commit)
 387                        printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
 388                else
 389                        printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
 390                                  new_branch,
 391                                  find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
 392        } else if (new_branch) {
 393                printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
 394        } else {
 395                struct strbuf s = STRBUF_INIT;
 396                if (!detach && !strbuf_check_branch_ref(&s, branch) &&
 397                    ref_exists(s.buf))
 398                        printf_ln(_("Preparing worktree (checking out '%s')"),
 399                                  branch);
 400                else {
 401                        struct commit *commit = lookup_commit_reference_by_name(branch);
 402                        if (!commit)
 403                                die(_("invalid reference: %s"), branch);
 404                        printf_ln(_("Preparing worktree (detached HEAD %s)"),
 405                                  find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
 406                }
 407                strbuf_release(&s);
 408        }
 409}
 410
 411static const char *dwim_branch(const char *path, const char **new_branch)
 412{
 413        int n;
 414        const char *s = worktree_basename(path, &n);
 415        const char *branchname = xstrndup(s, n);
 416        struct strbuf ref = STRBUF_INIT;
 417
 418        UNLEAK(branchname);
 419        if (!strbuf_check_branch_ref(&ref, branchname) &&
 420            ref_exists(ref.buf)) {
 421                strbuf_release(&ref);
 422                return branchname;
 423        }
 424
 425        *new_branch = branchname;
 426        if (guess_remote) {
 427                struct object_id oid;
 428                const char *remote =
 429                        unique_tracking_name(*new_branch, &oid, NULL);
 430                return remote;
 431        }
 432        return NULL;
 433}
 434
 435static int add(int ac, const char **av, const char *prefix)
 436{
 437        struct add_opts opts;
 438        const char *new_branch_force = NULL;
 439        char *path;
 440        const char *branch;
 441        const char *new_branch = NULL;
 442        const char *opt_track = NULL;
 443        struct option options[] = {
 444                OPT__FORCE(&opts.force,
 445                           N_("checkout <branch> even if already checked out in other worktree"),
 446                           PARSE_OPT_NOCOMPLETE),
 447                OPT_STRING('b', NULL, &new_branch, N_("branch"),
 448                           N_("create a new branch")),
 449                OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
 450                           N_("create or reset a branch")),
 451                OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
 452                OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
 453                OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
 454                OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
 455                OPT_PASSTHRU(0, "track", &opt_track, NULL,
 456                             N_("set up tracking mode (see git-branch(1))"),
 457                             PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
 458                OPT_BOOL(0, "guess-remote", &guess_remote,
 459                         N_("try to match the new branch name with a remote-tracking branch")),
 460                OPT_END()
 461        };
 462
 463        memset(&opts, 0, sizeof(opts));
 464        opts.checkout = 1;
 465        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 466        if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
 467                die(_("-b, -B, and --detach are mutually exclusive"));
 468        if (ac < 1 || ac > 2)
 469                usage_with_options(worktree_usage, options);
 470
 471        path = prefix_filename(prefix, av[0]);
 472        branch = ac < 2 ? "HEAD" : av[1];
 473
 474        if (!strcmp(branch, "-"))
 475                branch = "@{-1}";
 476
 477        if (new_branch_force) {
 478                struct strbuf symref = STRBUF_INIT;
 479
 480                new_branch = new_branch_force;
 481
 482                if (!opts.force &&
 483                    !strbuf_check_branch_ref(&symref, new_branch) &&
 484                    ref_exists(symref.buf))
 485                        die_if_checked_out(symref.buf, 0);
 486                strbuf_release(&symref);
 487        }
 488
 489        if (ac < 2 && !new_branch && !opts.detach) {
 490                const char *s = dwim_branch(path, &new_branch);
 491                if (s)
 492                        branch = s;
 493        }
 494
 495        if (ac == 2 && !new_branch && !opts.detach) {
 496                struct object_id oid;
 497                struct commit *commit;
 498                const char *remote;
 499
 500                commit = lookup_commit_reference_by_name(branch);
 501                if (!commit) {
 502                        remote = unique_tracking_name(branch, &oid, NULL);
 503                        if (remote) {
 504                                new_branch = branch;
 505                                branch = remote;
 506                        }
 507                }
 508        }
 509        if (!opts.quiet)
 510                print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
 511
 512        if (new_branch) {
 513                struct child_process cp = CHILD_PROCESS_INIT;
 514                cp.git_cmd = 1;
 515                argv_array_push(&cp.args, "branch");
 516                if (new_branch_force)
 517                        argv_array_push(&cp.args, "--force");
 518                if (opts.quiet)
 519                        argv_array_push(&cp.args, "--quiet");
 520                argv_array_push(&cp.args, new_branch);
 521                argv_array_push(&cp.args, branch);
 522                if (opt_track)
 523                        argv_array_push(&cp.args, opt_track);
 524                if (run_command(&cp))
 525                        return -1;
 526                branch = new_branch;
 527        } else if (opt_track) {
 528                die(_("--[no-]track can only be used if a new branch is created"));
 529        }
 530
 531        UNLEAK(path);
 532        UNLEAK(opts);
 533        return add_worktree(path, branch, &opts);
 534}
 535
 536static void show_worktree_porcelain(struct worktree *wt)
 537{
 538        printf("worktree %s\n", wt->path);
 539        if (wt->is_bare)
 540                printf("bare\n");
 541        else {
 542                printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
 543                if (wt->is_detached)
 544                        printf("detached\n");
 545                else if (wt->head_ref)
 546                        printf("branch %s\n", wt->head_ref);
 547        }
 548        printf("\n");
 549}
 550
 551static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
 552{
 553        struct strbuf sb = STRBUF_INIT;
 554        int cur_path_len = strlen(wt->path);
 555        int path_adj = cur_path_len - utf8_strwidth(wt->path);
 556
 557        strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
 558        if (wt->is_bare)
 559                strbuf_addstr(&sb, "(bare)");
 560        else {
 561                strbuf_addf(&sb, "%-*s ", abbrev_len,
 562                                find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
 563                if (wt->is_detached)
 564                        strbuf_addstr(&sb, "(detached HEAD)");
 565                else if (wt->head_ref) {
 566                        char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
 567                        strbuf_addf(&sb, "[%s]", ref);
 568                        free(ref);
 569                } else
 570                        strbuf_addstr(&sb, "(error)");
 571        }
 572        printf("%s\n", sb.buf);
 573
 574        strbuf_release(&sb);
 575}
 576
 577static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
 578{
 579        int i;
 580
 581        for (i = 0; wt[i]; i++) {
 582                int sha1_len;
 583                int path_len = strlen(wt[i]->path);
 584
 585                if (path_len > *maxlen)
 586                        *maxlen = path_len;
 587                sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
 588                if (sha1_len > *abbrev)
 589                        *abbrev = sha1_len;
 590        }
 591}
 592
 593static int list(int ac, const char **av, const char *prefix)
 594{
 595        int porcelain = 0;
 596
 597        struct option options[] = {
 598                OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
 599                OPT_END()
 600        };
 601
 602        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 603        if (ac)
 604                usage_with_options(worktree_usage, options);
 605        else {
 606                struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
 607                int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
 608
 609                if (!porcelain)
 610                        measure_widths(worktrees, &abbrev, &path_maxlen);
 611
 612                for (i = 0; worktrees[i]; i++) {
 613                        if (porcelain)
 614                                show_worktree_porcelain(worktrees[i]);
 615                        else
 616                                show_worktree(worktrees[i], path_maxlen, abbrev);
 617                }
 618                free_worktrees(worktrees);
 619        }
 620        return 0;
 621}
 622
 623static int lock_worktree(int ac, const char **av, const char *prefix)
 624{
 625        const char *reason = "", *old_reason;
 626        struct option options[] = {
 627                OPT_STRING(0, "reason", &reason, N_("string"),
 628                           N_("reason for locking")),
 629                OPT_END()
 630        };
 631        struct worktree **worktrees, *wt;
 632
 633        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 634        if (ac != 1)
 635                usage_with_options(worktree_usage, options);
 636
 637        worktrees = get_worktrees(0);
 638        wt = find_worktree(worktrees, prefix, av[0]);
 639        if (!wt)
 640                die(_("'%s' is not a working tree"), av[0]);
 641        if (is_main_worktree(wt))
 642                die(_("The main working tree cannot be locked or unlocked"));
 643
 644        old_reason = is_worktree_locked(wt);
 645        if (old_reason) {
 646                if (*old_reason)
 647                        die(_("'%s' is already locked, reason: %s"),
 648                            av[0], old_reason);
 649                die(_("'%s' is already locked"), av[0]);
 650        }
 651
 652        write_file(git_common_path("worktrees/%s/locked", wt->id),
 653                   "%s", reason);
 654        free_worktrees(worktrees);
 655        return 0;
 656}
 657
 658static int unlock_worktree(int ac, const char **av, const char *prefix)
 659{
 660        struct option options[] = {
 661                OPT_END()
 662        };
 663        struct worktree **worktrees, *wt;
 664        int ret;
 665
 666        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 667        if (ac != 1)
 668                usage_with_options(worktree_usage, options);
 669
 670        worktrees = get_worktrees(0);
 671        wt = find_worktree(worktrees, prefix, av[0]);
 672        if (!wt)
 673                die(_("'%s' is not a working tree"), av[0]);
 674        if (is_main_worktree(wt))
 675                die(_("The main working tree cannot be locked or unlocked"));
 676        if (!is_worktree_locked(wt))
 677                die(_("'%s' is not locked"), av[0]);
 678        ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
 679        free_worktrees(worktrees);
 680        return ret;
 681}
 682
 683static void validate_no_submodules(const struct worktree *wt)
 684{
 685        struct index_state istate = { NULL };
 686        int i, found_submodules = 0;
 687
 688        if (read_index_from(&istate, worktree_git_path(wt, "index"),
 689                            get_worktree_git_dir(wt)) > 0) {
 690                for (i = 0; i < istate.cache_nr; i++) {
 691                        struct cache_entry *ce = istate.cache[i];
 692
 693                        if (S_ISGITLINK(ce->ce_mode)) {
 694                                found_submodules = 1;
 695                                break;
 696                        }
 697                }
 698        }
 699        discard_index(&istate);
 700
 701        if (found_submodules)
 702                die(_("working trees containing submodules cannot be moved or removed"));
 703}
 704
 705static int move_worktree(int ac, const char **av, const char *prefix)
 706{
 707        struct option options[] = {
 708                OPT_END()
 709        };
 710        struct worktree **worktrees, *wt;
 711        struct strbuf dst = STRBUF_INIT;
 712        struct strbuf errmsg = STRBUF_INIT;
 713        const char *reason;
 714        char *path;
 715
 716        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 717        if (ac != 2)
 718                usage_with_options(worktree_usage, options);
 719
 720        path = prefix_filename(prefix, av[1]);
 721        strbuf_addstr(&dst, path);
 722        free(path);
 723
 724        worktrees = get_worktrees(0);
 725        wt = find_worktree(worktrees, prefix, av[0]);
 726        if (!wt)
 727                die(_("'%s' is not a working tree"), av[0]);
 728        if (is_main_worktree(wt))
 729                die(_("'%s' is a main working tree"), av[0]);
 730        if (is_directory(dst.buf)) {
 731                const char *sep = find_last_dir_sep(wt->path);
 732
 733                if (!sep)
 734                        die(_("could not figure out destination name from '%s'"),
 735                            wt->path);
 736                strbuf_trim_trailing_dir_sep(&dst);
 737                strbuf_addstr(&dst, sep);
 738        }
 739        if (file_exists(dst.buf))
 740                die(_("target '%s' already exists"), dst.buf);
 741
 742        validate_no_submodules(wt);
 743
 744        reason = is_worktree_locked(wt);
 745        if (reason) {
 746                if (*reason)
 747                        die(_("cannot move a locked working tree, lock reason: %s"),
 748                            reason);
 749                die(_("cannot move a locked working tree"));
 750        }
 751        if (validate_worktree(wt, &errmsg, 0))
 752                die(_("validation failed, cannot move working tree: %s"),
 753                    errmsg.buf);
 754        strbuf_release(&errmsg);
 755
 756        if (rename(wt->path, dst.buf) == -1)
 757                die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
 758
 759        update_worktree_location(wt, dst.buf);
 760
 761        strbuf_release(&dst);
 762        free_worktrees(worktrees);
 763        return 0;
 764}
 765
 766/*
 767 * Note, "git status --porcelain" is used to determine if it's safe to
 768 * delete a whole worktree. "git status" does not ignore user
 769 * configuration, so if a normal "git status" shows "clean" for the
 770 * user, then it's ok to remove it.
 771 *
 772 * This assumption may be a bad one. We may want to ignore
 773 * (potentially bad) user settings and only delete a worktree when
 774 * it's absolutely safe to do so from _our_ point of view because we
 775 * know better.
 776 */
 777static void check_clean_worktree(struct worktree *wt,
 778                                 const char *original_path)
 779{
 780        struct argv_array child_env = ARGV_ARRAY_INIT;
 781        struct child_process cp;
 782        char buf[1];
 783        int ret;
 784
 785        /*
 786         * Until we sort this out, all submodules are "dirty" and
 787         * will abort this function.
 788         */
 789        validate_no_submodules(wt);
 790
 791        argv_array_pushf(&child_env, "%s=%s/.git",
 792                         GIT_DIR_ENVIRONMENT, wt->path);
 793        argv_array_pushf(&child_env, "%s=%s",
 794                         GIT_WORK_TREE_ENVIRONMENT, wt->path);
 795        memset(&cp, 0, sizeof(cp));
 796        argv_array_pushl(&cp.args, "status",
 797                         "--porcelain", "--ignore-submodules=none",
 798                         NULL);
 799        cp.env = child_env.argv;
 800        cp.git_cmd = 1;
 801        cp.dir = wt->path;
 802        cp.out = -1;
 803        ret = start_command(&cp);
 804        if (ret)
 805                die_errno(_("failed to run 'git status' on '%s'"),
 806                          original_path);
 807        ret = xread(cp.out, buf, sizeof(buf));
 808        if (ret)
 809                die(_("'%s' is dirty, use --force to delete it"),
 810                    original_path);
 811        close(cp.out);
 812        ret = finish_command(&cp);
 813        if (ret)
 814                die_errno(_("failed to run 'git status' on '%s', code %d"),
 815                          original_path, ret);
 816}
 817
 818static int delete_git_work_tree(struct worktree *wt)
 819{
 820        struct strbuf sb = STRBUF_INIT;
 821        int ret = 0;
 822
 823        strbuf_addstr(&sb, wt->path);
 824        if (remove_dir_recursively(&sb, 0)) {
 825                error_errno(_("failed to delete '%s'"), sb.buf);
 826                ret = -1;
 827        }
 828        strbuf_release(&sb);
 829        return ret;
 830}
 831
 832static int remove_worktree(int ac, const char **av, const char *prefix)
 833{
 834        int force = 0;
 835        struct option options[] = {
 836                OPT__FORCE(&force,
 837                         N_("force removing even if the worktree is dirty"),
 838                         PARSE_OPT_NOCOMPLETE),
 839                OPT_END()
 840        };
 841        struct worktree **worktrees, *wt;
 842        struct strbuf errmsg = STRBUF_INIT;
 843        const char *reason;
 844        int ret = 0;
 845
 846        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 847        if (ac != 1)
 848                usage_with_options(worktree_usage, options);
 849
 850        worktrees = get_worktrees(0);
 851        wt = find_worktree(worktrees, prefix, av[0]);
 852        if (!wt)
 853                die(_("'%s' is not a working tree"), av[0]);
 854        if (is_main_worktree(wt))
 855                die(_("'%s' is a main working tree"), av[0]);
 856        reason = is_worktree_locked(wt);
 857        if (reason) {
 858                if (*reason)
 859                        die(_("cannot remove a locked working tree, lock reason: %s"),
 860                            reason);
 861                die(_("cannot remove a locked working tree"));
 862        }
 863        if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
 864                die(_("validation failed, cannot remove working tree: %s"),
 865                    errmsg.buf);
 866        strbuf_release(&errmsg);
 867
 868        if (file_exists(wt->path)) {
 869                if (!force)
 870                        check_clean_worktree(wt, av[0]);
 871
 872                ret |= delete_git_work_tree(wt);
 873        }
 874        /*
 875         * continue on even if ret is non-zero, there's no going back
 876         * from here.
 877         */
 878        ret |= delete_git_dir(wt->id);
 879
 880        free_worktrees(worktrees);
 881        return ret;
 882}
 883
 884int cmd_worktree(int ac, const char **av, const char *prefix)
 885{
 886        struct option options[] = {
 887                OPT_END()
 888        };
 889
 890        git_config(git_worktree_config, NULL);
 891
 892        if (ac < 2)
 893                usage_with_options(worktree_usage, options);
 894        if (!prefix)
 895                prefix = "";
 896        if (!strcmp(av[1], "add"))
 897                return add(ac - 1, av + 1, prefix);
 898        if (!strcmp(av[1], "prune"))
 899                return prune(ac - 1, av + 1, prefix);
 900        if (!strcmp(av[1], "list"))
 901                return list(ac - 1, av + 1, prefix);
 902        if (!strcmp(av[1], "lock"))
 903                return lock_worktree(ac - 1, av + 1, prefix);
 904        if (!strcmp(av[1], "unlock"))
 905                return unlock_worktree(ac - 1, av + 1, prefix);
 906        if (!strcmp(av[1], "move"))
 907                return move_worktree(ac - 1, av + 1, prefix);
 908        if (!strcmp(av[1], "remove"))
 909                return remove_worktree(ac - 1, av + 1, prefix);
 910        usage_with_options(worktree_usage, options);
 911}