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