Convert struct object to object_id
[git/git.git] / builtin / worktree.c
CommitLineData
df0b6cfb
NTND
1#include "cache.h"
2#include "builtin.h"
3#include "dir.h"
4#include "parse-options.h"
fc56361f 5#include "argv-array.h"
f7c9dac1
ES
6#include "branch.h"
7#include "refs.h"
fc56361f 8#include "run-command.h"
b979d950 9#include "sigchain.h"
799767cc 10#include "refs.h"
bb9c03b8
MR
11#include "utf8.h"
12#include "worktree.h"
df0b6cfb
NTND
13
14static const char * const worktree_usage[] = {
ae9f2745 15 N_("git worktree add [<options>] <path> [<branch>]"),
df0b6cfb 16 N_("git worktree prune [<options>]"),
bb9c03b8 17 N_("git worktree list [<options>]"),
df0b6cfb
NTND
18 NULL
19};
20
5dd6e234
ES
21struct add_opts {
22 int force;
23 int detach;
24 const char *new_branch;
25 int force_new_branch;
26};
27
df0b6cfb
NTND
28static int show_only;
29static int verbose;
30static unsigned long expire;
31
32static 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 = xmalloc(len + 1);
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
87static 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
121static 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
b979d950
ES
139static char *junk_work_tree;
140static char *junk_git_dir;
141static int is_junk;
142static pid_t junk_pid;
143
144static 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
161static void remove_junk_on_signal(int signo)
162{
163 remove_junk();
164 sigchain_pop(signo);
165 raise(signo);
166}
167
f5682b2a
ES
168static 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
80a0548f 187static int add_worktree(const char *path, const char *refname,
5dd6e234 188 const struct add_opts *opts)
b979d950
ES
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;
ae2a3827 195 struct argv_array child_env = ARGV_ARRAY_INIT;
b979d950 196 int counter = 0, len, ret;
f7c9dac1
ES
197 struct strbuf symref = STRBUF_INIT;
198 struct commit *commit = NULL;
b979d950
ES
199
200 if (file_exists(path) && !is_empty_dir(path))
201 die(_("'%s' already exists"), path);
202
f7c9dac1
ES
203 /* is 'refname' a branch or commit? */
204 if (opts->force_new_branch) /* definitely a branch */
205 ;
206 else 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);
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
f5682b2a 216 name = worktree_basename(path, &len);
b979d950
ES
217 strbuf_addstr(&sb_repo,
218 git_path("worktrees/%.*s", (int)(path + len - name), name));
219 len = sb_repo.len;
220 if (safe_create_leading_directories_const(sb_repo.buf))
221 die_errno(_("could not create leading directories of '%s'"),
222 sb_repo.buf);
223 while (!stat(sb_repo.buf, &st)) {
224 counter++;
225 strbuf_setlen(&sb_repo, len);
226 strbuf_addf(&sb_repo, "%d", counter);
227 }
228 name = strrchr(sb_repo.buf, '/') + 1;
229
230 junk_pid = getpid();
231 atexit(remove_junk);
232 sigchain_push_common(remove_junk_on_signal);
233
234 if (mkdir(sb_repo.buf, 0777))
235 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
236 junk_git_dir = xstrdup(sb_repo.buf);
237 is_junk = 1;
238
239 /*
240 * lock the incomplete repo so prune won't delete it, unlock
241 * after the preparation is over.
242 */
243 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
1f76a10b 244 write_file(sb.buf, "initializing");
b979d950
ES
245
246 strbuf_addf(&sb_git, "%s/.git", path);
247 if (safe_create_leading_directories_const(sb_git.buf))
248 die_errno(_("could not create leading directories of '%s'"),
249 sb_git.buf);
250 junk_work_tree = xstrdup(path);
251
252 strbuf_reset(&sb);
253 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
1f76a10b
JH
254 write_file(sb.buf, "%s", real_path(sb_git.buf));
255 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
b979d950
ES
256 real_path(get_git_common_dir()), name);
257 /*
258 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
259 * or is_git_directory() will reject the directory. Any value which
260 * looks like an object ID will do since it will be immediately
261 * replaced by the symbolic-ref or update-ref invocation in the new
262 * worktree.
b979d950 263 */
b979d950
ES
264 strbuf_reset(&sb);
265 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
d75bb73b 266 write_file(sb.buf, "0000000000000000000000000000000000000000");
b979d950
ES
267 strbuf_reset(&sb);
268 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 269 write_file(sb.buf, "../..");
b979d950 270
cd2f4713 271 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
b979d950 272
ae2a3827
ES
273 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
274 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
b979d950
ES
275 memset(&cp, 0, sizeof(cp));
276 cp.git_cmd = 1;
7f44e3d1
ES
277
278 if (commit)
279 argv_array_pushl(&cp.args, "update-ref", "HEAD",
f2fd0760 280 oid_to_hex(&commit->object.oid), NULL);
7f44e3d1
ES
281 else
282 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
283 symref.buf, NULL);
284 cp.env = child_env.argv;
285 ret = run_command(&cp);
286 if (ret)
287 goto done;
288
289 cp.argv = NULL;
290 argv_array_clear(&cp.args);
1c56190a 291 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
ae2a3827 292 cp.env = child_env.argv;
b979d950
ES
293 ret = run_command(&cp);
294 if (!ret) {
295 is_junk = 0;
296 free(junk_work_tree);
297 free(junk_git_dir);
298 junk_work_tree = NULL;
299 junk_git_dir = NULL;
300 }
7f44e3d1 301done:
b979d950
ES
302 strbuf_reset(&sb);
303 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
304 unlink_or_warn(sb.buf);
ae2a3827 305 argv_array_clear(&child_env);
b979d950 306 strbuf_release(&sb);
f7c9dac1 307 strbuf_release(&symref);
b979d950
ES
308 strbuf_release(&sb_repo);
309 strbuf_release(&sb_git);
310 return ret;
311}
312
fc56361f
ES
313static int add(int ac, const char **av, const char *prefix)
314{
5dd6e234
ES
315 struct add_opts opts;
316 const char *new_branch_force = NULL;
fc56361f 317 const char *path, *branch;
fc56361f 318 struct option options[] = {
5dd6e234
ES
319 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
320 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
cbdf60fa
ES
321 N_("create a new branch")),
322 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
323 N_("create or reset a branch")),
5dd6e234 324 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
fc56361f
ES
325 OPT_END()
326 };
327
5dd6e234 328 memset(&opts, 0, sizeof(opts));
fc56361f 329 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
ab0b2c53
ES
330 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
331 die(_("-b, -B, and --detach are mutually exclusive"));
0f4af3b9
ES
332 if (ac < 1 || ac > 2)
333 usage_with_options(worktree_usage, options);
fc56361f
ES
334
335 path = prefix ? prefix_filename(prefix, strlen(prefix), av[0]) : av[0];
0f4af3b9 336 branch = ac < 2 ? "HEAD" : av[1];
fc56361f 337
5dd6e234
ES
338 opts.force_new_branch = !!new_branch_force;
339 if (opts.force_new_branch)
340 opts.new_branch = new_branch_force;
eef005dc 341
5c942570 342 if (ac < 2 && !opts.new_branch && !opts.detach) {
1eb07d82
ES
343 int n;
344 const char *s = worktree_basename(path, &n);
5dd6e234 345 opts.new_branch = xstrndup(s, n);
1eb07d82
ES
346 }
347
c2842439
ES
348 if (opts.new_branch) {
349 struct child_process cp;
350 memset(&cp, 0, sizeof(cp));
351 cp.git_cmd = 1;
352 argv_array_push(&cp.args, "branch");
353 if (opts.force_new_branch)
354 argv_array_push(&cp.args, "--force");
355 argv_array_push(&cp.args, opts.new_branch);
356 argv_array_push(&cp.args, branch);
357 if (run_command(&cp))
358 return -1;
359 branch = opts.new_branch;
1eb07d82
ES
360 }
361
80a0548f 362 return add_worktree(path, branch, &opts);
fc56361f
ES
363}
364
bb9c03b8
MR
365static void show_worktree_porcelain(struct worktree *wt)
366{
367 printf("worktree %s\n", wt->path);
368 if (wt->is_bare)
369 printf("bare\n");
370 else {
371 printf("HEAD %s\n", sha1_to_hex(wt->head_sha1));
372 if (wt->is_detached)
373 printf("detached\n");
374 else
375 printf("branch %s\n", wt->head_ref);
376 }
377 printf("\n");
378}
379
380static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
381{
382 struct strbuf sb = STRBUF_INIT;
383 int cur_path_len = strlen(wt->path);
384 int path_adj = cur_path_len - utf8_strwidth(wt->path);
385
386 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
387 if (wt->is_bare)
388 strbuf_addstr(&sb, "(bare)");
389 else {
390 strbuf_addf(&sb, "%-*s ", abbrev_len,
391 find_unique_abbrev(wt->head_sha1, DEFAULT_ABBREV));
392 if (!wt->is_detached)
393 strbuf_addf(&sb, "[%s]", shorten_unambiguous_ref(wt->head_ref, 0));
394 else
395 strbuf_addstr(&sb, "(detached HEAD)");
396 }
397 printf("%s\n", sb.buf);
398
399 strbuf_release(&sb);
400}
401
402static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
403{
404 int i;
405
406 for (i = 0; wt[i]; i++) {
407 int sha1_len;
408 int path_len = strlen(wt[i]->path);
409
410 if (path_len > *maxlen)
411 *maxlen = path_len;
412 sha1_len = strlen(find_unique_abbrev(wt[i]->head_sha1, *abbrev));
413 if (sha1_len > *abbrev)
414 *abbrev = sha1_len;
415 }
416}
417
418static int list(int ac, const char **av, const char *prefix)
419{
420 int porcelain = 0;
421
422 struct option options[] = {
423 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
424 OPT_END()
425 };
426
427 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
428 if (ac)
429 usage_with_options(worktree_usage, options);
430 else {
431 struct worktree **worktrees = get_worktrees();
432 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
433
434 if (!porcelain)
435 measure_widths(worktrees, &abbrev, &path_maxlen);
436
437 for (i = 0; worktrees[i]; i++) {
438 if (porcelain)
439 show_worktree_porcelain(worktrees[i]);
440 else
441 show_worktree(worktrees[i], path_maxlen, abbrev);
442 }
443 free_worktrees(worktrees);
444 }
445 return 0;
446}
447
df0b6cfb
NTND
448int cmd_worktree(int ac, const char **av, const char *prefix)
449{
450 struct option options[] = {
451 OPT_END()
452 };
453
454 if (ac < 2)
455 usage_with_options(worktree_usage, options);
fc56361f
ES
456 if (!strcmp(av[1], "add"))
457 return add(ac - 1, av + 1, prefix);
df0b6cfb
NTND
458 if (!strcmp(av[1], "prune"))
459 return prune(ac - 1, av + 1, prefix);
bb9c03b8
MR
460 if (!strcmp(av[1], "list"))
461 return list(ac - 1, av + 1, prefix);
df0b6cfb
NTND
462 usage_with_options(worktree_usage, options);
463}