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