Merge git://repo.or.cz/git-gui
[git] / builtin-fetch.c
1 /*
2  * "git fetch"
3  */
4 #include "cache.h"
5 #include "refs.h"
6 #include "commit.h"
7 #include "builtin.h"
8 #include "path-list.h"
9 #include "remote.h"
10 #include "transport.h"
11 #include "run-command.h"
12 #include "parse-options.h"
13
14 static const char * const builtin_fetch_usage[] = {
15         "git-fetch [options] [<repository> <refspec>...]",
16         NULL
17 };
18
19 enum {
20         TAGS_UNSET = 0,
21         TAGS_DEFAULT = 1,
22         TAGS_SET = 2
23 };
24
25 static int append, force, keep, update_head_ok, verbose, quiet;
26 static int tags = TAGS_DEFAULT;
27 static const char *depth;
28 static const char *upload_pack;
29 static struct strbuf default_rla = STRBUF_INIT;
30 static struct transport *transport;
31
32 static struct option builtin_fetch_options[] = {
33         OPT__QUIET(&quiet),
34         OPT__VERBOSE(&verbose),
35         OPT_BOOLEAN('a', "append", &append,
36                     "append to .git/FETCH_HEAD instead of overwriting"),
37         OPT_STRING(0, "upload-pack", &upload_pack, "PATH",
38                    "path to upload pack on remote end"),
39         OPT_BOOLEAN('f', "force", &force,
40                     "force overwrite of local branch"),
41         OPT_SET_INT('t', "tags", &tags,
42                     "fetch all tags and associated objects", TAGS_SET),
43         OPT_SET_INT('n', NULL, &tags,
44                     "do not fetch all tags (--no-tags)", TAGS_UNSET),
45         OPT_BOOLEAN('k', "keep", &keep, "keep downloaded pack"),
46         OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
47                     "allow updating of HEAD ref"),
48         OPT_STRING(0, "depth", &depth, "DEPTH",
49                    "deepen history of shallow clone"),
50         OPT_END()
51 };
52
53 static void unlock_pack(void)
54 {
55         if (transport)
56                 transport_unlock_pack(transport);
57 }
58
59 static void unlock_pack_on_signal(int signo)
60 {
61         unlock_pack();
62         signal(SIGINT, SIG_DFL);
63         raise(signo);
64 }
65
66 static void add_merge_config(struct ref **head,
67                            const struct ref *remote_refs,
68                            struct branch *branch,
69                            struct ref ***tail)
70 {
71         int i;
72
73         for (i = 0; i < branch->merge_nr; i++) {
74                 struct ref *rm, **old_tail = *tail;
75                 struct refspec refspec;
76
77                 for (rm = *head; rm; rm = rm->next) {
78                         if (branch_merge_matches(branch, i, rm->name)) {
79                                 rm->merge = 1;
80                                 break;
81                         }
82                 }
83                 if (rm)
84                         continue;
85
86                 /*
87                  * Not fetched to a tracking branch?  We need to fetch
88                  * it anyway to allow this branch's "branch.$name.merge"
89                  * to be honored by git-pull, but we do not have to
90                  * fail if branch.$name.merge is misconfigured to point
91                  * at a nonexisting branch.  If we were indeed called by
92                  * git-pull, it will notice the misconfiguration because
93                  * there is no entry in the resulting FETCH_HEAD marked
94                  * for merging.
95                  */
96                 refspec.src = branch->merge[i]->src;
97                 refspec.dst = NULL;
98                 refspec.pattern = 0;
99                 refspec.force = 0;
100                 get_fetch_map(remote_refs, &refspec, tail, 1);
101                 for (rm = *old_tail; rm; rm = rm->next)
102                         rm->merge = 1;
103         }
104 }
105
106 static void find_non_local_tags(struct transport *transport,
107                         struct ref **head,
108                         struct ref ***tail);
109
110 static struct ref *get_ref_map(struct transport *transport,
111                                struct refspec *refs, int ref_count, int tags,
112                                int *autotags)
113 {
114         int i;
115         struct ref *rm;
116         struct ref *ref_map = NULL;
117         struct ref **tail = &ref_map;
118
119         const struct ref *remote_refs = transport_get_remote_refs(transport);
120
121         if (ref_count || tags == TAGS_SET) {
122                 for (i = 0; i < ref_count; i++) {
123                         get_fetch_map(remote_refs, &refs[i], &tail, 0);
124                         if (refs[i].dst && refs[i].dst[0])
125                                 *autotags = 1;
126                 }
127                 /* Merge everything on the command line, but not --tags */
128                 for (rm = ref_map; rm; rm = rm->next)
129                         rm->merge = 1;
130                 if (tags == TAGS_SET) {
131                         struct refspec refspec;
132                         refspec.src = "refs/tags/";
133                         refspec.dst = "refs/tags/";
134                         refspec.pattern = 1;
135                         refspec.force = 0;
136                         get_fetch_map(remote_refs, &refspec, &tail, 0);
137                 }
138         } else {
139                 /* Use the defaults */
140                 struct remote *remote = transport->remote;
141                 struct branch *branch = branch_get(NULL);
142                 int has_merge = branch_has_merge_config(branch);
143                 if (remote && (remote->fetch_refspec_nr || has_merge)) {
144                         for (i = 0; i < remote->fetch_refspec_nr; i++) {
145                                 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
146                                 if (remote->fetch[i].dst &&
147                                     remote->fetch[i].dst[0])
148                                         *autotags = 1;
149                                 if (!i && !has_merge && ref_map &&
150                                     !remote->fetch[0].pattern)
151                                         ref_map->merge = 1;
152                         }
153                         /*
154                          * if the remote we're fetching from is the same
155                          * as given in branch.<name>.remote, we add the
156                          * ref given in branch.<name>.merge, too.
157                          */
158                         if (has_merge &&
159                             !strcmp(branch->remote_name, remote->name))
160                                 add_merge_config(&ref_map, remote_refs, branch, &tail);
161                 } else {
162                         ref_map = get_remote_ref(remote_refs, "HEAD");
163                         if (!ref_map)
164                                 die("Couldn't find remote ref HEAD");
165                         ref_map->merge = 1;
166                         tail = &ref_map->next;
167                 }
168         }
169         if (tags == TAGS_DEFAULT && *autotags)
170                 find_non_local_tags(transport, &ref_map, &tail);
171         ref_remove_duplicates(ref_map);
172
173         return ref_map;
174 }
175
176 static int s_update_ref(const char *action,
177                         struct ref *ref,
178                         int check_old)
179 {
180         char msg[1024];
181         char *rla = getenv("GIT_REFLOG_ACTION");
182         static struct ref_lock *lock;
183
184         if (!rla)
185                 rla = default_rla.buf;
186         snprintf(msg, sizeof(msg), "%s: %s", rla, action);
187         lock = lock_any_ref_for_update(ref->name,
188                                        check_old ? ref->old_sha1 : NULL, 0);
189         if (!lock)
190                 return 1;
191         if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
192                 return 1;
193         return 0;
194 }
195
196 #define SUMMARY_WIDTH (2 * DEFAULT_ABBREV + 3)
197 #define REFCOL_WIDTH  10
198
199 static int update_local_ref(struct ref *ref,
200                             const char *remote,
201                             int verbose,
202                             char *display)
203 {
204         struct commit *current = NULL, *updated;
205         enum object_type type;
206         struct branch *current_branch = branch_get(NULL);
207         const char *pretty_ref = ref->name + (
208                 !prefixcmp(ref->name, "refs/heads/") ? 11 :
209                 !prefixcmp(ref->name, "refs/tags/") ? 10 :
210                 !prefixcmp(ref->name, "refs/remotes/") ? 13 :
211                 0);
212
213         *display = 0;
214         type = sha1_object_info(ref->new_sha1, NULL);
215         if (type < 0)
216                 die("object %s not found", sha1_to_hex(ref->new_sha1));
217
218         if (!*ref->name) {
219                 /* Not storing */
220                 if (verbose)
221                         sprintf(display, "* branch %s -> FETCH_HEAD", remote);
222                 return 0;
223         }
224
225         if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
226                 if (verbose)
227                         sprintf(display, "= %-*s %-*s -> %s", SUMMARY_WIDTH,
228                                 "[up to date]", REFCOL_WIDTH, remote,
229                                 pretty_ref);
230                 return 0;
231         }
232
233         if (current_branch &&
234             !strcmp(ref->name, current_branch->name) &&
235             !(update_head_ok || is_bare_repository()) &&
236             !is_null_sha1(ref->old_sha1)) {
237                 /*
238                  * If this is the head, and it's not okay to update
239                  * the head, and the old value of the head isn't empty...
240                  */
241                 sprintf(display, "! %-*s %-*s -> %s  (can't fetch in current branch)",
242                         SUMMARY_WIDTH, "[rejected]", REFCOL_WIDTH, remote,
243                         pretty_ref);
244                 return 1;
245         }
246
247         if (!is_null_sha1(ref->old_sha1) &&
248             !prefixcmp(ref->name, "refs/tags/")) {
249                 sprintf(display, "- %-*s %-*s -> %s",
250                         SUMMARY_WIDTH, "[tag update]", REFCOL_WIDTH, remote,
251                         pretty_ref);
252                 return s_update_ref("updating tag", ref, 0);
253         }
254
255         current = lookup_commit_reference_gently(ref->old_sha1, 1);
256         updated = lookup_commit_reference_gently(ref->new_sha1, 1);
257         if (!current || !updated) {
258                 const char *msg;
259                 const char *what;
260                 if (!strncmp(ref->name, "refs/tags/", 10)) {
261                         msg = "storing tag";
262                         what = "[new tag]";
263                 }
264                 else {
265                         msg = "storing head";
266                         what = "[new branch]";
267                 }
268
269                 sprintf(display, "* %-*s %-*s -> %s", SUMMARY_WIDTH, what,
270                         REFCOL_WIDTH, remote, pretty_ref);
271                 return s_update_ref(msg, ref, 0);
272         }
273
274         if (in_merge_bases(current, &updated, 1)) {
275                 char quickref[83];
276                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
277                 strcat(quickref, "..");
278                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
279                 sprintf(display, "  %-*s %-*s -> %s", SUMMARY_WIDTH, quickref,
280                         REFCOL_WIDTH, remote, pretty_ref);
281                 return s_update_ref("fast forward", ref, 1);
282         } else if (force || ref->force) {
283                 char quickref[84];
284                 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
285                 strcat(quickref, "...");
286                 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
287                 sprintf(display, "+ %-*s %-*s -> %s  (forced update)",
288                         SUMMARY_WIDTH, quickref, REFCOL_WIDTH, remote, pretty_ref);
289                 return s_update_ref("forced-update", ref, 1);
290         } else {
291                 sprintf(display, "! %-*s %-*s -> %s  (non fast forward)",
292                         SUMMARY_WIDTH, "[rejected]", REFCOL_WIDTH, remote,
293                         pretty_ref);
294                 return 1;
295         }
296 }
297
298 static int store_updated_refs(const char *url, struct ref *ref_map)
299 {
300         FILE *fp;
301         struct commit *commit;
302         int url_len, i, note_len, shown_url = 0;
303         char note[1024];
304         const char *what, *kind;
305         struct ref *rm;
306         char *filename = git_path("FETCH_HEAD");
307
308         fp = fopen(filename, "a");
309         if (!fp)
310                 return error("cannot open %s: %s\n", filename, strerror(errno));
311         for (rm = ref_map; rm; rm = rm->next) {
312                 struct ref *ref = NULL;
313
314                 if (rm->peer_ref) {
315                         ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
316                         strcpy(ref->name, rm->peer_ref->name);
317                         hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
318                         hashcpy(ref->new_sha1, rm->old_sha1);
319                         ref->force = rm->peer_ref->force;
320                 }
321
322                 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
323                 if (!commit)
324                         rm->merge = 0;
325
326                 if (!strcmp(rm->name, "HEAD")) {
327                         kind = "";
328                         what = "";
329                 }
330                 else if (!prefixcmp(rm->name, "refs/heads/")) {
331                         kind = "branch";
332                         what = rm->name + 11;
333                 }
334                 else if (!prefixcmp(rm->name, "refs/tags/")) {
335                         kind = "tag";
336                         what = rm->name + 10;
337                 }
338                 else if (!prefixcmp(rm->name, "refs/remotes/")) {
339                         kind = "remote branch";
340                         what = rm->name + 13;
341                 }
342                 else {
343                         kind = "";
344                         what = rm->name;
345                 }
346
347                 url_len = strlen(url);
348                 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
349                         ;
350                 url_len = i + 1;
351                 if (4 < i && !strncmp(".git", url + i - 3, 4))
352                         url_len = i - 3;
353
354                 note_len = 0;
355                 if (*what) {
356                         if (*kind)
357                                 note_len += sprintf(note + note_len, "%s ",
358                                                     kind);
359                         note_len += sprintf(note + note_len, "'%s' of ", what);
360                 }
361                 note_len += sprintf(note + note_len, "%.*s", url_len, url);
362                 fprintf(fp, "%s\t%s\t%s\n",
363                         sha1_to_hex(commit ? commit->object.sha1 :
364                                     rm->old_sha1),
365                         rm->merge ? "" : "not-for-merge",
366                         note);
367
368                 if (ref) {
369                         update_local_ref(ref, what, verbose, note);
370                         if (*note) {
371                                 if (!shown_url) {
372                                         fprintf(stderr, "From %.*s\n",
373                                                         url_len, url);
374                                         shown_url = 1;
375                                 }
376                                 fprintf(stderr, " %s\n", note);
377                         }
378                 }
379         }
380         fclose(fp);
381         return 0;
382 }
383
384 /*
385  * We would want to bypass the object transfer altogether if
386  * everything we are going to fetch already exists and connected
387  * locally.
388  *
389  * The refs we are going to fetch are in to_fetch (nr_heads in
390  * total).  If running
391  *
392  *  $ git-rev-list --objects to_fetch[0] to_fetch[1] ... --not --all
393  *
394  * does not error out, that means everything reachable from the
395  * refs we are going to fetch exists and is connected to some of
396  * our existing refs.
397  */
398 static int quickfetch(struct ref *ref_map)
399 {
400         struct child_process revlist;
401         struct ref *ref;
402         char **argv;
403         int i, err;
404
405         /*
406          * If we are deepening a shallow clone we already have these
407          * objects reachable.  Running rev-list here will return with
408          * a good (0) exit status and we'll bypass the fetch that we
409          * really need to perform.  Claiming failure now will ensure
410          * we perform the network exchange to deepen our history.
411          */
412         if (depth)
413                 return -1;
414
415         for (i = 0, ref = ref_map; ref; ref = ref->next)
416                 i++;
417         if (!i)
418                 return 0;
419
420         argv = xmalloc(sizeof(*argv) * (i + 6));
421         i = 0;
422         argv[i++] = xstrdup("rev-list");
423         argv[i++] = xstrdup("--quiet");
424         argv[i++] = xstrdup("--objects");
425         for (ref = ref_map; ref; ref = ref->next)
426                 argv[i++] = xstrdup(sha1_to_hex(ref->old_sha1));
427         argv[i++] = xstrdup("--not");
428         argv[i++] = xstrdup("--all");
429         argv[i++] = NULL;
430
431         memset(&revlist, 0, sizeof(revlist));
432         revlist.argv = (const char**)argv;
433         revlist.git_cmd = 1;
434         revlist.no_stdin = 1;
435         revlist.no_stdout = 1;
436         revlist.no_stderr = 1;
437         err = run_command(&revlist);
438
439         for (i = 0; argv[i]; i++)
440                 free(argv[i]);
441         free(argv);
442         return err;
443 }
444
445 static int fetch_refs(struct transport *transport, struct ref *ref_map)
446 {
447         int ret = quickfetch(ref_map);
448         if (ret)
449                 ret = transport_fetch_refs(transport, ref_map);
450         if (!ret)
451                 ret |= store_updated_refs(transport->url, ref_map);
452         transport_unlock_pack(transport);
453         return ret;
454 }
455
456 static int add_existing(const char *refname, const unsigned char *sha1,
457                         int flag, void *cbdata)
458 {
459         struct path_list *list = (struct path_list *)cbdata;
460         path_list_insert(refname, list);
461         return 0;
462 }
463
464 static int will_fetch(struct ref **head, const unsigned char *sha1)
465 {
466         struct ref *rm = *head;
467         while (rm) {
468                 if (!hashcmp(rm->old_sha1, sha1))
469                         return 1;
470                 rm = rm->next;
471         }
472         return 0;
473 }
474
475 static void find_non_local_tags(struct transport *transport,
476                         struct ref **head,
477                         struct ref ***tail)
478 {
479         struct path_list existing_refs = { NULL, 0, 0, 0 };
480         struct path_list new_refs = { NULL, 0, 0, 1 };
481         char *ref_name;
482         int ref_name_len;
483         const unsigned char *ref_sha1;
484         const struct ref *tag_ref;
485         struct ref *rm = NULL;
486         const struct ref *ref;
487
488         for_each_ref(add_existing, &existing_refs);
489         for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
490                 if (prefixcmp(ref->name, "refs/tags"))
491                         continue;
492
493                 ref_name = xstrdup(ref->name);
494                 ref_name_len = strlen(ref_name);
495                 ref_sha1 = ref->old_sha1;
496
497                 if (!strcmp(ref_name + ref_name_len - 3, "^{}")) {
498                         ref_name[ref_name_len - 3] = 0;
499                         tag_ref = transport_get_remote_refs(transport);
500                         while (tag_ref) {
501                                 if (!strcmp(tag_ref->name, ref_name)) {
502                                         ref_sha1 = tag_ref->old_sha1;
503                                         break;
504                                 }
505                                 tag_ref = tag_ref->next;
506                         }
507                 }
508
509                 if (!path_list_has_path(&existing_refs, ref_name) &&
510                     !path_list_has_path(&new_refs, ref_name) &&
511                     (has_sha1_file(ref->old_sha1) ||
512                      will_fetch(head, ref->old_sha1))) {
513                         path_list_insert(ref_name, &new_refs);
514
515                         rm = alloc_ref(strlen(ref_name) + 1);
516                         strcpy(rm->name, ref_name);
517                         rm->peer_ref = alloc_ref(strlen(ref_name) + 1);
518                         strcpy(rm->peer_ref->name, ref_name);
519                         hashcpy(rm->old_sha1, ref_sha1);
520
521                         **tail = rm;
522                         *tail = &rm->next;
523                 }
524                 free(ref_name);
525         }
526         path_list_clear(&existing_refs, 0);
527         path_list_clear(&new_refs, 0);
528 }
529
530 static int do_fetch(struct transport *transport,
531                     struct refspec *refs, int ref_count)
532 {
533         struct ref *ref_map;
534         struct ref *rm;
535         int autotags = (transport->remote->fetch_tags == 1);
536         if (transport->remote->fetch_tags == 2 && tags != TAGS_UNSET)
537                 tags = TAGS_SET;
538         if (transport->remote->fetch_tags == -1)
539                 tags = TAGS_UNSET;
540
541         if (!transport->get_refs_list || !transport->fetch)
542                 die("Don't know how to fetch from %s", transport->url);
543
544         /* if not appending, truncate FETCH_HEAD */
545         if (!append) {
546                 char *filename = git_path("FETCH_HEAD");
547                 FILE *fp = fopen(filename, "w");
548                 if (!fp)
549                         return error("cannot open %s: %s\n", filename, strerror(errno));
550                 fclose(fp);
551         }
552
553         ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
554
555         for (rm = ref_map; rm; rm = rm->next) {
556                 if (rm->peer_ref)
557                         read_ref(rm->peer_ref->name, rm->peer_ref->old_sha1);
558         }
559
560         if (tags == TAGS_DEFAULT && autotags)
561                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
562         if (fetch_refs(transport, ref_map)) {
563                 free_refs(ref_map);
564                 return 1;
565         }
566         free_refs(ref_map);
567
568         /* if neither --no-tags nor --tags was specified, do automated tag
569          * following ... */
570         if (tags == TAGS_DEFAULT && autotags) {
571                 struct ref **tail = &ref_map;
572                 ref_map = NULL;
573                 find_non_local_tags(transport, &ref_map, &tail);
574                 if (ref_map) {
575                         transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
576                         transport_set_option(transport, TRANS_OPT_DEPTH, "0");
577                         fetch_refs(transport, ref_map);
578                 }
579                 free_refs(ref_map);
580         }
581
582         transport_disconnect(transport);
583
584         return 0;
585 }
586
587 static void set_option(const char *name, const char *value)
588 {
589         int r = transport_set_option(transport, name, value);
590         if (r < 0)
591                 die("Option \"%s\" value \"%s\" is not valid for %s\n",
592                         name, value, transport->url);
593         if (r > 0)
594                 warning("Option \"%s\" is ignored for %s\n",
595                         name, transport->url);
596 }
597
598 int cmd_fetch(int argc, const char **argv, const char *prefix)
599 {
600         struct remote *remote;
601         int i;
602         static const char **refs = NULL;
603         int ref_nr = 0;
604
605         /* Record the command line for the reflog */
606         strbuf_addstr(&default_rla, "fetch");
607         for (i = 1; i < argc; i++)
608                 strbuf_addf(&default_rla, " %s", argv[i]);
609
610         argc = parse_options(argc, argv,
611                              builtin_fetch_options, builtin_fetch_usage, 0);
612
613         if (argc == 0)
614                 remote = remote_get(NULL);
615         else
616                 remote = remote_get(argv[0]);
617
618         transport = transport_get(remote, remote->url[0]);
619         if (verbose >= 2)
620                 transport->verbose = 1;
621         if (quiet)
622                 transport->verbose = -1;
623         if (upload_pack)
624                 set_option(TRANS_OPT_UPLOADPACK, upload_pack);
625         if (keep)
626                 set_option(TRANS_OPT_KEEP, "yes");
627         if (depth)
628                 set_option(TRANS_OPT_DEPTH, depth);
629
630         if (!transport->url)
631                 die("Where do you want to fetch from today?");
632
633         if (argc > 1) {
634                 int j = 0;
635                 refs = xcalloc(argc + 1, sizeof(const char *));
636                 for (i = 1; i < argc; i++) {
637                         if (!strcmp(argv[i], "tag")) {
638                                 char *ref;
639                                 i++;
640                                 ref = xmalloc(strlen(argv[i]) * 2 + 22);
641                                 strcpy(ref, "refs/tags/");
642                                 strcat(ref, argv[i]);
643                                 strcat(ref, ":refs/tags/");
644                                 strcat(ref, argv[i]);
645                                 refs[j++] = ref;
646                         } else
647                                 refs[j++] = argv[i];
648                 }
649                 refs[j] = NULL;
650                 ref_nr = j;
651         }
652
653         signal(SIGINT, unlock_pack_on_signal);
654         atexit(unlock_pack);
655         return do_fetch(transport,
656                         parse_fetch_refspec(ref_nr, refs), ref_nr);
657 }