builtin / worktree.con commit checkout: drop intimate knowledge of newly created worktree (272be14)
   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
  11static const char * const worktree_usage[] = {
  12        N_("git worktree add [<options>] <path> <branch>"),
  13        N_("git worktree prune [<options>]"),
  14        NULL
  15};
  16
  17struct add_opts {
  18        int force;
  19        int detach;
  20        const char *new_branch;
  21        int force_new_branch;
  22};
  23
  24static int show_only;
  25static int verbose;
  26static unsigned long expire;
  27
  28static int prune_worktree(const char *id, struct strbuf *reason)
  29{
  30        struct stat st;
  31        char *path;
  32        int fd, len;
  33
  34        if (!is_directory(git_path("worktrees/%s", id))) {
  35                strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
  36                return 1;
  37        }
  38        if (file_exists(git_path("worktrees/%s/locked", id)))
  39                return 0;
  40        if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
  41                strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
  42                return 1;
  43        }
  44        fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
  45        if (fd < 0) {
  46                strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
  47                            id, strerror(errno));
  48                return 1;
  49        }
  50        len = st.st_size;
  51        path = xmalloc(len + 1);
  52        read_in_full(fd, path, len);
  53        close(fd);
  54        while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
  55                len--;
  56        if (!len) {
  57                strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
  58                free(path);
  59                return 1;
  60        }
  61        path[len] = '\0';
  62        if (!file_exists(path)) {
  63                struct stat st_link;
  64                free(path);
  65                /*
  66                 * the repo is moved manually and has not been
  67                 * accessed since?
  68                 */
  69                if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
  70                    st_link.st_nlink > 1)
  71                        return 0;
  72                if (st.st_mtime <= expire) {
  73                        strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
  74                        return 1;
  75                } else {
  76                        return 0;
  77                }
  78        }
  79        free(path);
  80        return 0;
  81}
  82
  83static void prune_worktrees(void)
  84{
  85        struct strbuf reason = STRBUF_INIT;
  86        struct strbuf path = STRBUF_INIT;
  87        DIR *dir = opendir(git_path("worktrees"));
  88        struct dirent *d;
  89        int ret;
  90        if (!dir)
  91                return;
  92        while ((d = readdir(dir)) != NULL) {
  93                if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
  94                        continue;
  95                strbuf_reset(&reason);
  96                if (!prune_worktree(d->d_name, &reason))
  97                        continue;
  98                if (show_only || verbose)
  99                        printf("%s\n", reason.buf);
 100                if (show_only)
 101                        continue;
 102                strbuf_reset(&path);
 103                strbuf_addstr(&path, git_path("worktrees/%s", d->d_name));
 104                ret = remove_dir_recursively(&path, 0);
 105                if (ret < 0 && errno == ENOTDIR)
 106                        ret = unlink(path.buf);
 107                if (ret)
 108                        error(_("failed to remove: %s"), strerror(errno));
 109        }
 110        closedir(dir);
 111        if (!show_only)
 112                rmdir(git_path("worktrees"));
 113        strbuf_release(&reason);
 114        strbuf_release(&path);
 115}
 116
 117static int prune(int ac, const char **av, const char *prefix)
 118{
 119        struct option options[] = {
 120                OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
 121                OPT__VERBOSE(&verbose, N_("report pruned objects")),
 122                OPT_EXPIRY_DATE(0, "expire", &expire,
 123                                N_("expire objects older than <time>")),
 124                OPT_END()
 125        };
 126
 127        expire = ULONG_MAX;
 128        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 129        if (ac)
 130                usage_with_options(worktree_usage, options);
 131        prune_worktrees();
 132        return 0;
 133}
 134
 135static char *junk_work_tree;
 136static char *junk_git_dir;
 137static int is_junk;
 138static pid_t junk_pid;
 139
 140static void remove_junk(void)
 141{
 142        struct strbuf sb = STRBUF_INIT;
 143        if (!is_junk || getpid() != junk_pid)
 144                return;
 145        if (junk_git_dir) {
 146                strbuf_addstr(&sb, junk_git_dir);
 147                remove_dir_recursively(&sb, 0);
 148                strbuf_reset(&sb);
 149        }
 150        if (junk_work_tree) {
 151                strbuf_addstr(&sb, junk_work_tree);
 152                remove_dir_recursively(&sb, 0);
 153        }
 154        strbuf_release(&sb);
 155}
 156
 157static void remove_junk_on_signal(int signo)
 158{
 159        remove_junk();
 160        sigchain_pop(signo);
 161        raise(signo);
 162}
 163
 164static const char *worktree_basename(const char *path, int *olen)
 165{
 166        const char *name;
 167        int len;
 168
 169        len = strlen(path);
 170        while (len && is_dir_sep(path[len - 1]))
 171                len--;
 172
 173        for (name = path + len - 1; name > path; name--)
 174                if (is_dir_sep(*name)) {
 175                        name++;
 176                        break;
 177                }
 178
 179        *olen = len;
 180        return name;
 181}
 182
 183static int add_worktree(const char *path, const char *refname,
 184                        const struct add_opts *opts)
 185{
 186        struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
 187        struct strbuf sb = STRBUF_INIT;
 188        const char *name;
 189        struct stat st;
 190        struct child_process cp;
 191        struct argv_array child_env = ARGV_ARRAY_INIT;
 192        int counter = 0, len, ret;
 193        struct strbuf symref = STRBUF_INIT;
 194        struct commit *commit = NULL;
 195
 196        if (file_exists(path) && !is_empty_dir(path))
 197                die(_("'%s' already exists"), path);
 198
 199        /* is 'refname' a branch or commit? */
 200        if (opts->force_new_branch) /* definitely a branch */
 201                ;
 202        else if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
 203                 ref_exists(symref.buf)) { /* it's a branch */
 204                if (!opts->force)
 205                        die_if_checked_out(symref.buf);
 206        } else { /* must be a commit */
 207                commit = lookup_commit_reference_by_name(refname);
 208                if (!commit)
 209                        die(_("invalid reference: %s"), refname);
 210        }
 211
 212        name = worktree_basename(path, &len);
 213        strbuf_addstr(&sb_repo,
 214                      git_path("worktrees/%.*s", (int)(path + len - name), name));
 215        len = sb_repo.len;
 216        if (safe_create_leading_directories_const(sb_repo.buf))
 217                die_errno(_("could not create leading directories of '%s'"),
 218                          sb_repo.buf);
 219        while (!stat(sb_repo.buf, &st)) {
 220                counter++;
 221                strbuf_setlen(&sb_repo, len);
 222                strbuf_addf(&sb_repo, "%d", counter);
 223        }
 224        name = strrchr(sb_repo.buf, '/') + 1;
 225
 226        junk_pid = getpid();
 227        atexit(remove_junk);
 228        sigchain_push_common(remove_junk_on_signal);
 229
 230        if (mkdir(sb_repo.buf, 0777))
 231                die_errno(_("could not create directory of '%s'"), sb_repo.buf);
 232        junk_git_dir = xstrdup(sb_repo.buf);
 233        is_junk = 1;
 234
 235        /*
 236         * lock the incomplete repo so prune won't delete it, unlock
 237         * after the preparation is over.
 238         */
 239        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 240        write_file(sb.buf, 1, "initializing\n");
 241
 242        strbuf_addf(&sb_git, "%s/.git", path);
 243        if (safe_create_leading_directories_const(sb_git.buf))
 244                die_errno(_("could not create leading directories of '%s'"),
 245                          sb_git.buf);
 246        junk_work_tree = xstrdup(path);
 247
 248        strbuf_reset(&sb);
 249        strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
 250        write_file(sb.buf, 1, "%s\n", real_path(sb_git.buf));
 251        write_file(sb_git.buf, 1, "gitdir: %s/worktrees/%s\n",
 252                   real_path(get_git_common_dir()), name);
 253        /*
 254         * This is to keep resolve_ref() happy. We need a valid HEAD
 255         * or is_git_directory() will reject the directory. Any value which
 256         * looks like an object ID will do since it will be immediately
 257         * replaced by the symbolic-ref or update-ref invocation in the new
 258         * worktree.
 259         */
 260        strbuf_reset(&sb);
 261        strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
 262        write_file(sb.buf, 1, "0000000000000000000000000000000000000000\n");
 263        strbuf_reset(&sb);
 264        strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
 265        write_file(sb.buf, 1, "../..\n");
 266
 267        fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
 268
 269        argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
 270        argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
 271        memset(&cp, 0, sizeof(cp));
 272        cp.git_cmd = 1;
 273
 274        if (commit)
 275                argv_array_pushl(&cp.args, "update-ref", "HEAD",
 276                                 sha1_to_hex(commit->object.sha1), NULL);
 277        else
 278                argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
 279                                 symref.buf, NULL);
 280        cp.env = child_env.argv;
 281        ret = run_command(&cp);
 282        if (ret)
 283                goto done;
 284
 285        cp.argv = NULL;
 286        argv_array_clear(&cp.args);
 287        argv_array_pushl(&cp.args, "reset", "--hard", NULL);
 288        cp.env = child_env.argv;
 289        ret = run_command(&cp);
 290        if (!ret) {
 291                is_junk = 0;
 292                free(junk_work_tree);
 293                free(junk_git_dir);
 294                junk_work_tree = NULL;
 295                junk_git_dir = NULL;
 296        }
 297done:
 298        strbuf_reset(&sb);
 299        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 300        unlink_or_warn(sb.buf);
 301        argv_array_clear(&child_env);
 302        strbuf_release(&sb);
 303        strbuf_release(&symref);
 304        strbuf_release(&sb_repo);
 305        strbuf_release(&sb_git);
 306        return ret;
 307}
 308
 309static int add(int ac, const char **av, const char *prefix)
 310{
 311        struct add_opts opts;
 312        const char *new_branch_force = NULL;
 313        const char *path, *branch;
 314        struct option options[] = {
 315                OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
 316                OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
 317                           N_("create a new branch")),
 318                OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
 319                           N_("create or reset a branch")),
 320                OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
 321                OPT_END()
 322        };
 323
 324        memset(&opts, 0, sizeof(opts));
 325        ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
 326        if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
 327                die(_("-b, -B, and --detach are mutually exclusive"));
 328        if (ac < 1 || ac > 2)
 329                usage_with_options(worktree_usage, options);
 330
 331        path = prefix ? prefix_filename(prefix, strlen(prefix), av[0]) : av[0];
 332        branch = ac < 2 ? "HEAD" : av[1];
 333
 334        opts.force_new_branch = !!new_branch_force;
 335        if (opts.force_new_branch)
 336                opts.new_branch = new_branch_force;
 337
 338        if (ac < 2 && !opts.new_branch && !opts.detach) {
 339                int n;
 340                const char *s = worktree_basename(path, &n);
 341                opts.new_branch = xstrndup(s, n);
 342        }
 343
 344        if (opts.new_branch) {
 345                struct child_process cp;
 346                memset(&cp, 0, sizeof(cp));
 347                cp.git_cmd = 1;
 348                argv_array_push(&cp.args, "branch");
 349                if (opts.force_new_branch)
 350                        argv_array_push(&cp.args, "--force");
 351                argv_array_push(&cp.args, opts.new_branch);
 352                argv_array_push(&cp.args, branch);
 353                if (run_command(&cp))
 354                        return -1;
 355                branch = opts.new_branch;
 356        }
 357
 358        return add_worktree(path, branch, &opts);
 359}
 360
 361int cmd_worktree(int ac, const char **av, const char *prefix)
 362{
 363        struct option options[] = {
 364                OPT_END()
 365        };
 366
 367        if (ac < 2)
 368                usage_with_options(worktree_usage, options);
 369        if (!strcmp(av[1], "add"))
 370                return add(ac - 1, av + 1, prefix);
 371        if (!strcmp(av[1], "prune"))
 372                return prune(ac - 1, av + 1, prefix);
 373        usage_with_options(worktree_usage, options);
 374}