builtin / worktree.con commit worktree: disallow adding same path multiple times (cb56f55)
   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 void validate_worktree_add(const char *path, const struct add_opts *opts)
 223{
 224        struct worktree **worktrees;
 225        struct worktree *wt;
 226        int locked;
 227
 228        if (file_exists(path) && !is_empty_dir(path))
 229                die(_("'%s' already exists"), path);
 230
 231        worktrees = get_worktrees(0);
 232        /*
 233         * find_worktree()'s suffix matching may undesirably find the main
 234         * rather than a linked worktree (for instance, when the basenames
 235         * of the main worktree and the one being created are the same).
 236         * We're only interested in linked worktrees, so skip the main
 237         * worktree with +1.
 238         */
 239        wt = find_worktree(worktrees + 1, NULL, path);
 240        if (!wt)
 241                goto done;
 242
 243        locked = !!is_worktree_locked(wt);
 244        if (locked)
 245                die(_("'%s' is a missing but locked worktree;\nuse 'unlock' and 'prune' or 'remove' to clear"), path);
 246        else
 247                die(_("'%s' is a missing but already registered worktree;\nuse 'prune' or 'remove' to clear"), path);
 248
 249done:
 250        free_worktrees(worktrees);
 251}
 252
 253static int add_worktree(const char *path, const char *refname,
 254                        const struct add_opts *opts)
 255{
 256        struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
 257        struct strbuf sb = STRBUF_INIT;
 258        const char *name;
 259        struct stat st;
 260        struct child_process cp = CHILD_PROCESS_INIT;
 261        struct argv_array child_env = ARGV_ARRAY_INIT;
 262        int counter = 0, len, ret;
 263        struct strbuf symref = STRBUF_INIT;
 264        struct commit *commit = NULL;
 265        int is_branch = 0;
 266
 267        validate_worktree_add(path, opts);
 268
 269        /* is 'refname' a branch or commit? */
 270        if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
 271            ref_exists(symref.buf)) {
 272                is_branch = 1;
 273                if (!opts->force)
 274                        die_if_checked_out(symref.buf, 0);
 275        }
 276        commit = lookup_commit_reference_by_name(refname);
 277        if (!commit)
 278                die(_("invalid reference: %s"), refname);
 279
 280        name = worktree_basename(path, &len);
 281        git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
 282        len = sb_repo.len;
 283        if (safe_create_leading_directories_const(sb_repo.buf))
 284                die_errno(_("could not create leading directories of '%s'"),
 285                          sb_repo.buf);
 286        while (!stat(sb_repo.buf, &st)) {
 287                counter++;
 288                strbuf_setlen(&sb_repo, len);
 289                strbuf_addf(&sb_repo, "%d", counter);
 290        }
 291        name = strrchr(sb_repo.buf, '/') + 1;
 292
 293        junk_pid = getpid();
 294        atexit(remove_junk);
 295        sigchain_push_common(remove_junk_on_signal);
 296
 297        if (mkdir(sb_repo.buf, 0777))
 298                die_errno(_("could not create directory of '%s'"), sb_repo.buf);
 299        junk_git_dir = xstrdup(sb_repo.buf);
 300        is_junk = 1;
 301
 302        /*
 303         * lock the incomplete repo so prune won't delete it, unlock
 304         * after the preparation is over.
 305         */
 306        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 307        if (!opts->keep_locked)
 308                write_file(sb.buf, "initializing");
 309        else
 310                write_file(sb.buf, "added with --lock");
 311
 312        strbuf_addf(&sb_git, "%s/.git", path);
 313        if (safe_create_leading_directories_const(sb_git.buf))
 314                die_errno(_("could not create leading directories of '%s'"),
 315                          sb_git.buf);
 316        junk_work_tree = xstrdup(path);
 317
 318        strbuf_reset(&sb);
 319        strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
 320        write_file(sb.buf, "%s", real_path(sb_git.buf));
 321        write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
 322                   real_path(get_git_common_dir()), name);
 323        /*
 324         * This is to keep resolve_ref() happy. We need a valid HEAD
 325         * or is_git_directory() will reject the directory. Any value which
 326         * looks like an object ID will do since it will be immediately
 327         * replaced by the symbolic-ref or update-ref invocation in the new
 328         * worktree.
 329         */
 330        strbuf_reset(&sb);
 331        strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
 332        write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
 333        strbuf_reset(&sb);
 334        strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
 335        write_file(sb.buf, "../..");
 336
 337        argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
 338        argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
 339        cp.git_cmd = 1;
 340
 341        if (!is_branch)
 342                argv_array_pushl(&cp.args, "update-ref", "HEAD",
 343                                 oid_to_hex(&commit->object.oid), NULL);
 344        else {
 345                argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
 346                                 symref.buf, NULL);
 347                if (opts->quiet)
 348                        argv_array_push(&cp.args, "--quiet");
 349        }
 350
 351        cp.env = child_env.argv;
 352        ret = run_command(&cp);
 353        if (ret)
 354                goto done;
 355
 356        if (opts->checkout) {
 357                cp.argv = NULL;
 358                argv_array_clear(&cp.args);
 359                argv_array_pushl(&cp.args, "reset", "--hard", NULL);
 360                if (opts->quiet)
 361                        argv_array_push(&cp.args, "--quiet");
 362                cp.env = child_env.argv;
 363                ret = run_command(&cp);
 364                if (ret)
 365                        goto done;
 366        }
 367
 368        is_junk = 0;
 369        FREE_AND_NULL(junk_work_tree);
 370        FREE_AND_NULL(junk_git_dir);
 371
 372done:
 373        if (ret || !opts->keep_locked) {
 374                strbuf_reset(&sb);
 375                strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 376                unlink_or_warn(sb.buf);
 377        }
 378
 379        /*
 380         * Hook failure does not warrant worktree deletion, so run hook after
 381         * is_junk is cleared, but do return appropriate code when hook fails.
 382         */
 383        if (!ret && opts->checkout) {
 384                const char *hook = find_hook("post-checkout");
 385                if (hook) {
 386                        const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
 387                        cp.git_cmd = 0;
 388                        cp.no_stdin = 1;
 389                        cp.stdout_to_stderr = 1;
 390                        cp.dir = path;
 391                        cp.env = env;
 392                        cp.argv = NULL;
 393                        argv_array_pushl(&cp.args, absolute_path(hook),
 394                                         oid_to_hex(&null_oid),
 395                                         oid_to_hex(&commit->object.oid),
 396                                         "1", NULL);
 397                        ret = run_command(&cp);
 398                }
 399        }
 400
 401        argv_array_clear(&child_env);
 402        strbuf_release(&sb);
 403        strbuf_release(&symref);
 404        strbuf_release(&sb_repo);
 405        strbuf_release(&sb_git);
 406        return ret;
 407}
 408
 409static void print_preparing_worktree_line(int detach,
 410                                          const char *branch,
 411                                          const char *new_branch,
 412                                          int force_new_branch)
 413{
 414        if (force_new_branch) {
 415                struct commit *commit = lookup_commit_reference_by_name(new_branch);
 416                if (!commit)
 417                        printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
 418                else
 419                        printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
 420                                  new_branch,
 421                                  find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
 422        } else if (new_branch) {
 423                printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
 424        } else {
 425                struct strbuf s = STRBUF_INIT;
 426                if (!detach && !strbuf_check_branch_ref(&s, branch) &&
 427                    ref_exists(s.buf))
 428                        printf_ln(_("Preparing worktree (checking out '%s')"),
 429                                  branch);
 430                else {
 431                        struct commit *commit = lookup_commit_reference_by_name(branch);
 432                        if (!commit)
 433                                die(_("invalid reference: %s"), branch);
 434                        printf_ln(_("Preparing worktree (detached HEAD %s)"),
 435                                  find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
 436                }
 437                strbuf_release(&s);
 438        }
 439}
 440
 441static const char *dwim_branch(const char *path, const char **new_branch)
 442{
 443        int n;
 444        const char *s = worktree_basename(path, &n);
 445        const char *branchname = xstrndup(s, n);
 446        struct strbuf ref = STRBUF_INIT;
 447
 448        UNLEAK(branchname);
 449        if (!strbuf_check_branch_ref(&ref, branchname) &&
 450            ref_exists(ref.buf)) {
 451                strbuf_release(&ref);
 452                return branchname;
 453        }
 454
 455        *new_branch = branchname;
 456        if (guess_remote) {
 457                struct object_id oid;
 458                const char *remote =
 459                        unique_tracking_name(*new_branch, &oid, NULL);
 460                return remote;
 461        }
 462        return NULL;
 463}
 464
 465static int add(int ac, const char **av, const char *prefix)
 466{
 467        struct add_opts opts;
 468        const char *new_branch_force = NULL;
 469        char *path;
 470        const char *branch;
 471        const char *new_branch = NULL;
 472        const char *opt_track = NULL;
 473        struct option options[] = {
 474                OPT__FORCE(&opts.force,
 475                           N_("checkout <branch> even if already checked out in other worktree"),
 476                           PARSE_OPT_NOCOMPLETE),
 477                OPT_STRING('b', NULL, &new_branch, N_("branch"),
 478                           N_("create a new branch")),
 479                OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
 480                           N_("create or reset a branch")),
 481                OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
 482                OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
 483                OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
 484                OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
 485                OPT_PASSTHRU(0, "track", &opt_track, NULL,
 486                             N_("set up tracking mode (see git-branch(1))"),
 487                             PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
 488                OPT_BOOL(0, "guess-remote", &guess_remote,
 489                         N_("try to match the new branch name with a remote-tracking branch")),
 490                OPT_END()
 491        };
 492
 493        memset(&opts, 0, sizeof(opts));
 494        opts.checkout = 1;
 495        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 496        if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
 497                die(_("-b, -B, and --detach are mutually exclusive"));
 498        if (ac < 1 || ac > 2)
 499                usage_with_options(worktree_usage, options);
 500
 501        path = prefix_filename(prefix, av[0]);
 502        branch = ac < 2 ? "HEAD" : av[1];
 503
 504        if (!strcmp(branch, "-"))
 505                branch = "@{-1}";
 506
 507        if (new_branch_force) {
 508                struct strbuf symref = STRBUF_INIT;
 509
 510                new_branch = new_branch_force;
 511
 512                if (!opts.force &&
 513                    !strbuf_check_branch_ref(&symref, new_branch) &&
 514                    ref_exists(symref.buf))
 515                        die_if_checked_out(symref.buf, 0);
 516                strbuf_release(&symref);
 517        }
 518
 519        if (ac < 2 && !new_branch && !opts.detach) {
 520                const char *s = dwim_branch(path, &new_branch);
 521                if (s)
 522                        branch = s;
 523        }
 524
 525        if (ac == 2 && !new_branch && !opts.detach) {
 526                struct object_id oid;
 527                struct commit *commit;
 528                const char *remote;
 529
 530                commit = lookup_commit_reference_by_name(branch);
 531                if (!commit) {
 532                        remote = unique_tracking_name(branch, &oid, NULL);
 533                        if (remote) {
 534                                new_branch = branch;
 535                                branch = remote;
 536                        }
 537                }
 538        }
 539        if (!opts.quiet)
 540                print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
 541
 542        if (new_branch) {
 543                struct child_process cp = CHILD_PROCESS_INIT;
 544                cp.git_cmd = 1;
 545                argv_array_push(&cp.args, "branch");
 546                if (new_branch_force)
 547                        argv_array_push(&cp.args, "--force");
 548                if (opts.quiet)
 549                        argv_array_push(&cp.args, "--quiet");
 550                argv_array_push(&cp.args, new_branch);
 551                argv_array_push(&cp.args, branch);
 552                if (opt_track)
 553                        argv_array_push(&cp.args, opt_track);
 554                if (run_command(&cp))
 555                        return -1;
 556                branch = new_branch;
 557        } else if (opt_track) {
 558                die(_("--[no-]track can only be used if a new branch is created"));
 559        }
 560
 561        UNLEAK(path);
 562        UNLEAK(opts);
 563        return add_worktree(path, branch, &opts);
 564}
 565
 566static void show_worktree_porcelain(struct worktree *wt)
 567{
 568        printf("worktree %s\n", wt->path);
 569        if (wt->is_bare)
 570                printf("bare\n");
 571        else {
 572                printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
 573                if (wt->is_detached)
 574                        printf("detached\n");
 575                else if (wt->head_ref)
 576                        printf("branch %s\n", wt->head_ref);
 577        }
 578        printf("\n");
 579}
 580
 581static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
 582{
 583        struct strbuf sb = STRBUF_INIT;
 584        int cur_path_len = strlen(wt->path);
 585        int path_adj = cur_path_len - utf8_strwidth(wt->path);
 586
 587        strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
 588        if (wt->is_bare)
 589                strbuf_addstr(&sb, "(bare)");
 590        else {
 591                strbuf_addf(&sb, "%-*s ", abbrev_len,
 592                                find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
 593                if (wt->is_detached)
 594                        strbuf_addstr(&sb, "(detached HEAD)");
 595                else if (wt->head_ref) {
 596                        char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
 597                        strbuf_addf(&sb, "[%s]", ref);
 598                        free(ref);
 599                } else
 600                        strbuf_addstr(&sb, "(error)");
 601        }
 602        printf("%s\n", sb.buf);
 603
 604        strbuf_release(&sb);
 605}
 606
 607static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
 608{
 609        int i;
 610
 611        for (i = 0; wt[i]; i++) {
 612                int sha1_len;
 613                int path_len = strlen(wt[i]->path);
 614
 615                if (path_len > *maxlen)
 616                        *maxlen = path_len;
 617                sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
 618                if (sha1_len > *abbrev)
 619                        *abbrev = sha1_len;
 620        }
 621}
 622
 623static int list(int ac, const char **av, const char *prefix)
 624{
 625        int porcelain = 0;
 626
 627        struct option options[] = {
 628                OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
 629                OPT_END()
 630        };
 631
 632        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 633        if (ac)
 634                usage_with_options(worktree_usage, options);
 635        else {
 636                struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
 637                int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
 638
 639                if (!porcelain)
 640                        measure_widths(worktrees, &abbrev, &path_maxlen);
 641
 642                for (i = 0; worktrees[i]; i++) {
 643                        if (porcelain)
 644                                show_worktree_porcelain(worktrees[i]);
 645                        else
 646                                show_worktree(worktrees[i], path_maxlen, abbrev);
 647                }
 648                free_worktrees(worktrees);
 649        }
 650        return 0;
 651}
 652
 653static int lock_worktree(int ac, const char **av, const char *prefix)
 654{
 655        const char *reason = "", *old_reason;
 656        struct option options[] = {
 657                OPT_STRING(0, "reason", &reason, N_("string"),
 658                           N_("reason for locking")),
 659                OPT_END()
 660        };
 661        struct worktree **worktrees, *wt;
 662
 663        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 664        if (ac != 1)
 665                usage_with_options(worktree_usage, options);
 666
 667        worktrees = get_worktrees(0);
 668        wt = find_worktree(worktrees, prefix, av[0]);
 669        if (!wt)
 670                die(_("'%s' is not a working tree"), av[0]);
 671        if (is_main_worktree(wt))
 672                die(_("The main working tree cannot be locked or unlocked"));
 673
 674        old_reason = is_worktree_locked(wt);
 675        if (old_reason) {
 676                if (*old_reason)
 677                        die(_("'%s' is already locked, reason: %s"),
 678                            av[0], old_reason);
 679                die(_("'%s' is already locked"), av[0]);
 680        }
 681
 682        write_file(git_common_path("worktrees/%s/locked", wt->id),
 683                   "%s", reason);
 684        free_worktrees(worktrees);
 685        return 0;
 686}
 687
 688static int unlock_worktree(int ac, const char **av, const char *prefix)
 689{
 690        struct option options[] = {
 691                OPT_END()
 692        };
 693        struct worktree **worktrees, *wt;
 694        int ret;
 695
 696        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 697        if (ac != 1)
 698                usage_with_options(worktree_usage, options);
 699
 700        worktrees = get_worktrees(0);
 701        wt = find_worktree(worktrees, prefix, av[0]);
 702        if (!wt)
 703                die(_("'%s' is not a working tree"), av[0]);
 704        if (is_main_worktree(wt))
 705                die(_("The main working tree cannot be locked or unlocked"));
 706        if (!is_worktree_locked(wt))
 707                die(_("'%s' is not locked"), av[0]);
 708        ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
 709        free_worktrees(worktrees);
 710        return ret;
 711}
 712
 713static void validate_no_submodules(const struct worktree *wt)
 714{
 715        struct index_state istate = { NULL };
 716        int i, found_submodules = 0;
 717
 718        if (read_index_from(&istate, worktree_git_path(wt, "index"),
 719                            get_worktree_git_dir(wt)) > 0) {
 720                for (i = 0; i < istate.cache_nr; i++) {
 721                        struct cache_entry *ce = istate.cache[i];
 722
 723                        if (S_ISGITLINK(ce->ce_mode)) {
 724                                found_submodules = 1;
 725                                break;
 726                        }
 727                }
 728        }
 729        discard_index(&istate);
 730
 731        if (found_submodules)
 732                die(_("working trees containing submodules cannot be moved or removed"));
 733}
 734
 735static int move_worktree(int ac, const char **av, const char *prefix)
 736{
 737        struct option options[] = {
 738                OPT_END()
 739        };
 740        struct worktree **worktrees, *wt;
 741        struct strbuf dst = STRBUF_INIT;
 742        struct strbuf errmsg = STRBUF_INIT;
 743        const char *reason;
 744        char *path;
 745
 746        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 747        if (ac != 2)
 748                usage_with_options(worktree_usage, options);
 749
 750        path = prefix_filename(prefix, av[1]);
 751        strbuf_addstr(&dst, path);
 752        free(path);
 753
 754        worktrees = get_worktrees(0);
 755        wt = find_worktree(worktrees, prefix, av[0]);
 756        if (!wt)
 757                die(_("'%s' is not a working tree"), av[0]);
 758        if (is_main_worktree(wt))
 759                die(_("'%s' is a main working tree"), av[0]);
 760        if (is_directory(dst.buf)) {
 761                const char *sep = find_last_dir_sep(wt->path);
 762
 763                if (!sep)
 764                        die(_("could not figure out destination name from '%s'"),
 765                            wt->path);
 766                strbuf_trim_trailing_dir_sep(&dst);
 767                strbuf_addstr(&dst, sep);
 768        }
 769        if (file_exists(dst.buf))
 770                die(_("target '%s' already exists"), dst.buf);
 771
 772        validate_no_submodules(wt);
 773
 774        reason = is_worktree_locked(wt);
 775        if (reason) {
 776                if (*reason)
 777                        die(_("cannot move a locked working tree, lock reason: %s"),
 778                            reason);
 779                die(_("cannot move a locked working tree"));
 780        }
 781        if (validate_worktree(wt, &errmsg, 0))
 782                die(_("validation failed, cannot move working tree: %s"),
 783                    errmsg.buf);
 784        strbuf_release(&errmsg);
 785
 786        if (rename(wt->path, dst.buf) == -1)
 787                die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
 788
 789        update_worktree_location(wt, dst.buf);
 790
 791        strbuf_release(&dst);
 792        free_worktrees(worktrees);
 793        return 0;
 794}
 795
 796/*
 797 * Note, "git status --porcelain" is used to determine if it's safe to
 798 * delete a whole worktree. "git status" does not ignore user
 799 * configuration, so if a normal "git status" shows "clean" for the
 800 * user, then it's ok to remove it.
 801 *
 802 * This assumption may be a bad one. We may want to ignore
 803 * (potentially bad) user settings and only delete a worktree when
 804 * it's absolutely safe to do so from _our_ point of view because we
 805 * know better.
 806 */
 807static void check_clean_worktree(struct worktree *wt,
 808                                 const char *original_path)
 809{
 810        struct argv_array child_env = ARGV_ARRAY_INIT;
 811        struct child_process cp;
 812        char buf[1];
 813        int ret;
 814
 815        /*
 816         * Until we sort this out, all submodules are "dirty" and
 817         * will abort this function.
 818         */
 819        validate_no_submodules(wt);
 820
 821        argv_array_pushf(&child_env, "%s=%s/.git",
 822                         GIT_DIR_ENVIRONMENT, wt->path);
 823        argv_array_pushf(&child_env, "%s=%s",
 824                         GIT_WORK_TREE_ENVIRONMENT, wt->path);
 825        memset(&cp, 0, sizeof(cp));
 826        argv_array_pushl(&cp.args, "status",
 827                         "--porcelain", "--ignore-submodules=none",
 828                         NULL);
 829        cp.env = child_env.argv;
 830        cp.git_cmd = 1;
 831        cp.dir = wt->path;
 832        cp.out = -1;
 833        ret = start_command(&cp);
 834        if (ret)
 835                die_errno(_("failed to run 'git status' on '%s'"),
 836                          original_path);
 837        ret = xread(cp.out, buf, sizeof(buf));
 838        if (ret)
 839                die(_("'%s' is dirty, use --force to delete it"),
 840                    original_path);
 841        close(cp.out);
 842        ret = finish_command(&cp);
 843        if (ret)
 844                die_errno(_("failed to run 'git status' on '%s', code %d"),
 845                          original_path, ret);
 846}
 847
 848static int delete_git_work_tree(struct worktree *wt)
 849{
 850        struct strbuf sb = STRBUF_INIT;
 851        int ret = 0;
 852
 853        strbuf_addstr(&sb, wt->path);
 854        if (remove_dir_recursively(&sb, 0)) {
 855                error_errno(_("failed to delete '%s'"), sb.buf);
 856                ret = -1;
 857        }
 858        strbuf_release(&sb);
 859        return ret;
 860}
 861
 862static int remove_worktree(int ac, const char **av, const char *prefix)
 863{
 864        int force = 0;
 865        struct option options[] = {
 866                OPT__FORCE(&force,
 867                         N_("force removing even if the worktree is dirty"),
 868                         PARSE_OPT_NOCOMPLETE),
 869                OPT_END()
 870        };
 871        struct worktree **worktrees, *wt;
 872        struct strbuf errmsg = STRBUF_INIT;
 873        const char *reason;
 874        int ret = 0;
 875
 876        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 877        if (ac != 1)
 878                usage_with_options(worktree_usage, options);
 879
 880        worktrees = get_worktrees(0);
 881        wt = find_worktree(worktrees, prefix, av[0]);
 882        if (!wt)
 883                die(_("'%s' is not a working tree"), av[0]);
 884        if (is_main_worktree(wt))
 885                die(_("'%s' is a main working tree"), av[0]);
 886        reason = is_worktree_locked(wt);
 887        if (reason) {
 888                if (*reason)
 889                        die(_("cannot remove a locked working tree, lock reason: %s"),
 890                            reason);
 891                die(_("cannot remove a locked working tree"));
 892        }
 893        if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
 894                die(_("validation failed, cannot remove working tree: %s"),
 895                    errmsg.buf);
 896        strbuf_release(&errmsg);
 897
 898        if (file_exists(wt->path)) {
 899                if (!force)
 900                        check_clean_worktree(wt, av[0]);
 901
 902                ret |= delete_git_work_tree(wt);
 903        }
 904        /*
 905         * continue on even if ret is non-zero, there's no going back
 906         * from here.
 907         */
 908        ret |= delete_git_dir(wt->id);
 909
 910        free_worktrees(worktrees);
 911        return ret;
 912}
 913
 914int cmd_worktree(int ac, const char **av, const char *prefix)
 915{
 916        struct option options[] = {
 917                OPT_END()
 918        };
 919
 920        git_config(git_worktree_config, NULL);
 921
 922        if (ac < 2)
 923                usage_with_options(worktree_usage, options);
 924        if (!prefix)
 925                prefix = "";
 926        if (!strcmp(av[1], "add"))
 927                return add(ac - 1, av + 1, prefix);
 928        if (!strcmp(av[1], "prune"))
 929                return prune(ac - 1, av + 1, prefix);
 930        if (!strcmp(av[1], "list"))
 931                return list(ac - 1, av + 1, prefix);
 932        if (!strcmp(av[1], "lock"))
 933                return lock_worktree(ac - 1, av + 1, prefix);
 934        if (!strcmp(av[1], "unlock"))
 935                return unlock_worktree(ac - 1, av + 1, prefix);
 936        if (!strcmp(av[1], "move"))
 937                return move_worktree(ac - 1, av + 1, prefix);
 938        if (!strcmp(av[1], "remove"))
 939                return remove_worktree(ac - 1, av + 1, prefix);
 940        usage_with_options(worktree_usage, options);
 941}