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