Merge branch 'jt/connectivity-check-optim-in-partial-clone'
[git] / builtin / fast-export.c
1 /*
2  * "git fast-export" builtin command
3  *
4  * Copyright (C) 2007 Johannes E. Schindelin
5  */
6 #include "builtin.h"
7 #include "cache.h"
8 #include "config.h"
9 #include "refs.h"
10 #include "refspec.h"
11 #include "object-store.h"
12 #include "commit.h"
13 #include "object.h"
14 #include "tag.h"
15 #include "diff.h"
16 #include "diffcore.h"
17 #include "log-tree.h"
18 #include "revision.h"
19 #include "decorate.h"
20 #include "string-list.h"
21 #include "utf8.h"
22 #include "parse-options.h"
23 #include "quote.h"
24 #include "remote.h"
25 #include "blob.h"
26 #include "commit-slab.h"
27
28 static const char *fast_export_usage[] = {
29         N_("git fast-export [rev-list-opts]"),
30         NULL
31 };
32
33 static int progress;
34 static enum { SIGNED_TAG_ABORT, VERBATIM, WARN, WARN_STRIP, STRIP } signed_tag_mode = SIGNED_TAG_ABORT;
35 static enum { TAG_FILTERING_ABORT, DROP, REWRITE } tag_of_filtered_mode = TAG_FILTERING_ABORT;
36 static enum { REENCODE_ABORT, REENCODE_YES, REENCODE_NO } reencode_mode = REENCODE_ABORT;
37 static int fake_missing_tagger;
38 static int use_done_feature;
39 static int no_data;
40 static int full_tree;
41 static int reference_excluded_commits;
42 static int show_original_ids;
43 static int mark_tags;
44 static struct string_list extra_refs = STRING_LIST_INIT_NODUP;
45 static struct string_list tag_refs = STRING_LIST_INIT_NODUP;
46 static struct refspec refspecs = REFSPEC_INIT_FETCH;
47 static int anonymize;
48 static struct revision_sources revision_sources;
49
50 static int parse_opt_signed_tag_mode(const struct option *opt,
51                                      const char *arg, int unset)
52 {
53         if (unset || !strcmp(arg, "abort"))
54                 signed_tag_mode = SIGNED_TAG_ABORT;
55         else if (!strcmp(arg, "verbatim") || !strcmp(arg, "ignore"))
56                 signed_tag_mode = VERBATIM;
57         else if (!strcmp(arg, "warn"))
58                 signed_tag_mode = WARN;
59         else if (!strcmp(arg, "warn-strip"))
60                 signed_tag_mode = WARN_STRIP;
61         else if (!strcmp(arg, "strip"))
62                 signed_tag_mode = STRIP;
63         else
64                 return error("Unknown signed-tags mode: %s", arg);
65         return 0;
66 }
67
68 static int parse_opt_tag_of_filtered_mode(const struct option *opt,
69                                           const char *arg, int unset)
70 {
71         if (unset || !strcmp(arg, "abort"))
72                 tag_of_filtered_mode = TAG_FILTERING_ABORT;
73         else if (!strcmp(arg, "drop"))
74                 tag_of_filtered_mode = DROP;
75         else if (!strcmp(arg, "rewrite"))
76                 tag_of_filtered_mode = REWRITE;
77         else
78                 return error("Unknown tag-of-filtered mode: %s", arg);
79         return 0;
80 }
81
82 static int parse_opt_reencode_mode(const struct option *opt,
83                                    const char *arg, int unset)
84 {
85         if (unset) {
86                 reencode_mode = REENCODE_ABORT;
87                 return 0;
88         }
89
90         switch (git_parse_maybe_bool(arg)) {
91         case 0:
92                 reencode_mode = REENCODE_NO;
93                 break;
94         case 1:
95                 reencode_mode = REENCODE_YES;
96                 break;
97         default:
98                 if (!strcasecmp(arg, "abort"))
99                         reencode_mode = REENCODE_ABORT;
100                 else
101                         return error("Unknown reencoding mode: %s", arg);
102         }
103
104         return 0;
105 }
106
107 static struct decoration idnums;
108 static uint32_t last_idnum;
109
110 static int has_unshown_parent(struct commit *commit)
111 {
112         struct commit_list *parent;
113
114         for (parent = commit->parents; parent; parent = parent->next)
115                 if (!(parent->item->object.flags & SHOWN) &&
116                     !(parent->item->object.flags & UNINTERESTING))
117                         return 1;
118         return 0;
119 }
120
121 struct anonymized_entry {
122         struct hashmap_entry hash;
123         const char *orig;
124         size_t orig_len;
125         const char *anon;
126         size_t anon_len;
127 };
128
129 static int anonymized_entry_cmp(const void *unused_cmp_data,
130                                 const struct hashmap_entry *eptr,
131                                 const struct hashmap_entry *entry_or_key,
132                                 const void *unused_keydata)
133 {
134         const struct anonymized_entry *a, *b;
135
136         a = container_of(eptr, const struct anonymized_entry, hash);
137         b = container_of(entry_or_key, const struct anonymized_entry, hash);
138
139         return a->orig_len != b->orig_len ||
140                 memcmp(a->orig, b->orig, a->orig_len);
141 }
142
143 /*
144  * Basically keep a cache of X->Y so that we can repeatedly replace
145  * the same anonymized string with another. The actual generation
146  * is farmed out to the generate function.
147  */
148 static const void *anonymize_mem(struct hashmap *map,
149                                  void *(*generate)(const void *, size_t *),
150                                  const void *orig, size_t *len)
151 {
152         struct anonymized_entry key, *ret;
153
154         if (!map->cmpfn)
155                 hashmap_init(map, anonymized_entry_cmp, NULL, 0);
156
157         hashmap_entry_init(&key.hash, memhash(orig, *len));
158         key.orig = orig;
159         key.orig_len = *len;
160         ret = hashmap_get_entry(map, &key, hash, NULL);
161
162         if (!ret) {
163                 ret = xmalloc(sizeof(*ret));
164                 hashmap_entry_init(&ret->hash, key.hash.hash);
165                 ret->orig = xstrdup(orig);
166                 ret->orig_len = *len;
167                 ret->anon = generate(orig, len);
168                 ret->anon_len = *len;
169                 hashmap_put(map, &ret->hash);
170         }
171
172         *len = ret->anon_len;
173         return ret->anon;
174 }
175
176 /*
177  * We anonymize each component of a path individually,
178  * so that paths a/b and a/c will share a common root.
179  * The paths are cached via anonymize_mem so that repeated
180  * lookups for "a" will yield the same value.
181  */
182 static void anonymize_path(struct strbuf *out, const char *path,
183                            struct hashmap *map,
184                            void *(*generate)(const void *, size_t *))
185 {
186         while (*path) {
187                 const char *end_of_component = strchrnul(path, '/');
188                 size_t len = end_of_component - path;
189                 const char *c = anonymize_mem(map, generate, path, &len);
190                 strbuf_add(out, c, len);
191                 path = end_of_component;
192                 if (*path)
193                         strbuf_addch(out, *path++);
194         }
195 }
196
197 static inline void *mark_to_ptr(uint32_t mark)
198 {
199         return (void *)(uintptr_t)mark;
200 }
201
202 static inline uint32_t ptr_to_mark(void * mark)
203 {
204         return (uint32_t)(uintptr_t)mark;
205 }
206
207 static inline void mark_object(struct object *object, uint32_t mark)
208 {
209         add_decoration(&idnums, object, mark_to_ptr(mark));
210 }
211
212 static inline void mark_next_object(struct object *object)
213 {
214         mark_object(object, ++last_idnum);
215 }
216
217 static int get_object_mark(struct object *object)
218 {
219         void *decoration = lookup_decoration(&idnums, object);
220         if (!decoration)
221                 return 0;
222         return ptr_to_mark(decoration);
223 }
224
225 static struct commit *rewrite_commit(struct commit *p)
226 {
227         for (;;) {
228                 if (p->parents && p->parents->next)
229                         break;
230                 if (p->object.flags & UNINTERESTING)
231                         break;
232                 if (!(p->object.flags & TREESAME))
233                         break;
234                 if (!p->parents)
235                         return NULL;
236                 p = p->parents->item;
237         }
238         return p;
239 }
240
241 static void show_progress(void)
242 {
243         static int counter = 0;
244         if (!progress)
245                 return;
246         if ((++counter % progress) == 0)
247                 printf("progress %d objects\n", counter);
248 }
249
250 /*
251  * Ideally we would want some transformation of the blob data here
252  * that is unreversible, but would still be the same size and have
253  * the same data relationship to other blobs (so that we get the same
254  * delta and packing behavior as the original). But the first and last
255  * requirements there are probably mutually exclusive, so let's take
256  * the easy way out for now, and just generate arbitrary content.
257  *
258  * There's no need to cache this result with anonymize_mem, since
259  * we already handle blob content caching with marks.
260  */
261 static char *anonymize_blob(unsigned long *size)
262 {
263         static int counter;
264         struct strbuf out = STRBUF_INIT;
265         strbuf_addf(&out, "anonymous blob %d", counter++);
266         *size = out.len;
267         return strbuf_detach(&out, NULL);
268 }
269
270 static void export_blob(const struct object_id *oid)
271 {
272         unsigned long size;
273         enum object_type type;
274         char *buf;
275         struct object *object;
276         int eaten;
277
278         if (no_data)
279                 return;
280
281         if (is_null_oid(oid))
282                 return;
283
284         object = lookup_object(the_repository, oid);
285         if (object && object->flags & SHOWN)
286                 return;
287
288         if (anonymize) {
289                 buf = anonymize_blob(&size);
290                 object = (struct object *)lookup_blob(the_repository, oid);
291                 eaten = 0;
292         } else {
293                 buf = read_object_file(oid, &type, &size);
294                 if (!buf)
295                         die("could not read blob %s", oid_to_hex(oid));
296                 if (check_object_signature(oid, buf, size, type_name(type)) < 0)
297                         die("oid mismatch in blob %s", oid_to_hex(oid));
298                 object = parse_object_buffer(the_repository, oid, type,
299                                              size, buf, &eaten);
300         }
301
302         if (!object)
303                 die("Could not read blob %s", oid_to_hex(oid));
304
305         mark_next_object(object);
306
307         printf("blob\nmark :%"PRIu32"\n", last_idnum);
308         if (show_original_ids)
309                 printf("original-oid %s\n", oid_to_hex(oid));
310         printf("data %"PRIuMAX"\n", (uintmax_t)size);
311         if (size && fwrite(buf, size, 1, stdout) != 1)
312                 die_errno("could not write blob '%s'", oid_to_hex(oid));
313         printf("\n");
314
315         show_progress();
316
317         object->flags |= SHOWN;
318         if (!eaten)
319                 free(buf);
320 }
321
322 static int depth_first(const void *a_, const void *b_)
323 {
324         const struct diff_filepair *a = *((const struct diff_filepair **)a_);
325         const struct diff_filepair *b = *((const struct diff_filepair **)b_);
326         const char *name_a, *name_b;
327         int len_a, len_b, len;
328         int cmp;
329
330         name_a = a->one ? a->one->path : a->two->path;
331         name_b = b->one ? b->one->path : b->two->path;
332
333         len_a = strlen(name_a);
334         len_b = strlen(name_b);
335         len = (len_a < len_b) ? len_a : len_b;
336
337         /* strcmp will sort 'd' before 'd/e', we want 'd/e' before 'd' */
338         cmp = memcmp(name_a, name_b, len);
339         if (cmp)
340                 return cmp;
341         cmp = len_b - len_a;
342         if (cmp)
343                 return cmp;
344         /*
345          * Move 'R'ename entries last so that all references of the file
346          * appear in the output before it is renamed (e.g., when a file
347          * was copied and renamed in the same commit).
348          */
349         return (a->status == 'R') - (b->status == 'R');
350 }
351
352 static void print_path_1(const char *path)
353 {
354         int need_quote = quote_c_style(path, NULL, NULL, 0);
355         if (need_quote)
356                 quote_c_style(path, NULL, stdout, 0);
357         else if (strchr(path, ' '))
358                 printf("\"%s\"", path);
359         else
360                 printf("%s", path);
361 }
362
363 static void *anonymize_path_component(const void *path, size_t *len)
364 {
365         static int counter;
366         struct strbuf out = STRBUF_INIT;
367         strbuf_addf(&out, "path%d", counter++);
368         return strbuf_detach(&out, len);
369 }
370
371 static void print_path(const char *path)
372 {
373         if (!anonymize)
374                 print_path_1(path);
375         else {
376                 static struct hashmap paths;
377                 static struct strbuf anon = STRBUF_INIT;
378
379                 anonymize_path(&anon, path, &paths, anonymize_path_component);
380                 print_path_1(anon.buf);
381                 strbuf_reset(&anon);
382         }
383 }
384
385 static void *generate_fake_oid(const void *old, size_t *len)
386 {
387         static uint32_t counter = 1; /* avoid null oid */
388         const unsigned hashsz = the_hash_algo->rawsz;
389         unsigned char *out = xcalloc(hashsz, 1);
390         put_be32(out + hashsz - 4, counter++);
391         return out;
392 }
393
394 static const struct object_id *anonymize_oid(const struct object_id *oid)
395 {
396         static struct hashmap objs;
397         size_t len = the_hash_algo->rawsz;
398         return anonymize_mem(&objs, generate_fake_oid, oid, &len);
399 }
400
401 static void show_filemodify(struct diff_queue_struct *q,
402                             struct diff_options *options, void *data)
403 {
404         int i;
405         struct string_list *changed = data;
406
407         /*
408          * Handle files below a directory first, in case they are all deleted
409          * and the directory changes to a file or symlink.
410          */
411         QSORT(q->queue, q->nr, depth_first);
412
413         for (i = 0; i < q->nr; i++) {
414                 struct diff_filespec *ospec = q->queue[i]->one;
415                 struct diff_filespec *spec = q->queue[i]->two;
416
417                 switch (q->queue[i]->status) {
418                 case DIFF_STATUS_DELETED:
419                         printf("D ");
420                         print_path(spec->path);
421                         string_list_insert(changed, spec->path);
422                         putchar('\n');
423                         break;
424
425                 case DIFF_STATUS_COPIED:
426                 case DIFF_STATUS_RENAMED:
427                         /*
428                          * If a change in the file corresponding to ospec->path
429                          * has been observed, we cannot trust its contents
430                          * because the diff is calculated based on the prior
431                          * contents, not the current contents.  So, declare a
432                          * copy or rename only if there was no change observed.
433                          */
434                         if (!string_list_has_string(changed, ospec->path)) {
435                                 printf("%c ", q->queue[i]->status);
436                                 print_path(ospec->path);
437                                 putchar(' ');
438                                 print_path(spec->path);
439                                 string_list_insert(changed, spec->path);
440                                 putchar('\n');
441
442                                 if (oideq(&ospec->oid, &spec->oid) &&
443                                     ospec->mode == spec->mode)
444                                         break;
445                         }
446                         /* fallthrough */
447
448                 case DIFF_STATUS_TYPE_CHANGED:
449                 case DIFF_STATUS_MODIFIED:
450                 case DIFF_STATUS_ADDED:
451                         /*
452                          * Links refer to objects in another repositories;
453                          * output the SHA-1 verbatim.
454                          */
455                         if (no_data || S_ISGITLINK(spec->mode))
456                                 printf("M %06o %s ", spec->mode,
457                                        oid_to_hex(anonymize ?
458                                                   anonymize_oid(&spec->oid) :
459                                                   &spec->oid));
460                         else {
461                                 struct object *object = lookup_object(the_repository,
462                                                                       &spec->oid);
463                                 printf("M %06o :%d ", spec->mode,
464                                        get_object_mark(object));
465                         }
466                         print_path(spec->path);
467                         string_list_insert(changed, spec->path);
468                         putchar('\n');
469                         break;
470
471                 default:
472                         die("Unexpected comparison status '%c' for %s, %s",
473                                 q->queue[i]->status,
474                                 ospec->path ? ospec->path : "none",
475                                 spec->path ? spec->path : "none");
476                 }
477         }
478 }
479
480 static const char *find_encoding(const char *begin, const char *end)
481 {
482         const char *needle = "\nencoding ";
483         char *bol, *eol;
484
485         bol = memmem(begin, end ? end - begin : strlen(begin),
486                      needle, strlen(needle));
487         if (!bol)
488                 return NULL;
489         bol += strlen(needle);
490         eol = strchrnul(bol, '\n');
491         *eol = '\0';
492         return bol;
493 }
494
495 static void *anonymize_ref_component(const void *old, size_t *len)
496 {
497         static int counter;
498         struct strbuf out = STRBUF_INIT;
499         strbuf_addf(&out, "ref%d", counter++);
500         return strbuf_detach(&out, len);
501 }
502
503 static const char *anonymize_refname(const char *refname)
504 {
505         /*
506          * If any of these prefixes is found, we will leave it intact
507          * so that tags remain tags and so forth.
508          */
509         static const char *prefixes[] = {
510                 "refs/heads/",
511                 "refs/tags/",
512                 "refs/remotes/",
513                 "refs/"
514         };
515         static struct hashmap refs;
516         static struct strbuf anon = STRBUF_INIT;
517         int i;
518
519         /*
520          * We also leave "master" as a special case, since it does not reveal
521          * anything interesting.
522          */
523         if (!strcmp(refname, "refs/heads/master"))
524                 return refname;
525
526         strbuf_reset(&anon);
527         for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
528                 if (skip_prefix(refname, prefixes[i], &refname)) {
529                         strbuf_addstr(&anon, prefixes[i]);
530                         break;
531                 }
532         }
533
534         anonymize_path(&anon, refname, &refs, anonymize_ref_component);
535         return anon.buf;
536 }
537
538 /*
539  * We do not even bother to cache commit messages, as they are unlikely
540  * to be repeated verbatim, and it is not that interesting when they are.
541  */
542 static char *anonymize_commit_message(const char *old)
543 {
544         static int counter;
545         return xstrfmt("subject %d\n\nbody\n", counter++);
546 }
547
548 static struct hashmap idents;
549 static void *anonymize_ident(const void *old, size_t *len)
550 {
551         static int counter;
552         struct strbuf out = STRBUF_INIT;
553         strbuf_addf(&out, "User %d <user%d@example.com>", counter, counter);
554         counter++;
555         return strbuf_detach(&out, len);
556 }
557
558 /*
559  * Our strategy here is to anonymize the names and email addresses,
560  * but keep timestamps intact, as they influence things like traversal
561  * order (and by themselves should not be too revealing).
562  */
563 static void anonymize_ident_line(const char **beg, const char **end)
564 {
565         static struct strbuf buffers[] = { STRBUF_INIT, STRBUF_INIT };
566         static unsigned which_buffer;
567
568         struct strbuf *out;
569         struct ident_split split;
570         const char *end_of_header;
571
572         out = &buffers[which_buffer++];
573         which_buffer %= ARRAY_SIZE(buffers);
574         strbuf_reset(out);
575
576         /* skip "committer", "author", "tagger", etc */
577         end_of_header = strchr(*beg, ' ');
578         if (!end_of_header)
579                 BUG("malformed line fed to anonymize_ident_line: %.*s",
580                     (int)(*end - *beg), *beg);
581         end_of_header++;
582         strbuf_add(out, *beg, end_of_header - *beg);
583
584         if (!split_ident_line(&split, end_of_header, *end - end_of_header) &&
585             split.date_begin) {
586                 const char *ident;
587                 size_t len;
588
589                 len = split.mail_end - split.name_begin;
590                 ident = anonymize_mem(&idents, anonymize_ident,
591                                       split.name_begin, &len);
592                 strbuf_add(out, ident, len);
593                 strbuf_addch(out, ' ');
594                 strbuf_add(out, split.date_begin, split.tz_end - split.date_begin);
595         } else {
596                 strbuf_addstr(out, "Malformed Ident <malformed@example.com> 0 -0000");
597         }
598
599         *beg = out->buf;
600         *end = out->buf + out->len;
601 }
602
603 static void handle_commit(struct commit *commit, struct rev_info *rev,
604                           struct string_list *paths_of_changed_objects)
605 {
606         int saved_output_format = rev->diffopt.output_format;
607         const char *commit_buffer;
608         const char *author, *author_end, *committer, *committer_end;
609         const char *encoding, *message;
610         char *reencoded = NULL;
611         struct commit_list *p;
612         const char *refname;
613         int i;
614
615         rev->diffopt.output_format = DIFF_FORMAT_CALLBACK;
616
617         parse_commit_or_die(commit);
618         commit_buffer = get_commit_buffer(commit, NULL);
619         author = strstr(commit_buffer, "\nauthor ");
620         if (!author)
621                 die("could not find author in commit %s",
622                     oid_to_hex(&commit->object.oid));
623         author++;
624         author_end = strchrnul(author, '\n');
625         committer = strstr(author_end, "\ncommitter ");
626         if (!committer)
627                 die("could not find committer in commit %s",
628                     oid_to_hex(&commit->object.oid));
629         committer++;
630         committer_end = strchrnul(committer, '\n');
631         message = strstr(committer_end, "\n\n");
632         encoding = find_encoding(committer_end, message);
633         if (message)
634                 message += 2;
635
636         if (commit->parents &&
637             (get_object_mark(&commit->parents->item->object) != 0 ||
638              reference_excluded_commits) &&
639             !full_tree) {
640                 parse_commit_or_die(commit->parents->item);
641                 diff_tree_oid(get_commit_tree_oid(commit->parents->item),
642                               get_commit_tree_oid(commit), "", &rev->diffopt);
643         }
644         else
645                 diff_root_tree_oid(get_commit_tree_oid(commit),
646                                    "", &rev->diffopt);
647
648         /* Export the referenced blobs, and remember the marks. */
649         for (i = 0; i < diff_queued_diff.nr; i++)
650                 if (!S_ISGITLINK(diff_queued_diff.queue[i]->two->mode))
651                         export_blob(&diff_queued_diff.queue[i]->two->oid);
652
653         refname = *revision_sources_at(&revision_sources, commit);
654         /*
655          * FIXME: string_list_remove() below for each ref is overall
656          * O(N^2).  Compared to a history walk and diffing trees, this is
657          * just lost in the noise in practice.  However, theoretically a
658          * repo may have enough refs for this to become slow.
659          */
660         string_list_remove(&extra_refs, refname, 0);
661         if (anonymize) {
662                 refname = anonymize_refname(refname);
663                 anonymize_ident_line(&committer, &committer_end);
664                 anonymize_ident_line(&author, &author_end);
665         }
666
667         mark_next_object(&commit->object);
668         if (anonymize) {
669                 reencoded = anonymize_commit_message(message);
670         } else if (encoding) {
671                 switch(reencode_mode) {
672                 case REENCODE_YES:
673                         reencoded = reencode_string(message, "UTF-8", encoding);
674                         break;
675                 case REENCODE_NO:
676                         break;
677                 case REENCODE_ABORT:
678                         die("Encountered commit-specific encoding %s in commit "
679                             "%s; use --reencode=[yes|no] to handle it",
680                             encoding, oid_to_hex(&commit->object.oid));
681                 }
682         }
683         if (!commit->parents)
684                 printf("reset %s\n", refname);
685         printf("commit %s\nmark :%"PRIu32"\n", refname, last_idnum);
686         if (show_original_ids)
687                 printf("original-oid %s\n", oid_to_hex(&commit->object.oid));
688         printf("%.*s\n%.*s\n",
689                (int)(author_end - author), author,
690                (int)(committer_end - committer), committer);
691         if (!reencoded && encoding)
692                 printf("encoding %s\n", encoding);
693         printf("data %u\n%s",
694                (unsigned)(reencoded
695                           ? strlen(reencoded) : message
696                           ? strlen(message) : 0),
697                reencoded ? reencoded : message ? message : "");
698         free(reencoded);
699         unuse_commit_buffer(commit, commit_buffer);
700
701         for (i = 0, p = commit->parents; p; p = p->next) {
702                 struct object *obj = &p->item->object;
703                 int mark = get_object_mark(obj);
704
705                 if (!mark && !reference_excluded_commits)
706                         continue;
707                 if (i == 0)
708                         printf("from ");
709                 else
710                         printf("merge ");
711                 if (mark)
712                         printf(":%d\n", mark);
713                 else
714                         printf("%s\n", oid_to_hex(anonymize ?
715                                                   anonymize_oid(&obj->oid) :
716                                                   &obj->oid));
717                 i++;
718         }
719
720         if (full_tree)
721                 printf("deleteall\n");
722         log_tree_diff_flush(rev);
723         string_list_clear(paths_of_changed_objects, 0);
724         rev->diffopt.output_format = saved_output_format;
725
726         printf("\n");
727
728         show_progress();
729 }
730
731 static void *anonymize_tag(const void *old, size_t *len)
732 {
733         static int counter;
734         struct strbuf out = STRBUF_INIT;
735         strbuf_addf(&out, "tag message %d", counter++);
736         return strbuf_detach(&out, len);
737 }
738
739 static void handle_tail(struct object_array *commits, struct rev_info *revs,
740                         struct string_list *paths_of_changed_objects)
741 {
742         struct commit *commit;
743         while (commits->nr) {
744                 commit = (struct commit *)object_array_pop(commits);
745                 if (has_unshown_parent(commit)) {
746                         /* Queue again, to be handled later */
747                         add_object_array(&commit->object, NULL, commits);
748                         return;
749                 }
750                 handle_commit(commit, revs, paths_of_changed_objects);
751         }
752 }
753
754 static void handle_tag(const char *name, struct tag *tag)
755 {
756         unsigned long size;
757         enum object_type type;
758         char *buf;
759         const char *tagger, *tagger_end, *message;
760         size_t message_size = 0;
761         struct object *tagged;
762         int tagged_mark;
763         struct commit *p;
764
765         /* Trees have no identifier in fast-export output, thus we have no way
766          * to output tags of trees, tags of tags of trees, etc.  Simply omit
767          * such tags.
768          */
769         tagged = tag->tagged;
770         while (tagged->type == OBJ_TAG) {
771                 tagged = ((struct tag *)tagged)->tagged;
772         }
773         if (tagged->type == OBJ_TREE) {
774                 warning("Omitting tag %s,\nsince tags of trees (or tags of tags of trees, etc.) are not supported.",
775                         oid_to_hex(&tag->object.oid));
776                 return;
777         }
778
779         buf = read_object_file(&tag->object.oid, &type, &size);
780         if (!buf)
781                 die("could not read tag %s", oid_to_hex(&tag->object.oid));
782         message = memmem(buf, size, "\n\n", 2);
783         if (message) {
784                 message += 2;
785                 message_size = strlen(message);
786         }
787         tagger = memmem(buf, message ? message - buf : size, "\ntagger ", 8);
788         if (!tagger) {
789                 if (fake_missing_tagger)
790                         tagger = "tagger Unspecified Tagger "
791                                 "<unspecified-tagger> 0 +0000";
792                 else
793                         tagger = "";
794                 tagger_end = tagger + strlen(tagger);
795         } else {
796                 tagger++;
797                 tagger_end = strchrnul(tagger, '\n');
798                 if (anonymize)
799                         anonymize_ident_line(&tagger, &tagger_end);
800         }
801
802         if (anonymize) {
803                 name = anonymize_refname(name);
804                 if (message) {
805                         static struct hashmap tags;
806                         message = anonymize_mem(&tags, anonymize_tag,
807                                                 message, &message_size);
808                 }
809         }
810
811         /* handle signed tags */
812         if (message) {
813                 const char *signature = strstr(message,
814                                                "\n-----BEGIN PGP SIGNATURE-----\n");
815                 if (signature)
816                         switch(signed_tag_mode) {
817                         case SIGNED_TAG_ABORT:
818                                 die("encountered signed tag %s; use "
819                                     "--signed-tags=<mode> to handle it",
820                                     oid_to_hex(&tag->object.oid));
821                         case WARN:
822                                 warning("exporting signed tag %s",
823                                         oid_to_hex(&tag->object.oid));
824                                 /* fallthru */
825                         case VERBATIM:
826                                 break;
827                         case WARN_STRIP:
828                                 warning("stripping signature from tag %s",
829                                         oid_to_hex(&tag->object.oid));
830                                 /* fallthru */
831                         case STRIP:
832                                 message_size = signature + 1 - message;
833                                 break;
834                         }
835         }
836
837         /* handle tag->tagged having been filtered out due to paths specified */
838         tagged = tag->tagged;
839         tagged_mark = get_object_mark(tagged);
840         if (!tagged_mark) {
841                 switch(tag_of_filtered_mode) {
842                 case TAG_FILTERING_ABORT:
843                         die("tag %s tags unexported object; use "
844                             "--tag-of-filtered-object=<mode> to handle it",
845                             oid_to_hex(&tag->object.oid));
846                 case DROP:
847                         /* Ignore this tag altogether */
848                         free(buf);
849                         return;
850                 case REWRITE:
851                         if (tagged->type == OBJ_TAG && !mark_tags) {
852                                 die(_("Error: Cannot export nested tags unless --mark-tags is specified."));
853                         } else if (tagged->type == OBJ_COMMIT) {
854                                 p = rewrite_commit((struct commit *)tagged);
855                                 if (!p) {
856                                         printf("reset %s\nfrom %s\n\n",
857                                                name, oid_to_hex(&null_oid));
858                                         free(buf);
859                                         return;
860                                 }
861                                 tagged_mark = get_object_mark(&p->object);
862                         } else {
863                                 /* tagged->type is either OBJ_BLOB or OBJ_TAG */
864                                 tagged_mark = get_object_mark(tagged);
865                         }
866                 }
867         }
868
869         if (tagged->type == OBJ_TAG) {
870                 printf("reset %s\nfrom %s\n\n",
871                        name, oid_to_hex(&null_oid));
872         }
873         skip_prefix(name, "refs/tags/", &name);
874         printf("tag %s\n", name);
875         if (mark_tags) {
876                 mark_next_object(&tag->object);
877                 printf("mark :%"PRIu32"\n", last_idnum);
878         }
879         if (tagged_mark)
880                 printf("from :%d\n", tagged_mark);
881         else
882                 printf("from %s\n", oid_to_hex(&tagged->oid));
883
884         if (show_original_ids)
885                 printf("original-oid %s\n", oid_to_hex(&tag->object.oid));
886         printf("%.*s%sdata %d\n%.*s\n",
887                (int)(tagger_end - tagger), tagger,
888                tagger == tagger_end ? "" : "\n",
889                (int)message_size, (int)message_size, message ? message : "");
890         free(buf);
891 }
892
893 static struct commit *get_commit(struct rev_cmdline_entry *e, char *full_name)
894 {
895         switch (e->item->type) {
896         case OBJ_COMMIT:
897                 return (struct commit *)e->item;
898         case OBJ_TAG: {
899                 struct tag *tag = (struct tag *)e->item;
900
901                 /* handle nested tags */
902                 while (tag && tag->object.type == OBJ_TAG) {
903                         parse_object(the_repository, &tag->object.oid);
904                         string_list_append(&tag_refs, full_name)->util = tag;
905                         tag = (struct tag *)tag->tagged;
906                 }
907                 if (!tag)
908                         die("Tag %s points nowhere?", e->name);
909                 return (struct commit *)tag;
910                 break;
911         }
912         default:
913                 return NULL;
914         }
915 }
916
917 static void get_tags_and_duplicates(struct rev_cmdline_info *info)
918 {
919         int i;
920
921         for (i = 0; i < info->nr; i++) {
922                 struct rev_cmdline_entry *e = info->rev + i;
923                 struct object_id oid;
924                 struct commit *commit;
925                 char *full_name;
926
927                 if (e->flags & UNINTERESTING)
928                         continue;
929
930                 if (dwim_ref(e->name, strlen(e->name), &oid, &full_name) != 1)
931                         continue;
932
933                 if (refspecs.nr) {
934                         char *private;
935                         private = apply_refspecs(&refspecs, full_name);
936                         if (private) {
937                                 free(full_name);
938                                 full_name = private;
939                         }
940                 }
941
942                 commit = get_commit(e, full_name);
943                 if (!commit) {
944                         warning("%s: Unexpected object of type %s, skipping.",
945                                 e->name,
946                                 type_name(e->item->type));
947                         continue;
948                 }
949
950                 switch(commit->object.type) {
951                 case OBJ_COMMIT:
952                         break;
953                 case OBJ_BLOB:
954                         export_blob(&commit->object.oid);
955                         continue;
956                 default: /* OBJ_TAG (nested tags) is already handled */
957                         warning("Tag points to object of unexpected type %s, skipping.",
958                                 type_name(commit->object.type));
959                         continue;
960                 }
961
962                 /*
963                  * Make sure this ref gets properly updated eventually, whether
964                  * through a commit or manually at the end.
965                  */
966                 if (e->item->type != OBJ_TAG)
967                         string_list_append(&extra_refs, full_name)->util = commit;
968
969                 if (!*revision_sources_at(&revision_sources, commit))
970                         *revision_sources_at(&revision_sources, commit) = full_name;
971         }
972
973         string_list_sort(&extra_refs);
974         string_list_remove_duplicates(&extra_refs, 0);
975 }
976
977 static void handle_tags_and_duplicates(struct string_list *extras)
978 {
979         struct commit *commit;
980         int i;
981
982         for (i = extras->nr - 1; i >= 0; i--) {
983                 const char *name = extras->items[i].string;
984                 struct object *object = extras->items[i].util;
985                 int mark;
986
987                 switch (object->type) {
988                 case OBJ_TAG:
989                         handle_tag(name, (struct tag *)object);
990                         break;
991                 case OBJ_COMMIT:
992                         if (anonymize)
993                                 name = anonymize_refname(name);
994                         /* create refs pointing to already seen commits */
995                         commit = rewrite_commit((struct commit *)object);
996                         if (!commit) {
997                                 /*
998                                  * Neither this object nor any of its
999                                  * ancestors touch any relevant paths, so
1000                                  * it has been filtered to nothing.  Delete
1001                                  * it.
1002                                  */
1003                                 printf("reset %s\nfrom %s\n\n",
1004                                        name, oid_to_hex(&null_oid));
1005                                 continue;
1006                         }
1007
1008                         mark = get_object_mark(&commit->object);
1009                         if (!mark) {
1010                                 /*
1011                                  * Getting here means we have a commit which
1012                                  * was excluded by a negative refspec (e.g.
1013                                  * fast-export ^master master).  If we are
1014                                  * referencing excluded commits, set the ref
1015                                  * to the exact commit.  Otherwise, the user
1016                                  * wants the branch exported but every commit
1017                                  * in its history to be deleted, which basically
1018                                  * just means deletion of the ref.
1019                                  */
1020                                 if (!reference_excluded_commits) {
1021                                         /* delete the ref */
1022                                         printf("reset %s\nfrom %s\n\n",
1023                                                name, oid_to_hex(&null_oid));
1024                                         continue;
1025                                 }
1026                                 /* set ref to commit using oid, not mark */
1027                                 printf("reset %s\nfrom %s\n\n", name,
1028                                        oid_to_hex(&commit->object.oid));
1029                                 continue;
1030                         }
1031
1032                         printf("reset %s\nfrom :%d\n\n", name, mark
1033                                );
1034                         show_progress();
1035                         break;
1036                 }
1037         }
1038 }
1039
1040 static void export_marks(char *file)
1041 {
1042         unsigned int i;
1043         uint32_t mark;
1044         struct decoration_entry *deco = idnums.entries;
1045         FILE *f;
1046         int e = 0;
1047
1048         f = fopen_for_writing(file);
1049         if (!f)
1050                 die_errno("Unable to open marks file %s for writing.", file);
1051
1052         for (i = 0; i < idnums.size; i++) {
1053                 if (deco->base && deco->base->type == 1) {
1054                         mark = ptr_to_mark(deco->decoration);
1055                         if (fprintf(f, ":%"PRIu32" %s\n", mark,
1056                                 oid_to_hex(&deco->base->oid)) < 0) {
1057                             e = 1;
1058                             break;
1059                         }
1060                 }
1061                 deco++;
1062         }
1063
1064         e |= ferror(f);
1065         e |= fclose(f);
1066         if (e)
1067                 error("Unable to write marks file %s.", file);
1068 }
1069
1070 static void import_marks(char *input_file, int check_exists)
1071 {
1072         char line[512];
1073         FILE *f;
1074         struct stat sb;
1075
1076         if (check_exists && stat(input_file, &sb))
1077                 return;
1078
1079         f = xfopen(input_file, "r");
1080         while (fgets(line, sizeof(line), f)) {
1081                 uint32_t mark;
1082                 char *line_end, *mark_end;
1083                 struct object_id oid;
1084                 struct object *object;
1085                 struct commit *commit;
1086                 enum object_type type;
1087
1088                 line_end = strchr(line, '\n');
1089                 if (line[0] != ':' || !line_end)
1090                         die("corrupt mark line: %s", line);
1091                 *line_end = '\0';
1092
1093                 mark = strtoumax(line + 1, &mark_end, 10);
1094                 if (!mark || mark_end == line + 1
1095                         || *mark_end != ' ' || get_oid_hex(mark_end + 1, &oid))
1096                         die("corrupt mark line: %s", line);
1097
1098                 if (last_idnum < mark)
1099                         last_idnum = mark;
1100
1101                 type = oid_object_info(the_repository, &oid, NULL);
1102                 if (type < 0)
1103                         die("object not found: %s", oid_to_hex(&oid));
1104
1105                 if (type != OBJ_COMMIT)
1106                         /* only commits */
1107                         continue;
1108
1109                 commit = lookup_commit(the_repository, &oid);
1110                 if (!commit)
1111                         die("not a commit? can't happen: %s", oid_to_hex(&oid));
1112
1113                 object = &commit->object;
1114
1115                 if (object->flags & SHOWN)
1116                         error("Object %s already has a mark", oid_to_hex(&oid));
1117
1118                 mark_object(object, mark);
1119
1120                 object->flags |= SHOWN;
1121         }
1122         fclose(f);
1123 }
1124
1125 static void handle_deletes(void)
1126 {
1127         int i;
1128         for (i = 0; i < refspecs.nr; i++) {
1129                 struct refspec_item *refspec = &refspecs.items[i];
1130                 if (*refspec->src)
1131                         continue;
1132
1133                 printf("reset %s\nfrom %s\n\n",
1134                                 refspec->dst, oid_to_hex(&null_oid));
1135         }
1136 }
1137
1138 int cmd_fast_export(int argc, const char **argv, const char *prefix)
1139 {
1140         struct rev_info revs;
1141         struct object_array commits = OBJECT_ARRAY_INIT;
1142         struct commit *commit;
1143         char *export_filename = NULL,
1144              *import_filename = NULL,
1145              *import_filename_if_exists = NULL;
1146         uint32_t lastimportid;
1147         struct string_list refspecs_list = STRING_LIST_INIT_NODUP;
1148         struct string_list paths_of_changed_objects = STRING_LIST_INIT_DUP;
1149         struct option options[] = {
1150                 OPT_INTEGER(0, "progress", &progress,
1151                             N_("show progress after <n> objects")),
1152                 OPT_CALLBACK(0, "signed-tags", &signed_tag_mode, N_("mode"),
1153                              N_("select handling of signed tags"),
1154                              parse_opt_signed_tag_mode),
1155                 OPT_CALLBACK(0, "tag-of-filtered-object", &tag_of_filtered_mode, N_("mode"),
1156                              N_("select handling of tags that tag filtered objects"),
1157                              parse_opt_tag_of_filtered_mode),
1158                 OPT_CALLBACK(0, "reencode", &reencode_mode, N_("mode"),
1159                              N_("select handling of commit messages in an alternate encoding"),
1160                              parse_opt_reencode_mode),
1161                 OPT_STRING(0, "export-marks", &export_filename, N_("file"),
1162                              N_("Dump marks to this file")),
1163                 OPT_STRING(0, "import-marks", &import_filename, N_("file"),
1164                              N_("Import marks from this file")),
1165                 OPT_STRING(0, "import-marks-if-exists",
1166                              &import_filename_if_exists,
1167                              N_("file"),
1168                              N_("Import marks from this file if it exists")),
1169                 OPT_BOOL(0, "fake-missing-tagger", &fake_missing_tagger,
1170                          N_("Fake a tagger when tags lack one")),
1171                 OPT_BOOL(0, "full-tree", &full_tree,
1172                          N_("Output full tree for each commit")),
1173                 OPT_BOOL(0, "use-done-feature", &use_done_feature,
1174                              N_("Use the done feature to terminate the stream")),
1175                 OPT_BOOL(0, "no-data", &no_data, N_("Skip output of blob data")),
1176                 OPT_STRING_LIST(0, "refspec", &refspecs_list, N_("refspec"),
1177                              N_("Apply refspec to exported refs")),
1178                 OPT_BOOL(0, "anonymize", &anonymize, N_("anonymize output")),
1179                 OPT_BOOL(0, "reference-excluded-parents",
1180                          &reference_excluded_commits, N_("Reference parents which are not in fast-export stream by object id")),
1181                 OPT_BOOL(0, "show-original-ids", &show_original_ids,
1182                             N_("Show original object ids of blobs/commits")),
1183                 OPT_BOOL(0, "mark-tags", &mark_tags,
1184                             N_("Label tags with mark ids")),
1185
1186                 OPT_END()
1187         };
1188
1189         if (argc == 1)
1190                 usage_with_options (fast_export_usage, options);
1191
1192         /* we handle encodings */
1193         git_config(git_default_config, NULL);
1194
1195         repo_init_revisions(the_repository, &revs, prefix);
1196         init_revision_sources(&revision_sources);
1197         revs.topo_order = 1;
1198         revs.sources = &revision_sources;
1199         revs.rewrite_parents = 1;
1200         argc = parse_options(argc, argv, prefix, options, fast_export_usage,
1201                         PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN);
1202         argc = setup_revisions(argc, argv, &revs, NULL);
1203         if (argc > 1)
1204                 usage_with_options (fast_export_usage, options);
1205
1206         if (refspecs_list.nr) {
1207                 int i;
1208
1209                 for (i = 0; i < refspecs_list.nr; i++)
1210                         refspec_append(&refspecs, refspecs_list.items[i].string);
1211
1212                 string_list_clear(&refspecs_list, 1);
1213         }
1214
1215         if (use_done_feature)
1216                 printf("feature done\n");
1217
1218         if (import_filename && import_filename_if_exists)
1219                 die(_("Cannot pass both --import-marks and --import-marks-if-exists"));
1220         if (import_filename)
1221                 import_marks(import_filename, 0);
1222         else if (import_filename_if_exists)
1223                 import_marks(import_filename_if_exists, 1);
1224         lastimportid = last_idnum;
1225
1226         if (import_filename && revs.prune_data.nr)
1227                 full_tree = 1;
1228
1229         get_tags_and_duplicates(&revs.cmdline);
1230
1231         if (prepare_revision_walk(&revs))
1232                 die("revision walk setup failed");
1233         revs.diffopt.format_callback = show_filemodify;
1234         revs.diffopt.format_callback_data = &paths_of_changed_objects;
1235         revs.diffopt.flags.recursive = 1;
1236         while ((commit = get_revision(&revs))) {
1237                 if (has_unshown_parent(commit)) {
1238                         add_object_array(&commit->object, NULL, &commits);
1239                 }
1240                 else {
1241                         handle_commit(commit, &revs, &paths_of_changed_objects);
1242                         handle_tail(&commits, &revs, &paths_of_changed_objects);
1243                 }
1244         }
1245
1246         handle_tags_and_duplicates(&extra_refs);
1247         handle_tags_and_duplicates(&tag_refs);
1248         handle_deletes();
1249
1250         if (export_filename && lastimportid != last_idnum)
1251                 export_marks(export_filename);
1252
1253         if (use_done_feature)
1254                 printf("done\n");
1255
1256         refspec_clear(&refspecs);
1257
1258         return 0;
1259 }