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