builtin / worktree.con commit Merge branch 'et/add-chmod-x' into maint (c8b080a)
   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 prune [<options>]"),
  17        N_("git worktree list [<options>]"),
  18        NULL
  19};
  20
  21struct add_opts {
  22        int force;
  23        int detach;
  24        int checkout;
  25        const char *new_branch;
  26        int force_new_branch;
  27};
  28
  29static int show_only;
  30static int verbose;
  31static unsigned long expire;
  32
  33static int prune_worktree(const char *id, struct strbuf *reason)
  34{
  35        struct stat st;
  36        char *path;
  37        int fd, len;
  38
  39        if (!is_directory(git_path("worktrees/%s", id))) {
  40                strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
  41                return 1;
  42        }
  43        if (file_exists(git_path("worktrees/%s/locked", id)))
  44                return 0;
  45        if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
  46                strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
  47                return 1;
  48        }
  49        fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
  50        if (fd < 0) {
  51                strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
  52                            id, strerror(errno));
  53                return 1;
  54        }
  55        len = st.st_size;
  56        path = xmallocz(len);
  57        read_in_full(fd, path, len);
  58        close(fd);
  59        while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
  60                len--;
  61        if (!len) {
  62                strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
  63                free(path);
  64                return 1;
  65        }
  66        path[len] = '\0';
  67        if (!file_exists(path)) {
  68                struct stat st_link;
  69                free(path);
  70                /*
  71                 * the repo is moved manually and has not been
  72                 * accessed since?
  73                 */
  74                if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
  75                    st_link.st_nlink > 1)
  76                        return 0;
  77                if (st.st_mtime <= expire) {
  78                        strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
  79                        return 1;
  80                } else {
  81                        return 0;
  82                }
  83        }
  84        free(path);
  85        return 0;
  86}
  87
  88static void prune_worktrees(void)
  89{
  90        struct strbuf reason = STRBUF_INIT;
  91        struct strbuf path = STRBUF_INIT;
  92        DIR *dir = opendir(git_path("worktrees"));
  93        struct dirent *d;
  94        int ret;
  95        if (!dir)
  96                return;
  97        while ((d = readdir(dir)) != NULL) {
  98                if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
  99                        continue;
 100                strbuf_reset(&reason);
 101                if (!prune_worktree(d->d_name, &reason))
 102                        continue;
 103                if (show_only || verbose)
 104                        printf("%s\n", reason.buf);
 105                if (show_only)
 106                        continue;
 107                strbuf_reset(&path);
 108                strbuf_addstr(&path, git_path("worktrees/%s", d->d_name));
 109                ret = remove_dir_recursively(&path, 0);
 110                if (ret < 0 && errno == ENOTDIR)
 111                        ret = unlink(path.buf);
 112                if (ret)
 113                        error_errno(_("failed to remove '%s'"), path.buf);
 114        }
 115        closedir(dir);
 116        if (!show_only)
 117                rmdir(git_path("worktrees"));
 118        strbuf_release(&reason);
 119        strbuf_release(&path);
 120}
 121
 122static int prune(int ac, const char **av, const char *prefix)
 123{
 124        struct option options[] = {
 125                OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
 126                OPT__VERBOSE(&verbose, N_("report pruned objects")),
 127                OPT_EXPIRY_DATE(0, "expire", &expire,
 128                                N_("expire objects older than <time>")),
 129                OPT_END()
 130        };
 131
 132        expire = ULONG_MAX;
 133        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 134        if (ac)
 135                usage_with_options(worktree_usage, options);
 136        prune_worktrees();
 137        return 0;
 138}
 139
 140static char *junk_work_tree;
 141static char *junk_git_dir;
 142static int is_junk;
 143static pid_t junk_pid;
 144
 145static void remove_junk(void)
 146{
 147        struct strbuf sb = STRBUF_INIT;
 148        if (!is_junk || getpid() != junk_pid)
 149                return;
 150        if (junk_git_dir) {
 151                strbuf_addstr(&sb, junk_git_dir);
 152                remove_dir_recursively(&sb, 0);
 153                strbuf_reset(&sb);
 154        }
 155        if (junk_work_tree) {
 156                strbuf_addstr(&sb, junk_work_tree);
 157                remove_dir_recursively(&sb, 0);
 158        }
 159        strbuf_release(&sb);
 160}
 161
 162static void remove_junk_on_signal(int signo)
 163{
 164        remove_junk();
 165        sigchain_pop(signo);
 166        raise(signo);
 167}
 168
 169static const char *worktree_basename(const char *path, int *olen)
 170{
 171        const char *name;
 172        int len;
 173
 174        len = strlen(path);
 175        while (len && is_dir_sep(path[len - 1]))
 176                len--;
 177
 178        for (name = path + len - 1; name > path; name--)
 179                if (is_dir_sep(*name)) {
 180                        name++;
 181                        break;
 182                }
 183
 184        *olen = len;
 185        return name;
 186}
 187
 188static int add_worktree(const char *path, const char *refname,
 189                        const struct add_opts *opts)
 190{
 191        struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
 192        struct strbuf sb = STRBUF_INIT;
 193        const char *name;
 194        struct stat st;
 195        struct child_process cp;
 196        struct argv_array child_env = ARGV_ARRAY_INIT;
 197        int counter = 0, len, ret;
 198        struct strbuf symref = STRBUF_INIT;
 199        struct commit *commit = NULL;
 200
 201        if (file_exists(path) && !is_empty_dir(path))
 202                die(_("'%s' already exists"), path);
 203
 204        /* is 'refname' a branch or commit? */
 205        if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
 206                 ref_exists(symref.buf)) { /* it's a branch */
 207                if (!opts->force)
 208                        die_if_checked_out(symref.buf, 0);
 209        } else { /* must be a commit */
 210                commit = lookup_commit_reference_by_name(refname);
 211                if (!commit)
 212                        die(_("invalid reference: %s"), refname);
 213        }
 214
 215        name = worktree_basename(path, &len);
 216        strbuf_addstr(&sb_repo,
 217                      git_path("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, "0000000000000000000000000000000000000000");
 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        memset(&cp, 0, sizeof(cp));
 275        cp.git_cmd = 1;
 276
 277        if (commit)
 278                argv_array_pushl(&cp.args, "update-ref", "HEAD",
 279                                 oid_to_hex(&commit->object.oid), NULL);
 280        else
 281                argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
 282                                 symref.buf, NULL);
 283        cp.env = child_env.argv;
 284        ret = run_command(&cp);
 285        if (ret)
 286                goto done;
 287
 288        if (opts->checkout) {
 289                cp.argv = NULL;
 290                argv_array_clear(&cp.args);
 291                argv_array_pushl(&cp.args, "reset", "--hard", NULL);
 292                cp.env = child_env.argv;
 293                ret = run_command(&cp);
 294                if (ret)
 295                        goto done;
 296        }
 297
 298        is_junk = 0;
 299        free(junk_work_tree);
 300        free(junk_git_dir);
 301        junk_work_tree = NULL;
 302        junk_git_dir = NULL;
 303
 304done:
 305        strbuf_reset(&sb);
 306        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 307        unlink_or_warn(sb.buf);
 308        argv_array_clear(&child_env);
 309        strbuf_release(&sb);
 310        strbuf_release(&symref);
 311        strbuf_release(&sb_repo);
 312        strbuf_release(&sb_git);
 313        return ret;
 314}
 315
 316static int add(int ac, const char **av, const char *prefix)
 317{
 318        struct add_opts opts;
 319        const char *new_branch_force = NULL;
 320        const char *path, *branch;
 321        struct option options[] = {
 322                OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
 323                OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
 324                           N_("create a new branch")),
 325                OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
 326                           N_("create or reset a branch")),
 327                OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
 328                OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
 329                OPT_END()
 330        };
 331
 332        memset(&opts, 0, sizeof(opts));
 333        opts.checkout = 1;
 334        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 335        if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
 336                die(_("-b, -B, and --detach are mutually exclusive"));
 337        if (ac < 1 || ac > 2)
 338                usage_with_options(worktree_usage, options);
 339
 340        path = prefix ? prefix_filename(prefix, strlen(prefix), av[0]) : av[0];
 341        branch = ac < 2 ? "HEAD" : av[1];
 342
 343        opts.force_new_branch = !!new_branch_force;
 344        if (opts.force_new_branch) {
 345                struct strbuf symref = STRBUF_INIT;
 346
 347                opts.new_branch = new_branch_force;
 348
 349                if (!opts.force &&
 350                    !strbuf_check_branch_ref(&symref, opts.new_branch) &&
 351                    ref_exists(symref.buf))
 352                        die_if_checked_out(symref.buf, 0);
 353                strbuf_release(&symref);
 354        }
 355
 356        if (ac < 2 && !opts.new_branch && !opts.detach) {
 357                int n;
 358                const char *s = worktree_basename(path, &n);
 359                opts.new_branch = xstrndup(s, n);
 360        }
 361
 362        if (opts.new_branch) {
 363                struct child_process cp;
 364                memset(&cp, 0, sizeof(cp));
 365                cp.git_cmd = 1;
 366                argv_array_push(&cp.args, "branch");
 367                if (opts.force_new_branch)
 368                        argv_array_push(&cp.args, "--force");
 369                argv_array_push(&cp.args, opts.new_branch);
 370                argv_array_push(&cp.args, branch);
 371                if (run_command(&cp))
 372                        return -1;
 373                branch = opts.new_branch;
 374        }
 375
 376        return add_worktree(path, branch, &opts);
 377}
 378
 379static void show_worktree_porcelain(struct worktree *wt)
 380{
 381        printf("worktree %s\n", wt->path);
 382        if (wt->is_bare)
 383                printf("bare\n");
 384        else {
 385                printf("HEAD %s\n", sha1_to_hex(wt->head_sha1));
 386                if (wt->is_detached)
 387                        printf("detached\n");
 388                else
 389                        printf("branch %s\n", wt->head_ref);
 390        }
 391        printf("\n");
 392}
 393
 394static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
 395{
 396        struct strbuf sb = STRBUF_INIT;
 397        int cur_path_len = strlen(wt->path);
 398        int path_adj = cur_path_len - utf8_strwidth(wt->path);
 399
 400        strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
 401        if (wt->is_bare)
 402                strbuf_addstr(&sb, "(bare)");
 403        else {
 404                strbuf_addf(&sb, "%-*s ", abbrev_len,
 405                                find_unique_abbrev(wt->head_sha1, DEFAULT_ABBREV));
 406                if (!wt->is_detached)
 407                        strbuf_addf(&sb, "[%s]", shorten_unambiguous_ref(wt->head_ref, 0));
 408                else
 409                        strbuf_addstr(&sb, "(detached HEAD)");
 410        }
 411        printf("%s\n", sb.buf);
 412
 413        strbuf_release(&sb);
 414}
 415
 416static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
 417{
 418        int i;
 419
 420        for (i = 0; wt[i]; i++) {
 421                int sha1_len;
 422                int path_len = strlen(wt[i]->path);
 423
 424                if (path_len > *maxlen)
 425                        *maxlen = path_len;
 426                sha1_len = strlen(find_unique_abbrev(wt[i]->head_sha1, *abbrev));
 427                if (sha1_len > *abbrev)
 428                        *abbrev = sha1_len;
 429        }
 430}
 431
 432static int list(int ac, const char **av, const char *prefix)
 433{
 434        int porcelain = 0;
 435
 436        struct option options[] = {
 437                OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
 438                OPT_END()
 439        };
 440
 441        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 442        if (ac)
 443                usage_with_options(worktree_usage, options);
 444        else {
 445                struct worktree **worktrees = get_worktrees();
 446                int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
 447
 448                if (!porcelain)
 449                        measure_widths(worktrees, &abbrev, &path_maxlen);
 450
 451                for (i = 0; worktrees[i]; i++) {
 452                        if (porcelain)
 453                                show_worktree_porcelain(worktrees[i]);
 454                        else
 455                                show_worktree(worktrees[i], path_maxlen, abbrev);
 456                }
 457                free_worktrees(worktrees);
 458        }
 459        return 0;
 460}
 461
 462int cmd_worktree(int ac, const char **av, const char *prefix)
 463{
 464        struct option options[] = {
 465                OPT_END()
 466        };
 467
 468        if (ac < 2)
 469                usage_with_options(worktree_usage, options);
 470        if (!strcmp(av[1], "add"))
 471                return add(ac - 1, av + 1, prefix);
 472        if (!strcmp(av[1], "prune"))
 473                return prune(ac - 1, av + 1, prefix);
 474        if (!strcmp(av[1], "list"))
 475                return list(ac - 1, av + 1, prefix);
 476        usage_with_options(worktree_usage, options);
 477}