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