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