builtin / worktree.con commit worktree prune: improve prune logic when worktree is moved (327864a)
   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 prune [<options>]"),
  21        N_("git worktree unlock <path>"),
  22        NULL
  23};
  24
  25struct add_opts {
  26        int force;
  27        int detach;
  28        int checkout;
  29        int keep_locked;
  30        const char *new_branch;
  31        int force_new_branch;
  32};
  33
  34static int show_only;
  35static int verbose;
  36static int guess_remote;
  37static timestamp_t expire;
  38
  39static int git_worktree_config(const char *var, const char *value, void *cb)
  40{
  41        if (!strcmp(var, "worktree.guessremote")) {
  42                guess_remote = git_config_bool(var, value);
  43                return 0;
  44        }
  45
  46        return git_default_config(var, value, cb);
  47}
  48
  49static int prune_worktree(const char *id, struct strbuf *reason)
  50{
  51        struct stat st;
  52        char *path;
  53        int fd;
  54        size_t len;
  55        ssize_t read_result;
  56
  57        if (!is_directory(git_path("worktrees/%s", id))) {
  58                strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
  59                return 1;
  60        }
  61        if (file_exists(git_path("worktrees/%s/locked", id)))
  62                return 0;
  63        if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
  64                strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
  65                return 1;
  66        }
  67        fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
  68        if (fd < 0) {
  69                strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
  70                            id, strerror(errno));
  71                return 1;
  72        }
  73        len = xsize_t(st.st_size);
  74        path = xmallocz(len);
  75
  76        read_result = read_in_full(fd, path, len);
  77        if (read_result < 0) {
  78                strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
  79                            id, strerror(errno));
  80                close(fd);
  81                free(path);
  82                return 1;
  83        }
  84        close(fd);
  85
  86        if (read_result != len) {
  87                strbuf_addf(reason,
  88                            _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
  89                            id, (uintmax_t)len, (uintmax_t)read_result);
  90                free(path);
  91                return 1;
  92        }
  93        while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
  94                len--;
  95        if (!len) {
  96                strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
  97                free(path);
  98                return 1;
  99        }
 100        path[len] = '\0';
 101        if (!file_exists(path)) {
 102                free(path);
 103                if (stat(git_path("worktrees/%s/index", id), &st) ||
 104                    st.st_mtime <= expire) {
 105                        strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
 106                        return 1;
 107                } else {
 108                        return 0;
 109                }
 110        }
 111        free(path);
 112        return 0;
 113}
 114
 115static void prune_worktrees(void)
 116{
 117        struct strbuf reason = STRBUF_INIT;
 118        struct strbuf path = STRBUF_INIT;
 119        DIR *dir = opendir(git_path("worktrees"));
 120        struct dirent *d;
 121        int ret;
 122        if (!dir)
 123                return;
 124        while ((d = readdir(dir)) != NULL) {
 125                if (is_dot_or_dotdot(d->d_name))
 126                        continue;
 127                strbuf_reset(&reason);
 128                if (!prune_worktree(d->d_name, &reason))
 129                        continue;
 130                if (show_only || verbose)
 131                        printf("%s\n", reason.buf);
 132                if (show_only)
 133                        continue;
 134                git_path_buf(&path, "worktrees/%s", d->d_name);
 135                ret = remove_dir_recursively(&path, 0);
 136                if (ret < 0 && errno == ENOTDIR)
 137                        ret = unlink(path.buf);
 138                if (ret)
 139                        error_errno(_("failed to remove '%s'"), path.buf);
 140        }
 141        closedir(dir);
 142        if (!show_only)
 143                rmdir(git_path("worktrees"));
 144        strbuf_release(&reason);
 145        strbuf_release(&path);
 146}
 147
 148static int prune(int ac, const char **av, const char *prefix)
 149{
 150        struct option options[] = {
 151                OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
 152                OPT__VERBOSE(&verbose, N_("report pruned working trees")),
 153                OPT_EXPIRY_DATE(0, "expire", &expire,
 154                                N_("expire working trees older than <time>")),
 155                OPT_END()
 156        };
 157
 158        expire = TIME_MAX;
 159        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 160        if (ac)
 161                usage_with_options(worktree_usage, options);
 162        prune_worktrees();
 163        return 0;
 164}
 165
 166static char *junk_work_tree;
 167static char *junk_git_dir;
 168static int is_junk;
 169static pid_t junk_pid;
 170
 171static void remove_junk(void)
 172{
 173        struct strbuf sb = STRBUF_INIT;
 174        if (!is_junk || getpid() != junk_pid)
 175                return;
 176        if (junk_git_dir) {
 177                strbuf_addstr(&sb, junk_git_dir);
 178                remove_dir_recursively(&sb, 0);
 179                strbuf_reset(&sb);
 180        }
 181        if (junk_work_tree) {
 182                strbuf_addstr(&sb, junk_work_tree);
 183                remove_dir_recursively(&sb, 0);
 184        }
 185        strbuf_release(&sb);
 186}
 187
 188static void remove_junk_on_signal(int signo)
 189{
 190        remove_junk();
 191        sigchain_pop(signo);
 192        raise(signo);
 193}
 194
 195static const char *worktree_basename(const char *path, int *olen)
 196{
 197        const char *name;
 198        int len;
 199
 200        len = strlen(path);
 201        while (len && is_dir_sep(path[len - 1]))
 202                len--;
 203
 204        for (name = path + len - 1; name > path; name--)
 205                if (is_dir_sep(*name)) {
 206                        name++;
 207                        break;
 208                }
 209
 210        *olen = len;
 211        return name;
 212}
 213
 214static int add_worktree(const char *path, const char *refname,
 215                        const struct add_opts *opts)
 216{
 217        struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
 218        struct strbuf sb = STRBUF_INIT;
 219        const char *name;
 220        struct stat st;
 221        struct child_process cp = CHILD_PROCESS_INIT;
 222        struct argv_array child_env = ARGV_ARRAY_INIT;
 223        int counter = 0, len, ret;
 224        struct strbuf symref = STRBUF_INIT;
 225        struct commit *commit = NULL;
 226        int is_branch = 0;
 227
 228        if (file_exists(path) && !is_empty_dir(path))
 229                die(_("'%s' already exists"), path);
 230
 231        /* is 'refname' a branch or commit? */
 232        if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
 233            ref_exists(symref.buf)) {
 234                is_branch = 1;
 235                if (!opts->force)
 236                        die_if_checked_out(symref.buf, 0);
 237        }
 238        commit = lookup_commit_reference_by_name(refname);
 239        if (!commit)
 240                die(_("invalid reference: %s"), refname);
 241
 242        name = worktree_basename(path, &len);
 243        git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
 244        len = sb_repo.len;
 245        if (safe_create_leading_directories_const(sb_repo.buf))
 246                die_errno(_("could not create leading directories of '%s'"),
 247                          sb_repo.buf);
 248        while (!stat(sb_repo.buf, &st)) {
 249                counter++;
 250                strbuf_setlen(&sb_repo, len);
 251                strbuf_addf(&sb_repo, "%d", counter);
 252        }
 253        name = strrchr(sb_repo.buf, '/') + 1;
 254
 255        junk_pid = getpid();
 256        atexit(remove_junk);
 257        sigchain_push_common(remove_junk_on_signal);
 258
 259        if (mkdir(sb_repo.buf, 0777))
 260                die_errno(_("could not create directory of '%s'"), sb_repo.buf);
 261        junk_git_dir = xstrdup(sb_repo.buf);
 262        is_junk = 1;
 263
 264        /*
 265         * lock the incomplete repo so prune won't delete it, unlock
 266         * after the preparation is over.
 267         */
 268        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 269        if (!opts->keep_locked)
 270                write_file(sb.buf, "initializing");
 271        else
 272                write_file(sb.buf, "added with --lock");
 273
 274        strbuf_addf(&sb_git, "%s/.git", path);
 275        if (safe_create_leading_directories_const(sb_git.buf))
 276                die_errno(_("could not create leading directories of '%s'"),
 277                          sb_git.buf);
 278        junk_work_tree = xstrdup(path);
 279
 280        strbuf_reset(&sb);
 281        strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
 282        write_file(sb.buf, "%s", real_path(sb_git.buf));
 283        write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
 284                   real_path(get_git_common_dir()), name);
 285        /*
 286         * This is to keep resolve_ref() happy. We need a valid HEAD
 287         * or is_git_directory() will reject the directory. Any value which
 288         * looks like an object ID will do since it will be immediately
 289         * replaced by the symbolic-ref or update-ref invocation in the new
 290         * worktree.
 291         */
 292        strbuf_reset(&sb);
 293        strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
 294        write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
 295        strbuf_reset(&sb);
 296        strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
 297        write_file(sb.buf, "../..");
 298
 299        fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
 300
 301        argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
 302        argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
 303        cp.git_cmd = 1;
 304
 305        if (!is_branch)
 306                argv_array_pushl(&cp.args, "update-ref", "HEAD",
 307                                 oid_to_hex(&commit->object.oid), NULL);
 308        else
 309                argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
 310                                 symref.buf, NULL);
 311        cp.env = child_env.argv;
 312        ret = run_command(&cp);
 313        if (ret)
 314                goto done;
 315
 316        if (opts->checkout) {
 317                cp.argv = NULL;
 318                argv_array_clear(&cp.args);
 319                argv_array_pushl(&cp.args, "reset", "--hard", NULL);
 320                cp.env = child_env.argv;
 321                ret = run_command(&cp);
 322                if (ret)
 323                        goto done;
 324        }
 325
 326        is_junk = 0;
 327        FREE_AND_NULL(junk_work_tree);
 328        FREE_AND_NULL(junk_git_dir);
 329
 330done:
 331        if (ret || !opts->keep_locked) {
 332                strbuf_reset(&sb);
 333                strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 334                unlink_or_warn(sb.buf);
 335        }
 336
 337        /*
 338         * Hook failure does not warrant worktree deletion, so run hook after
 339         * is_junk is cleared, but do return appropriate code when hook fails.
 340         */
 341        if (!ret && opts->checkout) {
 342                const char *hook = find_hook("post-checkout");
 343                if (hook) {
 344                        const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
 345                        cp.git_cmd = 0;
 346                        cp.no_stdin = 1;
 347                        cp.stdout_to_stderr = 1;
 348                        cp.dir = path;
 349                        cp.env = env;
 350                        cp.argv = NULL;
 351                        argv_array_pushl(&cp.args, absolute_path(hook),
 352                                         oid_to_hex(&null_oid),
 353                                         oid_to_hex(&commit->object.oid),
 354                                         "1", NULL);
 355                        ret = run_command(&cp);
 356                }
 357        }
 358
 359        argv_array_clear(&child_env);
 360        strbuf_release(&sb);
 361        strbuf_release(&symref);
 362        strbuf_release(&sb_repo);
 363        strbuf_release(&sb_git);
 364        return ret;
 365}
 366
 367static int add(int ac, const char **av, const char *prefix)
 368{
 369        struct add_opts opts;
 370        const char *new_branch_force = NULL;
 371        char *path;
 372        const char *branch;
 373        const char *opt_track = NULL;
 374        struct option options[] = {
 375                OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
 376                OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
 377                           N_("create a new branch")),
 378                OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
 379                           N_("create or reset a branch")),
 380                OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
 381                OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
 382                OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
 383                OPT_PASSTHRU(0, "track", &opt_track, NULL,
 384                             N_("set up tracking mode (see git-branch(1))"),
 385                             PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
 386                OPT_BOOL(0, "guess-remote", &guess_remote,
 387                         N_("try to match the new branch name with a remote-tracking branch")),
 388                OPT_END()
 389        };
 390
 391        memset(&opts, 0, sizeof(opts));
 392        opts.checkout = 1;
 393        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 394        if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
 395                die(_("-b, -B, and --detach are mutually exclusive"));
 396        if (ac < 1 || ac > 2)
 397                usage_with_options(worktree_usage, options);
 398
 399        path = prefix_filename(prefix, av[0]);
 400        branch = ac < 2 ? "HEAD" : av[1];
 401
 402        if (!strcmp(branch, "-"))
 403                branch = "@{-1}";
 404
 405        opts.force_new_branch = !!new_branch_force;
 406        if (opts.force_new_branch) {
 407                struct strbuf symref = STRBUF_INIT;
 408
 409                opts.new_branch = new_branch_force;
 410
 411                if (!opts.force &&
 412                    !strbuf_check_branch_ref(&symref, opts.new_branch) &&
 413                    ref_exists(symref.buf))
 414                        die_if_checked_out(symref.buf, 0);
 415                strbuf_release(&symref);
 416        }
 417
 418        if (ac < 2 && !opts.new_branch && !opts.detach) {
 419                int n;
 420                const char *s = worktree_basename(path, &n);
 421                opts.new_branch = xstrndup(s, n);
 422                if (guess_remote) {
 423                        struct object_id oid;
 424                        const char *remote =
 425                                unique_tracking_name(opts.new_branch, &oid);
 426                        if (remote)
 427                                branch = remote;
 428                }
 429        }
 430
 431        if (ac == 2 && !opts.new_branch && !opts.detach) {
 432                struct object_id oid;
 433                struct commit *commit;
 434                const char *remote;
 435
 436                commit = lookup_commit_reference_by_name(branch);
 437                if (!commit) {
 438                        remote = unique_tracking_name(branch, &oid);
 439                        if (remote) {
 440                                opts.new_branch = branch;
 441                                branch = remote;
 442                        }
 443                }
 444        }
 445
 446        if (opts.new_branch) {
 447                struct child_process cp = CHILD_PROCESS_INIT;
 448                cp.git_cmd = 1;
 449                argv_array_push(&cp.args, "branch");
 450                if (opts.force_new_branch)
 451                        argv_array_push(&cp.args, "--force");
 452                argv_array_push(&cp.args, opts.new_branch);
 453                argv_array_push(&cp.args, branch);
 454                if (opt_track)
 455                        argv_array_push(&cp.args, opt_track);
 456                if (run_command(&cp))
 457                        return -1;
 458                branch = opts.new_branch;
 459        } else if (opt_track) {
 460                die(_("--[no-]track can only be used if a new branch is created"));
 461        }
 462
 463        UNLEAK(path);
 464        UNLEAK(opts);
 465        return add_worktree(path, branch, &opts);
 466}
 467
 468static void show_worktree_porcelain(struct worktree *wt)
 469{
 470        printf("worktree %s\n", wt->path);
 471        if (wt->is_bare)
 472                printf("bare\n");
 473        else {
 474                printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
 475                if (wt->is_detached)
 476                        printf("detached\n");
 477                else if (wt->head_ref)
 478                        printf("branch %s\n", wt->head_ref);
 479        }
 480        printf("\n");
 481}
 482
 483static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
 484{
 485        struct strbuf sb = STRBUF_INIT;
 486        int cur_path_len = strlen(wt->path);
 487        int path_adj = cur_path_len - utf8_strwidth(wt->path);
 488
 489        strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
 490        if (wt->is_bare)
 491                strbuf_addstr(&sb, "(bare)");
 492        else {
 493                strbuf_addf(&sb, "%-*s ", abbrev_len,
 494                                find_unique_abbrev(wt->head_oid.hash, DEFAULT_ABBREV));
 495                if (wt->is_detached)
 496                        strbuf_addstr(&sb, "(detached HEAD)");
 497                else if (wt->head_ref) {
 498                        char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
 499                        strbuf_addf(&sb, "[%s]", ref);
 500                        free(ref);
 501                } else
 502                        strbuf_addstr(&sb, "(error)");
 503        }
 504        printf("%s\n", sb.buf);
 505
 506        strbuf_release(&sb);
 507}
 508
 509static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
 510{
 511        int i;
 512
 513        for (i = 0; wt[i]; i++) {
 514                int sha1_len;
 515                int path_len = strlen(wt[i]->path);
 516
 517                if (path_len > *maxlen)
 518                        *maxlen = path_len;
 519                sha1_len = strlen(find_unique_abbrev(wt[i]->head_oid.hash, *abbrev));
 520                if (sha1_len > *abbrev)
 521                        *abbrev = sha1_len;
 522        }
 523}
 524
 525static int list(int ac, const char **av, const char *prefix)
 526{
 527        int porcelain = 0;
 528
 529        struct option options[] = {
 530                OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
 531                OPT_END()
 532        };
 533
 534        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 535        if (ac)
 536                usage_with_options(worktree_usage, options);
 537        else {
 538                struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
 539                int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
 540
 541                if (!porcelain)
 542                        measure_widths(worktrees, &abbrev, &path_maxlen);
 543
 544                for (i = 0; worktrees[i]; i++) {
 545                        if (porcelain)
 546                                show_worktree_porcelain(worktrees[i]);
 547                        else
 548                                show_worktree(worktrees[i], path_maxlen, abbrev);
 549                }
 550                free_worktrees(worktrees);
 551        }
 552        return 0;
 553}
 554
 555static int lock_worktree(int ac, const char **av, const char *prefix)
 556{
 557        const char *reason = "", *old_reason;
 558        struct option options[] = {
 559                OPT_STRING(0, "reason", &reason, N_("string"),
 560                           N_("reason for locking")),
 561                OPT_END()
 562        };
 563        struct worktree **worktrees, *wt;
 564
 565        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 566        if (ac != 1)
 567                usage_with_options(worktree_usage, options);
 568
 569        worktrees = get_worktrees(0);
 570        wt = find_worktree(worktrees, prefix, av[0]);
 571        if (!wt)
 572                die(_("'%s' is not a working tree"), av[0]);
 573        if (is_main_worktree(wt))
 574                die(_("The main working tree cannot be locked or unlocked"));
 575
 576        old_reason = is_worktree_locked(wt);
 577        if (old_reason) {
 578                if (*old_reason)
 579                        die(_("'%s' is already locked, reason: %s"),
 580                            av[0], old_reason);
 581                die(_("'%s' is already locked"), av[0]);
 582        }
 583
 584        write_file(git_common_path("worktrees/%s/locked", wt->id),
 585                   "%s", reason);
 586        free_worktrees(worktrees);
 587        return 0;
 588}
 589
 590static int unlock_worktree(int ac, const char **av, const char *prefix)
 591{
 592        struct option options[] = {
 593                OPT_END()
 594        };
 595        struct worktree **worktrees, *wt;
 596        int ret;
 597
 598        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 599        if (ac != 1)
 600                usage_with_options(worktree_usage, options);
 601
 602        worktrees = get_worktrees(0);
 603        wt = find_worktree(worktrees, prefix, av[0]);
 604        if (!wt)
 605                die(_("'%s' is not a working tree"), av[0]);
 606        if (is_main_worktree(wt))
 607                die(_("The main working tree cannot be locked or unlocked"));
 608        if (!is_worktree_locked(wt))
 609                die(_("'%s' is not locked"), av[0]);
 610        ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
 611        free_worktrees(worktrees);
 612        return ret;
 613}
 614
 615int cmd_worktree(int ac, const char **av, const char *prefix)
 616{
 617        struct option options[] = {
 618                OPT_END()
 619        };
 620
 621        git_config(git_worktree_config, NULL);
 622
 623        if (ac < 2)
 624                usage_with_options(worktree_usage, options);
 625        if (!prefix)
 626                prefix = "";
 627        if (!strcmp(av[1], "add"))
 628                return add(ac - 1, av + 1, prefix);
 629        if (!strcmp(av[1], "prune"))
 630                return prune(ac - 1, av + 1, prefix);
 631        if (!strcmp(av[1], "list"))
 632                return list(ac - 1, av + 1, prefix);
 633        if (!strcmp(av[1], "lock"))
 634                return lock_worktree(ac - 1, av + 1, prefix);
 635        if (!strcmp(av[1], "unlock"))
 636                return unlock_worktree(ac - 1, av + 1, prefix);
 637        usage_with_options(worktree_usage, options);
 638}