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