Merge branch 'jk/refspecs-negative'
[git] / bundle.c
1 #include "cache.h"
2 #include "lockfile.h"
3 #include "bundle.h"
4 #include "object-store.h"
5 #include "repository.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "diff.h"
9 #include "revision.h"
10 #include "list-objects.h"
11 #include "run-command.h"
12 #include "refs.h"
13 #include "strvec.h"
14
15
16 static const char v2_bundle_signature[] = "# v2 git bundle\n";
17 static const char v3_bundle_signature[] = "# v3 git bundle\n";
18 static struct {
19         int version;
20         const char *signature;
21 } bundle_sigs[] = {
22         { 2, v2_bundle_signature },
23         { 3, v3_bundle_signature },
24 };
25
26 static void add_to_ref_list(const struct object_id *oid, const char *name,
27                 struct ref_list *list)
28 {
29         ALLOC_GROW(list->list, list->nr + 1, list->alloc);
30         oidcpy(&list->list[list->nr].oid, oid);
31         list->list[list->nr].name = xstrdup(name);
32         list->nr++;
33 }
34
35 static int parse_capability(struct bundle_header *header, const char *capability)
36 {
37         const char *arg;
38         if (skip_prefix(capability, "object-format=", &arg)) {
39                 int algo = hash_algo_by_name(arg);
40                 if (algo == GIT_HASH_UNKNOWN)
41                         return error(_("unrecognized bundle hash algorithm: %s"), arg);
42                 header->hash_algo = &hash_algos[algo];
43                 return 0;
44         }
45         return error(_("unknown capability '%s'"), capability);
46 }
47
48 static int parse_bundle_signature(struct bundle_header *header, const char *line)
49 {
50         int i;
51
52         for (i = 0; i < ARRAY_SIZE(bundle_sigs); i++) {
53                 if (!strcmp(line, bundle_sigs[i].signature)) {
54                         header->version = bundle_sigs[i].version;
55                         return 0;
56                 }
57         }
58         return -1;
59 }
60
61 static int parse_bundle_header(int fd, struct bundle_header *header,
62                                const char *report_path)
63 {
64         struct strbuf buf = STRBUF_INIT;
65         int status = 0;
66
67         /* The bundle header begins with the signature */
68         if (strbuf_getwholeline_fd(&buf, fd, '\n') ||
69             parse_bundle_signature(header, buf.buf)) {
70                 if (report_path)
71                         error(_("'%s' does not look like a v2 or v3 bundle file"),
72                               report_path);
73                 status = -1;
74                 goto abort;
75         }
76
77         header->hash_algo = the_hash_algo;
78
79         /* The bundle header ends with an empty line */
80         while (!strbuf_getwholeline_fd(&buf, fd, '\n') &&
81                buf.len && buf.buf[0] != '\n') {
82                 struct object_id oid;
83                 int is_prereq = 0;
84                 const char *p;
85
86                 strbuf_rtrim(&buf);
87
88                 if (header->version == 3 && *buf.buf == '@') {
89                         if (parse_capability(header, buf.buf + 1)) {
90                                 status = -1;
91                                 break;
92                         }
93                         continue;
94                 }
95
96                 if (*buf.buf == '-') {
97                         is_prereq = 1;
98                         strbuf_remove(&buf, 0, 1);
99                 }
100
101                 /*
102                  * Tip lines have object name, SP, and refname.
103                  * Prerequisites have object name that is optionally
104                  * followed by SP and subject line.
105                  */
106                 if (parse_oid_hex_algop(buf.buf, &oid, &p, header->hash_algo) ||
107                     (*p && !isspace(*p)) ||
108                     (!is_prereq && !*p)) {
109                         if (report_path)
110                                 error(_("unrecognized header: %s%s (%d)"),
111                                       (is_prereq ? "-" : ""), buf.buf, (int)buf.len);
112                         status = -1;
113                         break;
114                 } else {
115                         if (is_prereq)
116                                 add_to_ref_list(&oid, "", &header->prerequisites);
117                         else
118                                 add_to_ref_list(&oid, p + 1, &header->references);
119                 }
120         }
121
122  abort:
123         if (status) {
124                 close(fd);
125                 fd = -1;
126         }
127         strbuf_release(&buf);
128         return fd;
129 }
130
131 int read_bundle_header(const char *path, struct bundle_header *header)
132 {
133         int fd = open(path, O_RDONLY);
134
135         if (fd < 0)
136                 return error(_("could not open '%s'"), path);
137         return parse_bundle_header(fd, header, path);
138 }
139
140 int is_bundle(const char *path, int quiet)
141 {
142         struct bundle_header header;
143         int fd = open(path, O_RDONLY);
144
145         if (fd < 0)
146                 return 0;
147         memset(&header, 0, sizeof(header));
148         fd = parse_bundle_header(fd, &header, quiet ? NULL : path);
149         if (fd >= 0)
150                 close(fd);
151         return (fd >= 0);
152 }
153
154 static int list_refs(struct ref_list *r, int argc, const char **argv)
155 {
156         int i;
157
158         for (i = 0; i < r->nr; i++) {
159                 if (argc > 1) {
160                         int j;
161                         for (j = 1; j < argc; j++)
162                                 if (!strcmp(r->list[i].name, argv[j]))
163                                         break;
164                         if (j == argc)
165                                 continue;
166                 }
167                 printf("%s %s\n", oid_to_hex(&r->list[i].oid),
168                                 r->list[i].name);
169         }
170         return 0;
171 }
172
173 /* Remember to update object flag allocation in object.h */
174 #define PREREQ_MARK (1u<<16)
175
176 int verify_bundle(struct repository *r,
177                   struct bundle_header *header,
178                   int verbose)
179 {
180         /*
181          * Do fast check, then if any prereqs are missing then go line by line
182          * to be verbose about the errors
183          */
184         struct ref_list *p = &header->prerequisites;
185         struct rev_info revs;
186         const char *argv[] = {NULL, "--all", NULL};
187         struct commit *commit;
188         int i, ret = 0, req_nr;
189         const char *message = _("Repository lacks these prerequisite commits:");
190
191         if (!r || !r->objects || !r->objects->odb)
192                 return error(_("need a repository to verify a bundle"));
193
194         repo_init_revisions(r, &revs, NULL);
195         for (i = 0; i < p->nr; i++) {
196                 struct ref_list_entry *e = p->list + i;
197                 struct object *o = parse_object(r, &e->oid);
198                 if (o) {
199                         o->flags |= PREREQ_MARK;
200                         add_pending_object(&revs, o, e->name);
201                         continue;
202                 }
203                 if (++ret == 1)
204                         error("%s", message);
205                 error("%s %s", oid_to_hex(&e->oid), e->name);
206         }
207         if (revs.pending.nr != p->nr)
208                 return ret;
209         req_nr = revs.pending.nr;
210         setup_revisions(2, argv, &revs, NULL);
211
212         if (prepare_revision_walk(&revs))
213                 die(_("revision walk setup failed"));
214
215         i = req_nr;
216         while (i && (commit = get_revision(&revs)))
217                 if (commit->object.flags & PREREQ_MARK)
218                         i--;
219
220         for (i = 0; i < p->nr; i++) {
221                 struct ref_list_entry *e = p->list + i;
222                 struct object *o = parse_object(r, &e->oid);
223                 assert(o); /* otherwise we'd have returned early */
224                 if (o->flags & SHOWN)
225                         continue;
226                 if (++ret == 1)
227                         error("%s", message);
228                 error("%s %s", oid_to_hex(&e->oid), e->name);
229         }
230
231         /* Clean up objects used, as they will be reused. */
232         for (i = 0; i < p->nr; i++) {
233                 struct ref_list_entry *e = p->list + i;
234                 commit = lookup_commit_reference_gently(r, &e->oid, 1);
235                 if (commit)
236                         clear_commit_marks(commit, ALL_REV_FLAGS);
237         }
238
239         if (verbose) {
240                 struct ref_list *r;
241
242                 r = &header->references;
243                 printf_ln(Q_("The bundle contains this ref:",
244                              "The bundle contains these %d refs:",
245                              r->nr),
246                           r->nr);
247                 list_refs(r, 0, NULL);
248                 r = &header->prerequisites;
249                 if (!r->nr) {
250                         printf_ln(_("The bundle records a complete history."));
251                 } else {
252                         printf_ln(Q_("The bundle requires this ref:",
253                                      "The bundle requires these %d refs:",
254                                      r->nr),
255                                   r->nr);
256                         list_refs(r, 0, NULL);
257                 }
258         }
259         return ret;
260 }
261
262 int list_bundle_refs(struct bundle_header *header, int argc, const char **argv)
263 {
264         return list_refs(&header->references, argc, argv);
265 }
266
267 static int is_tag_in_date_range(struct object *tag, struct rev_info *revs)
268 {
269         unsigned long size;
270         enum object_type type;
271         char *buf = NULL, *line, *lineend;
272         timestamp_t date;
273         int result = 1;
274
275         if (revs->max_age == -1 && revs->min_age == -1)
276                 goto out;
277
278         buf = read_object_file(&tag->oid, &type, &size);
279         if (!buf)
280                 goto out;
281         line = memmem(buf, size, "\ntagger ", 8);
282         if (!line++)
283                 goto out;
284         lineend = memchr(line, '\n', buf + size - line);
285         line = memchr(line, '>', lineend ? lineend - line : buf + size - line);
286         if (!line++)
287                 goto out;
288         date = parse_timestamp(line, NULL, 10);
289         result = (revs->max_age == -1 || revs->max_age < date) &&
290                 (revs->min_age == -1 || revs->min_age > date);
291 out:
292         free(buf);
293         return result;
294 }
295
296
297 /* Write the pack data to bundle_fd */
298 static int write_pack_data(int bundle_fd, struct rev_info *revs, struct strvec *pack_options)
299 {
300         struct child_process pack_objects = CHILD_PROCESS_INIT;
301         int i;
302
303         strvec_pushl(&pack_objects.args,
304                      "pack-objects",
305                      "--stdout", "--thin", "--delta-base-offset",
306                      NULL);
307         strvec_pushv(&pack_objects.args, pack_options->v);
308         pack_objects.in = -1;
309         pack_objects.out = bundle_fd;
310         pack_objects.git_cmd = 1;
311
312         /*
313          * start_command() will close our descriptor if it's >1. Duplicate it
314          * to avoid surprising the caller.
315          */
316         if (pack_objects.out > 1) {
317                 pack_objects.out = dup(pack_objects.out);
318                 if (pack_objects.out < 0) {
319                         error_errno(_("unable to dup bundle descriptor"));
320                         child_process_clear(&pack_objects);
321                         return -1;
322                 }
323         }
324
325         if (start_command(&pack_objects))
326                 return error(_("Could not spawn pack-objects"));
327
328         for (i = 0; i < revs->pending.nr; i++) {
329                 struct object *object = revs->pending.objects[i].item;
330                 if (object->flags & UNINTERESTING)
331                         write_or_die(pack_objects.in, "^", 1);
332                 write_or_die(pack_objects.in, oid_to_hex(&object->oid), the_hash_algo->hexsz);
333                 write_or_die(pack_objects.in, "\n", 1);
334         }
335         close(pack_objects.in);
336         if (finish_command(&pack_objects))
337                 return error(_("pack-objects died"));
338         return 0;
339 }
340
341 static int compute_and_write_prerequisites(int bundle_fd,
342                                            struct rev_info *revs,
343                                            int argc, const char **argv)
344 {
345         struct child_process rls = CHILD_PROCESS_INIT;
346         struct strbuf buf = STRBUF_INIT;
347         FILE *rls_fout;
348         int i;
349
350         strvec_pushl(&rls.args,
351                      "rev-list", "--boundary", "--pretty=oneline",
352                      NULL);
353         for (i = 1; i < argc; i++)
354                 strvec_push(&rls.args, argv[i]);
355         rls.out = -1;
356         rls.git_cmd = 1;
357         if (start_command(&rls))
358                 return -1;
359         rls_fout = xfdopen(rls.out, "r");
360         while (strbuf_getwholeline(&buf, rls_fout, '\n') != EOF) {
361                 struct object_id oid;
362                 if (buf.len > 0 && buf.buf[0] == '-') {
363                         write_or_die(bundle_fd, buf.buf, buf.len);
364                         if (!get_oid_hex(buf.buf + 1, &oid)) {
365                                 struct object *object = parse_object_or_die(&oid,
366                                                                             buf.buf);
367                                 object->flags |= UNINTERESTING;
368                                 add_pending_object(revs, object, buf.buf);
369                         }
370                 } else if (!get_oid_hex(buf.buf, &oid)) {
371                         struct object *object = parse_object_or_die(&oid,
372                                                                     buf.buf);
373                         object->flags |= SHOWN;
374                 }
375         }
376         strbuf_release(&buf);
377         fclose(rls_fout);
378         if (finish_command(&rls))
379                 return error(_("rev-list died"));
380         return 0;
381 }
382
383 /*
384  * Write out bundle refs based on the tips already
385  * parsed into revs.pending. As a side effect, may
386  * manipulate revs.pending to include additional
387  * necessary objects (like tags).
388  *
389  * Returns the number of refs written, or negative
390  * on error.
391  */
392 static int write_bundle_refs(int bundle_fd, struct rev_info *revs)
393 {
394         int i;
395         int ref_count = 0;
396
397         for (i = 0; i < revs->pending.nr; i++) {
398                 struct object_array_entry *e = revs->pending.objects + i;
399                 struct object_id oid;
400                 char *ref;
401                 const char *display_ref;
402                 int flag;
403
404                 if (e->item->flags & UNINTERESTING)
405                         continue;
406                 if (dwim_ref(e->name, strlen(e->name), &oid, &ref, 0) != 1)
407                         goto skip_write_ref;
408                 if (read_ref_full(e->name, RESOLVE_REF_READING, &oid, &flag))
409                         flag = 0;
410                 display_ref = (flag & REF_ISSYMREF) ? e->name : ref;
411
412                 if (e->item->type == OBJ_TAG &&
413                                 !is_tag_in_date_range(e->item, revs)) {
414                         e->item->flags |= UNINTERESTING;
415                         goto skip_write_ref;
416                 }
417
418                 /*
419                  * Make sure the refs we wrote out is correct; --max-count and
420                  * other limiting options could have prevented all the tips
421                  * from getting output.
422                  *
423                  * Non commit objects such as tags and blobs do not have
424                  * this issue as they are not affected by those extra
425                  * constraints.
426                  */
427                 if (!(e->item->flags & SHOWN) && e->item->type == OBJ_COMMIT) {
428                         warning(_("ref '%s' is excluded by the rev-list options"),
429                                 e->name);
430                         goto skip_write_ref;
431                 }
432                 /*
433                  * If you run "git bundle create bndl v1.0..v2.0", the
434                  * name of the positive ref is "v2.0" but that is the
435                  * commit that is referenced by the tag, and not the tag
436                  * itself.
437                  */
438                 if (!oideq(&oid, &e->item->oid)) {
439                         /*
440                          * Is this the positive end of a range expressed
441                          * in terms of a tag (e.g. v2.0 from the range
442                          * "v1.0..v2.0")?
443                          */
444                         struct commit *one = lookup_commit_reference(revs->repo, &oid);
445                         struct object *obj;
446
447                         if (e->item == &(one->object)) {
448                                 /*
449                                  * Need to include e->name as an
450                                  * independent ref to the pack-objects
451                                  * input, so that the tag is included
452                                  * in the output; otherwise we would
453                                  * end up triggering "empty bundle"
454                                  * error.
455                                  */
456                                 obj = parse_object_or_die(&oid, e->name);
457                                 obj->flags |= SHOWN;
458                                 add_pending_object(revs, obj, e->name);
459                         }
460                         goto skip_write_ref;
461                 }
462
463                 ref_count++;
464                 write_or_die(bundle_fd, oid_to_hex(&e->item->oid), the_hash_algo->hexsz);
465                 write_or_die(bundle_fd, " ", 1);
466                 write_or_die(bundle_fd, display_ref, strlen(display_ref));
467                 write_or_die(bundle_fd, "\n", 1);
468  skip_write_ref:
469                 free(ref);
470         }
471
472         /* end header */
473         write_or_die(bundle_fd, "\n", 1);
474         return ref_count;
475 }
476
477 int create_bundle(struct repository *r, const char *path,
478                   int argc, const char **argv, struct strvec *pack_options, int version)
479 {
480         struct lock_file lock = LOCK_INIT;
481         int bundle_fd = -1;
482         int bundle_to_stdout;
483         int ref_count = 0;
484         struct rev_info revs;
485         int min_version = the_hash_algo == &hash_algos[GIT_HASH_SHA1] ? 2 : 3;
486
487         bundle_to_stdout = !strcmp(path, "-");
488         if (bundle_to_stdout)
489                 bundle_fd = 1;
490         else
491                 bundle_fd = hold_lock_file_for_update(&lock, path,
492                                                       LOCK_DIE_ON_ERROR);
493
494         if (version == -1)
495                 version = min_version;
496
497         if (version < 2 || version > 3) {
498                 die(_("unsupported bundle version %d"), version);
499         } else if (version < min_version) {
500                 die(_("cannot write bundle version %d with algorithm %s"), version, the_hash_algo->name);
501         } else if (version == 2) {
502                 write_or_die(bundle_fd, v2_bundle_signature, strlen(v2_bundle_signature));
503         } else {
504                 const char *capability = "@object-format=";
505                 write_or_die(bundle_fd, v3_bundle_signature, strlen(v3_bundle_signature));
506                 write_or_die(bundle_fd, capability, strlen(capability));
507                 write_or_die(bundle_fd, the_hash_algo->name, strlen(the_hash_algo->name));
508                 write_or_die(bundle_fd, "\n", 1);
509         }
510
511         /* init revs to list objects for pack-objects later */
512         save_commit_buffer = 0;
513         repo_init_revisions(r, &revs, NULL);
514
515         /* write prerequisites */
516         if (compute_and_write_prerequisites(bundle_fd, &revs, argc, argv))
517                 goto err;
518
519         argc = setup_revisions(argc, argv, &revs, NULL);
520
521         if (argc > 1) {
522                 error(_("unrecognized argument: %s"), argv[1]);
523                 goto err;
524         }
525
526         object_array_remove_duplicates(&revs.pending);
527
528         ref_count = write_bundle_refs(bundle_fd, &revs);
529         if (!ref_count)
530                 die(_("Refusing to create empty bundle."));
531         else if (ref_count < 0)
532                 goto err;
533
534         /* write pack */
535         if (write_pack_data(bundle_fd, &revs, pack_options))
536                 goto err;
537
538         if (!bundle_to_stdout) {
539                 if (commit_lock_file(&lock))
540                         die_errno(_("cannot create '%s'"), path);
541         }
542         return 0;
543 err:
544         rollback_lock_file(&lock);
545         return -1;
546 }
547
548 int unbundle(struct repository *r, struct bundle_header *header,
549              int bundle_fd, int flags)
550 {
551         const char *argv_index_pack[] = {"index-pack",
552                                          "--fix-thin", "--stdin", NULL, NULL};
553         struct child_process ip = CHILD_PROCESS_INIT;
554
555         if (flags & BUNDLE_VERBOSE)
556                 argv_index_pack[3] = "-v";
557
558         if (verify_bundle(r, header, 0))
559                 return -1;
560         ip.argv = argv_index_pack;
561         ip.in = bundle_fd;
562         ip.no_stdout = 1;
563         ip.git_cmd = 1;
564         if (run_command(&ip))
565                 return error(_("index-pack died"));
566         return 0;
567 }