58fc176db681298bc6daf14b4cc09752d3b9bccc
1/*
2 * Builtin "git pull"
3 *
4 * Based on git-pull.sh by Junio C Hamano
5 *
6 * Fetch one or more remote refs and merge it/them into the current HEAD.
7 */
8#include "cache.h"
9#include "builtin.h"
10#include "parse-options.h"
11#include "exec_cmd.h"
12#include "run-command.h"
13#include "sha1-array.h"
14#include "remote.h"
15#include "dir.h"
16#include "refs.h"
17#include "revision.h"
18#include "tempfile.h"
19#include "lockfile.h"
20
21enum rebase_type {
22 REBASE_INVALID = -1,
23 REBASE_FALSE = 0,
24 REBASE_TRUE,
25 REBASE_PRESERVE,
26 REBASE_INTERACTIVE
27};
28
29/**
30 * Parses the value of --rebase. If value is a false value, returns
31 * REBASE_FALSE. If value is a true value, returns REBASE_TRUE. If value is
32 * "preserve", returns REBASE_PRESERVE. If value is a invalid value, dies with
33 * a fatal error if fatal is true, otherwise returns REBASE_INVALID.
34 */
35static enum rebase_type parse_config_rebase(const char *key, const char *value,
36 int fatal)
37{
38 int v = git_config_maybe_bool("pull.rebase", value);
39
40 if (!v)
41 return REBASE_FALSE;
42 else if (v > 0)
43 return REBASE_TRUE;
44 else if (!strcmp(value, "preserve"))
45 return REBASE_PRESERVE;
46 else if (!strcmp(value, "interactive"))
47 return REBASE_INTERACTIVE;
48
49 if (fatal)
50 die(_("Invalid value for %s: %s"), key, value);
51 else
52 error(_("Invalid value for %s: %s"), key, value);
53
54 return REBASE_INVALID;
55}
56
57/**
58 * Callback for --rebase, which parses arg with parse_config_rebase().
59 */
60static int parse_opt_rebase(const struct option *opt, const char *arg, int unset)
61{
62 enum rebase_type *value = opt->value;
63
64 if (arg)
65 *value = parse_config_rebase("--rebase", arg, 0);
66 else
67 *value = unset ? REBASE_FALSE : REBASE_TRUE;
68 return *value == REBASE_INVALID ? -1 : 0;
69}
70
71static const char * const pull_usage[] = {
72 N_("git pull [<options>] [<repository> [<refspec>...]]"),
73 NULL
74};
75
76/* Shared options */
77static int opt_verbosity;
78static char *opt_progress;
79
80/* Options passed to git-merge or git-rebase */
81static enum rebase_type opt_rebase = -1;
82static char *opt_diffstat;
83static char *opt_log;
84static char *opt_squash;
85static char *opt_commit;
86static char *opt_edit;
87static char *opt_ff;
88static char *opt_verify_signatures;
89static int opt_autostash = -1;
90static int config_autostash;
91static struct argv_array opt_strategies = ARGV_ARRAY_INIT;
92static struct argv_array opt_strategy_opts = ARGV_ARRAY_INIT;
93static char *opt_gpg_sign;
94static int opt_allow_unrelated_histories;
95
96/* Options passed to git-fetch */
97static char *opt_all;
98static char *opt_append;
99static char *opt_upload_pack;
100static int opt_force;
101static char *opt_tags;
102static char *opt_prune;
103static char *opt_recurse_submodules;
104static char *max_children;
105static int opt_dry_run;
106static char *opt_keep;
107static char *opt_depth;
108static char *opt_unshallow;
109static char *opt_update_shallow;
110static char *opt_refmap;
111
112static struct option pull_options[] = {
113 /* Shared options */
114 OPT__VERBOSITY(&opt_verbosity),
115 OPT_PASSTHRU(0, "progress", &opt_progress, NULL,
116 N_("force progress reporting"),
117 PARSE_OPT_NOARG),
118
119 /* Options passed to git-merge or git-rebase */
120 OPT_GROUP(N_("Options related to merging")),
121 { OPTION_CALLBACK, 'r', "rebase", &opt_rebase,
122 "false|true|preserve|interactive",
123 N_("incorporate changes by rebasing rather than merging"),
124 PARSE_OPT_OPTARG, parse_opt_rebase },
125 OPT_PASSTHRU('n', NULL, &opt_diffstat, NULL,
126 N_("do not show a diffstat at the end of the merge"),
127 PARSE_OPT_NOARG | PARSE_OPT_NONEG),
128 OPT_PASSTHRU(0, "stat", &opt_diffstat, NULL,
129 N_("show a diffstat at the end of the merge"),
130 PARSE_OPT_NOARG),
131 OPT_PASSTHRU(0, "summary", &opt_diffstat, NULL,
132 N_("(synonym to --stat)"),
133 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN),
134 OPT_PASSTHRU(0, "log", &opt_log, N_("n"),
135 N_("add (at most <n>) entries from shortlog to merge commit message"),
136 PARSE_OPT_OPTARG),
137 OPT_PASSTHRU(0, "squash", &opt_squash, NULL,
138 N_("create a single commit instead of doing a merge"),
139 PARSE_OPT_NOARG),
140 OPT_PASSTHRU(0, "commit", &opt_commit, NULL,
141 N_("perform a commit if the merge succeeds (default)"),
142 PARSE_OPT_NOARG),
143 OPT_PASSTHRU(0, "edit", &opt_edit, NULL,
144 N_("edit message before committing"),
145 PARSE_OPT_NOARG),
146 OPT_PASSTHRU(0, "ff", &opt_ff, NULL,
147 N_("allow fast-forward"),
148 PARSE_OPT_NOARG),
149 OPT_PASSTHRU(0, "ff-only", &opt_ff, NULL,
150 N_("abort if fast-forward is not possible"),
151 PARSE_OPT_NOARG | PARSE_OPT_NONEG),
152 OPT_PASSTHRU(0, "verify-signatures", &opt_verify_signatures, NULL,
153 N_("verify that the named commit has a valid GPG signature"),
154 PARSE_OPT_NOARG),
155 OPT_BOOL(0, "autostash", &opt_autostash,
156 N_("automatically stash/stash pop before and after rebase")),
157 OPT_PASSTHRU_ARGV('s', "strategy", &opt_strategies, N_("strategy"),
158 N_("merge strategy to use"),
159 0),
160 OPT_PASSTHRU_ARGV('X', "strategy-option", &opt_strategy_opts,
161 N_("option=value"),
162 N_("option for selected merge strategy"),
163 0),
164 OPT_PASSTHRU('S', "gpg-sign", &opt_gpg_sign, N_("key-id"),
165 N_("GPG sign commit"),
166 PARSE_OPT_OPTARG),
167 OPT_SET_INT(0, "allow-unrelated-histories",
168 &opt_allow_unrelated_histories,
169 N_("allow merging unrelated histories"), 1),
170
171 /* Options passed to git-fetch */
172 OPT_GROUP(N_("Options related to fetching")),
173 OPT_PASSTHRU(0, "all", &opt_all, NULL,
174 N_("fetch from all remotes"),
175 PARSE_OPT_NOARG),
176 OPT_PASSTHRU('a', "append", &opt_append, NULL,
177 N_("append to .git/FETCH_HEAD instead of overwriting"),
178 PARSE_OPT_NOARG),
179 OPT_PASSTHRU(0, "upload-pack", &opt_upload_pack, N_("path"),
180 N_("path to upload pack on remote end"),
181 0),
182 OPT__FORCE(&opt_force, N_("force overwrite of local branch")),
183 OPT_PASSTHRU('t', "tags", &opt_tags, NULL,
184 N_("fetch all tags and associated objects"),
185 PARSE_OPT_NOARG),
186 OPT_PASSTHRU('p', "prune", &opt_prune, NULL,
187 N_("prune remote-tracking branches no longer on remote"),
188 PARSE_OPT_NOARG),
189 OPT_PASSTHRU(0, "recurse-submodules", &opt_recurse_submodules,
190 N_("on-demand"),
191 N_("control recursive fetching of submodules"),
192 PARSE_OPT_OPTARG),
193 OPT_PASSTHRU('j', "jobs", &max_children, N_("n"),
194 N_("number of submodules pulled in parallel"),
195 PARSE_OPT_OPTARG),
196 OPT_BOOL(0, "dry-run", &opt_dry_run,
197 N_("dry run")),
198 OPT_PASSTHRU('k', "keep", &opt_keep, NULL,
199 N_("keep downloaded pack"),
200 PARSE_OPT_NOARG),
201 OPT_PASSTHRU(0, "depth", &opt_depth, N_("depth"),
202 N_("deepen history of shallow clone"),
203 0),
204 OPT_PASSTHRU(0, "unshallow", &opt_unshallow, NULL,
205 N_("convert to a complete repository"),
206 PARSE_OPT_NONEG | PARSE_OPT_NOARG),
207 OPT_PASSTHRU(0, "update-shallow", &opt_update_shallow, NULL,
208 N_("accept refs that update .git/shallow"),
209 PARSE_OPT_NOARG),
210 OPT_PASSTHRU(0, "refmap", &opt_refmap, N_("refmap"),
211 N_("specify fetch refmap"),
212 PARSE_OPT_NONEG),
213
214 OPT_END()
215};
216
217/**
218 * Pushes "-q" or "-v" switches into arr to match the opt_verbosity level.
219 */
220static void argv_push_verbosity(struct argv_array *arr)
221{
222 int verbosity;
223
224 for (verbosity = opt_verbosity; verbosity > 0; verbosity--)
225 argv_array_push(arr, "-v");
226
227 for (verbosity = opt_verbosity; verbosity < 0; verbosity++)
228 argv_array_push(arr, "-q");
229}
230
231/**
232 * Pushes "-f" switches into arr to match the opt_force level.
233 */
234static void argv_push_force(struct argv_array *arr)
235{
236 int force = opt_force;
237 while (force-- > 0)
238 argv_array_push(arr, "-f");
239}
240
241/**
242 * Sets the GIT_REFLOG_ACTION environment variable to the concatenation of argv
243 */
244static void set_reflog_message(int argc, const char **argv)
245{
246 int i;
247 struct strbuf msg = STRBUF_INIT;
248
249 for (i = 0; i < argc; i++) {
250 if (i)
251 strbuf_addch(&msg, ' ');
252 strbuf_addstr(&msg, argv[i]);
253 }
254
255 setenv("GIT_REFLOG_ACTION", msg.buf, 0);
256
257 strbuf_release(&msg);
258}
259
260/**
261 * If pull.ff is unset, returns NULL. If pull.ff is "true", returns "--ff". If
262 * pull.ff is "false", returns "--no-ff". If pull.ff is "only", returns
263 * "--ff-only". Otherwise, if pull.ff is set to an invalid value, die with an
264 * error.
265 */
266static const char *config_get_ff(void)
267{
268 const char *value;
269
270 if (git_config_get_value("pull.ff", &value))
271 return NULL;
272
273 switch (git_config_maybe_bool("pull.ff", value)) {
274 case 0:
275 return "--no-ff";
276 case 1:
277 return "--ff";
278 }
279
280 if (!strcmp(value, "only"))
281 return "--ff-only";
282
283 die(_("Invalid value for pull.ff: %s"), value);
284}
285
286/**
287 * Returns the default configured value for --rebase. It first looks for the
288 * value of "branch.$curr_branch.rebase", where $curr_branch is the current
289 * branch, and if HEAD is detached or the configuration key does not exist,
290 * looks for the value of "pull.rebase". If both configuration keys do not
291 * exist, returns REBASE_FALSE.
292 */
293static enum rebase_type config_get_rebase(void)
294{
295 struct branch *curr_branch = branch_get("HEAD");
296 const char *value;
297
298 if (curr_branch) {
299 char *key = xstrfmt("branch.%s.rebase", curr_branch->name);
300
301 if (!git_config_get_value(key, &value)) {
302 enum rebase_type ret = parse_config_rebase(key, value, 1);
303 free(key);
304 return ret;
305 }
306
307 free(key);
308 }
309
310 if (!git_config_get_value("pull.rebase", &value))
311 return parse_config_rebase("pull.rebase", value, 1);
312
313 return REBASE_FALSE;
314}
315
316/**
317 * Read config variables.
318 */
319static int git_pull_config(const char *var, const char *value, void *cb)
320{
321 if (!strcmp(var, "rebase.autostash")) {
322 config_autostash = git_config_bool(var, value);
323 return 0;
324 }
325 return git_default_config(var, value, cb);
326}
327
328/**
329 * Returns 1 if there are unstaged changes, 0 otherwise.
330 */
331static int has_unstaged_changes(void)
332{
333 struct rev_info rev_info;
334 int result;
335
336 init_revisions(&rev_info, NULL);
337 DIFF_OPT_SET(&rev_info.diffopt, IGNORE_SUBMODULES);
338 DIFF_OPT_SET(&rev_info.diffopt, QUICK);
339 diff_setup_done(&rev_info.diffopt);
340 result = run_diff_files(&rev_info, 0);
341 return diff_result_code(&rev_info.diffopt, result);
342}
343
344/**
345 * Returns 1 if there are uncommitted changes, 0 otherwise.
346 */
347static int has_uncommitted_changes(void)
348{
349 struct rev_info rev_info;
350 int result;
351
352 if (is_cache_unborn())
353 return 0;
354
355 init_revisions(&rev_info, NULL);
356 DIFF_OPT_SET(&rev_info.diffopt, IGNORE_SUBMODULES);
357 DIFF_OPT_SET(&rev_info.diffopt, QUICK);
358 add_head_to_pending(&rev_info);
359 diff_setup_done(&rev_info.diffopt);
360 result = run_diff_index(&rev_info, 1);
361 return diff_result_code(&rev_info.diffopt, result);
362}
363
364/**
365 * If the work tree has unstaged or uncommitted changes, dies with the
366 * appropriate message.
367 */
368static int require_clean_work_tree(const char *action, const char *hint,
369 int gently)
370{
371 struct lock_file *lock_file = xcalloc(1, sizeof(*lock_file));
372 int err = 0;
373
374 hold_locked_index(lock_file, 0);
375 refresh_cache(REFRESH_QUIET);
376 update_index_if_able(&the_index, lock_file);
377 rollback_lock_file(lock_file);
378
379 if (has_unstaged_changes()) {
380 /* TRANSLATORS: the action is e.g. "pull with rebase" */
381 error(_("Cannot %s: You have unstaged changes."), _(action));
382 err = 1;
383 }
384
385 if (has_uncommitted_changes()) {
386 if (err)
387 error(_("Additionally, your index contains uncommitted changes."));
388 else
389 error(_("Cannot %s: Your index contains uncommitted changes."),
390 _(action));
391 err = 1;
392 }
393
394 if (err) {
395 if (hint)
396 error("%s", hint);
397 if (!gently)
398 exit(128);
399 }
400
401 return err;
402}
403
404/**
405 * Appends merge candidates from FETCH_HEAD that are not marked not-for-merge
406 * into merge_heads.
407 */
408static void get_merge_heads(struct sha1_array *merge_heads)
409{
410 const char *filename = git_path("FETCH_HEAD");
411 FILE *fp;
412 struct strbuf sb = STRBUF_INIT;
413 unsigned char sha1[GIT_SHA1_RAWSZ];
414
415 if (!(fp = fopen(filename, "r")))
416 die_errno(_("could not open '%s' for reading"), filename);
417 while (strbuf_getline_lf(&sb, fp) != EOF) {
418 if (get_sha1_hex(sb.buf, sha1))
419 continue; /* invalid line: does not start with SHA1 */
420 if (starts_with(sb.buf + GIT_SHA1_HEXSZ, "\tnot-for-merge\t"))
421 continue; /* ref is not-for-merge */
422 sha1_array_append(merge_heads, sha1);
423 }
424 fclose(fp);
425 strbuf_release(&sb);
426}
427
428/**
429 * Used by die_no_merge_candidates() as a for_each_remote() callback to
430 * retrieve the name of the remote if the repository only has one remote.
431 */
432static int get_only_remote(struct remote *remote, void *cb_data)
433{
434 const char **remote_name = cb_data;
435
436 if (*remote_name)
437 return -1;
438
439 *remote_name = remote->name;
440 return 0;
441}
442
443/**
444 * Dies with the appropriate reason for why there are no merge candidates:
445 *
446 * 1. We fetched from a specific remote, and a refspec was given, but it ended
447 * up not fetching anything. This is usually because the user provided a
448 * wildcard refspec which had no matches on the remote end.
449 *
450 * 2. We fetched from a non-default remote, but didn't specify a branch to
451 * merge. We can't use the configured one because it applies to the default
452 * remote, thus the user must specify the branches to merge.
453 *
454 * 3. We fetched from the branch's or repo's default remote, but:
455 *
456 * a. We are not on a branch, so there will never be a configured branch to
457 * merge with.
458 *
459 * b. We are on a branch, but there is no configured branch to merge with.
460 *
461 * 4. We fetched from the branch's or repo's default remote, but the configured
462 * branch to merge didn't get fetched. (Either it doesn't exist, or wasn't
463 * part of the configured fetch refspec.)
464 */
465static void NORETURN die_no_merge_candidates(const char *repo, const char **refspecs)
466{
467 struct branch *curr_branch = branch_get("HEAD");
468 const char *remote = curr_branch ? curr_branch->remote_name : NULL;
469
470 if (*refspecs) {
471 if (opt_rebase)
472 fprintf_ln(stderr, _("There is no candidate for rebasing against among the refs that you just fetched."));
473 else
474 fprintf_ln(stderr, _("There are no candidates for merging among the refs that you just fetched."));
475 fprintf_ln(stderr, _("Generally this means that you provided a wildcard refspec which had no\n"
476 "matches on the remote end."));
477 } else if (repo && curr_branch && (!remote || strcmp(repo, remote))) {
478 fprintf_ln(stderr, _("You asked to pull from the remote '%s', but did not specify\n"
479 "a branch. Because this is not the default configured remote\n"
480 "for your current branch, you must specify a branch on the command line."),
481 repo);
482 } else if (!curr_branch) {
483 fprintf_ln(stderr, _("You are not currently on a branch."));
484 if (opt_rebase)
485 fprintf_ln(stderr, _("Please specify which branch you want to rebase against."));
486 else
487 fprintf_ln(stderr, _("Please specify which branch you want to merge with."));
488 fprintf_ln(stderr, _("See git-pull(1) for details."));
489 fprintf(stderr, "\n");
490 fprintf_ln(stderr, " git pull %s %s", _("<remote>"), _("<branch>"));
491 fprintf(stderr, "\n");
492 } else if (!curr_branch->merge_nr) {
493 const char *remote_name = NULL;
494
495 if (for_each_remote(get_only_remote, &remote_name) || !remote_name)
496 remote_name = _("<remote>");
497
498 fprintf_ln(stderr, _("There is no tracking information for the current branch."));
499 if (opt_rebase)
500 fprintf_ln(stderr, _("Please specify which branch you want to rebase against."));
501 else
502 fprintf_ln(stderr, _("Please specify which branch you want to merge with."));
503 fprintf_ln(stderr, _("See git-pull(1) for details."));
504 fprintf(stderr, "\n");
505 fprintf_ln(stderr, " git pull %s %s", _("<remote>"), _("<branch>"));
506 fprintf(stderr, "\n");
507 fprintf_ln(stderr, _("If you wish to set tracking information for this branch you can do so with:"));
508 fprintf(stderr, "\n");
509 fprintf_ln(stderr, " git branch --set-upstream-to=%s/%s %s\n",
510 remote_name, _("<branch>"), curr_branch->name);
511 } else
512 fprintf_ln(stderr, _("Your configuration specifies to merge with the ref '%s'\n"
513 "from the remote, but no such ref was fetched."),
514 *curr_branch->merge_name);
515 exit(1);
516}
517
518/**
519 * Parses argv into [<repo> [<refspecs>...]], returning their values in `repo`
520 * as a string and `refspecs` as a null-terminated array of strings. If `repo`
521 * is not provided in argv, it is set to NULL.
522 */
523static void parse_repo_refspecs(int argc, const char **argv, const char **repo,
524 const char ***refspecs)
525{
526 if (argc > 0) {
527 *repo = *argv++;
528 argc--;
529 } else
530 *repo = NULL;
531 *refspecs = argv;
532}
533
534/**
535 * Runs git-fetch, returning its exit status. `repo` and `refspecs` are the
536 * repository and refspecs to fetch, or NULL if they are not provided.
537 */
538static int run_fetch(const char *repo, const char **refspecs)
539{
540 struct argv_array args = ARGV_ARRAY_INIT;
541 int ret;
542
543 argv_array_pushl(&args, "fetch", "--update-head-ok", NULL);
544
545 /* Shared options */
546 argv_push_verbosity(&args);
547 if (opt_progress)
548 argv_array_push(&args, opt_progress);
549
550 /* Options passed to git-fetch */
551 if (opt_all)
552 argv_array_push(&args, opt_all);
553 if (opt_append)
554 argv_array_push(&args, opt_append);
555 if (opt_upload_pack)
556 argv_array_push(&args, opt_upload_pack);
557 argv_push_force(&args);
558 if (opt_tags)
559 argv_array_push(&args, opt_tags);
560 if (opt_prune)
561 argv_array_push(&args, opt_prune);
562 if (opt_recurse_submodules)
563 argv_array_push(&args, opt_recurse_submodules);
564 if (max_children)
565 argv_array_push(&args, max_children);
566 if (opt_dry_run)
567 argv_array_push(&args, "--dry-run");
568 if (opt_keep)
569 argv_array_push(&args, opt_keep);
570 if (opt_depth)
571 argv_array_push(&args, opt_depth);
572 if (opt_unshallow)
573 argv_array_push(&args, opt_unshallow);
574 if (opt_update_shallow)
575 argv_array_push(&args, opt_update_shallow);
576 if (opt_refmap)
577 argv_array_push(&args, opt_refmap);
578
579 if (repo) {
580 argv_array_push(&args, repo);
581 argv_array_pushv(&args, refspecs);
582 } else if (*refspecs)
583 die("BUG: refspecs without repo?");
584 ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
585 argv_array_clear(&args);
586 return ret;
587}
588
589/**
590 * "Pulls into void" by branching off merge_head.
591 */
592static int pull_into_void(const unsigned char *merge_head,
593 const unsigned char *curr_head)
594{
595 /*
596 * Two-way merge: we treat the index as based on an empty tree,
597 * and try to fast-forward to HEAD. This ensures we will not lose
598 * index/worktree changes that the user already made on the unborn
599 * branch.
600 */
601 if (checkout_fast_forward(EMPTY_TREE_SHA1_BIN, merge_head, 0))
602 return 1;
603
604 if (update_ref("initial pull", "HEAD", merge_head, curr_head, 0, UPDATE_REFS_DIE_ON_ERR))
605 return 1;
606
607 return 0;
608}
609
610/**
611 * Runs git-merge, returning its exit status.
612 */
613static int run_merge(void)
614{
615 int ret;
616 struct argv_array args = ARGV_ARRAY_INIT;
617
618 argv_array_pushl(&args, "merge", NULL);
619
620 /* Shared options */
621 argv_push_verbosity(&args);
622 if (opt_progress)
623 argv_array_push(&args, opt_progress);
624
625 /* Options passed to git-merge */
626 if (opt_diffstat)
627 argv_array_push(&args, opt_diffstat);
628 if (opt_log)
629 argv_array_push(&args, opt_log);
630 if (opt_squash)
631 argv_array_push(&args, opt_squash);
632 if (opt_commit)
633 argv_array_push(&args, opt_commit);
634 if (opt_edit)
635 argv_array_push(&args, opt_edit);
636 if (opt_ff)
637 argv_array_push(&args, opt_ff);
638 if (opt_verify_signatures)
639 argv_array_push(&args, opt_verify_signatures);
640 argv_array_pushv(&args, opt_strategies.argv);
641 argv_array_pushv(&args, opt_strategy_opts.argv);
642 if (opt_gpg_sign)
643 argv_array_push(&args, opt_gpg_sign);
644 if (opt_allow_unrelated_histories > 0)
645 argv_array_push(&args, "--allow-unrelated-histories");
646
647 argv_array_push(&args, "FETCH_HEAD");
648 ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
649 argv_array_clear(&args);
650 return ret;
651}
652
653/**
654 * Returns remote's upstream branch for the current branch. If remote is NULL,
655 * the current branch's configured default remote is used. Returns NULL if
656 * `remote` does not name a valid remote, HEAD does not point to a branch,
657 * remote is not the branch's configured remote or the branch does not have any
658 * configured upstream branch.
659 */
660static const char *get_upstream_branch(const char *remote)
661{
662 struct remote *rm;
663 struct branch *curr_branch;
664 const char *curr_branch_remote;
665
666 rm = remote_get(remote);
667 if (!rm)
668 return NULL;
669
670 curr_branch = branch_get("HEAD");
671 if (!curr_branch)
672 return NULL;
673
674 curr_branch_remote = remote_for_branch(curr_branch, NULL);
675 assert(curr_branch_remote);
676
677 if (strcmp(curr_branch_remote, rm->name))
678 return NULL;
679
680 return branch_get_upstream(curr_branch, NULL);
681}
682
683/**
684 * Derives the remote tracking branch from the remote and refspec.
685 *
686 * FIXME: The current implementation assumes the default mapping of
687 * refs/heads/<branch_name> to refs/remotes/<remote_name>/<branch_name>.
688 */
689static const char *get_tracking_branch(const char *remote, const char *refspec)
690{
691 struct refspec *spec;
692 const char *spec_src;
693 const char *merge_branch;
694
695 spec = parse_fetch_refspec(1, &refspec);
696 spec_src = spec->src;
697 if (!*spec_src || !strcmp(spec_src, "HEAD"))
698 spec_src = "HEAD";
699 else if (skip_prefix(spec_src, "heads/", &spec_src))
700 ;
701 else if (skip_prefix(spec_src, "refs/heads/", &spec_src))
702 ;
703 else if (starts_with(spec_src, "refs/") ||
704 starts_with(spec_src, "tags/") ||
705 starts_with(spec_src, "remotes/"))
706 spec_src = "";
707
708 if (*spec_src) {
709 if (!strcmp(remote, "."))
710 merge_branch = mkpath("refs/heads/%s", spec_src);
711 else
712 merge_branch = mkpath("refs/remotes/%s/%s", remote, spec_src);
713 } else
714 merge_branch = NULL;
715
716 free_refspec(1, spec);
717 return merge_branch;
718}
719
720/**
721 * Given the repo and refspecs, sets fork_point to the point at which the
722 * current branch forked from its remote tracking branch. Returns 0 on success,
723 * -1 on failure.
724 */
725static int get_rebase_fork_point(unsigned char *fork_point, const char *repo,
726 const char *refspec)
727{
728 int ret;
729 struct branch *curr_branch;
730 const char *remote_branch;
731 struct child_process cp = CHILD_PROCESS_INIT;
732 struct strbuf sb = STRBUF_INIT;
733
734 curr_branch = branch_get("HEAD");
735 if (!curr_branch)
736 return -1;
737
738 if (refspec)
739 remote_branch = get_tracking_branch(repo, refspec);
740 else
741 remote_branch = get_upstream_branch(repo);
742
743 if (!remote_branch)
744 return -1;
745
746 argv_array_pushl(&cp.args, "merge-base", "--fork-point",
747 remote_branch, curr_branch->name, NULL);
748 cp.no_stdin = 1;
749 cp.no_stderr = 1;
750 cp.git_cmd = 1;
751
752 ret = capture_command(&cp, &sb, GIT_SHA1_HEXSZ);
753 if (ret)
754 goto cleanup;
755
756 ret = get_sha1_hex(sb.buf, fork_point);
757 if (ret)
758 goto cleanup;
759
760cleanup:
761 strbuf_release(&sb);
762 return ret ? -1 : 0;
763}
764
765/**
766 * Sets merge_base to the octopus merge base of curr_head, merge_head and
767 * fork_point. Returns 0 if a merge base is found, 1 otherwise.
768 */
769static int get_octopus_merge_base(unsigned char *merge_base,
770 const unsigned char *curr_head,
771 const unsigned char *merge_head,
772 const unsigned char *fork_point)
773{
774 struct commit_list *revs = NULL, *result;
775
776 commit_list_insert(lookup_commit_reference(curr_head), &revs);
777 commit_list_insert(lookup_commit_reference(merge_head), &revs);
778 if (!is_null_sha1(fork_point))
779 commit_list_insert(lookup_commit_reference(fork_point), &revs);
780
781 result = reduce_heads(get_octopus_merge_bases(revs));
782 free_commit_list(revs);
783 if (!result)
784 return 1;
785
786 hashcpy(merge_base, result->item->object.oid.hash);
787 return 0;
788}
789
790/**
791 * Given the current HEAD SHA1, the merge head returned from git-fetch and the
792 * fork point calculated by get_rebase_fork_point(), runs git-rebase with the
793 * appropriate arguments and returns its exit status.
794 */
795static int run_rebase(const unsigned char *curr_head,
796 const unsigned char *merge_head,
797 const unsigned char *fork_point)
798{
799 int ret;
800 unsigned char oct_merge_base[GIT_SHA1_RAWSZ];
801 struct argv_array args = ARGV_ARRAY_INIT;
802
803 if (!get_octopus_merge_base(oct_merge_base, curr_head, merge_head, fork_point))
804 if (!is_null_sha1(fork_point) && !hashcmp(oct_merge_base, fork_point))
805 fork_point = NULL;
806
807 argv_array_push(&args, "rebase");
808
809 /* Shared options */
810 argv_push_verbosity(&args);
811
812 /* Options passed to git-rebase */
813 if (opt_rebase == REBASE_PRESERVE)
814 argv_array_push(&args, "--preserve-merges");
815 else if (opt_rebase == REBASE_INTERACTIVE)
816 argv_array_push(&args, "--interactive");
817 if (opt_diffstat)
818 argv_array_push(&args, opt_diffstat);
819 argv_array_pushv(&args, opt_strategies.argv);
820 argv_array_pushv(&args, opt_strategy_opts.argv);
821 if (opt_gpg_sign)
822 argv_array_push(&args, opt_gpg_sign);
823 if (opt_autostash == 0)
824 argv_array_push(&args, "--no-autostash");
825 else if (opt_autostash == 1)
826 argv_array_push(&args, "--autostash");
827 if (opt_verify_signatures &&
828 !strcmp(opt_verify_signatures, "--verify-signatures"))
829 warning(_("ignoring --verify-signatures for rebase"));
830
831 argv_array_push(&args, "--onto");
832 argv_array_push(&args, sha1_to_hex(merge_head));
833
834 if (fork_point && !is_null_sha1(fork_point))
835 argv_array_push(&args, sha1_to_hex(fork_point));
836 else
837 argv_array_push(&args, sha1_to_hex(merge_head));
838
839 ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
840 argv_array_clear(&args);
841 return ret;
842}
843
844int cmd_pull(int argc, const char **argv, const char *prefix)
845{
846 const char *repo, **refspecs;
847 struct sha1_array merge_heads = SHA1_ARRAY_INIT;
848 unsigned char orig_head[GIT_SHA1_RAWSZ], curr_head[GIT_SHA1_RAWSZ];
849 unsigned char rebase_fork_point[GIT_SHA1_RAWSZ];
850
851 if (!getenv("GIT_REFLOG_ACTION"))
852 set_reflog_message(argc, argv);
853
854 argc = parse_options(argc, argv, prefix, pull_options, pull_usage, 0);
855
856 parse_repo_refspecs(argc, argv, &repo, &refspecs);
857
858 if (!opt_ff)
859 opt_ff = xstrdup_or_null(config_get_ff());
860
861 if (opt_rebase < 0)
862 opt_rebase = config_get_rebase();
863
864 git_config(git_pull_config, NULL);
865
866 if (read_cache_unmerged())
867 die_resolve_conflict("pull");
868
869 if (file_exists(git_path("MERGE_HEAD")))
870 die_conclude_merge();
871
872 if (get_sha1("HEAD", orig_head))
873 hashclr(orig_head);
874
875 if (!opt_rebase && opt_autostash != -1)
876 die(_("--[no-]autostash option is only valid with --rebase."));
877
878 if (opt_rebase) {
879 int autostash = config_autostash;
880 if (opt_autostash != -1)
881 autostash = opt_autostash;
882
883 if (is_null_sha1(orig_head) && !is_cache_unborn())
884 die(_("Updating an unborn branch with changes added to the index."));
885
886 if (!autostash)
887 require_clean_work_tree(N_("pull with rebase"),
888 _("please commit or stash them."), 0);
889
890 if (get_rebase_fork_point(rebase_fork_point, repo, *refspecs))
891 hashclr(rebase_fork_point);
892 }
893
894 if (run_fetch(repo, refspecs))
895 return 1;
896
897 if (opt_dry_run)
898 return 0;
899
900 if (get_sha1("HEAD", curr_head))
901 hashclr(curr_head);
902
903 if (!is_null_sha1(orig_head) && !is_null_sha1(curr_head) &&
904 hashcmp(orig_head, curr_head)) {
905 /*
906 * The fetch involved updating the current branch.
907 *
908 * The working tree and the index file are still based on
909 * orig_head commit, but we are merging into curr_head.
910 * Update the working tree to match curr_head.
911 */
912
913 warning(_("fetch updated the current branch head.\n"
914 "fast-forwarding your working tree from\n"
915 "commit %s."), sha1_to_hex(orig_head));
916
917 if (checkout_fast_forward(orig_head, curr_head, 0))
918 die(_("Cannot fast-forward your working tree.\n"
919 "After making sure that you saved anything precious from\n"
920 "$ git diff %s\n"
921 "output, run\n"
922 "$ git reset --hard\n"
923 "to recover."), sha1_to_hex(orig_head));
924 }
925
926 get_merge_heads(&merge_heads);
927
928 if (!merge_heads.nr)
929 die_no_merge_candidates(repo, refspecs);
930
931 if (is_null_sha1(orig_head)) {
932 if (merge_heads.nr > 1)
933 die(_("Cannot merge multiple branches into empty head."));
934 return pull_into_void(*merge_heads.sha1, curr_head);
935 } else if (opt_rebase) {
936 if (merge_heads.nr > 1)
937 die(_("Cannot rebase onto multiple branches."));
938 return run_rebase(curr_head, *merge_heads.sha1, rebase_fork_point);
939 } else
940 return run_merge();
941}