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