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