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