checkout.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869
  1. #define USE_THE_INDEX_COMPATIBILITY_MACROS
  2. #include "builtin.h"
  3. #include "advice.h"
  4. #include "blob.h"
  5. #include "branch.h"
  6. #include "cache-tree.h"
  7. #include "checkout.h"
  8. #include "commit.h"
  9. #include "config.h"
  10. #include "diff.h"
  11. #include "dir.h"
  12. #include "ll-merge.h"
  13. #include "lockfile.h"
  14. #include "merge-recursive.h"
  15. #include "object-store.h"
  16. #include "parse-options.h"
  17. #include "refs.h"
  18. #include "remote.h"
  19. #include "resolve-undo.h"
  20. #include "revision.h"
  21. #include "run-command.h"
  22. #include "submodule.h"
  23. #include "submodule-config.h"
  24. #include "tree.h"
  25. #include "tree-walk.h"
  26. #include "unpack-trees.h"
  27. #include "wt-status.h"
  28. #include "xdiff-interface.h"
  29. static const char * const checkout_usage[] = {
  30. N_("git checkout [<options>] <branch>"),
  31. N_("git checkout [<options>] [<branch>] -- <file>..."),
  32. NULL,
  33. };
  34. static const char * const switch_branch_usage[] = {
  35. N_("git switch [<options>] [<branch>]"),
  36. NULL,
  37. };
  38. static const char * const restore_usage[] = {
  39. N_("git restore [<options>] [--source=<branch>] <file>..."),
  40. NULL,
  41. };
  42. struct checkout_opts {
  43. int patch_mode;
  44. int quiet;
  45. int merge;
  46. int force;
  47. int force_detach;
  48. int implicit_detach;
  49. int writeout_stage;
  50. int overwrite_ignore;
  51. int ignore_skipworktree;
  52. int ignore_other_worktrees;
  53. int show_progress;
  54. int count_checkout_paths;
  55. int overlay_mode;
  56. int dwim_new_local_branch;
  57. int discard_changes;
  58. int accept_ref;
  59. int accept_pathspec;
  60. int switch_branch_doing_nothing_is_ok;
  61. int only_merge_on_switching_branches;
  62. int can_switch_when_in_progress;
  63. int orphan_from_empty_tree;
  64. int empty_pathspec_ok;
  65. int checkout_index;
  66. int checkout_worktree;
  67. const char *ignore_unmerged_opt;
  68. int ignore_unmerged;
  69. int pathspec_file_nul;
  70. const char *pathspec_from_file;
  71. const char *new_branch;
  72. const char *new_branch_force;
  73. const char *new_orphan_branch;
  74. int new_branch_log;
  75. enum branch_track track;
  76. struct diff_options diff_options;
  77. char *conflict_style;
  78. int branch_exists;
  79. const char *prefix;
  80. struct pathspec pathspec;
  81. const char *from_treeish;
  82. struct tree *source_tree;
  83. };
  84. struct branch_info {
  85. const char *name; /* The short name used */
  86. const char *path; /* The full name of a real branch */
  87. struct commit *commit; /* The named commit */
  88. char *refname; /* The full name of the ref being checked out. */
  89. struct object_id oid; /* The object ID of the commit being checked out. */
  90. /*
  91. * if not null the branch is detached because it's already
  92. * checked out in this checkout
  93. */
  94. char *checkout;
  95. };
  96. static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
  97. int changed)
  98. {
  99. return run_hook_le(NULL, "post-checkout",
  100. oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
  101. oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
  102. changed ? "1" : "0", NULL);
  103. /* "new_commit" can be NULL when checking out from the index before
  104. a commit exists. */
  105. }
  106. static int update_some(const struct object_id *oid, struct strbuf *base,
  107. const char *pathname, unsigned mode, int stage, void *context)
  108. {
  109. int len;
  110. struct cache_entry *ce;
  111. int pos;
  112. if (S_ISDIR(mode))
  113. return READ_TREE_RECURSIVE;
  114. len = base->len + strlen(pathname);
  115. ce = make_empty_cache_entry(&the_index, len);
  116. oidcpy(&ce->oid, oid);
  117. memcpy(ce->name, base->buf, base->len);
  118. memcpy(ce->name + base->len, pathname, len - base->len);
  119. ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
  120. ce->ce_namelen = len;
  121. ce->ce_mode = create_ce_mode(mode);
  122. /*
  123. * If the entry is the same as the current index, we can leave the old
  124. * entry in place. Whether it is UPTODATE or not, checkout_entry will
  125. * do the right thing.
  126. */
  127. pos = cache_name_pos(ce->name, ce->ce_namelen);
  128. if (pos >= 0) {
  129. struct cache_entry *old = active_cache[pos];
  130. if (ce->ce_mode == old->ce_mode &&
  131. !ce_intent_to_add(old) &&
  132. oideq(&ce->oid, &old->oid)) {
  133. old->ce_flags |= CE_UPDATE;
  134. discard_cache_entry(ce);
  135. return 0;
  136. }
  137. }
  138. add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
  139. return 0;
  140. }
  141. static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
  142. {
  143. read_tree_recursive(the_repository, tree, "", 0, 0,
  144. pathspec, update_some, NULL);
  145. /* update the index with the given tree's info
  146. * for all args, expanding wildcards, and exit
  147. * with any non-zero return code.
  148. */
  149. return 0;
  150. }
  151. static int skip_same_name(const struct cache_entry *ce, int pos)
  152. {
  153. while (++pos < active_nr &&
  154. !strcmp(active_cache[pos]->name, ce->name))
  155. ; /* skip */
  156. return pos;
  157. }
  158. static int check_stage(int stage, const struct cache_entry *ce, int pos,
  159. int overlay_mode)
  160. {
  161. while (pos < active_nr &&
  162. !strcmp(active_cache[pos]->name, ce->name)) {
  163. if (ce_stage(active_cache[pos]) == stage)
  164. return 0;
  165. pos++;
  166. }
  167. if (!overlay_mode)
  168. return 0;
  169. if (stage == 2)
  170. return error(_("path '%s' does not have our version"), ce->name);
  171. else
  172. return error(_("path '%s' does not have their version"), ce->name);
  173. }
  174. static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
  175. {
  176. unsigned seen = 0;
  177. const char *name = ce->name;
  178. while (pos < active_nr) {
  179. ce = active_cache[pos];
  180. if (strcmp(name, ce->name))
  181. break;
  182. seen |= (1 << ce_stage(ce));
  183. pos++;
  184. }
  185. if ((stages & seen) != stages)
  186. return error(_("path '%s' does not have all necessary versions"),
  187. name);
  188. return 0;
  189. }
  190. static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
  191. const struct checkout *state, int *nr_checkouts,
  192. int overlay_mode)
  193. {
  194. while (pos < active_nr &&
  195. !strcmp(active_cache[pos]->name, ce->name)) {
  196. if (ce_stage(active_cache[pos]) == stage)
  197. return checkout_entry(active_cache[pos], state,
  198. NULL, nr_checkouts);
  199. pos++;
  200. }
  201. if (!overlay_mode) {
  202. unlink_entry(ce);
  203. return 0;
  204. }
  205. if (stage == 2)
  206. return error(_("path '%s' does not have our version"), ce->name);
  207. else
  208. return error(_("path '%s' does not have their version"), ce->name);
  209. }
  210. static int checkout_merged(int pos, const struct checkout *state, int *nr_checkouts)
  211. {
  212. struct cache_entry *ce = active_cache[pos];
  213. const char *path = ce->name;
  214. mmfile_t ancestor, ours, theirs;
  215. int status;
  216. struct object_id oid;
  217. mmbuffer_t result_buf;
  218. struct object_id threeway[3];
  219. unsigned mode = 0;
  220. struct ll_merge_options ll_opts;
  221. int renormalize = 0;
  222. memset(threeway, 0, sizeof(threeway));
  223. while (pos < active_nr) {
  224. int stage;
  225. stage = ce_stage(ce);
  226. if (!stage || strcmp(path, ce->name))
  227. break;
  228. oidcpy(&threeway[stage - 1], &ce->oid);
  229. if (stage == 2)
  230. mode = create_ce_mode(ce->ce_mode);
  231. pos++;
  232. ce = active_cache[pos];
  233. }
  234. if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
  235. return error(_("path '%s' does not have necessary versions"), path);
  236. read_mmblob(&ancestor, &threeway[0]);
  237. read_mmblob(&ours, &threeway[1]);
  238. read_mmblob(&theirs, &threeway[2]);
  239. memset(&ll_opts, 0, sizeof(ll_opts));
  240. git_config_get_bool("merge.renormalize", &renormalize);
  241. ll_opts.renormalize = renormalize;
  242. status = ll_merge(&result_buf, path, &ancestor, "base",
  243. &ours, "ours", &theirs, "theirs",
  244. state->istate, &ll_opts);
  245. free(ancestor.ptr);
  246. free(ours.ptr);
  247. free(theirs.ptr);
  248. if (status < 0 || !result_buf.ptr) {
  249. free(result_buf.ptr);
  250. return error(_("path '%s': cannot merge"), path);
  251. }
  252. /*
  253. * NEEDSWORK:
  254. * There is absolutely no reason to write this as a blob object
  255. * and create a phony cache entry. This hack is primarily to get
  256. * to the write_entry() machinery that massages the contents to
  257. * work-tree format and writes out which only allows it for a
  258. * cache entry. The code in write_entry() needs to be refactored
  259. * to allow us to feed a <buffer, size, mode> instead of a cache
  260. * entry. Such a refactoring would help merge_recursive as well
  261. * (it also writes the merge result to the object database even
  262. * when it may contain conflicts).
  263. */
  264. if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
  265. die(_("Unable to add merge result for '%s'"), path);
  266. free(result_buf.ptr);
  267. ce = make_transient_cache_entry(mode, &oid, path, 2);
  268. if (!ce)
  269. die(_("make_cache_entry failed for path '%s'"), path);
  270. status = checkout_entry(ce, state, NULL, nr_checkouts);
  271. discard_cache_entry(ce);
  272. return status;
  273. }
  274. static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
  275. char *ps_matched,
  276. const struct checkout_opts *opts)
  277. {
  278. ce->ce_flags &= ~CE_MATCHED;
  279. if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
  280. return;
  281. if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
  282. /*
  283. * "git checkout tree-ish -- path", but this entry
  284. * is in the original index but is not in tree-ish
  285. * or does not match the pathspec; it will not be
  286. * checked out to the working tree. We will not do
  287. * anything to this entry at all.
  288. */
  289. return;
  290. /*
  291. * Either this entry came from the tree-ish we are
  292. * checking the paths out of, or we are checking out
  293. * of the index.
  294. *
  295. * If it comes from the tree-ish, we already know it
  296. * matches the pathspec and could just stamp
  297. * CE_MATCHED to it from update_some(). But we still
  298. * need ps_matched and read_tree_recursive (and
  299. * eventually tree_entry_interesting) cannot fill
  300. * ps_matched yet. Once it can, we can avoid calling
  301. * match_pathspec() for _all_ entries when
  302. * opts->source_tree != NULL.
  303. */
  304. if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
  305. ce->ce_flags |= CE_MATCHED;
  306. }
  307. static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
  308. char *ps_matched,
  309. const struct checkout_opts *opts)
  310. {
  311. ce->ce_flags &= ~CE_MATCHED;
  312. if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
  313. return;
  314. if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
  315. ce->ce_flags |= CE_MATCHED;
  316. if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
  317. /*
  318. * In overlay mode, but the path is not in
  319. * tree-ish, which means we should remove it
  320. * from the index and the working tree.
  321. */
  322. ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
  323. }
  324. }
  325. static int checkout_worktree(const struct checkout_opts *opts,
  326. const struct branch_info *info)
  327. {
  328. struct checkout state = CHECKOUT_INIT;
  329. int nr_checkouts = 0, nr_unmerged = 0;
  330. int errs = 0;
  331. int pos;
  332. state.force = 1;
  333. state.refresh_cache = 1;
  334. state.istate = &the_index;
  335. init_checkout_metadata(&state.meta, info->refname,
  336. info->commit ? &info->commit->object.oid : &info->oid,
  337. NULL);
  338. enable_delayed_checkout(&state);
  339. for (pos = 0; pos < active_nr; pos++) {
  340. struct cache_entry *ce = active_cache[pos];
  341. if (ce->ce_flags & CE_MATCHED) {
  342. if (!ce_stage(ce)) {
  343. errs |= checkout_entry(ce, &state,
  344. NULL, &nr_checkouts);
  345. continue;
  346. }
  347. if (opts->writeout_stage)
  348. errs |= checkout_stage(opts->writeout_stage,
  349. ce, pos,
  350. &state,
  351. &nr_checkouts, opts->overlay_mode);
  352. else if (opts->merge)
  353. errs |= checkout_merged(pos, &state,
  354. &nr_unmerged);
  355. pos = skip_same_name(ce, pos) - 1;
  356. }
  357. }
  358. remove_marked_cache_entries(&the_index, 1);
  359. remove_scheduled_dirs();
  360. errs |= finish_delayed_checkout(&state, &nr_checkouts);
  361. if (opts->count_checkout_paths) {
  362. if (nr_unmerged)
  363. fprintf_ln(stderr, Q_("Recreated %d merge conflict",
  364. "Recreated %d merge conflicts",
  365. nr_unmerged),
  366. nr_unmerged);
  367. if (opts->source_tree)
  368. fprintf_ln(stderr, Q_("Updated %d path from %s",
  369. "Updated %d paths from %s",
  370. nr_checkouts),
  371. nr_checkouts,
  372. find_unique_abbrev(&opts->source_tree->object.oid,
  373. DEFAULT_ABBREV));
  374. else if (!nr_unmerged || nr_checkouts)
  375. fprintf_ln(stderr, Q_("Updated %d path from the index",
  376. "Updated %d paths from the index",
  377. nr_checkouts),
  378. nr_checkouts);
  379. }
  380. return errs;
  381. }
  382. static int checkout_paths(const struct checkout_opts *opts,
  383. const struct branch_info *new_branch_info)
  384. {
  385. int pos;
  386. static char *ps_matched;
  387. struct object_id rev;
  388. struct commit *head;
  389. int errs = 0;
  390. struct lock_file lock_file = LOCK_INIT;
  391. int checkout_index;
  392. trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
  393. if (opts->track != BRANCH_TRACK_UNSPECIFIED)
  394. die(_("'%s' cannot be used with updating paths"), "--track");
  395. if (opts->new_branch_log)
  396. die(_("'%s' cannot be used with updating paths"), "-l");
  397. if (opts->ignore_unmerged && opts->patch_mode)
  398. die(_("'%s' cannot be used with updating paths"),
  399. opts->ignore_unmerged_opt);
  400. if (opts->force_detach)
  401. die(_("'%s' cannot be used with updating paths"), "--detach");
  402. if (opts->merge && opts->patch_mode)
  403. die(_("'%s' cannot be used with %s"), "--merge", "--patch");
  404. if (opts->ignore_unmerged && opts->merge)
  405. die(_("'%s' cannot be used with %s"),
  406. opts->ignore_unmerged_opt, "-m");
  407. if (opts->new_branch)
  408. die(_("Cannot update paths and switch to branch '%s' at the same time."),
  409. opts->new_branch);
  410. if (!opts->checkout_worktree && !opts->checkout_index)
  411. die(_("neither '%s' or '%s' is specified"),
  412. "--staged", "--worktree");
  413. if (!opts->checkout_worktree && !opts->from_treeish)
  414. die(_("'%s' must be used when '%s' is not specified"),
  415. "--worktree", "--source");
  416. if (opts->checkout_index && !opts->checkout_worktree &&
  417. opts->writeout_stage)
  418. die(_("'%s' or '%s' cannot be used with %s"),
  419. "--ours", "--theirs", "--staged");
  420. if (opts->checkout_index && !opts->checkout_worktree &&
  421. opts->merge)
  422. die(_("'%s' or '%s' cannot be used with %s"),
  423. "--merge", "--conflict", "--staged");
  424. if (opts->patch_mode) {
  425. const char *patch_mode;
  426. if (opts->checkout_index && opts->checkout_worktree)
  427. patch_mode = "--patch=checkout";
  428. else if (opts->checkout_index && !opts->checkout_worktree)
  429. patch_mode = "--patch=reset";
  430. else if (!opts->checkout_index && opts->checkout_worktree)
  431. patch_mode = "--patch=worktree";
  432. else
  433. BUG("either flag must have been set, worktree=%d, index=%d",
  434. opts->checkout_worktree, opts->checkout_index);
  435. return run_add_interactive(new_branch_info->name, patch_mode, &opts->pathspec);
  436. }
  437. repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
  438. if (read_cache_preload(&opts->pathspec) < 0)
  439. return error(_("index file corrupt"));
  440. if (opts->source_tree)
  441. read_tree_some(opts->source_tree, &opts->pathspec);
  442. ps_matched = xcalloc(opts->pathspec.nr, 1);
  443. /*
  444. * Make sure all pathspecs participated in locating the paths
  445. * to be checked out.
  446. */
  447. for (pos = 0; pos < active_nr; pos++)
  448. if (opts->overlay_mode)
  449. mark_ce_for_checkout_overlay(active_cache[pos],
  450. ps_matched,
  451. opts);
  452. else
  453. mark_ce_for_checkout_no_overlay(active_cache[pos],
  454. ps_matched,
  455. opts);
  456. if (report_path_error(ps_matched, &opts->pathspec)) {
  457. free(ps_matched);
  458. return 1;
  459. }
  460. free(ps_matched);
  461. /* "checkout -m path" to recreate conflicted state */
  462. if (opts->merge)
  463. unmerge_marked_index(&the_index);
  464. /* Any unmerged paths? */
  465. for (pos = 0; pos < active_nr; pos++) {
  466. const struct cache_entry *ce = active_cache[pos];
  467. if (ce->ce_flags & CE_MATCHED) {
  468. if (!ce_stage(ce))
  469. continue;
  470. if (opts->ignore_unmerged) {
  471. if (!opts->quiet)
  472. warning(_("path '%s' is unmerged"), ce->name);
  473. } else if (opts->writeout_stage) {
  474. errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
  475. } else if (opts->merge) {
  476. errs |= check_stages((1<<2) | (1<<3), ce, pos);
  477. } else {
  478. errs = 1;
  479. error(_("path '%s' is unmerged"), ce->name);
  480. }
  481. pos = skip_same_name(ce, pos) - 1;
  482. }
  483. }
  484. if (errs)
  485. return 1;
  486. /* Now we are committed to check them out */
  487. if (opts->checkout_worktree)
  488. errs |= checkout_worktree(opts, new_branch_info);
  489. else
  490. remove_marked_cache_entries(&the_index, 1);
  491. /*
  492. * Allow updating the index when checking out from the index.
  493. * This is to save new stat info.
  494. */
  495. if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
  496. checkout_index = 1;
  497. else
  498. checkout_index = opts->checkout_index;
  499. if (checkout_index) {
  500. if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
  501. die(_("unable to write new index file"));
  502. } else {
  503. /*
  504. * NEEDSWORK: if --worktree is not specified, we
  505. * should save stat info of checked out files in the
  506. * index to avoid the next (potentially costly)
  507. * refresh. But it's a bit tricker to do...
  508. */
  509. rollback_lock_file(&lock_file);
  510. }
  511. read_ref_full("HEAD", 0, &rev, NULL);
  512. head = lookup_commit_reference_gently(the_repository, &rev, 1);
  513. errs |= post_checkout_hook(head, head, 0);
  514. return errs;
  515. }
  516. static void show_local_changes(struct object *head,
  517. const struct diff_options *opts)
  518. {
  519. struct rev_info rev;
  520. /* I think we want full paths, even if we're in a subdirectory. */
  521. repo_init_revisions(the_repository, &rev, NULL);
  522. rev.diffopt.flags = opts->flags;
  523. rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
  524. diff_setup_done(&rev.diffopt);
  525. add_pending_object(&rev, head, NULL);
  526. run_diff_index(&rev, 0);
  527. }
  528. static void describe_detached_head(const char *msg, struct commit *commit)
  529. {
  530. struct strbuf sb = STRBUF_INIT;
  531. if (!parse_commit(commit))
  532. pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
  533. if (print_sha1_ellipsis()) {
  534. fprintf(stderr, "%s %s... %s\n", msg,
  535. find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
  536. } else {
  537. fprintf(stderr, "%s %s %s\n", msg,
  538. find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
  539. }
  540. strbuf_release(&sb);
  541. }
  542. static int reset_tree(struct tree *tree, const struct checkout_opts *o,
  543. int worktree, int *writeout_error,
  544. struct branch_info *info)
  545. {
  546. struct unpack_trees_options opts;
  547. struct tree_desc tree_desc;
  548. memset(&opts, 0, sizeof(opts));
  549. opts.head_idx = -1;
  550. opts.update = worktree;
  551. opts.skip_unmerged = !worktree;
  552. opts.reset = 1;
  553. opts.merge = 1;
  554. opts.fn = oneway_merge;
  555. opts.verbose_update = o->show_progress;
  556. opts.src_index = &the_index;
  557. opts.dst_index = &the_index;
  558. init_checkout_metadata(&opts.meta, info->refname,
  559. info->commit ? &info->commit->object.oid : &null_oid,
  560. NULL);
  561. parse_tree(tree);
  562. init_tree_desc(&tree_desc, tree->buffer, tree->size);
  563. switch (unpack_trees(1, &tree_desc, &opts)) {
  564. case -2:
  565. *writeout_error = 1;
  566. /*
  567. * We return 0 nevertheless, as the index is all right
  568. * and more importantly we have made best efforts to
  569. * update paths in the work tree, and we cannot revert
  570. * them.
  571. */
  572. /* fallthrough */
  573. case 0:
  574. return 0;
  575. default:
  576. return 128;
  577. }
  578. }
  579. static void setup_branch_path(struct branch_info *branch)
  580. {
  581. struct strbuf buf = STRBUF_INIT;
  582. /*
  583. * If this is a ref, resolve it; otherwise, look up the OID for our
  584. * expression. Failure here is okay.
  585. */
  586. if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
  587. repo_get_oid_committish(the_repository, branch->name, &branch->oid);
  588. strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
  589. if (strcmp(buf.buf, branch->name))
  590. branch->name = xstrdup(buf.buf);
  591. strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
  592. branch->path = strbuf_detach(&buf, NULL);
  593. }
  594. static int merge_working_tree(const struct checkout_opts *opts,
  595. struct branch_info *old_branch_info,
  596. struct branch_info *new_branch_info,
  597. int *writeout_error)
  598. {
  599. int ret;
  600. struct lock_file lock_file = LOCK_INIT;
  601. struct tree *new_tree;
  602. hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
  603. if (read_cache_preload(NULL) < 0)
  604. return error(_("index file corrupt"));
  605. resolve_undo_clear();
  606. if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
  607. if (new_branch_info->commit)
  608. BUG("'switch --orphan' should never accept a commit as starting point");
  609. new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
  610. } else
  611. new_tree = get_commit_tree(new_branch_info->commit);
  612. if (opts->discard_changes) {
  613. ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
  614. if (ret)
  615. return ret;
  616. } else {
  617. struct tree_desc trees[2];
  618. struct tree *tree;
  619. struct unpack_trees_options topts;
  620. memset(&topts, 0, sizeof(topts));
  621. topts.head_idx = -1;
  622. topts.src_index = &the_index;
  623. topts.dst_index = &the_index;
  624. setup_unpack_trees_porcelain(&topts, "checkout");
  625. refresh_cache(REFRESH_QUIET);
  626. if (unmerged_cache()) {
  627. error(_("you need to resolve your current index first"));
  628. return 1;
  629. }
  630. /* 2-way merge to the new branch */
  631. topts.initial_checkout = is_cache_unborn();
  632. topts.update = 1;
  633. topts.merge = 1;
  634. topts.quiet = opts->merge && old_branch_info->commit;
  635. topts.verbose_update = opts->show_progress;
  636. topts.fn = twoway_merge;
  637. init_checkout_metadata(&topts.meta, new_branch_info->refname,
  638. new_branch_info->commit ?
  639. &new_branch_info->commit->object.oid :
  640. &new_branch_info->oid, NULL);
  641. if (opts->overwrite_ignore) {
  642. topts.dir = xcalloc(1, sizeof(*topts.dir));
  643. topts.dir->flags |= DIR_SHOW_IGNORED;
  644. setup_standard_excludes(topts.dir);
  645. }
  646. tree = parse_tree_indirect(old_branch_info->commit ?
  647. &old_branch_info->commit->object.oid :
  648. the_hash_algo->empty_tree);
  649. init_tree_desc(&trees[0], tree->buffer, tree->size);
  650. parse_tree(new_tree);
  651. tree = new_tree;
  652. init_tree_desc(&trees[1], tree->buffer, tree->size);
  653. ret = unpack_trees(2, trees, &topts);
  654. clear_unpack_trees_porcelain(&topts);
  655. if (ret == -1) {
  656. /*
  657. * Unpack couldn't do a trivial merge; either
  658. * give up or do a real merge, depending on
  659. * whether the merge flag was used.
  660. */
  661. struct tree *work;
  662. struct tree *old_tree;
  663. struct merge_options o;
  664. struct strbuf sb = STRBUF_INIT;
  665. struct strbuf old_commit_shortname = STRBUF_INIT;
  666. if (!opts->merge)
  667. return 1;
  668. /*
  669. * Without old_branch_info->commit, the below is the same as
  670. * the two-tree unpack we already tried and failed.
  671. */
  672. if (!old_branch_info->commit)
  673. return 1;
  674. old_tree = get_commit_tree(old_branch_info->commit);
  675. if (repo_index_has_changes(the_repository, old_tree, &sb))
  676. die(_("cannot continue with staged changes in "
  677. "the following files:\n%s"), sb.buf);
  678. strbuf_release(&sb);
  679. /* Do more real merge */
  680. /*
  681. * We update the index fully, then write the
  682. * tree from the index, then merge the new
  683. * branch with the current tree, with the old
  684. * branch as the base. Then we reset the index
  685. * (but not the working tree) to the new
  686. * branch, leaving the working tree as the
  687. * merged version, but skipping unmerged
  688. * entries in the index.
  689. */
  690. add_files_to_cache(NULL, NULL, 0);
  691. init_merge_options(&o, the_repository);
  692. o.verbosity = 0;
  693. work = write_in_core_index_as_tree(the_repository);
  694. ret = reset_tree(new_tree,
  695. opts, 1,
  696. writeout_error, new_branch_info);
  697. if (ret)
  698. return ret;
  699. o.ancestor = old_branch_info->name;
  700. if (old_branch_info->name == NULL) {
  701. strbuf_add_unique_abbrev(&old_commit_shortname,
  702. &old_branch_info->commit->object.oid,
  703. DEFAULT_ABBREV);
  704. o.ancestor = old_commit_shortname.buf;
  705. }
  706. o.branch1 = new_branch_info->name;
  707. o.branch2 = "local";
  708. ret = merge_trees(&o,
  709. new_tree,
  710. work,
  711. old_tree);
  712. if (ret < 0)
  713. exit(128);
  714. ret = reset_tree(new_tree,
  715. opts, 0,
  716. writeout_error, new_branch_info);
  717. strbuf_release(&o.obuf);
  718. strbuf_release(&old_commit_shortname);
  719. if (ret)
  720. return ret;
  721. }
  722. }
  723. if (!active_cache_tree)
  724. active_cache_tree = cache_tree();
  725. if (!cache_tree_fully_valid(active_cache_tree))
  726. cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
  727. if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
  728. die(_("unable to write new index file"));
  729. if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
  730. show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
  731. return 0;
  732. }
  733. static void report_tracking(struct branch_info *new_branch_info)
  734. {
  735. struct strbuf sb = STRBUF_INIT;
  736. struct branch *branch = branch_get(new_branch_info->name);
  737. if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
  738. return;
  739. fputs(sb.buf, stdout);
  740. strbuf_release(&sb);
  741. }
  742. static void update_refs_for_switch(const struct checkout_opts *opts,
  743. struct branch_info *old_branch_info,
  744. struct branch_info *new_branch_info)
  745. {
  746. struct strbuf msg = STRBUF_INIT;
  747. const char *old_desc, *reflog_msg;
  748. if (opts->new_branch) {
  749. if (opts->new_orphan_branch) {
  750. char *refname;
  751. refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
  752. if (opts->new_branch_log &&
  753. !should_autocreate_reflog(refname)) {
  754. int ret;
  755. struct strbuf err = STRBUF_INIT;
  756. ret = safe_create_reflog(refname, 1, &err);
  757. if (ret) {
  758. fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
  759. opts->new_orphan_branch, err.buf);
  760. strbuf_release(&err);
  761. free(refname);
  762. return;
  763. }
  764. strbuf_release(&err);
  765. }
  766. free(refname);
  767. }
  768. else
  769. create_branch(the_repository,
  770. opts->new_branch, new_branch_info->name,
  771. opts->new_branch_force ? 1 : 0,
  772. opts->new_branch_force ? 1 : 0,
  773. opts->new_branch_log,
  774. opts->quiet,
  775. opts->track);
  776. new_branch_info->name = opts->new_branch;
  777. setup_branch_path(new_branch_info);
  778. }
  779. old_desc = old_branch_info->name;
  780. if (!old_desc && old_branch_info->commit)
  781. old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
  782. reflog_msg = getenv("GIT_REFLOG_ACTION");
  783. if (!reflog_msg)
  784. strbuf_addf(&msg, "checkout: moving from %s to %s",
  785. old_desc ? old_desc : "(invalid)", new_branch_info->name);
  786. else
  787. strbuf_insertstr(&msg, 0, reflog_msg);
  788. if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
  789. /* Nothing to do. */
  790. } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
  791. update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
  792. REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
  793. if (!opts->quiet) {
  794. if (old_branch_info->path &&
  795. advice_detached_head && !opts->force_detach)
  796. detach_advice(new_branch_info->name);
  797. describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
  798. }
  799. } else if (new_branch_info->path) { /* Switch branches. */
  800. if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
  801. die(_("unable to update HEAD"));
  802. if (!opts->quiet) {
  803. if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
  804. if (opts->new_branch_force)
  805. fprintf(stderr, _("Reset branch '%s'\n"),
  806. new_branch_info->name);
  807. else
  808. fprintf(stderr, _("Already on '%s'\n"),
  809. new_branch_info->name);
  810. } else if (opts->new_branch) {
  811. if (opts->branch_exists)
  812. fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
  813. else
  814. fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
  815. } else {
  816. fprintf(stderr, _("Switched to branch '%s'\n"),
  817. new_branch_info->name);
  818. }
  819. }
  820. if (old_branch_info->path && old_branch_info->name) {
  821. if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
  822. delete_reflog(old_branch_info->path);
  823. }
  824. }
  825. remove_branch_state(the_repository, !opts->quiet);
  826. strbuf_release(&msg);
  827. if (!opts->quiet &&
  828. (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
  829. report_tracking(new_branch_info);
  830. }
  831. static int add_pending_uninteresting_ref(const char *refname,
  832. const struct object_id *oid,
  833. int flags, void *cb_data)
  834. {
  835. add_pending_oid(cb_data, refname, oid, UNINTERESTING);
  836. return 0;
  837. }
  838. static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
  839. {
  840. strbuf_addstr(sb, " ");
  841. strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
  842. strbuf_addch(sb, ' ');
  843. if (!parse_commit(commit))
  844. pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
  845. strbuf_addch(sb, '\n');
  846. }
  847. #define ORPHAN_CUTOFF 4
  848. static void suggest_reattach(struct commit *commit, struct rev_info *revs)
  849. {
  850. struct commit *c, *last = NULL;
  851. struct strbuf sb = STRBUF_INIT;
  852. int lost = 0;
  853. while ((c = get_revision(revs)) != NULL) {
  854. if (lost < ORPHAN_CUTOFF)
  855. describe_one_orphan(&sb, c);
  856. last = c;
  857. lost++;
  858. }
  859. if (ORPHAN_CUTOFF < lost) {
  860. int more = lost - ORPHAN_CUTOFF;
  861. if (more == 1)
  862. describe_one_orphan(&sb, last);
  863. else
  864. strbuf_addf(&sb, _(" ... and %d more.\n"), more);
  865. }
  866. fprintf(stderr,
  867. Q_(
  868. /* The singular version */
  869. "Warning: you are leaving %d commit behind, "
  870. "not connected to\n"
  871. "any of your branches:\n\n"
  872. "%s\n",
  873. /* The plural version */
  874. "Warning: you are leaving %d commits behind, "
  875. "not connected to\n"
  876. "any of your branches:\n\n"
  877. "%s\n",
  878. /* Give ngettext() the count */
  879. lost),
  880. lost,
  881. sb.buf);
  882. strbuf_release(&sb);
  883. if (advice_detached_head)
  884. fprintf(stderr,
  885. Q_(
  886. /* The singular version */
  887. "If you want to keep it by creating a new branch, "
  888. "this may be a good time\nto do so with:\n\n"
  889. " git branch <new-branch-name> %s\n\n",
  890. /* The plural version */
  891. "If you want to keep them by creating a new branch, "
  892. "this may be a good time\nto do so with:\n\n"
  893. " git branch <new-branch-name> %s\n\n",
  894. /* Give ngettext() the count */
  895. lost),
  896. find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
  897. }
  898. /*
  899. * We are about to leave commit that was at the tip of a detached
  900. * HEAD. If it is not reachable from any ref, this is the last chance
  901. * for the user to do so without resorting to reflog.
  902. */
  903. static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
  904. {
  905. struct rev_info revs;
  906. struct object *object = &old_commit->object;
  907. repo_init_revisions(the_repository, &revs, NULL);
  908. setup_revisions(0, NULL, &revs, NULL);
  909. object->flags &= ~UNINTERESTING;
  910. add_pending_object(&revs, object, oid_to_hex(&object->oid));
  911. for_each_ref(add_pending_uninteresting_ref, &revs);
  912. if (new_commit)
  913. add_pending_oid(&revs, "HEAD",
  914. &new_commit->object.oid,
  915. UNINTERESTING);
  916. if (prepare_revision_walk(&revs))
  917. die(_("internal error in revision walk"));
  918. if (!(old_commit->object.flags & UNINTERESTING))
  919. suggest_reattach(old_commit, &revs);
  920. else
  921. describe_detached_head(_("Previous HEAD position was"), old_commit);
  922. /* Clean up objects used, as they will be reused. */
  923. clear_commit_marks_all(ALL_REV_FLAGS);
  924. }
  925. static int switch_branches(const struct checkout_opts *opts,
  926. struct branch_info *new_branch_info)
  927. {
  928. int ret = 0;
  929. struct branch_info old_branch_info;
  930. void *path_to_free;
  931. struct object_id rev;
  932. int flag, writeout_error = 0;
  933. int do_merge = 1;
  934. trace2_cmd_mode("branch");
  935. memset(&old_branch_info, 0, sizeof(old_branch_info));
  936. old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
  937. if (old_branch_info.path)
  938. old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
  939. if (!(flag & REF_ISSYMREF))
  940. old_branch_info.path = NULL;
  941. if (old_branch_info.path)
  942. skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
  943. if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
  944. if (new_branch_info->name)
  945. BUG("'switch --orphan' should never accept a commit as starting point");
  946. new_branch_info->commit = NULL;
  947. new_branch_info->name = "(empty)";
  948. do_merge = 1;
  949. }
  950. if (!new_branch_info->name) {
  951. new_branch_info->name = "HEAD";
  952. new_branch_info->commit = old_branch_info.commit;
  953. if (!new_branch_info->commit)
  954. die(_("You are on a branch yet to be born"));
  955. parse_commit_or_die(new_branch_info->commit);
  956. if (opts->only_merge_on_switching_branches)
  957. do_merge = 0;
  958. }
  959. if (do_merge) {
  960. ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
  961. if (ret) {
  962. free(path_to_free);
  963. return ret;
  964. }
  965. }
  966. if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
  967. orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
  968. update_refs_for_switch(opts, &old_branch_info, new_branch_info);
  969. ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
  970. free(path_to_free);
  971. return ret || writeout_error;
  972. }
  973. static int git_checkout_config(const char *var, const char *value, void *cb)
  974. {
  975. if (!strcmp(var, "diff.ignoresubmodules")) {
  976. struct checkout_opts *opts = cb;
  977. handle_ignore_submodules_arg(&opts->diff_options, value);
  978. return 0;
  979. }
  980. if (starts_with(var, "submodule."))
  981. return git_default_submodule_config(var, value, NULL);
  982. return git_xmerge_config(var, value, NULL);
  983. }
  984. static void setup_new_branch_info_and_source_tree(
  985. struct branch_info *new_branch_info,
  986. struct checkout_opts *opts,
  987. struct object_id *rev,
  988. const char *arg)
  989. {
  990. struct tree **source_tree = &opts->source_tree;
  991. struct object_id branch_rev;
  992. new_branch_info->name = arg;
  993. setup_branch_path(new_branch_info);
  994. if (!check_refname_format(new_branch_info->path, 0) &&
  995. !read_ref(new_branch_info->path, &branch_rev))
  996. oidcpy(rev, &branch_rev);
  997. else {
  998. free((char *)new_branch_info->path);
  999. new_branch_info->path = NULL; /* not an existing branch */
  1000. }
  1001. new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
  1002. if (!new_branch_info->commit) {
  1003. /* not a commit */
  1004. *source_tree = parse_tree_indirect(rev);
  1005. } else {
  1006. parse_commit_or_die(new_branch_info->commit);
  1007. *source_tree = get_commit_tree(new_branch_info->commit);
  1008. }
  1009. }
  1010. static const char *parse_remote_branch(const char *arg,
  1011. struct object_id *rev,
  1012. int could_be_checkout_paths)
  1013. {
  1014. int num_matches = 0;
  1015. const char *remote = unique_tracking_name(arg, rev, &num_matches);
  1016. if (remote && could_be_checkout_paths) {
  1017. die(_("'%s' could be both a local file and a tracking branch.\n"
  1018. "Please use -- (and optionally --no-guess) to disambiguate"),
  1019. arg);
  1020. }
  1021. if (!remote && num_matches > 1) {
  1022. if (advice_checkout_ambiguous_remote_branch_name) {
  1023. advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
  1024. "you can do so by fully qualifying the name with the --track option:\n"
  1025. "\n"
  1026. " git checkout --track origin/<name>\n"
  1027. "\n"
  1028. "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
  1029. "one remote, e.g. the 'origin' remote, consider setting\n"
  1030. "checkout.defaultRemote=origin in your config."));
  1031. }
  1032. die(_("'%s' matched multiple (%d) remote tracking branches"),
  1033. arg, num_matches);
  1034. }
  1035. return remote;
  1036. }
  1037. static int parse_branchname_arg(int argc, const char **argv,
  1038. int dwim_new_local_branch_ok,
  1039. struct branch_info *new_branch_info,
  1040. struct checkout_opts *opts,
  1041. struct object_id *rev)
  1042. {
  1043. const char **new_branch = &opts->new_branch;
  1044. int argcount = 0;
  1045. const char *arg;
  1046. int dash_dash_pos;
  1047. int has_dash_dash = 0;
  1048. int i;
  1049. /*
  1050. * case 1: git checkout <ref> -- [<paths>]
  1051. *
  1052. * <ref> must be a valid tree, everything after the '--' must be
  1053. * a path.
  1054. *
  1055. * case 2: git checkout -- [<paths>]
  1056. *
  1057. * everything after the '--' must be paths.
  1058. *
  1059. * case 3: git checkout <something> [--]
  1060. *
  1061. * (a) If <something> is a commit, that is to
  1062. * switch to the branch or detach HEAD at it. As a special case,
  1063. * if <something> is A...B (missing A or B means HEAD but you can
  1064. * omit at most one side), and if there is a unique merge base
  1065. * between A and B, A...B names that merge base.
  1066. *
  1067. * (b) If <something> is _not_ a commit, either "--" is present
  1068. * or <something> is not a path, no -t or -b was given, and
  1069. * and there is a tracking branch whose name is <something>
  1070. * in one and only one remote (or if the branch exists on the
  1071. * remote named in checkout.defaultRemote), then this is a
  1072. * short-hand to fork local <something> from that
  1073. * remote-tracking branch.
  1074. *
  1075. * (c) Otherwise, if "--" is present, treat it like case (1).
  1076. *
  1077. * (d) Otherwise :
  1078. * - if it's a reference, treat it like case (1)
  1079. * - else if it's a path, treat it like case (2)
  1080. * - else: fail.
  1081. *
  1082. * case 4: git checkout <something> <paths>
  1083. *
  1084. * The first argument must not be ambiguous.
  1085. * - If it's *only* a reference, treat it like case (1).
  1086. * - If it's only a path, treat it like case (2).
  1087. * - else: fail.
  1088. *
  1089. */
  1090. if (!argc)
  1091. return 0;
  1092. if (!opts->accept_pathspec) {
  1093. if (argc > 1)
  1094. die(_("only one reference expected"));
  1095. has_dash_dash = 1; /* helps disambiguate */
  1096. }
  1097. arg = argv[0];
  1098. dash_dash_pos = -1;
  1099. for (i = 0; i < argc; i++) {
  1100. if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
  1101. dash_dash_pos = i;
  1102. break;
  1103. }
  1104. }
  1105. if (dash_dash_pos == 0)
  1106. return 1; /* case (2) */
  1107. else if (dash_dash_pos == 1)
  1108. has_dash_dash = 1; /* case (3) or (1) */
  1109. else if (dash_dash_pos >= 2)
  1110. die(_("only one reference expected, %d given."), dash_dash_pos);
  1111. opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
  1112. if (!strcmp(arg, "-"))
  1113. arg = "@{-1}";
  1114. if (get_oid_mb(arg, rev)) {
  1115. /*
  1116. * Either case (3) or (4), with <something> not being
  1117. * a commit, or an attempt to use case (1) with an
  1118. * invalid ref.
  1119. *
  1120. * It's likely an error, but we need to find out if
  1121. * we should auto-create the branch, case (3).(b).
  1122. */
  1123. int recover_with_dwim = dwim_new_local_branch_ok;
  1124. int could_be_checkout_paths = !has_dash_dash &&
  1125. check_filename(opts->prefix, arg);
  1126. if (!has_dash_dash && !no_wildcard(arg))
  1127. recover_with_dwim = 0;
  1128. /*
  1129. * Accept "git checkout foo", "git checkout foo --"
  1130. * and "git switch foo" as candidates for dwim.
  1131. */
  1132. if (!(argc == 1 && !has_dash_dash) &&
  1133. !(argc == 2 && has_dash_dash) &&
  1134. opts->accept_pathspec)
  1135. recover_with_dwim = 0;
  1136. if (recover_with_dwim) {
  1137. const char *remote = parse_remote_branch(arg, rev,
  1138. could_be_checkout_paths);
  1139. if (remote) {
  1140. *new_branch = arg;
  1141. arg = remote;
  1142. /* DWIMmed to create local branch, case (3).(b) */
  1143. } else {
  1144. recover_with_dwim = 0;
  1145. }
  1146. }
  1147. if (!recover_with_dwim) {
  1148. if (has_dash_dash)
  1149. die(_("invalid reference: %s"), arg);
  1150. return argcount;
  1151. }
  1152. }
  1153. /* we can't end up being in (2) anymore, eat the argument */
  1154. argcount++;
  1155. argv++;
  1156. argc--;
  1157. setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
  1158. if (!opts->source_tree) /* case (1): want a tree */
  1159. die(_("reference is not a tree: %s"), arg);
  1160. if (!has_dash_dash) { /* case (3).(d) -> (1) */
  1161. /*
  1162. * Do not complain the most common case
  1163. * git checkout branch
  1164. * even if there happen to be a file called 'branch';
  1165. * it would be extremely annoying.
  1166. */
  1167. if (argc)
  1168. verify_non_filename(opts->prefix, arg);
  1169. } else if (opts->accept_pathspec) {
  1170. argcount++;
  1171. argv++;
  1172. argc--;
  1173. }
  1174. return argcount;
  1175. }
  1176. static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
  1177. {
  1178. int status;
  1179. struct strbuf branch_ref = STRBUF_INIT;
  1180. trace2_cmd_mode("unborn");
  1181. if (!opts->new_branch)
  1182. die(_("You are on a branch yet to be born"));
  1183. strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
  1184. status = create_symref("HEAD", branch_ref.buf, "checkout -b");
  1185. strbuf_release(&branch_ref);
  1186. if (!opts->quiet)
  1187. fprintf(stderr, _("Switched to a new branch '%s'\n"),
  1188. opts->new_branch);
  1189. return status;
  1190. }
  1191. static void die_expecting_a_branch(const struct branch_info *branch_info)
  1192. {
  1193. struct object_id oid;
  1194. char *to_free;
  1195. if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
  1196. const char *ref = to_free;
  1197. if (skip_prefix(ref, "refs/tags/", &ref))
  1198. die(_("a branch is expected, got tag '%s'"), ref);
  1199. if (skip_prefix(ref, "refs/remotes/", &ref))
  1200. die(_("a branch is expected, got remote branch '%s'"), ref);
  1201. die(_("a branch is expected, got '%s'"), ref);
  1202. }
  1203. if (branch_info->commit)
  1204. die(_("a branch is expected, got commit '%s'"), branch_info->name);
  1205. /*
  1206. * This case should never happen because we already die() on
  1207. * non-commit, but just in case.
  1208. */
  1209. die(_("a branch is expected, got '%s'"), branch_info->name);
  1210. }
  1211. static void die_if_some_operation_in_progress(void)
  1212. {
  1213. struct wt_status_state state;
  1214. memset(&state, 0, sizeof(state));
  1215. wt_status_get_state(the_repository, &state, 0);
  1216. if (state.merge_in_progress)
  1217. die(_("cannot switch branch while merging\n"
  1218. "Consider \"git merge --quit\" "
  1219. "or \"git worktree add\"."));
  1220. if (state.am_in_progress)
  1221. die(_("cannot switch branch in the middle of an am session\n"
  1222. "Consider \"git am --quit\" "
  1223. "or \"git worktree add\"."));
  1224. if (state.rebase_interactive_in_progress || state.rebase_in_progress)
  1225. die(_("cannot switch branch while rebasing\n"
  1226. "Consider \"git rebase --quit\" "
  1227. "or \"git worktree add\"."));
  1228. if (state.cherry_pick_in_progress)
  1229. die(_("cannot switch branch while cherry-picking\n"
  1230. "Consider \"git cherry-pick --quit\" "
  1231. "or \"git worktree add\"."));
  1232. if (state.revert_in_progress)
  1233. die(_("cannot switch branch while reverting\n"
  1234. "Consider \"git revert --quit\" "
  1235. "or \"git worktree add\"."));
  1236. if (state.bisect_in_progress)
  1237. warning(_("you are switching branch while bisecting"));
  1238. }
  1239. static int checkout_branch(struct checkout_opts *opts,
  1240. struct branch_info *new_branch_info)
  1241. {
  1242. if (opts->pathspec.nr)
  1243. die(_("paths cannot be used with switching branches"));
  1244. if (opts->patch_mode)
  1245. die(_("'%s' cannot be used with switching branches"),
  1246. "--patch");
  1247. if (opts->overlay_mode != -1)
  1248. die(_("'%s' cannot be used with switching branches"),
  1249. "--[no]-overlay");
  1250. if (opts->writeout_stage)
  1251. die(_("'%s' cannot be used with switching branches"),
  1252. "--ours/--theirs");
  1253. if (opts->force && opts->merge)
  1254. die(_("'%s' cannot be used with '%s'"), "-f", "-m");
  1255. if (opts->discard_changes && opts->merge)
  1256. die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
  1257. if (opts->force_detach && opts->new_branch)
  1258. die(_("'%s' cannot be used with '%s'"),
  1259. "--detach", "-b/-B/--orphan");
  1260. if (opts->new_orphan_branch) {
  1261. if (opts->track != BRANCH_TRACK_UNSPECIFIED)
  1262. die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
  1263. if (opts->orphan_from_empty_tree && new_branch_info->name)
  1264. die(_("'%s' cannot take <start-point>"), "--orphan");
  1265. } else if (opts->force_detach) {
  1266. if (opts->track != BRANCH_TRACK_UNSPECIFIED)
  1267. die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
  1268. } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
  1269. opts->track = git_branch_track;
  1270. if (new_branch_info->name && !new_branch_info->commit)
  1271. die(_("Cannot switch branch to a non-commit '%s'"),
  1272. new_branch_info->name);
  1273. if (!opts->switch_branch_doing_nothing_is_ok &&
  1274. !new_branch_info->name &&
  1275. !opts->new_branch &&
  1276. !opts->force_detach)
  1277. die(_("missing branch or commit argument"));
  1278. if (!opts->implicit_detach &&
  1279. !opts->force_detach &&
  1280. !opts->new_branch &&
  1281. !opts->new_branch_force &&
  1282. new_branch_info->name &&
  1283. !new_branch_info->path)
  1284. die_expecting_a_branch(new_branch_info);
  1285. if (!opts->can_switch_when_in_progress)
  1286. die_if_some_operation_in_progress();
  1287. if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
  1288. !opts->ignore_other_worktrees) {
  1289. int flag;
  1290. char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
  1291. if (head_ref &&
  1292. (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
  1293. die_if_checked_out(new_branch_info->path, 1);
  1294. free(head_ref);
  1295. }
  1296. if (!new_branch_info->commit && opts->new_branch) {
  1297. struct object_id rev;
  1298. int flag;
  1299. if (!read_ref_full("HEAD", 0, &rev, &flag) &&
  1300. (flag & REF_ISSYMREF) && is_null_oid(&rev))
  1301. return switch_unborn_to_new_branch(opts);
  1302. }
  1303. return switch_branches(opts, new_branch_info);
  1304. }
  1305. static struct option *add_common_options(struct checkout_opts *opts,
  1306. struct option *prevopts)
  1307. {
  1308. struct option options[] = {
  1309. OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
  1310. OPT_CALLBACK_F(0, "recurse-submodules", NULL,
  1311. "checkout", "control recursive updating of submodules",
  1312. PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
  1313. OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
  1314. OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
  1315. OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
  1316. N_("conflict style (merge or diff3)")),
  1317. OPT_END()
  1318. };
  1319. struct option *newopts = parse_options_concat(prevopts, options);
  1320. free(prevopts);
  1321. return newopts;
  1322. }
  1323. static struct option *add_common_switch_branch_options(
  1324. struct checkout_opts *opts, struct option *prevopts)
  1325. {
  1326. struct option options[] = {
  1327. OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
  1328. OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
  1329. BRANCH_TRACK_EXPLICIT),
  1330. OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
  1331. PARSE_OPT_NOCOMPLETE),
  1332. OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
  1333. OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
  1334. N_("update ignored files (default)"),
  1335. PARSE_OPT_NOCOMPLETE),
  1336. OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
  1337. N_("do not check if another worktree is holding the given ref")),
  1338. OPT_END()
  1339. };
  1340. struct option *newopts = parse_options_concat(prevopts, options);
  1341. free(prevopts);
  1342. return newopts;
  1343. }
  1344. static struct option *add_checkout_path_options(struct checkout_opts *opts,
  1345. struct option *prevopts)
  1346. {
  1347. struct option options[] = {
  1348. OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
  1349. N_("checkout our version for unmerged files"),
  1350. 2, PARSE_OPT_NONEG),
  1351. OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
  1352. N_("checkout their version for unmerged files"),
  1353. 3, PARSE_OPT_NONEG),
  1354. OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
  1355. OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
  1356. N_("do not limit pathspecs to sparse entries only")),
  1357. OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
  1358. OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
  1359. OPT_END()
  1360. };
  1361. struct option *newopts = parse_options_concat(prevopts, options);
  1362. free(prevopts);
  1363. return newopts;
  1364. }
  1365. /* create-branch option (either b or c) */
  1366. static char cb_option = 'b';
  1367. static int checkout_main(int argc, const char **argv, const char *prefix,
  1368. struct checkout_opts *opts, struct option *options,
  1369. const char * const usagestr[])
  1370. {
  1371. struct branch_info new_branch_info;
  1372. int parseopt_flags = 0;
  1373. memset(&new_branch_info, 0, sizeof(new_branch_info));
  1374. opts->overwrite_ignore = 1;
  1375. opts->prefix = prefix;
  1376. opts->show_progress = -1;
  1377. git_config(git_checkout_config, opts);
  1378. opts->track = BRANCH_TRACK_UNSPECIFIED;
  1379. if (!opts->accept_pathspec && !opts->accept_ref)
  1380. BUG("make up your mind, you need to take _something_");
  1381. if (opts->accept_pathspec && opts->accept_ref)
  1382. parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
  1383. argc = parse_options(argc, argv, prefix, options,
  1384. usagestr, parseopt_flags);
  1385. if (opts->show_progress < 0) {
  1386. if (opts->quiet)
  1387. opts->show_progress = 0;
  1388. else
  1389. opts->show_progress = isatty(2);
  1390. }
  1391. if (opts->conflict_style) {
  1392. opts->merge = 1; /* implied */
  1393. git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
  1394. }
  1395. if (opts->force) {
  1396. opts->discard_changes = 1;
  1397. opts->ignore_unmerged_opt = "--force";
  1398. opts->ignore_unmerged = 1;
  1399. }
  1400. if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
  1401. die(_("-%c, -%c and --orphan are mutually exclusive"),
  1402. cb_option, toupper(cb_option));
  1403. if (opts->overlay_mode == 1 && opts->patch_mode)
  1404. die(_("-p and --overlay are mutually exclusive"));
  1405. if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
  1406. if (opts->checkout_index < 0)
  1407. opts->checkout_index = 0;
  1408. if (opts->checkout_worktree < 0)
  1409. opts->checkout_worktree = 0;
  1410. } else {
  1411. if (opts->checkout_index < 0)
  1412. opts->checkout_index = -opts->checkout_index - 1;
  1413. if (opts->checkout_worktree < 0)
  1414. opts->checkout_worktree = -opts->checkout_worktree - 1;
  1415. }
  1416. if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
  1417. BUG("these flags should be non-negative by now");
  1418. /*
  1419. * convenient shortcut: "git restore --staged [--worktree]" equals
  1420. * "git restore --staged [--worktree] --source HEAD"
  1421. */
  1422. if (!opts->from_treeish && opts->checkout_index)
  1423. opts->from_treeish = "HEAD";
  1424. /*
  1425. * From here on, new_branch will contain the branch to be checked out,
  1426. * and new_branch_force and new_orphan_branch will tell us which one of
  1427. * -b/-B/-c/-C/--orphan is being used.
  1428. */
  1429. if (opts->new_branch_force)
  1430. opts->new_branch = opts->new_branch_force;
  1431. if (opts->new_orphan_branch)
  1432. opts->new_branch = opts->new_orphan_branch;
  1433. /* --track without -c/-C/-b/-B/--orphan should DWIM */
  1434. if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
  1435. const char *argv0 = argv[0];
  1436. if (!argc || !strcmp(argv0, "--"))
  1437. die(_("--track needs a branch name"));
  1438. skip_prefix(argv0, "refs/", &argv0);
  1439. skip_prefix(argv0, "remotes/", &argv0);
  1440. argv0 = strchr(argv0, '/');
  1441. if (!argv0 || !argv0[1])
  1442. die(_("missing branch name; try -%c"), cb_option);
  1443. opts->new_branch = argv0 + 1;
  1444. }
  1445. /*
  1446. * Extract branch name from command line arguments, so
  1447. * all that is left is pathspecs.
  1448. *
  1449. * Handle
  1450. *
  1451. * 1) git checkout <tree> -- [<paths>]
  1452. * 2) git checkout -- [<paths>]
  1453. * 3) git checkout <something> [<paths>]
  1454. *
  1455. * including "last branch" syntax and DWIM-ery for names of
  1456. * remote branches, erroring out for invalid or ambiguous cases.
  1457. */
  1458. if (argc && opts->accept_ref) {
  1459. struct object_id rev;
  1460. int dwim_ok =
  1461. !opts->patch_mode &&
  1462. opts->dwim_new_local_branch &&
  1463. opts->track == BRANCH_TRACK_UNSPECIFIED &&
  1464. !opts->new_branch;
  1465. int n = parse_branchname_arg(argc, argv, dwim_ok,
  1466. &new_branch_info, opts, &rev);
  1467. argv += n;
  1468. argc -= n;
  1469. } else if (!opts->accept_ref && opts->from_treeish) {
  1470. struct object_id rev;
  1471. if (get_oid_mb(opts->from_treeish, &rev))
  1472. die(_("could not resolve %s"), opts->from_treeish);
  1473. setup_new_branch_info_and_source_tree(&new_branch_info,
  1474. opts, &rev,
  1475. opts->from_treeish);
  1476. if (!opts->source_tree)
  1477. die(_("reference is not a tree: %s"), opts->from_treeish);
  1478. }
  1479. if (argc) {
  1480. parse_pathspec(&opts->pathspec, 0,
  1481. opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
  1482. prefix, argv);
  1483. if (!opts->pathspec.nr)
  1484. die(_("invalid path specification"));
  1485. /*
  1486. * Try to give more helpful suggestion.
  1487. * new_branch && argc > 1 will be caught later.
  1488. */
  1489. if (opts->new_branch && argc == 1 && !new_branch_info.commit)
  1490. die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
  1491. argv[0], opts->new_branch);
  1492. if (opts->force_detach)
  1493. die(_("git checkout: --detach does not take a path argument '%s'"),
  1494. argv[0]);
  1495. }
  1496. if (opts->pathspec_from_file) {
  1497. if (opts->pathspec.nr)
  1498. die(_("--pathspec-from-file is incompatible with pathspec arguments"));
  1499. if (opts->force_detach)
  1500. die(_("--pathspec-from-file is incompatible with --detach"));
  1501. if (opts->patch_mode)
  1502. die(_("--pathspec-from-file is incompatible with --patch"));
  1503. parse_pathspec_file(&opts->pathspec, 0,
  1504. 0,
  1505. prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
  1506. } else if (opts->pathspec_file_nul) {
  1507. die(_("--pathspec-file-nul requires --pathspec-from-file"));
  1508. }
  1509. opts->pathspec.recursive = 1;
  1510. if (opts->pathspec.nr) {
  1511. if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
  1512. die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
  1513. "checking out of the index."));
  1514. } else {
  1515. if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
  1516. !opts->patch_mode) /* patch mode is special */
  1517. die(_("you must specify path(s) to restore"));
  1518. }
  1519. if (opts->new_branch) {
  1520. struct strbuf buf = STRBUF_INIT;
  1521. if (opts->new_branch_force)
  1522. opts->branch_exists = validate_branchname(opts->new_branch, &buf);
  1523. else
  1524. opts->branch_exists =
  1525. validate_new_branchname(opts->new_branch, &buf, 0);
  1526. strbuf_release(&buf);
  1527. }
  1528. UNLEAK(opts);
  1529. if (opts->patch_mode || opts->pathspec.nr)
  1530. return checkout_paths(opts, &new_branch_info);
  1531. else
  1532. return checkout_branch(opts, &new_branch_info);
  1533. }
  1534. int cmd_checkout(int argc, const char **argv, const char *prefix)
  1535. {
  1536. struct checkout_opts opts;
  1537. struct option *options;
  1538. struct option checkout_options[] = {
  1539. OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
  1540. N_("create and checkout a new branch")),
  1541. OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
  1542. N_("create/reset and checkout a branch")),
  1543. OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
  1544. OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
  1545. N_("second guess 'git checkout <no-such-branch>' (default)")),
  1546. OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
  1547. OPT_END()
  1548. };
  1549. int ret;
  1550. memset(&opts, 0, sizeof(opts));
  1551. opts.dwim_new_local_branch = 1;
  1552. opts.switch_branch_doing_nothing_is_ok = 1;
  1553. opts.only_merge_on_switching_branches = 0;
  1554. opts.accept_ref = 1;
  1555. opts.accept_pathspec = 1;
  1556. opts.implicit_detach = 1;
  1557. opts.can_switch_when_in_progress = 1;
  1558. opts.orphan_from_empty_tree = 0;
  1559. opts.empty_pathspec_ok = 1;
  1560. opts.overlay_mode = -1;
  1561. opts.checkout_index = -2; /* default on */
  1562. opts.checkout_worktree = -2; /* default on */
  1563. if (argc == 3 && !strcmp(argv[1], "-b")) {
  1564. /*
  1565. * User ran 'git checkout -b <branch>' and expects
  1566. * the same behavior as 'git switch -c <branch>'.
  1567. */
  1568. opts.switch_branch_doing_nothing_is_ok = 0;
  1569. opts.only_merge_on_switching_branches = 1;
  1570. }
  1571. options = parse_options_dup(checkout_options);
  1572. options = add_common_options(&opts, options);
  1573. options = add_common_switch_branch_options(&opts, options);
  1574. options = add_checkout_path_options(&opts, options);
  1575. ret = checkout_main(argc, argv, prefix, &opts,
  1576. options, checkout_usage);
  1577. FREE_AND_NULL(options);
  1578. return ret;
  1579. }
  1580. int cmd_switch(int argc, const char **argv, const char *prefix)
  1581. {
  1582. struct checkout_opts opts;
  1583. struct option *options = NULL;
  1584. struct option switch_options[] = {
  1585. OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
  1586. N_("create and switch to a new branch")),
  1587. OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
  1588. N_("create/reset and switch to a branch")),
  1589. OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
  1590. N_("second guess 'git switch <no-such-branch>'")),
  1591. OPT_BOOL(0, "discard-changes", &opts.discard_changes,
  1592. N_("throw away local modifications")),
  1593. OPT_END()
  1594. };
  1595. int ret;
  1596. memset(&opts, 0, sizeof(opts));
  1597. opts.dwim_new_local_branch = 1;
  1598. opts.accept_ref = 1;
  1599. opts.accept_pathspec = 0;
  1600. opts.switch_branch_doing_nothing_is_ok = 0;
  1601. opts.only_merge_on_switching_branches = 1;
  1602. opts.implicit_detach = 0;
  1603. opts.can_switch_when_in_progress = 0;
  1604. opts.orphan_from_empty_tree = 1;
  1605. opts.overlay_mode = -1;
  1606. options = parse_options_dup(switch_options);
  1607. options = add_common_options(&opts, options);
  1608. options = add_common_switch_branch_options(&opts, options);
  1609. cb_option = 'c';
  1610. ret = checkout_main(argc, argv, prefix, &opts,
  1611. options, switch_branch_usage);
  1612. FREE_AND_NULL(options);
  1613. return ret;
  1614. }
  1615. int cmd_restore(int argc, const char **argv, const char *prefix)
  1616. {
  1617. struct checkout_opts opts;
  1618. struct option *options;
  1619. struct option restore_options[] = {
  1620. OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
  1621. N_("which tree-ish to checkout from")),
  1622. OPT_BOOL('S', "staged", &opts.checkout_index,
  1623. N_("restore the index")),
  1624. OPT_BOOL('W', "worktree", &opts.checkout_worktree,
  1625. N_("restore the working tree (default)")),
  1626. OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
  1627. N_("ignore unmerged entries")),
  1628. OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
  1629. OPT_END()
  1630. };
  1631. int ret;
  1632. memset(&opts, 0, sizeof(opts));
  1633. opts.accept_ref = 0;
  1634. opts.accept_pathspec = 1;
  1635. opts.empty_pathspec_ok = 0;
  1636. opts.overlay_mode = 0;
  1637. opts.checkout_index = -1; /* default off */
  1638. opts.checkout_worktree = -2; /* default on */
  1639. opts.ignore_unmerged_opt = "--ignore-unmerged";
  1640. options = parse_options_dup(restore_options);
  1641. options = add_common_options(&opts, options);
  1642. options = add_checkout_path_options(&opts, options);
  1643. ret = checkout_main(argc, argv, prefix, &opts,
  1644. options, restore_usage);
  1645. FREE_AND_NULL(options);
  1646. return ret;
  1647. }