worktree.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. #include "cache.h"
  2. #include "checkout.h"
  3. #include "config.h"
  4. #include "builtin.h"
  5. #include "dir.h"
  6. #include "parse-options.h"
  7. #include "strvec.h"
  8. #include "branch.h"
  9. #include "refs.h"
  10. #include "run-command.h"
  11. #include "sigchain.h"
  12. #include "submodule.h"
  13. #include "utf8.h"
  14. #include "worktree.h"
  15. static const char * const worktree_usage[] = {
  16. N_("git worktree add [<options>] <path> [<commit-ish>]"),
  17. N_("git worktree list [<options>]"),
  18. N_("git worktree lock [<options>] <path>"),
  19. N_("git worktree move <worktree> <new-path>"),
  20. N_("git worktree prune [<options>]"),
  21. N_("git worktree remove [<options>] <worktree>"),
  22. N_("git worktree unlock <path>"),
  23. NULL
  24. };
  25. struct add_opts {
  26. int force;
  27. int detach;
  28. int quiet;
  29. int checkout;
  30. int keep_locked;
  31. };
  32. static int show_only;
  33. static int verbose;
  34. static int guess_remote;
  35. static timestamp_t expire;
  36. static int git_worktree_config(const char *var, const char *value, void *cb)
  37. {
  38. if (!strcmp(var, "worktree.guessremote")) {
  39. guess_remote = git_config_bool(var, value);
  40. return 0;
  41. }
  42. return git_default_config(var, value, cb);
  43. }
  44. static int delete_git_dir(const char *id)
  45. {
  46. struct strbuf sb = STRBUF_INIT;
  47. int ret;
  48. strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
  49. ret = remove_dir_recursively(&sb, 0);
  50. if (ret < 0 && errno == ENOTDIR)
  51. ret = unlink(sb.buf);
  52. if (ret)
  53. error_errno(_("failed to delete '%s'"), sb.buf);
  54. strbuf_release(&sb);
  55. return ret;
  56. }
  57. static void delete_worktrees_dir_if_empty(void)
  58. {
  59. rmdir(git_path("worktrees")); /* ignore failed removal */
  60. }
  61. /*
  62. * Return true if worktree entry should be pruned, along with the reason for
  63. * pruning. Otherwise, return false and the worktree's path, or NULL if it
  64. * cannot be determined. Caller is responsible for freeing returned path.
  65. */
  66. static int should_prune_worktree(const char *id, struct strbuf *reason, char **wtpath)
  67. {
  68. struct stat st;
  69. char *path;
  70. int fd;
  71. size_t len;
  72. ssize_t read_result;
  73. *wtpath = NULL;
  74. if (!is_directory(git_path("worktrees/%s", id))) {
  75. strbuf_addstr(reason, _("not a valid directory"));
  76. return 1;
  77. }
  78. if (file_exists(git_path("worktrees/%s/locked", id)))
  79. return 0;
  80. if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
  81. strbuf_addstr(reason, _("gitdir file does not exist"));
  82. return 1;
  83. }
  84. fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
  85. if (fd < 0) {
  86. strbuf_addf(reason, _("unable to read gitdir file (%s)"),
  87. strerror(errno));
  88. return 1;
  89. }
  90. len = xsize_t(st.st_size);
  91. path = xmallocz(len);
  92. read_result = read_in_full(fd, path, len);
  93. if (read_result < 0) {
  94. strbuf_addf(reason, _("unable to read gitdir file (%s)"),
  95. strerror(errno));
  96. close(fd);
  97. free(path);
  98. return 1;
  99. }
  100. close(fd);
  101. if (read_result != len) {
  102. strbuf_addf(reason,
  103. _("short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
  104. (uintmax_t)len, (uintmax_t)read_result);
  105. free(path);
  106. return 1;
  107. }
  108. while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
  109. len--;
  110. if (!len) {
  111. strbuf_addstr(reason, _("invalid gitdir file"));
  112. free(path);
  113. return 1;
  114. }
  115. path[len] = '\0';
  116. if (!file_exists(path)) {
  117. if (stat(git_path("worktrees/%s/index", id), &st) ||
  118. st.st_mtime <= expire) {
  119. strbuf_addstr(reason, _("gitdir file points to non-existent location"));
  120. free(path);
  121. return 1;
  122. } else {
  123. *wtpath = path;
  124. return 0;
  125. }
  126. }
  127. *wtpath = path;
  128. return 0;
  129. }
  130. static void prune_worktree(const char *id, const char *reason)
  131. {
  132. if (show_only || verbose)
  133. printf_ln(_("Removing %s/%s: %s"), "worktrees", id, reason);
  134. if (!show_only)
  135. delete_git_dir(id);
  136. }
  137. static int prune_cmp(const void *a, const void *b)
  138. {
  139. const struct string_list_item *x = a;
  140. const struct string_list_item *y = b;
  141. int c;
  142. if ((c = fspathcmp(x->string, y->string)))
  143. return c;
  144. /*
  145. * paths same; prune_dupes() removes all but the first worktree entry
  146. * having the same path, so sort main worktree ('util' is NULL) above
  147. * linked worktrees ('util' not NULL) since main worktree can't be
  148. * removed
  149. */
  150. if (!x->util)
  151. return -1;
  152. if (!y->util)
  153. return 1;
  154. /* paths same; sort by .git/worktrees/<id> */
  155. return strcmp(x->util, y->util);
  156. }
  157. static void prune_dups(struct string_list *l)
  158. {
  159. int i;
  160. QSORT(l->items, l->nr, prune_cmp);
  161. for (i = 1; i < l->nr; i++) {
  162. if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
  163. prune_worktree(l->items[i].util, "duplicate entry");
  164. }
  165. }
  166. static void prune_worktrees(void)
  167. {
  168. struct strbuf reason = STRBUF_INIT;
  169. struct strbuf main_path = STRBUF_INIT;
  170. struct string_list kept = STRING_LIST_INIT_NODUP;
  171. DIR *dir = opendir(git_path("worktrees"));
  172. struct dirent *d;
  173. if (!dir)
  174. return;
  175. while ((d = readdir(dir)) != NULL) {
  176. char *path;
  177. if (is_dot_or_dotdot(d->d_name))
  178. continue;
  179. strbuf_reset(&reason);
  180. if (should_prune_worktree(d->d_name, &reason, &path))
  181. prune_worktree(d->d_name, reason.buf);
  182. else if (path)
  183. string_list_append(&kept, path)->util = xstrdup(d->d_name);
  184. }
  185. closedir(dir);
  186. strbuf_add_absolute_path(&main_path, get_git_common_dir());
  187. /* massage main worktree absolute path to match 'gitdir' content */
  188. strbuf_strip_suffix(&main_path, "/.");
  189. string_list_append(&kept, strbuf_detach(&main_path, NULL));
  190. prune_dups(&kept);
  191. string_list_clear(&kept, 1);
  192. if (!show_only)
  193. delete_worktrees_dir_if_empty();
  194. strbuf_release(&reason);
  195. }
  196. static int prune(int ac, const char **av, const char *prefix)
  197. {
  198. struct option options[] = {
  199. OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
  200. OPT__VERBOSE(&verbose, N_("report pruned working trees")),
  201. OPT_EXPIRY_DATE(0, "expire", &expire,
  202. N_("expire working trees older than <time>")),
  203. OPT_END()
  204. };
  205. expire = TIME_MAX;
  206. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  207. if (ac)
  208. usage_with_options(worktree_usage, options);
  209. prune_worktrees();
  210. return 0;
  211. }
  212. static char *junk_work_tree;
  213. static char *junk_git_dir;
  214. static int is_junk;
  215. static pid_t junk_pid;
  216. static void remove_junk(void)
  217. {
  218. struct strbuf sb = STRBUF_INIT;
  219. if (!is_junk || getpid() != junk_pid)
  220. return;
  221. if (junk_git_dir) {
  222. strbuf_addstr(&sb, junk_git_dir);
  223. remove_dir_recursively(&sb, 0);
  224. strbuf_reset(&sb);
  225. }
  226. if (junk_work_tree) {
  227. strbuf_addstr(&sb, junk_work_tree);
  228. remove_dir_recursively(&sb, 0);
  229. }
  230. strbuf_release(&sb);
  231. }
  232. static void remove_junk_on_signal(int signo)
  233. {
  234. remove_junk();
  235. sigchain_pop(signo);
  236. raise(signo);
  237. }
  238. static const char *worktree_basename(const char *path, int *olen)
  239. {
  240. const char *name;
  241. int len;
  242. len = strlen(path);
  243. while (len && is_dir_sep(path[len - 1]))
  244. len--;
  245. for (name = path + len - 1; name > path; name--)
  246. if (is_dir_sep(*name)) {
  247. name++;
  248. break;
  249. }
  250. *olen = len;
  251. return name;
  252. }
  253. /* check that path is viable location for worktree */
  254. static void check_candidate_path(const char *path,
  255. int force,
  256. struct worktree **worktrees,
  257. const char *cmd)
  258. {
  259. struct worktree *wt;
  260. int locked;
  261. if (file_exists(path) && !is_empty_dir(path))
  262. die(_("'%s' already exists"), path);
  263. wt = find_worktree_by_path(worktrees, path);
  264. if (!wt)
  265. return;
  266. locked = !!worktree_lock_reason(wt);
  267. if ((!locked && force) || (locked && force > 1)) {
  268. if (delete_git_dir(wt->id))
  269. die(_("unusable worktree destination '%s'"), path);
  270. return;
  271. }
  272. if (locked)
  273. die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), cmd, path);
  274. else
  275. die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), cmd, path);
  276. }
  277. static int add_worktree(const char *path, const char *refname,
  278. const struct add_opts *opts)
  279. {
  280. struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
  281. struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
  282. const char *name;
  283. struct child_process cp = CHILD_PROCESS_INIT;
  284. struct strvec child_env = STRVEC_INIT;
  285. unsigned int counter = 0;
  286. int len, ret;
  287. struct strbuf symref = STRBUF_INIT;
  288. struct commit *commit = NULL;
  289. int is_branch = 0;
  290. struct strbuf sb_name = STRBUF_INIT;
  291. struct worktree **worktrees;
  292. worktrees = get_worktrees();
  293. check_candidate_path(path, opts->force, worktrees, "add");
  294. free_worktrees(worktrees);
  295. worktrees = NULL;
  296. /* is 'refname' a branch or commit? */
  297. if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
  298. ref_exists(symref.buf)) {
  299. is_branch = 1;
  300. if (!opts->force)
  301. die_if_checked_out(symref.buf, 0);
  302. }
  303. commit = lookup_commit_reference_by_name(refname);
  304. if (!commit)
  305. die(_("invalid reference: %s"), refname);
  306. name = worktree_basename(path, &len);
  307. strbuf_add(&sb, name, path + len - name);
  308. sanitize_refname_component(sb.buf, &sb_name);
  309. if (!sb_name.len)
  310. BUG("How come '%s' becomes empty after sanitization?", sb.buf);
  311. strbuf_reset(&sb);
  312. name = sb_name.buf;
  313. git_path_buf(&sb_repo, "worktrees/%s", name);
  314. len = sb_repo.len;
  315. if (safe_create_leading_directories_const(sb_repo.buf))
  316. die_errno(_("could not create leading directories of '%s'"),
  317. sb_repo.buf);
  318. while (mkdir(sb_repo.buf, 0777)) {
  319. counter++;
  320. if ((errno != EEXIST) || !counter /* overflow */)
  321. die_errno(_("could not create directory of '%s'"),
  322. sb_repo.buf);
  323. strbuf_setlen(&sb_repo, len);
  324. strbuf_addf(&sb_repo, "%d", counter);
  325. }
  326. name = strrchr(sb_repo.buf, '/') + 1;
  327. junk_pid = getpid();
  328. atexit(remove_junk);
  329. sigchain_push_common(remove_junk_on_signal);
  330. junk_git_dir = xstrdup(sb_repo.buf);
  331. is_junk = 1;
  332. /*
  333. * lock the incomplete repo so prune won't delete it, unlock
  334. * after the preparation is over.
  335. */
  336. strbuf_addf(&sb, "%s/locked", sb_repo.buf);
  337. if (!opts->keep_locked)
  338. write_file(sb.buf, "initializing");
  339. else
  340. write_file(sb.buf, "added with --lock");
  341. strbuf_addf(&sb_git, "%s/.git", path);
  342. if (safe_create_leading_directories_const(sb_git.buf))
  343. die_errno(_("could not create leading directories of '%s'"),
  344. sb_git.buf);
  345. junk_work_tree = xstrdup(path);
  346. strbuf_reset(&sb);
  347. strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
  348. strbuf_realpath(&realpath, sb_git.buf, 1);
  349. write_file(sb.buf, "%s", realpath.buf);
  350. strbuf_realpath(&realpath, get_git_common_dir(), 1);
  351. write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
  352. realpath.buf, name);
  353. /*
  354. * This is to keep resolve_ref() happy. We need a valid HEAD
  355. * or is_git_directory() will reject the directory. Any value which
  356. * looks like an object ID will do since it will be immediately
  357. * replaced by the symbolic-ref or update-ref invocation in the new
  358. * worktree.
  359. */
  360. strbuf_reset(&sb);
  361. strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
  362. write_file(sb.buf, "%s", oid_to_hex(&null_oid));
  363. strbuf_reset(&sb);
  364. strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
  365. write_file(sb.buf, "../..");
  366. strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
  367. strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
  368. cp.git_cmd = 1;
  369. if (!is_branch)
  370. strvec_pushl(&cp.args, "update-ref", "HEAD",
  371. oid_to_hex(&commit->object.oid), NULL);
  372. else {
  373. strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
  374. symref.buf, NULL);
  375. if (opts->quiet)
  376. strvec_push(&cp.args, "--quiet");
  377. }
  378. cp.env = child_env.v;
  379. ret = run_command(&cp);
  380. if (ret)
  381. goto done;
  382. if (opts->checkout) {
  383. cp.argv = NULL;
  384. strvec_clear(&cp.args);
  385. strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
  386. if (opts->quiet)
  387. strvec_push(&cp.args, "--quiet");
  388. cp.env = child_env.v;
  389. ret = run_command(&cp);
  390. if (ret)
  391. goto done;
  392. }
  393. is_junk = 0;
  394. FREE_AND_NULL(junk_work_tree);
  395. FREE_AND_NULL(junk_git_dir);
  396. done:
  397. if (ret || !opts->keep_locked) {
  398. strbuf_reset(&sb);
  399. strbuf_addf(&sb, "%s/locked", sb_repo.buf);
  400. unlink_or_warn(sb.buf);
  401. }
  402. /*
  403. * Hook failure does not warrant worktree deletion, so run hook after
  404. * is_junk is cleared, but do return appropriate code when hook fails.
  405. */
  406. if (!ret && opts->checkout) {
  407. const char *hook = find_hook("post-checkout");
  408. if (hook) {
  409. const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
  410. cp.git_cmd = 0;
  411. cp.no_stdin = 1;
  412. cp.stdout_to_stderr = 1;
  413. cp.dir = path;
  414. cp.env = env;
  415. cp.argv = NULL;
  416. cp.trace2_hook_name = "post-checkout";
  417. strvec_pushl(&cp.args, absolute_path(hook),
  418. oid_to_hex(&null_oid),
  419. oid_to_hex(&commit->object.oid),
  420. "1", NULL);
  421. ret = run_command(&cp);
  422. }
  423. }
  424. strvec_clear(&child_env);
  425. strbuf_release(&sb);
  426. strbuf_release(&symref);
  427. strbuf_release(&sb_repo);
  428. strbuf_release(&sb_git);
  429. strbuf_release(&sb_name);
  430. strbuf_release(&realpath);
  431. return ret;
  432. }
  433. static void print_preparing_worktree_line(int detach,
  434. const char *branch,
  435. const char *new_branch,
  436. int force_new_branch)
  437. {
  438. if (force_new_branch) {
  439. struct commit *commit = lookup_commit_reference_by_name(new_branch);
  440. if (!commit)
  441. printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
  442. else
  443. printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
  444. new_branch,
  445. find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
  446. } else if (new_branch) {
  447. printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
  448. } else {
  449. struct strbuf s = STRBUF_INIT;
  450. if (!detach && !strbuf_check_branch_ref(&s, branch) &&
  451. ref_exists(s.buf))
  452. printf_ln(_("Preparing worktree (checking out '%s')"),
  453. branch);
  454. else {
  455. struct commit *commit = lookup_commit_reference_by_name(branch);
  456. if (!commit)
  457. die(_("invalid reference: %s"), branch);
  458. printf_ln(_("Preparing worktree (detached HEAD %s)"),
  459. find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
  460. }
  461. strbuf_release(&s);
  462. }
  463. }
  464. static const char *dwim_branch(const char *path, const char **new_branch)
  465. {
  466. int n;
  467. const char *s = worktree_basename(path, &n);
  468. const char *branchname = xstrndup(s, n);
  469. struct strbuf ref = STRBUF_INIT;
  470. UNLEAK(branchname);
  471. if (!strbuf_check_branch_ref(&ref, branchname) &&
  472. ref_exists(ref.buf)) {
  473. strbuf_release(&ref);
  474. return branchname;
  475. }
  476. *new_branch = branchname;
  477. if (guess_remote) {
  478. struct object_id oid;
  479. const char *remote =
  480. unique_tracking_name(*new_branch, &oid, NULL);
  481. return remote;
  482. }
  483. return NULL;
  484. }
  485. static int add(int ac, const char **av, const char *prefix)
  486. {
  487. struct add_opts opts;
  488. const char *new_branch_force = NULL;
  489. char *path;
  490. const char *branch;
  491. const char *new_branch = NULL;
  492. const char *opt_track = NULL;
  493. struct option options[] = {
  494. OPT__FORCE(&opts.force,
  495. N_("checkout <branch> even if already checked out in other worktree"),
  496. PARSE_OPT_NOCOMPLETE),
  497. OPT_STRING('b', NULL, &new_branch, N_("branch"),
  498. N_("create a new branch")),
  499. OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
  500. N_("create or reset a branch")),
  501. OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
  502. OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
  503. OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
  504. OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
  505. OPT_PASSTHRU(0, "track", &opt_track, NULL,
  506. N_("set up tracking mode (see git-branch(1))"),
  507. PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
  508. OPT_BOOL(0, "guess-remote", &guess_remote,
  509. N_("try to match the new branch name with a remote-tracking branch")),
  510. OPT_END()
  511. };
  512. memset(&opts, 0, sizeof(opts));
  513. opts.checkout = 1;
  514. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  515. if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
  516. die(_("-b, -B, and --detach are mutually exclusive"));
  517. if (ac < 1 || ac > 2)
  518. usage_with_options(worktree_usage, options);
  519. path = prefix_filename(prefix, av[0]);
  520. branch = ac < 2 ? "HEAD" : av[1];
  521. if (!strcmp(branch, "-"))
  522. branch = "@{-1}";
  523. if (new_branch_force) {
  524. struct strbuf symref = STRBUF_INIT;
  525. new_branch = new_branch_force;
  526. if (!opts.force &&
  527. !strbuf_check_branch_ref(&symref, new_branch) &&
  528. ref_exists(symref.buf))
  529. die_if_checked_out(symref.buf, 0);
  530. strbuf_release(&symref);
  531. }
  532. if (ac < 2 && !new_branch && !opts.detach) {
  533. const char *s = dwim_branch(path, &new_branch);
  534. if (s)
  535. branch = s;
  536. }
  537. if (ac == 2 && !new_branch && !opts.detach) {
  538. struct object_id oid;
  539. struct commit *commit;
  540. const char *remote;
  541. commit = lookup_commit_reference_by_name(branch);
  542. if (!commit) {
  543. remote = unique_tracking_name(branch, &oid, NULL);
  544. if (remote) {
  545. new_branch = branch;
  546. branch = remote;
  547. }
  548. }
  549. }
  550. if (!opts.quiet)
  551. print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
  552. if (new_branch) {
  553. struct child_process cp = CHILD_PROCESS_INIT;
  554. cp.git_cmd = 1;
  555. strvec_push(&cp.args, "branch");
  556. if (new_branch_force)
  557. strvec_push(&cp.args, "--force");
  558. if (opts.quiet)
  559. strvec_push(&cp.args, "--quiet");
  560. strvec_push(&cp.args, new_branch);
  561. strvec_push(&cp.args, branch);
  562. if (opt_track)
  563. strvec_push(&cp.args, opt_track);
  564. if (run_command(&cp))
  565. return -1;
  566. branch = new_branch;
  567. } else if (opt_track) {
  568. die(_("--[no-]track can only be used if a new branch is created"));
  569. }
  570. UNLEAK(path);
  571. UNLEAK(opts);
  572. return add_worktree(path, branch, &opts);
  573. }
  574. static void show_worktree_porcelain(struct worktree *wt)
  575. {
  576. printf("worktree %s\n", wt->path);
  577. if (wt->is_bare)
  578. printf("bare\n");
  579. else {
  580. printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
  581. if (wt->is_detached)
  582. printf("detached\n");
  583. else if (wt->head_ref)
  584. printf("branch %s\n", wt->head_ref);
  585. }
  586. printf("\n");
  587. }
  588. static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
  589. {
  590. struct strbuf sb = STRBUF_INIT;
  591. int cur_path_len = strlen(wt->path);
  592. int path_adj = cur_path_len - utf8_strwidth(wt->path);
  593. strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
  594. if (wt->is_bare)
  595. strbuf_addstr(&sb, "(bare)");
  596. else {
  597. strbuf_addf(&sb, "%-*s ", abbrev_len,
  598. find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
  599. if (wt->is_detached)
  600. strbuf_addstr(&sb, "(detached HEAD)");
  601. else if (wt->head_ref) {
  602. char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
  603. strbuf_addf(&sb, "[%s]", ref);
  604. free(ref);
  605. } else
  606. strbuf_addstr(&sb, "(error)");
  607. }
  608. printf("%s\n", sb.buf);
  609. strbuf_release(&sb);
  610. }
  611. static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
  612. {
  613. int i;
  614. for (i = 0; wt[i]; i++) {
  615. int sha1_len;
  616. int path_len = strlen(wt[i]->path);
  617. if (path_len > *maxlen)
  618. *maxlen = path_len;
  619. sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
  620. if (sha1_len > *abbrev)
  621. *abbrev = sha1_len;
  622. }
  623. }
  624. static int pathcmp(const void *a_, const void *b_)
  625. {
  626. const struct worktree *const *a = a_;
  627. const struct worktree *const *b = b_;
  628. return fspathcmp((*a)->path, (*b)->path);
  629. }
  630. static void pathsort(struct worktree **wt)
  631. {
  632. int n = 0;
  633. struct worktree **p = wt;
  634. while (*p++)
  635. n++;
  636. QSORT(wt, n, pathcmp);
  637. }
  638. static int list(int ac, const char **av, const char *prefix)
  639. {
  640. int porcelain = 0;
  641. struct option options[] = {
  642. OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
  643. OPT_END()
  644. };
  645. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  646. if (ac)
  647. usage_with_options(worktree_usage, options);
  648. else {
  649. struct worktree **worktrees = get_worktrees();
  650. int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
  651. /* sort worktrees by path but keep main worktree at top */
  652. pathsort(worktrees + 1);
  653. if (!porcelain)
  654. measure_widths(worktrees, &abbrev, &path_maxlen);
  655. for (i = 0; worktrees[i]; i++) {
  656. if (porcelain)
  657. show_worktree_porcelain(worktrees[i]);
  658. else
  659. show_worktree(worktrees[i], path_maxlen, abbrev);
  660. }
  661. free_worktrees(worktrees);
  662. }
  663. return 0;
  664. }
  665. static int lock_worktree(int ac, const char **av, const char *prefix)
  666. {
  667. const char *reason = "", *old_reason;
  668. struct option options[] = {
  669. OPT_STRING(0, "reason", &reason, N_("string"),
  670. N_("reason for locking")),
  671. OPT_END()
  672. };
  673. struct worktree **worktrees, *wt;
  674. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  675. if (ac != 1)
  676. usage_with_options(worktree_usage, options);
  677. worktrees = get_worktrees();
  678. wt = find_worktree(worktrees, prefix, av[0]);
  679. if (!wt)
  680. die(_("'%s' is not a working tree"), av[0]);
  681. if (is_main_worktree(wt))
  682. die(_("The main working tree cannot be locked or unlocked"));
  683. old_reason = worktree_lock_reason(wt);
  684. if (old_reason) {
  685. if (*old_reason)
  686. die(_("'%s' is already locked, reason: %s"),
  687. av[0], old_reason);
  688. die(_("'%s' is already locked"), av[0]);
  689. }
  690. write_file(git_common_path("worktrees/%s/locked", wt->id),
  691. "%s", reason);
  692. free_worktrees(worktrees);
  693. return 0;
  694. }
  695. static int unlock_worktree(int ac, const char **av, const char *prefix)
  696. {
  697. struct option options[] = {
  698. OPT_END()
  699. };
  700. struct worktree **worktrees, *wt;
  701. int ret;
  702. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  703. if (ac != 1)
  704. usage_with_options(worktree_usage, options);
  705. worktrees = get_worktrees();
  706. wt = find_worktree(worktrees, prefix, av[0]);
  707. if (!wt)
  708. die(_("'%s' is not a working tree"), av[0]);
  709. if (is_main_worktree(wt))
  710. die(_("The main working tree cannot be locked or unlocked"));
  711. if (!worktree_lock_reason(wt))
  712. die(_("'%s' is not locked"), av[0]);
  713. ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
  714. free_worktrees(worktrees);
  715. return ret;
  716. }
  717. static void validate_no_submodules(const struct worktree *wt)
  718. {
  719. struct index_state istate = { NULL };
  720. struct strbuf path = STRBUF_INIT;
  721. int i, found_submodules = 0;
  722. if (is_directory(worktree_git_path(wt, "modules"))) {
  723. /*
  724. * There could be false positives, e.g. the "modules"
  725. * directory exists but is empty. But it's a rare case and
  726. * this simpler check is probably good enough for now.
  727. */
  728. found_submodules = 1;
  729. } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
  730. get_worktree_git_dir(wt)) > 0) {
  731. for (i = 0; i < istate.cache_nr; i++) {
  732. struct cache_entry *ce = istate.cache[i];
  733. int err;
  734. if (!S_ISGITLINK(ce->ce_mode))
  735. continue;
  736. strbuf_reset(&path);
  737. strbuf_addf(&path, "%s/%s", wt->path, ce->name);
  738. if (!is_submodule_populated_gently(path.buf, &err))
  739. continue;
  740. found_submodules = 1;
  741. break;
  742. }
  743. }
  744. discard_index(&istate);
  745. strbuf_release(&path);
  746. if (found_submodules)
  747. die(_("working trees containing submodules cannot be moved or removed"));
  748. }
  749. static int move_worktree(int ac, const char **av, const char *prefix)
  750. {
  751. int force = 0;
  752. struct option options[] = {
  753. OPT__FORCE(&force,
  754. N_("force move even if worktree is dirty or locked"),
  755. PARSE_OPT_NOCOMPLETE),
  756. OPT_END()
  757. };
  758. struct worktree **worktrees, *wt;
  759. struct strbuf dst = STRBUF_INIT;
  760. struct strbuf errmsg = STRBUF_INIT;
  761. const char *reason = NULL;
  762. char *path;
  763. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  764. if (ac != 2)
  765. usage_with_options(worktree_usage, options);
  766. path = prefix_filename(prefix, av[1]);
  767. strbuf_addstr(&dst, path);
  768. free(path);
  769. worktrees = get_worktrees();
  770. wt = find_worktree(worktrees, prefix, av[0]);
  771. if (!wt)
  772. die(_("'%s' is not a working tree"), av[0]);
  773. if (is_main_worktree(wt))
  774. die(_("'%s' is a main working tree"), av[0]);
  775. if (is_directory(dst.buf)) {
  776. const char *sep = find_last_dir_sep(wt->path);
  777. if (!sep)
  778. die(_("could not figure out destination name from '%s'"),
  779. wt->path);
  780. strbuf_trim_trailing_dir_sep(&dst);
  781. strbuf_addstr(&dst, sep);
  782. }
  783. check_candidate_path(dst.buf, force, worktrees, "move");
  784. validate_no_submodules(wt);
  785. if (force < 2)
  786. reason = worktree_lock_reason(wt);
  787. if (reason) {
  788. if (*reason)
  789. die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
  790. reason);
  791. die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
  792. }
  793. if (validate_worktree(wt, &errmsg, 0))
  794. die(_("validation failed, cannot move working tree: %s"),
  795. errmsg.buf);
  796. strbuf_release(&errmsg);
  797. if (rename(wt->path, dst.buf) == -1)
  798. die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
  799. update_worktree_location(wt, dst.buf);
  800. strbuf_release(&dst);
  801. free_worktrees(worktrees);
  802. return 0;
  803. }
  804. /*
  805. * Note, "git status --porcelain" is used to determine if it's safe to
  806. * delete a whole worktree. "git status" does not ignore user
  807. * configuration, so if a normal "git status" shows "clean" for the
  808. * user, then it's ok to remove it.
  809. *
  810. * This assumption may be a bad one. We may want to ignore
  811. * (potentially bad) user settings and only delete a worktree when
  812. * it's absolutely safe to do so from _our_ point of view because we
  813. * know better.
  814. */
  815. static void check_clean_worktree(struct worktree *wt,
  816. const char *original_path)
  817. {
  818. struct child_process cp;
  819. char buf[1];
  820. int ret;
  821. /*
  822. * Until we sort this out, all submodules are "dirty" and
  823. * will abort this function.
  824. */
  825. validate_no_submodules(wt);
  826. child_process_init(&cp);
  827. strvec_pushf(&cp.env_array, "%s=%s/.git",
  828. GIT_DIR_ENVIRONMENT, wt->path);
  829. strvec_pushf(&cp.env_array, "%s=%s",
  830. GIT_WORK_TREE_ENVIRONMENT, wt->path);
  831. strvec_pushl(&cp.args, "status",
  832. "--porcelain", "--ignore-submodules=none",
  833. NULL);
  834. cp.git_cmd = 1;
  835. cp.dir = wt->path;
  836. cp.out = -1;
  837. ret = start_command(&cp);
  838. if (ret)
  839. die_errno(_("failed to run 'git status' on '%s'"),
  840. original_path);
  841. ret = xread(cp.out, buf, sizeof(buf));
  842. if (ret)
  843. die(_("'%s' contains modified or untracked files, use --force to delete it"),
  844. original_path);
  845. close(cp.out);
  846. ret = finish_command(&cp);
  847. if (ret)
  848. die_errno(_("failed to run 'git status' on '%s', code %d"),
  849. original_path, ret);
  850. }
  851. static int delete_git_work_tree(struct worktree *wt)
  852. {
  853. struct strbuf sb = STRBUF_INIT;
  854. int ret = 0;
  855. strbuf_addstr(&sb, wt->path);
  856. if (remove_dir_recursively(&sb, 0)) {
  857. error_errno(_("failed to delete '%s'"), sb.buf);
  858. ret = -1;
  859. }
  860. strbuf_release(&sb);
  861. return ret;
  862. }
  863. static int remove_worktree(int ac, const char **av, const char *prefix)
  864. {
  865. int force = 0;
  866. struct option options[] = {
  867. OPT__FORCE(&force,
  868. N_("force removal even if worktree is dirty or locked"),
  869. PARSE_OPT_NOCOMPLETE),
  870. OPT_END()
  871. };
  872. struct worktree **worktrees, *wt;
  873. struct strbuf errmsg = STRBUF_INIT;
  874. const char *reason = NULL;
  875. int ret = 0;
  876. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  877. if (ac != 1)
  878. usage_with_options(worktree_usage, options);
  879. worktrees = get_worktrees();
  880. wt = find_worktree(worktrees, prefix, av[0]);
  881. if (!wt)
  882. die(_("'%s' is not a working tree"), av[0]);
  883. if (is_main_worktree(wt))
  884. die(_("'%s' is a main working tree"), av[0]);
  885. if (force < 2)
  886. reason = worktree_lock_reason(wt);
  887. if (reason) {
  888. if (*reason)
  889. die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
  890. reason);
  891. die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
  892. }
  893. if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
  894. die(_("validation failed, cannot remove working tree: %s"),
  895. errmsg.buf);
  896. strbuf_release(&errmsg);
  897. if (file_exists(wt->path)) {
  898. if (!force)
  899. check_clean_worktree(wt, av[0]);
  900. ret |= delete_git_work_tree(wt);
  901. }
  902. /*
  903. * continue on even if ret is non-zero, there's no going back
  904. * from here.
  905. */
  906. ret |= delete_git_dir(wt->id);
  907. delete_worktrees_dir_if_empty();
  908. free_worktrees(worktrees);
  909. return ret;
  910. }
  911. static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
  912. {
  913. if (!iserr) {
  914. printf_ln(_("repair: %s: %s"), msg, path);
  915. } else {
  916. int *exit_status = (int *)cb_data;
  917. fprintf_ln(stderr, _("error: %s: %s"), msg, path);
  918. *exit_status = 1;
  919. }
  920. }
  921. static int repair(int ac, const char **av, const char *prefix)
  922. {
  923. const char **p;
  924. const char *self[] = { ".", NULL };
  925. struct option options[] = {
  926. OPT_END()
  927. };
  928. int rc = 0;
  929. ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
  930. repair_worktrees(report_repair, &rc);
  931. p = ac > 0 ? av : self;
  932. for (; *p; p++)
  933. repair_worktree_at_path(*p, report_repair, &rc);
  934. return rc;
  935. }
  936. int cmd_worktree(int ac, const char **av, const char *prefix)
  937. {
  938. struct option options[] = {
  939. OPT_END()
  940. };
  941. git_config(git_worktree_config, NULL);
  942. if (ac < 2)
  943. usage_with_options(worktree_usage, options);
  944. if (!prefix)
  945. prefix = "";
  946. if (!strcmp(av[1], "add"))
  947. return add(ac - 1, av + 1, prefix);
  948. if (!strcmp(av[1], "prune"))
  949. return prune(ac - 1, av + 1, prefix);
  950. if (!strcmp(av[1], "list"))
  951. return list(ac - 1, av + 1, prefix);
  952. if (!strcmp(av[1], "lock"))
  953. return lock_worktree(ac - 1, av + 1, prefix);
  954. if (!strcmp(av[1], "unlock"))
  955. return unlock_worktree(ac - 1, av + 1, prefix);
  956. if (!strcmp(av[1], "move"))
  957. return move_worktree(ac - 1, av + 1, prefix);
  958. if (!strcmp(av[1], "remove"))
  959. return remove_worktree(ac - 1, av + 1, prefix);
  960. if (!strcmp(av[1], "repair"))
  961. return repair(ac - 1, av + 1, prefix);
  962. usage_with_options(worktree_usage, options);
  963. }