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