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