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