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