Coverage Report

Created: 2024-09-08 06:23

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