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