Merge branch 'js/mingw-open-in-gdb'
[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(the_repository, oid, buf, size,
297                                            type_name(type)) < 0)
298                         die("oid mismatch in blob %s", oid_to_hex(oid));
299                 object = parse_object_buffer(the_repository, oid, type,
300                                              size, buf, &eaten);
301         }
302
303         if (!object)
304                 die("Could not read blob %s", oid_to_hex(oid));
305
306         mark_next_object(object);
307
308         printf("blob\nmark :%"PRIu32"\n", last_idnum);
309         if (show_original_ids)
310                 printf("original-oid %s\n", oid_to_hex(oid));
311         printf("data %"PRIuMAX"\n", (uintmax_t)size);
312         if (size && fwrite(buf, size, 1, stdout) != 1)
313                 die_errno("could not write blob '%s'", oid_to_hex(oid));
314         printf("\n");
315
316         show_progress();
317
318         object->flags |= SHOWN;
319         if (!eaten)
320                 free(buf);
321 }
322
323 static int depth_first(const void *a_, const void *b_)
324 {
325         const struct diff_filepair *a = *((const struct diff_filepair **)a_);
326         const struct diff_filepair *b = *((const struct diff_filepair **)b_);
327         const char *name_a, *name_b;
328         int len_a, len_b, len;
329         int cmp;
330
331         name_a = a->one ? a->one->path : a->two->path;
332         name_b = b->one ? b->one->path : b->two->path;
333
334         len_a = strlen(name_a);
335         len_b = strlen(name_b);
336         len = (len_a < len_b) ? len_a : len_b;
337
338         /* strcmp will sort 'd' before 'd/e', we want 'd/e' before 'd' */
339         cmp = memcmp(name_a, name_b, len);
340         if (cmp)
341                 return cmp;
342         cmp = len_b - len_a;
343         if (cmp)
344                 return cmp;
345         /*
346          * Move 'R'ename entries last so that all references of the file
347          * appear in the output before it is renamed (e.g., when a file
348          * was copied and renamed in the same commit).
349          */
350         return (a->status == 'R') - (b->status == 'R');
351 }
352
353 static void print_path_1(const char *path)
354 {
355         int need_quote = quote_c_style(path, NULL, NULL, 0);
356         if (need_quote)
357                 quote_c_style(path, NULL, stdout, 0);
358         else if (strchr(path, ' '))
359                 printf("\"%s\"", path);
360         else
361                 printf("%s", path);
362 }
363
364 static void *anonymize_path_component(const void *path, size_t *len)
365 {
366         static int counter;
367         struct strbuf out = STRBUF_INIT;
368         strbuf_addf(&out, "path%d", counter++);
369         return strbuf_detach(&out, len);
370 }
371
372 static void print_path(const char *path)
373 {
374         if (!anonymize)
375                 print_path_1(path);
376         else {
377                 static struct hashmap paths;
378                 static struct strbuf anon = STRBUF_INIT;
379
380                 anonymize_path(&anon, path, &paths, anonymize_path_component);
381                 print_path_1(anon.buf);
382                 strbuf_reset(&anon);
383         }
384 }
385
386 static void *generate_fake_oid(const void *old, size_t *len)
387 {
388         static uint32_t counter = 1; /* avoid null oid */
389         const unsigned hashsz = the_hash_algo->rawsz;
390         unsigned char *out = xcalloc(hashsz, 1);
391         put_be32(out + hashsz - 4, counter++);
392         return out;
393 }
394
395 static const struct object_id *anonymize_oid(const struct object_id *oid)
396 {
397         static struct hashmap objs;
398         size_t len = the_hash_algo->rawsz;
399         return anonymize_mem(&objs, generate_fake_oid, oid, &len);
400 }
401
402 static void show_filemodify(struct diff_queue_struct *q,
403                             struct diff_options *options, void *data)
404 {
405         int i;
406         struct string_list *changed = data;
407
408         /*
409          * Handle files below a directory first, in case they are all deleted
410          * and the directory changes to a file or symlink.
411          */
412         QSORT(q->queue, q->nr, depth_first);
413
414         for (i = 0; i < q->nr; i++) {
415                 struct diff_filespec *ospec = q->queue[i]->one;
416                 struct diff_filespec *spec = q->queue[i]->two;
417
418                 switch (q->queue[i]->status) {
419                 case DIFF_STATUS_DELETED:
420                         printf("D ");
421                         print_path(spec->path);
422                         string_list_insert(changed, spec->path);
423                         putchar('\n');
424                         break;
425
426                 case DIFF_STATUS_COPIED:
427                 case DIFF_STATUS_RENAMED:
428                         /*
429                          * If a change in the file corresponding to ospec->path
430                          * has been observed, we cannot trust its contents
431                          * because the diff is calculated based on the prior
432                          * contents, not the current contents.  So, declare a
433                          * copy or rename only if there was no change observed.
434                          */
435                         if (!string_list_has_string(changed, ospec->path)) {
436                                 printf("%c ", q->queue[i]->status);
437                                 print_path(ospec->path);
438                                 putchar(' ');
439                                 print_path(spec->path);
440                                 string_list_insert(changed, spec->path);
441                                 putchar('\n');
442
443                                 if (oideq(&ospec->oid, &spec->oid) &&
444                                     ospec->mode == spec->mode)
445                                         break;
446                         }
447                         /* fallthrough */
448
449                 case DIFF_STATUS_TYPE_CHANGED:
450                 case DIFF_STATUS_MODIFIED:
451                 case DIFF_STATUS_ADDED:
452                         /*
453                          * Links refer to objects in another repositories;
454                          * output the SHA-1 verbatim.
455                          */
456                         if (no_data || S_ISGITLINK(spec->mode))
457                                 printf("M %06o %s ", spec->mode,
458                                        oid_to_hex(anonymize ?
459                                                   anonymize_oid(&spec->oid) :
460                                                   &spec->oid));
461                         else {
462                                 struct object *object = lookup_object(the_repository,
463                                                                       &spec->oid);
464                                 printf("M %06o :%d ", spec->mode,
465                                        get_object_mark(object));
466                         }
467                         print_path(spec->path);
468                         string_list_insert(changed, spec->path);
469                         putchar('\n');
470                         break;
471
472                 default:
473                         die("Unexpected comparison status '%c' for %s, %s",
474                                 q->queue[i]->status,
475                                 ospec->path ? ospec->path : "none",
476                                 spec->path ? spec->path : "none");
477                 }
478         }
479 }
480
481 static const char *find_encoding(const char *begin, const char *end)
482 {
483         const char *needle = "\nencoding ";
484         char *bol, *eol;
485
486         bol = memmem(begin, end ? end - begin : strlen(begin),
487                      needle, strlen(needle));
488         if (!bol)
489                 return NULL;
490         bol += strlen(needle);
491         eol = strchrnul(bol, '\n');
492         *eol = '\0';
493         return bol;
494 }
495
496 static void *anonymize_ref_component(const void *old, size_t *len)
497 {
498         static int counter;
499         struct strbuf out = STRBUF_INIT;
500         strbuf_addf(&out, "ref%d", counter++);
501         return strbuf_detach(&out, len);
502 }
503
504 static const char *anonymize_refname(const char *refname)
505 {
506         /*
507          * If any of these prefixes is found, we will leave it intact
508          * so that tags remain tags and so forth.
509          */
510         static const char *prefixes[] = {
511                 "refs/heads/",
512                 "refs/tags/",
513                 "refs/remotes/",
514                 "refs/"
515         };
516         static struct hashmap refs;
517         static struct strbuf anon = STRBUF_INIT;
518         int i;
519
520         /*
521          * We also leave "master" as a special case, since it does not reveal
522          * anything interesting.
523          */
524         if (!strcmp(refname, "refs/heads/master"))
525                 return refname;
526
527         strbuf_reset(&anon);
528         for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
529                 if (skip_prefix(refname, prefixes[i], &refname)) {
530                         strbuf_addstr(&anon, prefixes[i]);
531                         break;
532                 }
533         }
534
535         anonymize_path(&anon, refname, &refs, anonymize_ref_component);
536         return anon.buf;
537 }
538
539 /*
540  * We do not even bother to cache commit messages, as they are unlikely
541  * to be repeated verbatim, and it is not that interesting when they are.
542  */
543 static char *anonymize_commit_message(const char *old)
544 {
545         static int counter;
546         return xstrfmt("subject %d\n\nbody\n", counter++);
547 }
548
549 static struct hashmap idents;
550 static void *anonymize_ident(const void *old, size_t *len)
551 {
552         static int counter;
553         struct strbuf out = STRBUF_INIT;
554         strbuf_addf(&out, "User %d <user%d@example.com>", counter, counter);
555         counter++;
556         return strbuf_detach(&out, len);
557 }
558
559 /*
560  * Our strategy here is to anonymize the names and email addresses,
561  * but keep timestamps intact, as they influence things like traversal
562  * order (and by themselves should not be too revealing).
563  */
564 static void anonymize_ident_line(const char **beg, const char **end)
565 {
566         static struct strbuf buffers[] = { STRBUF_INIT, STRBUF_INIT };
567         static unsigned which_buffer;
568
569         struct strbuf *out;
570         struct ident_split split;
571         const char *end_of_header;
572
573         out = &buffers[which_buffer++];
574         which_buffer %= ARRAY_SIZE(buffers);
575         strbuf_reset(out);
576
577         /* skip "committer", "author", "tagger", etc */
578         end_of_header = strchr(*beg, ' ');
579         if (!end_of_header)
580                 BUG("malformed line fed to anonymize_ident_line: %.*s",
581                     (int)(*end - *beg), *beg);
582         end_of_header++;
583         strbuf_add(out, *beg, end_of_header - *beg);
584
585         if (!split_ident_line(&split, end_of_header, *end - end_of_header) &&
586             split.date_begin) {
587                 const char *ident;
588                 size_t len;
589
590                 len = split.mail_end - split.name_begin;
591                 ident = anonymize_mem(&idents, anonymize_ident,
592                                       split.name_begin, &len);
593                 strbuf_add(out, ident, len);
594                 strbuf_addch(out, ' ');
595                 strbuf_add(out, split.date_begin, split.tz_end - split.date_begin);
596         } else {
597                 strbuf_addstr(out, "Malformed Ident <malformed@example.com> 0 -0000");
598         }
599
600         *beg = out->buf;
601         *end = out->buf + out->len;
602 }
603
604 static void handle_commit(struct commit *commit, struct rev_info *rev,
605                           struct string_list *paths_of_changed_objects)
606 {
607         int saved_output_format = rev->diffopt.output_format;
608         const char *commit_buffer;
609         const char *author, *author_end, *committer, *committer_end;
610         const char *encoding, *message;
611         char *reencoded = NULL;
612         struct commit_list *p;
613         const char *refname;
614         int i;
615
616         rev->diffopt.output_format = DIFF_FORMAT_CALLBACK;
617
618         parse_commit_or_die(commit);
619         commit_buffer = get_commit_buffer(commit, NULL);
620         author = strstr(commit_buffer, "\nauthor ");
621         if (!author)
622                 die("could not find author in commit %s",
623                     oid_to_hex(&commit->object.oid));
624         author++;
625         author_end = strchrnul(author, '\n');
626         committer = strstr(author_end, "\ncommitter ");
627         if (!committer)
628                 die("could not find committer in commit %s",
629                     oid_to_hex(&commit->object.oid));
630         committer++;
631         committer_end = strchrnul(committer, '\n');
632         message = strstr(committer_end, "\n\n");
633         encoding = find_encoding(committer_end, message);
634         if (message)
635                 message += 2;
636
637         if (commit->parents &&
638             (get_object_mark(&commit->parents->item->object) != 0 ||
639              reference_excluded_commits) &&
640             !full_tree) {
641                 parse_commit_or_die(commit->parents->item);
642                 diff_tree_oid(get_commit_tree_oid(commit->parents->item),
643                               get_commit_tree_oid(commit), "", &rev->diffopt);
644         }
645         else
646                 diff_root_tree_oid(get_commit_tree_oid(commit),
647                                    "", &rev->diffopt);
648
649         /* Export the referenced blobs, and remember the marks. */
650         for (i = 0; i < diff_queued_diff.nr; i++)
651                 if (!S_ISGITLINK(diff_queued_diff.queue[i]->two->mode))
652                         export_blob(&diff_queued_diff.queue[i]->two->oid);
653
654         refname = *revision_sources_at(&revision_sources, commit);
655         /*
656          * FIXME: string_list_remove() below for each ref is overall
657          * O(N^2).  Compared to a history walk and diffing trees, this is
658          * just lost in the noise in practice.  However, theoretically a
659          * repo may have enough refs for this to become slow.
660          */
661         string_list_remove(&extra_refs, refname, 0);
662         if (anonymize) {
663                 refname = anonymize_refname(refname);
664                 anonymize_ident_line(&committer, &committer_end);
665                 anonymize_ident_line(&author, &author_end);
666         }
667
668         mark_next_object(&commit->object);
669         if (anonymize) {
670                 reencoded = anonymize_commit_message(message);
671         } else if (encoding) {
672                 switch(reencode_mode) {
673                 case REENCODE_YES:
674                         reencoded = reencode_string(message, "UTF-8", encoding);
675                         break;
676                 case REENCODE_NO:
677                         break;
678                 case REENCODE_ABORT:
679                         die("Encountered commit-specific encoding %s in commit "
680                             "%s; use --reencode=[yes|no] to handle it",
681                             encoding, oid_to_hex(&commit->object.oid));
682                 }
683         }
684         if (!commit->parents)
685                 printf("reset %s\n", refname);
686         printf("commit %s\nmark :%"PRIu32"\n", refname, last_idnum);
687         if (show_original_ids)
688                 printf("original-oid %s\n", oid_to_hex(&commit->object.oid));
689         printf("%.*s\n%.*s\n",
690                (int)(author_end - author), author,
691                (int)(committer_end - committer), committer);
692         if (!reencoded && encoding)
693                 printf("encoding %s\n", encoding);
694         printf("data %u\n%s",
695                (unsigned)(reencoded
696                           ? strlen(reencoded) : message
697                           ? strlen(message) : 0),
698                reencoded ? reencoded : message ? message : "");
699         free(reencoded);
700         unuse_commit_buffer(commit, commit_buffer);
701
702         for (i = 0, p = commit->parents; p; p = p->next) {
703                 struct object *obj = &p->item->object;
704                 int mark = get_object_mark(obj);
705
706                 if (!mark && !reference_excluded_commits)
707                         continue;
708                 if (i == 0)
709                         printf("from ");
710                 else
711                         printf("merge ");
712                 if (mark)
713                         printf(":%d\n", mark);
714                 else
715                         printf("%s\n", oid_to_hex(anonymize ?
716                                                   anonymize_oid(&obj->oid) :
717                                                   &obj->oid));
718                 i++;
719         }
720
721         if (full_tree)
722                 printf("deleteall\n");
723         log_tree_diff_flush(rev);
724         string_list_clear(paths_of_changed_objects, 0);
725         rev->diffopt.output_format = saved_output_format;
726
727         printf("\n");
728
729         show_progress();
730 }
731
732 static void *anonymize_tag(const void *old, size_t *len)
733 {
734         static int counter;
735         struct strbuf out = STRBUF_INIT;
736         strbuf_addf(&out, "tag message %d", counter++);
737         return strbuf_detach(&out, len);
738 }
739
740 static void handle_tail(struct object_array *commits, struct rev_info *revs,
741                         struct string_list *paths_of_changed_objects)
742 {
743         struct commit *commit;
744         while (commits->nr) {
745                 commit = (struct commit *)object_array_pop(commits);
746                 if (has_unshown_parent(commit)) {
747                         /* Queue again, to be handled later */
748                         add_object_array(&commit->object, NULL, commits);
749                         return;
750                 }
751                 handle_commit(commit, revs, paths_of_changed_objects);
752         }
753 }
754
755 static void handle_tag(const char *name, struct tag *tag)
756 {
757         unsigned long size;
758         enum object_type type;
759         char *buf;
760         const char *tagger, *tagger_end, *message;
761         size_t message_size = 0;
762         struct object *tagged;
763         int tagged_mark;
764         struct commit *p;
765
766         /* Trees have no identifier in fast-export output, thus we have no way
767          * to output tags of trees, tags of tags of trees, etc.  Simply omit
768          * such tags.
769          */
770         tagged = tag->tagged;
771         while (tagged->type == OBJ_TAG) {
772                 tagged = ((struct tag *)tagged)->tagged;
773         }
774         if (tagged->type == OBJ_TREE) {
775                 warning("Omitting tag %s,\nsince tags of trees (or tags of tags of trees, etc.) are not supported.",
776                         oid_to_hex(&tag->object.oid));
777                 return;
778         }
779
780         buf = read_object_file(&tag->object.oid, &type, &size);
781         if (!buf)
782                 die("could not read tag %s", oid_to_hex(&tag->object.oid));
783         message = memmem(buf, size, "\n\n", 2);
784         if (message) {
785                 message += 2;
786                 message_size = strlen(message);
787         }
788         tagger = memmem(buf, message ? message - buf : size, "\ntagger ", 8);
789         if (!tagger) {
790                 if (fake_missing_tagger)
791                         tagger = "tagger Unspecified Tagger "
792                                 "<unspecified-tagger> 0 +0000";
793                 else
794                         tagger = "";
795                 tagger_end = tagger + strlen(tagger);
796         } else {
797                 tagger++;
798                 tagger_end = strchrnul(tagger, '\n');
799                 if (anonymize)
800                         anonymize_ident_line(&tagger, &tagger_end);
801         }
802
803         if (anonymize) {
804                 name = anonymize_refname(name);
805                 if (message) {
806                         static struct hashmap tags;
807                         message = anonymize_mem(&tags, anonymize_tag,
808                                                 message, &message_size);
809                 }
810         }
811
812         /* handle signed tags */
813         if (message) {
814                 const char *signature = strstr(message,
815                                                "\n-----BEGIN PGP SIGNATURE-----\n");
816                 if (signature)
817                         switch(signed_tag_mode) {
818                         case SIGNED_TAG_ABORT:
819                                 die("encountered signed tag %s; use "
820                                     "--signed-tags=<mode> to handle it",
821                                     oid_to_hex(&tag->object.oid));
822                         case WARN:
823                                 warning("exporting signed tag %s",
824                                         oid_to_hex(&tag->object.oid));
825                                 /* fallthru */
826                         case VERBATIM:
827                                 break;
828                         case WARN_STRIP:
829                                 warning("stripping signature from tag %s",
830                                         oid_to_hex(&tag->object.oid));
831                                 /* fallthru */
832                         case STRIP:
833                                 message_size = signature + 1 - message;
834                                 break;
835                         }
836         }
837
838         /* handle tag->tagged having been filtered out due to paths specified */
839         tagged = tag->tagged;
840         tagged_mark = get_object_mark(tagged);
841         if (!tagged_mark) {
842                 switch(tag_of_filtered_mode) {
843                 case TAG_FILTERING_ABORT:
844                         die("tag %s tags unexported object; use "
845                             "--tag-of-filtered-object=<mode> to handle it",
846                             oid_to_hex(&tag->object.oid));
847                 case DROP:
848                         /* Ignore this tag altogether */
849                         free(buf);
850                         return;
851                 case REWRITE:
852                         if (tagged->type == OBJ_TAG && !mark_tags) {
853                                 die(_("Error: Cannot export nested tags unless --mark-tags is specified."));
854                         } else if (tagged->type == OBJ_COMMIT) {
855                                 p = rewrite_commit((struct commit *)tagged);
856                                 if (!p) {
857                                         printf("reset %s\nfrom %s\n\n",
858                                                name, oid_to_hex(&null_oid));
859                                         free(buf);
860                                         return;
861                                 }
862                                 tagged_mark = get_object_mark(&p->object);
863                         } else {
864                                 /* tagged->type is either OBJ_BLOB or OBJ_TAG */
865                                 tagged_mark = get_object_mark(tagged);
866                         }
867                 }
868         }
869
870         if (tagged->type == OBJ_TAG) {
871                 printf("reset %s\nfrom %s\n\n",
872                        name, oid_to_hex(&null_oid));
873         }
874         skip_prefix(name, "refs/tags/", &name);
875         printf("tag %s\n", name);
876         if (mark_tags) {
877                 mark_next_object(&tag->object);
878                 printf("mark :%"PRIu32"\n", last_idnum);
879         }
880         if (tagged_mark)
881                 printf("from :%d\n", tagged_mark);
882         else
883                 printf("from %s\n", oid_to_hex(&tagged->oid));
884
885         if (show_original_ids)
886                 printf("original-oid %s\n", oid_to_hex(&tag->object.oid));
887         printf("%.*s%sdata %d\n%.*s\n",
888                (int)(tagger_end - tagger), tagger,
889                tagger == tagger_end ? "" : "\n",
890                (int)message_size, (int)message_size, message ? message : "");
891         free(buf);
892 }
893
894 static struct commit *get_commit(struct rev_cmdline_entry *e, char *full_name)
895 {
896         switch (e->item->type) {
897         case OBJ_COMMIT:
898                 return (struct commit *)e->item;
899         case OBJ_TAG: {
900                 struct tag *tag = (struct tag *)e->item;
901
902                 /* handle nested tags */
903                 while (tag && tag->object.type == OBJ_TAG) {
904                         parse_object(the_repository, &tag->object.oid);
905                         string_list_append(&tag_refs, full_name)->util = tag;
906                         tag = (struct tag *)tag->tagged;
907                 }
908                 if (!tag)
909                         die("Tag %s points nowhere?", e->name);
910                 return (struct commit *)tag;
911                 break;
912         }
913         default:
914                 return NULL;
915         }
916 }
917
918 static void get_tags_and_duplicates(struct rev_cmdline_info *info)
919 {
920         int i;
921
922         for (i = 0; i < info->nr; i++) {
923                 struct rev_cmdline_entry *e = info->rev + i;
924                 struct object_id oid;
925                 struct commit *commit;
926                 char *full_name;
927
928                 if (e->flags & UNINTERESTING)
929                         continue;
930
931                 if (dwim_ref(e->name, strlen(e->name), &oid, &full_name) != 1)
932                         continue;
933
934                 if (refspecs.nr) {
935                         char *private;
936                         private = apply_refspecs(&refspecs, full_name);
937                         if (private) {
938                                 free(full_name);
939                                 full_name = private;
940                         }
941                 }
942
943                 commit = get_commit(e, full_name);
944                 if (!commit) {
945                         warning("%s: Unexpected object of type %s, skipping.",
946                                 e->name,
947                                 type_name(e->item->type));
948                         continue;
949                 }
950
951                 switch(commit->object.type) {
952                 case OBJ_COMMIT:
953                         break;
954                 case OBJ_BLOB:
955                         export_blob(&commit->object.oid);
956                         continue;
957                 default: /* OBJ_TAG (nested tags) is already handled */
958                         warning("Tag points to object of unexpected type %s, skipping.",
959                                 type_name(commit->object.type));
960                         continue;
961                 }
962
963                 /*
964                  * Make sure this ref gets properly updated eventually, whether
965                  * through a commit or manually at the end.
966                  */
967                 if (e->item->type != OBJ_TAG)
968                         string_list_append(&extra_refs, full_name)->util = commit;
969
970                 if (!*revision_sources_at(&revision_sources, commit))
971                         *revision_sources_at(&revision_sources, commit) = full_name;
972         }
973
974         string_list_sort(&extra_refs);
975         string_list_remove_duplicates(&extra_refs, 0);
976 }
977
978 static void handle_tags_and_duplicates(struct string_list *extras)
979 {
980         struct commit *commit;
981         int i;
982
983         for (i = extras->nr - 1; i >= 0; i--) {
984                 const char *name = extras->items[i].string;
985                 struct object *object = extras->items[i].util;
986                 int mark;
987
988                 switch (object->type) {
989                 case OBJ_TAG:
990                         handle_tag(name, (struct tag *)object);
991                         break;
992                 case OBJ_COMMIT:
993                         if (anonymize)
994                                 name = anonymize_refname(name);
995                         /* create refs pointing to already seen commits */
996                         commit = rewrite_commit((struct commit *)object);
997                         if (!commit) {
998                                 /*
999                                  * Neither this object nor any of its
1000                                  * ancestors touch any relevant paths, so
1001                                  * it has been filtered to nothing.  Delete
1002                                  * it.
1003                                  */
1004                                 printf("reset %s\nfrom %s\n\n",
1005                                        name, oid_to_hex(&null_oid));
1006                                 continue;
1007                         }
1008
1009                         mark = get_object_mark(&commit->object);
1010                         if (!mark) {
1011                                 /*
1012                                  * Getting here means we have a commit which
1013                                  * was excluded by a negative refspec (e.g.
1014                                  * fast-export ^master master).  If we are
1015                                  * referencing excluded commits, set the ref
1016                                  * to the exact commit.  Otherwise, the user
1017                                  * wants the branch exported but every commit
1018                                  * in its history to be deleted, which basically
1019                                  * just means deletion of the ref.
1020                                  */
1021                                 if (!reference_excluded_commits) {
1022                                         /* delete the ref */
1023                                         printf("reset %s\nfrom %s\n\n",
1024                                                name, oid_to_hex(&null_oid));
1025                                         continue;
1026                                 }
1027                                 /* set ref to commit using oid, not mark */
1028                                 printf("reset %s\nfrom %s\n\n", name,
1029                                        oid_to_hex(&commit->object.oid));
1030                                 continue;
1031                         }
1032
1033                         printf("reset %s\nfrom :%d\n\n", name, mark
1034                                );
1035                         show_progress();
1036                         break;
1037                 }
1038         }
1039 }
1040
1041 static void export_marks(char *file)
1042 {
1043         unsigned int i;
1044         uint32_t mark;
1045         struct decoration_entry *deco = idnums.entries;
1046         FILE *f;
1047         int e = 0;
1048
1049         f = fopen_for_writing(file);
1050         if (!f)
1051                 die_errno("Unable to open marks file %s for writing.", file);
1052
1053         for (i = 0; i < idnums.size; i++) {
1054                 if (deco->base && deco->base->type == 1) {
1055                         mark = ptr_to_mark(deco->decoration);
1056                         if (fprintf(f, ":%"PRIu32" %s\n", mark,
1057                                 oid_to_hex(&deco->base->oid)) < 0) {
1058                             e = 1;
1059                             break;
1060                         }
1061                 }
1062                 deco++;
1063         }
1064
1065         e |= ferror(f);
1066         e |= fclose(f);
1067         if (e)
1068                 error("Unable to write marks file %s.", file);
1069 }
1070
1071 static void import_marks(char *input_file, int check_exists)
1072 {
1073         char line[512];
1074         FILE *f;
1075         struct stat sb;
1076
1077         if (check_exists && stat(input_file, &sb))
1078                 return;
1079
1080         f = xfopen(input_file, "r");
1081         while (fgets(line, sizeof(line), f)) {
1082                 uint32_t mark;
1083                 char *line_end, *mark_end;
1084                 struct object_id oid;
1085                 struct object *object;
1086                 struct commit *commit;
1087                 enum object_type type;
1088
1089                 line_end = strchr(line, '\n');
1090                 if (line[0] != ':' || !line_end)
1091                         die("corrupt mark line: %s", line);
1092                 *line_end = '\0';
1093
1094                 mark = strtoumax(line + 1, &mark_end, 10);
1095                 if (!mark || mark_end == line + 1
1096                         || *mark_end != ' ' || get_oid_hex(mark_end + 1, &oid))
1097                         die("corrupt mark line: %s", line);
1098
1099                 if (last_idnum < mark)
1100                         last_idnum = mark;
1101
1102                 type = oid_object_info(the_repository, &oid, NULL);
1103                 if (type < 0)
1104                         die("object not found: %s", oid_to_hex(&oid));
1105
1106                 if (type != OBJ_COMMIT)
1107                         /* only commits */
1108                         continue;
1109
1110                 commit = lookup_commit(the_repository, &oid);
1111                 if (!commit)
1112                         die("not a commit? can't happen: %s", oid_to_hex(&oid));
1113
1114                 object = &commit->object;
1115
1116                 if (object->flags & SHOWN)
1117                         error("Object %s already has a mark", oid_to_hex(&oid));
1118
1119                 mark_object(object, mark);
1120
1121                 object->flags |= SHOWN;
1122         }
1123         fclose(f);
1124 }
1125
1126 static void handle_deletes(void)
1127 {
1128         int i;
1129         for (i = 0; i < refspecs.nr; i++) {
1130                 struct refspec_item *refspec = &refspecs.items[i];
1131                 if (*refspec->src)
1132                         continue;
1133
1134                 printf("reset %s\nfrom %s\n\n",
1135                                 refspec->dst, oid_to_hex(&null_oid));
1136         }
1137 }
1138
1139 int cmd_fast_export(int argc, const char **argv, const char *prefix)
1140 {
1141         struct rev_info revs;
1142         struct object_array commits = OBJECT_ARRAY_INIT;
1143         struct commit *commit;
1144         char *export_filename = NULL,
1145              *import_filename = NULL,
1146              *import_filename_if_exists = NULL;
1147         uint32_t lastimportid;
1148         struct string_list refspecs_list = STRING_LIST_INIT_NODUP;
1149         struct string_list paths_of_changed_objects = STRING_LIST_INIT_DUP;
1150         struct option options[] = {
1151                 OPT_INTEGER(0, "progress", &progress,
1152                             N_("show progress after <n> objects")),
1153                 OPT_CALLBACK(0, "signed-tags", &signed_tag_mode, N_("mode"),
1154                              N_("select handling of signed tags"),
1155                              parse_opt_signed_tag_mode),
1156                 OPT_CALLBACK(0, "tag-of-filtered-object", &tag_of_filtered_mode, N_("mode"),
1157                              N_("select handling of tags that tag filtered objects"),
1158                              parse_opt_tag_of_filtered_mode),
1159                 OPT_CALLBACK(0, "reencode", &reencode_mode, N_("mode"),
1160                              N_("select handling of commit messages in an alternate encoding"),
1161                              parse_opt_reencode_mode),
1162                 OPT_STRING(0, "export-marks", &export_filename, N_("file"),
1163                              N_("Dump marks to this file")),
1164                 OPT_STRING(0, "import-marks", &import_filename, N_("file"),
1165                              N_("Import marks from this file")),
1166                 OPT_STRING(0, "import-marks-if-exists",
1167                              &import_filename_if_exists,
1168                              N_("file"),
1169                              N_("Import marks from this file if it exists")),
1170                 OPT_BOOL(0, "fake-missing-tagger", &fake_missing_tagger,
1171                          N_("Fake a tagger when tags lack one")),
1172                 OPT_BOOL(0, "full-tree", &full_tree,
1173                          N_("Output full tree for each commit")),
1174                 OPT_BOOL(0, "use-done-feature", &use_done_feature,
1175                              N_("Use the done feature to terminate the stream")),
1176                 OPT_BOOL(0, "no-data", &no_data, N_("Skip output of blob data")),
1177                 OPT_STRING_LIST(0, "refspec", &refspecs_list, N_("refspec"),
1178                              N_("Apply refspec to exported refs")),
1179                 OPT_BOOL(0, "anonymize", &anonymize, N_("anonymize output")),
1180                 OPT_BOOL(0, "reference-excluded-parents",
1181                          &reference_excluded_commits, N_("Reference parents which are not in fast-export stream by object id")),
1182                 OPT_BOOL(0, "show-original-ids", &show_original_ids,
1183                             N_("Show original object ids of blobs/commits")),
1184                 OPT_BOOL(0, "mark-tags", &mark_tags,
1185                             N_("Label tags with mark ids")),
1186
1187                 OPT_END()
1188         };
1189
1190         if (argc == 1)
1191                 usage_with_options (fast_export_usage, options);
1192
1193         /* we handle encodings */
1194         git_config(git_default_config, NULL);
1195
1196         repo_init_revisions(the_repository, &revs, prefix);
1197         init_revision_sources(&revision_sources);
1198         revs.topo_order = 1;
1199         revs.sources = &revision_sources;
1200         revs.rewrite_parents = 1;
1201         argc = parse_options(argc, argv, prefix, options, fast_export_usage,
1202                         PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN);
1203         argc = setup_revisions(argc, argv, &revs, NULL);
1204         if (argc > 1)
1205                 usage_with_options (fast_export_usage, options);
1206
1207         if (refspecs_list.nr) {
1208                 int i;
1209
1210                 for (i = 0; i < refspecs_list.nr; i++)
1211                         refspec_append(&refspecs, refspecs_list.items[i].string);
1212
1213                 string_list_clear(&refspecs_list, 1);
1214         }
1215
1216         if (use_done_feature)
1217                 printf("feature done\n");
1218
1219         if (import_filename && import_filename_if_exists)
1220                 die(_("Cannot pass both --import-marks and --import-marks-if-exists"));
1221         if (import_filename)
1222                 import_marks(import_filename, 0);
1223         else if (import_filename_if_exists)
1224                 import_marks(import_filename_if_exists, 1);
1225         lastimportid = last_idnum;
1226
1227         if (import_filename && revs.prune_data.nr)
1228                 full_tree = 1;
1229
1230         get_tags_and_duplicates(&revs.cmdline);
1231
1232         if (prepare_revision_walk(&revs))
1233                 die("revision walk setup failed");
1234         revs.diffopt.format_callback = show_filemodify;
1235         revs.diffopt.format_callback_data = &paths_of_changed_objects;
1236         revs.diffopt.flags.recursive = 1;
1237         while ((commit = get_revision(&revs))) {
1238                 if (has_unshown_parent(commit)) {
1239                         add_object_array(&commit->object, NULL, &commits);
1240                 }
1241                 else {
1242                         handle_commit(commit, &revs, &paths_of_changed_objects);
1243                         handle_tail(&commits, &revs, &paths_of_changed_objects);
1244                 }
1245         }
1246
1247         handle_tags_and_duplicates(&extra_refs);
1248         handle_tags_and_duplicates(&tag_refs);
1249         handle_deletes();
1250
1251         if (export_filename && lastimportid != last_idnum)
1252                 export_marks(export_filename);
1253
1254         if (use_done_feature)
1255                 printf("done\n");
1256
1257         refspec_clear(&refspecs);
1258
1259         return 0;
1260 }