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