builtin / log.con commit format-patch: add --range-diff option to embed diff in cover letter (31e2617)
   1/*
   2 * Builtin "git log" and related commands (show, whatchanged)
   3 *
   4 * (C) Copyright 2006 Linus Torvalds
   5 *               2006 Junio Hamano
   6 */
   7#include "cache.h"
   8#include "config.h"
   9#include "refs.h"
  10#include "object-store.h"
  11#include "color.h"
  12#include "commit.h"
  13#include "diff.h"
  14#include "revision.h"
  15#include "log-tree.h"
  16#include "builtin.h"
  17#include "tag.h"
  18#include "reflog-walk.h"
  19#include "patch-ids.h"
  20#include "run-command.h"
  21#include "shortlog.h"
  22#include "remote.h"
  23#include "string-list.h"
  24#include "parse-options.h"
  25#include "line-log.h"
  26#include "branch.h"
  27#include "streaming.h"
  28#include "version.h"
  29#include "mailmap.h"
  30#include "gpg-interface.h"
  31#include "progress.h"
  32#include "commit-slab.h"
  33#include "repository.h"
  34#include "interdiff.h"
  35#include "range-diff.h"
  36
  37#define MAIL_DEFAULT_WRAP 72
  38
  39/* Set a default date-time format for git log ("log.date" config variable) */
  40static const char *default_date_mode = NULL;
  41
  42static int default_abbrev_commit;
  43static int default_show_root = 1;
  44static int default_follow;
  45static int default_show_signature;
  46static int decoration_style;
  47static int decoration_given;
  48static int use_mailmap_config;
  49static const char *fmt_patch_subject_prefix = "PATCH";
  50static const char *fmt_pretty;
  51
  52static const char * const builtin_log_usage[] = {
  53        N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
  54        N_("git show [<options>] <object>..."),
  55        NULL
  56};
  57
  58struct line_opt_callback_data {
  59        struct rev_info *rev;
  60        const char *prefix;
  61        struct string_list args;
  62};
  63
  64static int auto_decoration_style(void)
  65{
  66        return (isatty(1) || pager_in_use()) ? DECORATE_SHORT_REFS : 0;
  67}
  68
  69static int parse_decoration_style(const char *value)
  70{
  71        switch (git_parse_maybe_bool(value)) {
  72        case 1:
  73                return DECORATE_SHORT_REFS;
  74        case 0:
  75                return 0;
  76        default:
  77                break;
  78        }
  79        if (!strcmp(value, "full"))
  80                return DECORATE_FULL_REFS;
  81        else if (!strcmp(value, "short"))
  82                return DECORATE_SHORT_REFS;
  83        else if (!strcmp(value, "auto"))
  84                return auto_decoration_style();
  85        return -1;
  86}
  87
  88static int decorate_callback(const struct option *opt, const char *arg, int unset)
  89{
  90        if (unset)
  91                decoration_style = 0;
  92        else if (arg)
  93                decoration_style = parse_decoration_style(arg);
  94        else
  95                decoration_style = DECORATE_SHORT_REFS;
  96
  97        if (decoration_style < 0)
  98                die(_("invalid --decorate option: %s"), arg);
  99
 100        decoration_given = 1;
 101
 102        return 0;
 103}
 104
 105static int log_line_range_callback(const struct option *option, const char *arg, int unset)
 106{
 107        struct line_opt_callback_data *data = option->value;
 108
 109        if (!arg)
 110                return -1;
 111
 112        data->rev->line_level_traverse = 1;
 113        string_list_append(&data->args, arg);
 114
 115        return 0;
 116}
 117
 118static void init_log_defaults(void)
 119{
 120        init_grep_defaults();
 121        init_diff_ui_defaults();
 122
 123        decoration_style = auto_decoration_style();
 124}
 125
 126static void cmd_log_init_defaults(struct rev_info *rev)
 127{
 128        if (fmt_pretty)
 129                get_commit_format(fmt_pretty, rev);
 130        if (default_follow)
 131                rev->diffopt.flags.default_follow_renames = 1;
 132        rev->verbose_header = 1;
 133        rev->diffopt.flags.recursive = 1;
 134        rev->diffopt.stat_width = -1; /* use full terminal width */
 135        rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
 136        rev->abbrev_commit = default_abbrev_commit;
 137        rev->show_root_diff = default_show_root;
 138        rev->subject_prefix = fmt_patch_subject_prefix;
 139        rev->show_signature = default_show_signature;
 140        rev->diffopt.flags.allow_textconv = 1;
 141
 142        if (default_date_mode)
 143                parse_date_format(default_date_mode, &rev->date_mode);
 144}
 145
 146static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
 147                         struct rev_info *rev, struct setup_revision_opt *opt)
 148{
 149        struct userformat_want w;
 150        int quiet = 0, source = 0, mailmap = 0;
 151        static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
 152        static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
 153        static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
 154        struct decoration_filter decoration_filter = {&decorate_refs_include,
 155                                                      &decorate_refs_exclude};
 156        static struct revision_sources revision_sources;
 157
 158        const struct option builtin_log_options[] = {
 159                OPT__QUIET(&quiet, N_("suppress diff output")),
 160                OPT_BOOL(0, "source", &source, N_("show source")),
 161                OPT_BOOL(0, "use-mailmap", &mailmap, N_("Use mail map file")),
 162                OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
 163                                N_("pattern"), N_("only decorate refs that match <pattern>")),
 164                OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
 165                                N_("pattern"), N_("do not decorate refs that match <pattern>")),
 166                { OPTION_CALLBACK, 0, "decorate", NULL, NULL, N_("decorate options"),
 167                  PARSE_OPT_OPTARG, decorate_callback},
 168                OPT_CALLBACK('L', NULL, &line_cb, "n,m:file",
 169                             N_("Process line range n,m in file, counting from 1"),
 170                             log_line_range_callback),
 171                OPT_END()
 172        };
 173
 174        line_cb.rev = rev;
 175        line_cb.prefix = prefix;
 176
 177        mailmap = use_mailmap_config;
 178        argc = parse_options(argc, argv, prefix,
 179                             builtin_log_options, builtin_log_usage,
 180                             PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
 181                             PARSE_OPT_KEEP_DASHDASH);
 182
 183        if (quiet)
 184                rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
 185        argc = setup_revisions(argc, argv, rev, opt);
 186
 187        /* Any arguments at this point are not recognized */
 188        if (argc > 1)
 189                die(_("unrecognized argument: %s"), argv[1]);
 190
 191        memset(&w, 0, sizeof(w));
 192        userformat_find_requirements(NULL, &w);
 193
 194        if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
 195                rev->show_notes = 1;
 196        if (rev->show_notes)
 197                init_display_notes(&rev->notes_opt);
 198
 199        if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
 200            rev->diffopt.filter || rev->diffopt.flags.follow_renames)
 201                rev->always_show_header = 0;
 202
 203        if (source) {
 204                init_revision_sources(&revision_sources);
 205                rev->sources = &revision_sources;
 206        }
 207
 208        if (mailmap) {
 209                rev->mailmap = xcalloc(1, sizeof(struct string_list));
 210                read_mailmap(rev->mailmap, NULL);
 211        }
 212
 213        if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
 214                /*
 215                 * "log --pretty=raw" is special; ignore UI oriented
 216                 * configuration variables such as decoration.
 217                 */
 218                if (!decoration_given)
 219                        decoration_style = 0;
 220                if (!rev->abbrev_commit_given)
 221                        rev->abbrev_commit = 0;
 222        }
 223
 224        if (decoration_style) {
 225                rev->show_decorations = 1;
 226                load_ref_decorations(&decoration_filter, decoration_style);
 227        }
 228
 229        if (rev->line_level_traverse)
 230                line_log_init(rev, line_cb.prefix, &line_cb.args);
 231
 232        setup_pager();
 233}
 234
 235static void cmd_log_init(int argc, const char **argv, const char *prefix,
 236                         struct rev_info *rev, struct setup_revision_opt *opt)
 237{
 238        cmd_log_init_defaults(rev);
 239        cmd_log_init_finish(argc, argv, prefix, rev, opt);
 240}
 241
 242/*
 243 * This gives a rough estimate for how many commits we
 244 * will print out in the list.
 245 */
 246static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
 247{
 248        int n = 0;
 249
 250        while (list) {
 251                struct commit *commit = list->item;
 252                unsigned int flags = commit->object.flags;
 253                list = list->next;
 254                if (!(flags & (TREESAME | UNINTERESTING)))
 255                        n++;
 256        }
 257        return n;
 258}
 259
 260static void show_early_header(struct rev_info *rev, const char *stage, int nr)
 261{
 262        if (rev->shown_one) {
 263                rev->shown_one = 0;
 264                if (rev->commit_format != CMIT_FMT_ONELINE)
 265                        putchar(rev->diffopt.line_termination);
 266        }
 267        fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
 268}
 269
 270static struct itimerval early_output_timer;
 271
 272static void log_show_early(struct rev_info *revs, struct commit_list *list)
 273{
 274        int i = revs->early_output, close_file = revs->diffopt.close_file;
 275        int show_header = 1;
 276
 277        revs->diffopt.close_file = 0;
 278        sort_in_topological_order(&list, revs->sort_order);
 279        while (list && i) {
 280                struct commit *commit = list->item;
 281                switch (simplify_commit(revs, commit)) {
 282                case commit_show:
 283                        if (show_header) {
 284                                int n = estimate_commit_count(revs, list);
 285                                show_early_header(revs, "incomplete", n);
 286                                show_header = 0;
 287                        }
 288                        log_tree_commit(revs, commit);
 289                        i--;
 290                        break;
 291                case commit_ignore:
 292                        break;
 293                case commit_error:
 294                        if (close_file)
 295                                fclose(revs->diffopt.file);
 296                        return;
 297                }
 298                list = list->next;
 299        }
 300
 301        /* Did we already get enough commits for the early output? */
 302        if (!i) {
 303                if (close_file)
 304                        fclose(revs->diffopt.file);
 305                return;
 306        }
 307
 308        /*
 309         * ..if no, then repeat it twice a second until we
 310         * do.
 311         *
 312         * NOTE! We don't use "it_interval", because if the
 313         * reader isn't listening, we want our output to be
 314         * throttled by the writing, and not have the timer
 315         * trigger every second even if we're blocked on a
 316         * reader!
 317         */
 318        early_output_timer.it_value.tv_sec = 0;
 319        early_output_timer.it_value.tv_usec = 500000;
 320        setitimer(ITIMER_REAL, &early_output_timer, NULL);
 321}
 322
 323static void early_output(int signal)
 324{
 325        show_early_output = log_show_early;
 326}
 327
 328static void setup_early_output(struct rev_info *rev)
 329{
 330        struct sigaction sa;
 331
 332        /*
 333         * Set up the signal handler, minimally intrusively:
 334         * we only set a single volatile integer word (not
 335         * using sigatomic_t - trying to avoid unnecessary
 336         * system dependencies and headers), and using
 337         * SA_RESTART.
 338         */
 339        memset(&sa, 0, sizeof(sa));
 340        sa.sa_handler = early_output;
 341        sigemptyset(&sa.sa_mask);
 342        sa.sa_flags = SA_RESTART;
 343        sigaction(SIGALRM, &sa, NULL);
 344
 345        /*
 346         * If we can get the whole output in less than a
 347         * tenth of a second, don't even bother doing the
 348         * early-output thing..
 349         *
 350         * This is a one-time-only trigger.
 351         */
 352        early_output_timer.it_value.tv_sec = 0;
 353        early_output_timer.it_value.tv_usec = 100000;
 354        setitimer(ITIMER_REAL, &early_output_timer, NULL);
 355}
 356
 357static void finish_early_output(struct rev_info *rev)
 358{
 359        int n = estimate_commit_count(rev, rev->commits);
 360        signal(SIGALRM, SIG_IGN);
 361        show_early_header(rev, "done", n);
 362}
 363
 364static int cmd_log_walk(struct rev_info *rev)
 365{
 366        struct commit *commit;
 367        int saved_nrl = 0;
 368        int saved_dcctc = 0, close_file = rev->diffopt.close_file;
 369
 370        if (rev->early_output)
 371                setup_early_output(rev);
 372
 373        if (prepare_revision_walk(rev))
 374                die(_("revision walk setup failed"));
 375
 376        if (rev->early_output)
 377                finish_early_output(rev);
 378
 379        /*
 380         * For --check and --exit-code, the exit code is based on CHECK_FAILED
 381         * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
 382         * retain that state information if replacing rev->diffopt in this loop
 383         */
 384        rev->diffopt.close_file = 0;
 385        while ((commit = get_revision(rev)) != NULL) {
 386                if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
 387                        /*
 388                         * We decremented max_count in get_revision,
 389                         * but we didn't actually show the commit.
 390                         */
 391                        rev->max_count++;
 392                if (!rev->reflog_info) {
 393                        /*
 394                         * We may show a given commit multiple times when
 395                         * walking the reflogs.
 396                         */
 397                        free_commit_buffer(commit);
 398                        free_commit_list(commit->parents);
 399                        commit->parents = NULL;
 400                }
 401                if (saved_nrl < rev->diffopt.needed_rename_limit)
 402                        saved_nrl = rev->diffopt.needed_rename_limit;
 403                if (rev->diffopt.degraded_cc_to_c)
 404                        saved_dcctc = 1;
 405        }
 406        rev->diffopt.degraded_cc_to_c = saved_dcctc;
 407        rev->diffopt.needed_rename_limit = saved_nrl;
 408        if (close_file)
 409                fclose(rev->diffopt.file);
 410
 411        if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
 412            rev->diffopt.flags.check_failed) {
 413                return 02;
 414        }
 415        return diff_result_code(&rev->diffopt, 0);
 416}
 417
 418static int git_log_config(const char *var, const char *value, void *cb)
 419{
 420        const char *slot_name;
 421
 422        if (!strcmp(var, "format.pretty"))
 423                return git_config_string(&fmt_pretty, var, value);
 424        if (!strcmp(var, "format.subjectprefix"))
 425                return git_config_string(&fmt_patch_subject_prefix, var, value);
 426        if (!strcmp(var, "log.abbrevcommit")) {
 427                default_abbrev_commit = git_config_bool(var, value);
 428                return 0;
 429        }
 430        if (!strcmp(var, "log.date"))
 431                return git_config_string(&default_date_mode, var, value);
 432        if (!strcmp(var, "log.decorate")) {
 433                decoration_style = parse_decoration_style(value);
 434                if (decoration_style < 0)
 435                        decoration_style = 0; /* maybe warn? */
 436                return 0;
 437        }
 438        if (!strcmp(var, "log.showroot")) {
 439                default_show_root = git_config_bool(var, value);
 440                return 0;
 441        }
 442        if (!strcmp(var, "log.follow")) {
 443                default_follow = git_config_bool(var, value);
 444                return 0;
 445        }
 446        if (skip_prefix(var, "color.decorate.", &slot_name))
 447                return parse_decorate_color_config(var, slot_name, value);
 448        if (!strcmp(var, "log.mailmap")) {
 449                use_mailmap_config = git_config_bool(var, value);
 450                return 0;
 451        }
 452        if (!strcmp(var, "log.showsignature")) {
 453                default_show_signature = git_config_bool(var, value);
 454                return 0;
 455        }
 456
 457        if (grep_config(var, value, cb) < 0)
 458                return -1;
 459        if (git_gpg_config(var, value, cb) < 0)
 460                return -1;
 461        return git_diff_ui_config(var, value, cb);
 462}
 463
 464int cmd_whatchanged(int argc, const char **argv, const char *prefix)
 465{
 466        struct rev_info rev;
 467        struct setup_revision_opt opt;
 468
 469        init_log_defaults();
 470        git_config(git_log_config, NULL);
 471
 472        init_revisions(&rev, prefix);
 473        rev.diff = 1;
 474        rev.simplify_history = 0;
 475        memset(&opt, 0, sizeof(opt));
 476        opt.def = "HEAD";
 477        opt.revarg_opt = REVARG_COMMITTISH;
 478        cmd_log_init(argc, argv, prefix, &rev, &opt);
 479        if (!rev.diffopt.output_format)
 480                rev.diffopt.output_format = DIFF_FORMAT_RAW;
 481        return cmd_log_walk(&rev);
 482}
 483
 484static void show_tagger(char *buf, int len, struct rev_info *rev)
 485{
 486        struct strbuf out = STRBUF_INIT;
 487        struct pretty_print_context pp = {0};
 488
 489        pp.fmt = rev->commit_format;
 490        pp.date_mode = rev->date_mode;
 491        pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
 492        fprintf(rev->diffopt.file, "%s", out.buf);
 493        strbuf_release(&out);
 494}
 495
 496static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
 497{
 498        struct object_id oidc;
 499        struct object_context obj_context;
 500        char *buf;
 501        unsigned long size;
 502
 503        fflush(rev->diffopt.file);
 504        if (!rev->diffopt.flags.textconv_set_via_cmdline ||
 505            !rev->diffopt.flags.allow_textconv)
 506                return stream_blob_to_fd(1, oid, NULL, 0);
 507
 508        if (get_oid_with_context(obj_name, GET_OID_RECORD_PATH,
 509                                 &oidc, &obj_context))
 510                die(_("Not a valid object name %s"), obj_name);
 511        if (!obj_context.path ||
 512            !textconv_object(obj_context.path, obj_context.mode, &oidc, 1, &buf, &size)) {
 513                free(obj_context.path);
 514                return stream_blob_to_fd(1, oid, NULL, 0);
 515        }
 516
 517        if (!buf)
 518                die(_("git show %s: bad file"), obj_name);
 519
 520        write_or_die(1, buf, size);
 521        free(obj_context.path);
 522        return 0;
 523}
 524
 525static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
 526{
 527        unsigned long size;
 528        enum object_type type;
 529        char *buf = read_object_file(oid, &type, &size);
 530        int offset = 0;
 531
 532        if (!buf)
 533                return error(_("Could not read object %s"), oid_to_hex(oid));
 534
 535        assert(type == OBJ_TAG);
 536        while (offset < size && buf[offset] != '\n') {
 537                int new_offset = offset + 1;
 538                while (new_offset < size && buf[new_offset++] != '\n')
 539                        ; /* do nothing */
 540                if (starts_with(buf + offset, "tagger "))
 541                        show_tagger(buf + offset + 7,
 542                                    new_offset - offset - 7, rev);
 543                offset = new_offset;
 544        }
 545
 546        if (offset < size)
 547                fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
 548        free(buf);
 549        return 0;
 550}
 551
 552static int show_tree_object(const struct object_id *oid,
 553                struct strbuf *base,
 554                const char *pathname, unsigned mode, int stage, void *context)
 555{
 556        FILE *file = context;
 557        fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
 558        return 0;
 559}
 560
 561static void show_setup_revisions_tweak(struct rev_info *rev,
 562                                       struct setup_revision_opt *opt)
 563{
 564        if (rev->ignore_merges) {
 565                /* There was no "-m" on the command line */
 566                rev->ignore_merges = 0;
 567                if (!rev->first_parent_only && !rev->combine_merges) {
 568                        /* No "--first-parent", "-c", or "--cc" */
 569                        rev->combine_merges = 1;
 570                        rev->dense_combined_merges = 1;
 571                }
 572        }
 573        if (!rev->diffopt.output_format)
 574                rev->diffopt.output_format = DIFF_FORMAT_PATCH;
 575}
 576
 577int cmd_show(int argc, const char **argv, const char *prefix)
 578{
 579        struct rev_info rev;
 580        struct object_array_entry *objects;
 581        struct setup_revision_opt opt;
 582        struct pathspec match_all;
 583        int i, count, ret = 0;
 584
 585        init_log_defaults();
 586        git_config(git_log_config, NULL);
 587
 588        memset(&match_all, 0, sizeof(match_all));
 589        init_revisions(&rev, prefix);
 590        rev.diff = 1;
 591        rev.always_show_header = 1;
 592        rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
 593        rev.diffopt.stat_width = -1;    /* Scale to real terminal size */
 594
 595        memset(&opt, 0, sizeof(opt));
 596        opt.def = "HEAD";
 597        opt.tweak = show_setup_revisions_tweak;
 598        cmd_log_init(argc, argv, prefix, &rev, &opt);
 599
 600        if (!rev.no_walk)
 601                return cmd_log_walk(&rev);
 602
 603        count = rev.pending.nr;
 604        objects = rev.pending.objects;
 605        for (i = 0; i < count && !ret; i++) {
 606                struct object *o = objects[i].item;
 607                const char *name = objects[i].name;
 608                switch (o->type) {
 609                case OBJ_BLOB:
 610                        ret = show_blob_object(&o->oid, &rev, name);
 611                        break;
 612                case OBJ_TAG: {
 613                        struct tag *t = (struct tag *)o;
 614
 615                        if (rev.shown_one)
 616                                putchar('\n');
 617                        fprintf(rev.diffopt.file, "%stag %s%s\n",
 618                                        diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
 619                                        t->tag,
 620                                        diff_get_color_opt(&rev.diffopt, DIFF_RESET));
 621                        ret = show_tag_object(&o->oid, &rev);
 622                        rev.shown_one = 1;
 623                        if (ret)
 624                                break;
 625                        o = parse_object(the_repository, &t->tagged->oid);
 626                        if (!o)
 627                                ret = error(_("Could not read object %s"),
 628                                            oid_to_hex(&t->tagged->oid));
 629                        objects[i].item = o;
 630                        i--;
 631                        break;
 632                }
 633                case OBJ_TREE:
 634                        if (rev.shown_one)
 635                                putchar('\n');
 636                        fprintf(rev.diffopt.file, "%stree %s%s\n\n",
 637                                        diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
 638                                        name,
 639                                        diff_get_color_opt(&rev.diffopt, DIFF_RESET));
 640                        read_tree_recursive((struct tree *)o, "", 0, 0, &match_all,
 641                                        show_tree_object, rev.diffopt.file);
 642                        rev.shown_one = 1;
 643                        break;
 644                case OBJ_COMMIT:
 645                        rev.pending.nr = rev.pending.alloc = 0;
 646                        rev.pending.objects = NULL;
 647                        add_object_array(o, name, &rev.pending);
 648                        ret = cmd_log_walk(&rev);
 649                        break;
 650                default:
 651                        ret = error(_("Unknown type: %d"), o->type);
 652                }
 653        }
 654        free(objects);
 655        return ret;
 656}
 657
 658/*
 659 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
 660 */
 661int cmd_log_reflog(int argc, const char **argv, const char *prefix)
 662{
 663        struct rev_info rev;
 664        struct setup_revision_opt opt;
 665
 666        init_log_defaults();
 667        git_config(git_log_config, NULL);
 668
 669        init_revisions(&rev, prefix);
 670        init_reflog_walk(&rev.reflog_info);
 671        rev.verbose_header = 1;
 672        memset(&opt, 0, sizeof(opt));
 673        opt.def = "HEAD";
 674        cmd_log_init_defaults(&rev);
 675        rev.abbrev_commit = 1;
 676        rev.commit_format = CMIT_FMT_ONELINE;
 677        rev.use_terminator = 1;
 678        rev.always_show_header = 1;
 679        cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
 680
 681        return cmd_log_walk(&rev);
 682}
 683
 684static void log_setup_revisions_tweak(struct rev_info *rev,
 685                                      struct setup_revision_opt *opt)
 686{
 687        if (rev->diffopt.flags.default_follow_renames &&
 688            rev->prune_data.nr == 1)
 689                rev->diffopt.flags.follow_renames = 1;
 690
 691        /* Turn --cc/-c into -p --cc/-c when -p was not given */
 692        if (!rev->diffopt.output_format && rev->combine_merges)
 693                rev->diffopt.output_format = DIFF_FORMAT_PATCH;
 694
 695        /* Turn -m on when --cc/-c was given */
 696        if (rev->combine_merges)
 697                rev->ignore_merges = 0;
 698}
 699
 700int cmd_log(int argc, const char **argv, const char *prefix)
 701{
 702        struct rev_info rev;
 703        struct setup_revision_opt opt;
 704
 705        init_log_defaults();
 706        git_config(git_log_config, NULL);
 707
 708        init_revisions(&rev, prefix);
 709        rev.always_show_header = 1;
 710        memset(&opt, 0, sizeof(opt));
 711        opt.def = "HEAD";
 712        opt.revarg_opt = REVARG_COMMITTISH;
 713        opt.tweak = log_setup_revisions_tweak;
 714        cmd_log_init(argc, argv, prefix, &rev, &opt);
 715        return cmd_log_walk(&rev);
 716}
 717
 718/* format-patch */
 719
 720static const char *fmt_patch_suffix = ".patch";
 721static int numbered = 0;
 722static int auto_number = 1;
 723
 724static char *default_attach = NULL;
 725
 726static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
 727static struct string_list extra_to = STRING_LIST_INIT_NODUP;
 728static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
 729
 730static void add_header(const char *value)
 731{
 732        struct string_list_item *item;
 733        int len = strlen(value);
 734        while (len && value[len - 1] == '\n')
 735                len--;
 736
 737        if (!strncasecmp(value, "to: ", 4)) {
 738                item = string_list_append(&extra_to, value + 4);
 739                len -= 4;
 740        } else if (!strncasecmp(value, "cc: ", 4)) {
 741                item = string_list_append(&extra_cc, value + 4);
 742                len -= 4;
 743        } else {
 744                item = string_list_append(&extra_hdr, value);
 745        }
 746
 747        item->string[len] = '\0';
 748}
 749
 750#define THREAD_SHALLOW 1
 751#define THREAD_DEEP 2
 752static int thread;
 753static int do_signoff;
 754static int base_auto;
 755static char *from;
 756static const char *signature = git_version_string;
 757static const char *signature_file;
 758static int config_cover_letter;
 759static const char *config_output_directory;
 760
 761enum {
 762        COVER_UNSET,
 763        COVER_OFF,
 764        COVER_ON,
 765        COVER_AUTO
 766};
 767
 768static int git_format_config(const char *var, const char *value, void *cb)
 769{
 770        if (!strcmp(var, "format.headers")) {
 771                if (!value)
 772                        die(_("format.headers without value"));
 773                add_header(value);
 774                return 0;
 775        }
 776        if (!strcmp(var, "format.suffix"))
 777                return git_config_string(&fmt_patch_suffix, var, value);
 778        if (!strcmp(var, "format.to")) {
 779                if (!value)
 780                        return config_error_nonbool(var);
 781                string_list_append(&extra_to, value);
 782                return 0;
 783        }
 784        if (!strcmp(var, "format.cc")) {
 785                if (!value)
 786                        return config_error_nonbool(var);
 787                string_list_append(&extra_cc, value);
 788                return 0;
 789        }
 790        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
 791            !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
 792                return 0;
 793        }
 794        if (!strcmp(var, "format.numbered")) {
 795                if (value && !strcasecmp(value, "auto")) {
 796                        auto_number = 1;
 797                        return 0;
 798                }
 799                numbered = git_config_bool(var, value);
 800                auto_number = auto_number && numbered;
 801                return 0;
 802        }
 803        if (!strcmp(var, "format.attach")) {
 804                if (value && *value)
 805                        default_attach = xstrdup(value);
 806                else
 807                        default_attach = xstrdup(git_version_string);
 808                return 0;
 809        }
 810        if (!strcmp(var, "format.thread")) {
 811                if (value && !strcasecmp(value, "deep")) {
 812                        thread = THREAD_DEEP;
 813                        return 0;
 814                }
 815                if (value && !strcasecmp(value, "shallow")) {
 816                        thread = THREAD_SHALLOW;
 817                        return 0;
 818                }
 819                thread = git_config_bool(var, value) && THREAD_SHALLOW;
 820                return 0;
 821        }
 822        if (!strcmp(var, "format.signoff")) {
 823                do_signoff = git_config_bool(var, value);
 824                return 0;
 825        }
 826        if (!strcmp(var, "format.signature"))
 827                return git_config_string(&signature, var, value);
 828        if (!strcmp(var, "format.signaturefile"))
 829                return git_config_pathname(&signature_file, var, value);
 830        if (!strcmp(var, "format.coverletter")) {
 831                if (value && !strcasecmp(value, "auto")) {
 832                        config_cover_letter = COVER_AUTO;
 833                        return 0;
 834                }
 835                config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
 836                return 0;
 837        }
 838        if (!strcmp(var, "format.outputdirectory"))
 839                return git_config_string(&config_output_directory, var, value);
 840        if (!strcmp(var, "format.useautobase")) {
 841                base_auto = git_config_bool(var, value);
 842                return 0;
 843        }
 844        if (!strcmp(var, "format.from")) {
 845                int b = git_parse_maybe_bool(value);
 846                free(from);
 847                if (b < 0)
 848                        from = xstrdup(value);
 849                else if (b)
 850                        from = xstrdup(git_committer_info(IDENT_NO_DATE));
 851                else
 852                        from = NULL;
 853                return 0;
 854        }
 855
 856        return git_log_config(var, value, cb);
 857}
 858
 859static const char *output_directory = NULL;
 860static int outdir_offset;
 861
 862static int open_next_file(struct commit *commit, const char *subject,
 863                         struct rev_info *rev, int quiet)
 864{
 865        struct strbuf filename = STRBUF_INIT;
 866        int suffix_len = strlen(rev->patch_suffix) + 1;
 867
 868        if (output_directory) {
 869                strbuf_addstr(&filename, output_directory);
 870                if (filename.len >=
 871                    PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len) {
 872                        strbuf_release(&filename);
 873                        return error(_("name of output directory is too long"));
 874                }
 875                strbuf_complete(&filename, '/');
 876        }
 877
 878        if (rev->numbered_files)
 879                strbuf_addf(&filename, "%d", rev->nr);
 880        else if (commit)
 881                fmt_output_commit(&filename, commit, rev);
 882        else
 883                fmt_output_subject(&filename, subject, rev);
 884
 885        if (!quiet)
 886                printf("%s\n", filename.buf + outdir_offset);
 887
 888        if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
 889                error_errno(_("Cannot open patch file %s"), filename.buf);
 890                strbuf_release(&filename);
 891                return -1;
 892        }
 893
 894        strbuf_release(&filename);
 895        return 0;
 896}
 897
 898static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
 899{
 900        struct rev_info check_rev;
 901        struct commit *commit, *c1, *c2;
 902        struct object *o1, *o2;
 903        unsigned flags1, flags2;
 904
 905        if (rev->pending.nr != 2)
 906                die(_("Need exactly one range."));
 907
 908        o1 = rev->pending.objects[0].item;
 909        o2 = rev->pending.objects[1].item;
 910        flags1 = o1->flags;
 911        flags2 = o2->flags;
 912        c1 = lookup_commit_reference(the_repository, &o1->oid);
 913        c2 = lookup_commit_reference(the_repository, &o2->oid);
 914
 915        if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
 916                die(_("Not a range."));
 917
 918        init_patch_ids(ids);
 919
 920        /* given a range a..b get all patch ids for b..a */
 921        init_revisions(&check_rev, rev->prefix);
 922        check_rev.max_parents = 1;
 923        o1->flags ^= UNINTERESTING;
 924        o2->flags ^= UNINTERESTING;
 925        add_pending_object(&check_rev, o1, "o1");
 926        add_pending_object(&check_rev, o2, "o2");
 927        if (prepare_revision_walk(&check_rev))
 928                die(_("revision walk setup failed"));
 929
 930        while ((commit = get_revision(&check_rev)) != NULL) {
 931                add_commit_patch_id(commit, ids);
 932        }
 933
 934        /* reset for next revision walk */
 935        clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
 936        clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
 937        o1->flags = flags1;
 938        o2->flags = flags2;
 939}
 940
 941static void gen_message_id(struct rev_info *info, char *base)
 942{
 943        struct strbuf buf = STRBUF_INIT;
 944        strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
 945                    (timestamp_t) time(NULL),
 946                    git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
 947        info->message_id = strbuf_detach(&buf, NULL);
 948}
 949
 950static void print_signature(FILE *file)
 951{
 952        if (!signature || !*signature)
 953                return;
 954
 955        fprintf(file, "-- \n%s", signature);
 956        if (signature[strlen(signature)-1] != '\n')
 957                putc('\n', file);
 958        putc('\n', file);
 959}
 960
 961static void add_branch_description(struct strbuf *buf, const char *branch_name)
 962{
 963        struct strbuf desc = STRBUF_INIT;
 964        if (!branch_name || !*branch_name)
 965                return;
 966        read_branch_desc(&desc, branch_name);
 967        if (desc.len) {
 968                strbuf_addch(buf, '\n');
 969                strbuf_addbuf(buf, &desc);
 970                strbuf_addch(buf, '\n');
 971        }
 972        strbuf_release(&desc);
 973}
 974
 975static char *find_branch_name(struct rev_info *rev)
 976{
 977        int i, positive = -1;
 978        struct object_id branch_oid;
 979        const struct object_id *tip_oid;
 980        const char *ref, *v;
 981        char *full_ref, *branch = NULL;
 982
 983        for (i = 0; i < rev->cmdline.nr; i++) {
 984                if (rev->cmdline.rev[i].flags & UNINTERESTING)
 985                        continue;
 986                if (positive < 0)
 987                        positive = i;
 988                else
 989                        return NULL;
 990        }
 991        if (positive < 0)
 992                return NULL;
 993        ref = rev->cmdline.rev[positive].name;
 994        tip_oid = &rev->cmdline.rev[positive].item->oid;
 995        if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref) &&
 996            skip_prefix(full_ref, "refs/heads/", &v) &&
 997            !oidcmp(tip_oid, &branch_oid))
 998                branch = xstrdup(v);
 999        free(full_ref);
1000        return branch;
1001}
1002
1003static void show_diffstat(struct rev_info *rev,
1004                          struct commit *origin, struct commit *head)
1005{
1006        struct diff_options opts;
1007
1008        memcpy(&opts, &rev->diffopt, sizeof(opts));
1009        opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1010        opts.stat_width = MAIL_DEFAULT_WRAP;
1011
1012        diff_setup_done(&opts);
1013
1014        diff_tree_oid(get_commit_tree_oid(origin),
1015                      get_commit_tree_oid(head),
1016                      "", &opts);
1017        diffcore_std(&opts);
1018        diff_flush(&opts);
1019
1020        fprintf(rev->diffopt.file, "\n");
1021}
1022
1023static void make_cover_letter(struct rev_info *rev, int use_stdout,
1024                              struct commit *origin,
1025                              int nr, struct commit **list,
1026                              const char *branch_name,
1027                              int quiet)
1028{
1029        const char *committer;
1030        const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
1031        const char *msg;
1032        struct shortlog log;
1033        struct strbuf sb = STRBUF_INIT;
1034        int i;
1035        const char *encoding = "UTF-8";
1036        int need_8bit_cte = 0;
1037        struct pretty_print_context pp = {0};
1038        struct commit *head = list[0];
1039
1040        if (!cmit_fmt_is_mail(rev->commit_format))
1041                die(_("Cover letter needs email format"));
1042
1043        committer = git_committer_info(0);
1044
1045        if (!use_stdout &&
1046            open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1047                return;
1048
1049        log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1050
1051        for (i = 0; !need_8bit_cte && i < nr; i++) {
1052                const char *buf = get_commit_buffer(list[i], NULL);
1053                if (has_non_ascii(buf))
1054                        need_8bit_cte = 1;
1055                unuse_commit_buffer(list[i], buf);
1056        }
1057
1058        if (!branch_name)
1059                branch_name = find_branch_name(rev);
1060
1061        msg = body;
1062        pp.fmt = CMIT_FMT_EMAIL;
1063        pp.date_mode.type = DATE_RFC2822;
1064        pp.rev = rev;
1065        pp.print_email_subject = 1;
1066        pp_user_info(&pp, NULL, &sb, committer, encoding);
1067        pp_title_line(&pp, &msg, &sb, encoding, need_8bit_cte);
1068        pp_remainder(&pp, &msg, &sb, 0);
1069        add_branch_description(&sb, branch_name);
1070        fprintf(rev->diffopt.file, "%s\n", sb.buf);
1071
1072        strbuf_release(&sb);
1073
1074        shortlog_init(&log);
1075        log.wrap_lines = 1;
1076        log.wrap = MAIL_DEFAULT_WRAP;
1077        log.in1 = 2;
1078        log.in2 = 4;
1079        log.file = rev->diffopt.file;
1080        for (i = 0; i < nr; i++)
1081                shortlog_add_commit(&log, list[i]);
1082
1083        shortlog_output(&log);
1084
1085        /* We can only do diffstat with a unique reference point */
1086        if (origin)
1087                show_diffstat(rev, origin, head);
1088
1089        if (rev->idiff_oid1) {
1090                fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1091                show_interdiff(rev, 0);
1092        }
1093
1094        if (rev->rdiff1) {
1095                fprintf_ln(rev->diffopt.file, "%s", _("Range-diff:"));
1096                show_range_diff(rev->rdiff1, rev->rdiff2,
1097                                rev->creation_factor, 1, &rev->diffopt);
1098        }
1099}
1100
1101static const char *clean_message_id(const char *msg_id)
1102{
1103        char ch;
1104        const char *a, *z, *m;
1105
1106        m = msg_id;
1107        while ((ch = *m) && (isspace(ch) || (ch == '<')))
1108                m++;
1109        a = m;
1110        z = NULL;
1111        while ((ch = *m)) {
1112                if (!isspace(ch) && (ch != '>'))
1113                        z = m;
1114                m++;
1115        }
1116        if (!z)
1117                die(_("insane in-reply-to: %s"), msg_id);
1118        if (++z == m)
1119                return a;
1120        return xmemdupz(a, z - a);
1121}
1122
1123static const char *set_outdir(const char *prefix, const char *output_directory)
1124{
1125        if (output_directory && is_absolute_path(output_directory))
1126                return output_directory;
1127
1128        if (!prefix || !*prefix) {
1129                if (output_directory)
1130                        return output_directory;
1131                /* The user did not explicitly ask for "./" */
1132                outdir_offset = 2;
1133                return "./";
1134        }
1135
1136        outdir_offset = strlen(prefix);
1137        if (!output_directory)
1138                return prefix;
1139
1140        return prefix_filename(prefix, output_directory);
1141}
1142
1143static const char * const builtin_format_patch_usage[] = {
1144        N_("git format-patch [<options>] [<since> | <revision-range>]"),
1145        NULL
1146};
1147
1148static int keep_subject = 0;
1149
1150static int keep_callback(const struct option *opt, const char *arg, int unset)
1151{
1152        ((struct rev_info *)opt->value)->total = -1;
1153        keep_subject = 1;
1154        return 0;
1155}
1156
1157static int subject_prefix = 0;
1158
1159static int subject_prefix_callback(const struct option *opt, const char *arg,
1160                            int unset)
1161{
1162        subject_prefix = 1;
1163        ((struct rev_info *)opt->value)->subject_prefix = arg;
1164        return 0;
1165}
1166
1167static int rfc_callback(const struct option *opt, const char *arg, int unset)
1168{
1169        return subject_prefix_callback(opt, "RFC PATCH", unset);
1170}
1171
1172static int numbered_cmdline_opt = 0;
1173
1174static int numbered_callback(const struct option *opt, const char *arg,
1175                             int unset)
1176{
1177        *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1178        if (unset)
1179                auto_number =  0;
1180        return 0;
1181}
1182
1183static int no_numbered_callback(const struct option *opt, const char *arg,
1184                                int unset)
1185{
1186        return numbered_callback(opt, arg, 1);
1187}
1188
1189static int output_directory_callback(const struct option *opt, const char *arg,
1190                              int unset)
1191{
1192        const char **dir = (const char **)opt->value;
1193        if (*dir)
1194                die(_("Two output directories?"));
1195        *dir = arg;
1196        return 0;
1197}
1198
1199static int thread_callback(const struct option *opt, const char *arg, int unset)
1200{
1201        int *thread = (int *)opt->value;
1202        if (unset)
1203                *thread = 0;
1204        else if (!arg || !strcmp(arg, "shallow"))
1205                *thread = THREAD_SHALLOW;
1206        else if (!strcmp(arg, "deep"))
1207                *thread = THREAD_DEEP;
1208        else
1209                return 1;
1210        return 0;
1211}
1212
1213static int attach_callback(const struct option *opt, const char *arg, int unset)
1214{
1215        struct rev_info *rev = (struct rev_info *)opt->value;
1216        if (unset)
1217                rev->mime_boundary = NULL;
1218        else if (arg)
1219                rev->mime_boundary = arg;
1220        else
1221                rev->mime_boundary = git_version_string;
1222        rev->no_inline = unset ? 0 : 1;
1223        return 0;
1224}
1225
1226static int inline_callback(const struct option *opt, const char *arg, int unset)
1227{
1228        struct rev_info *rev = (struct rev_info *)opt->value;
1229        if (unset)
1230                rev->mime_boundary = NULL;
1231        else if (arg)
1232                rev->mime_boundary = arg;
1233        else
1234                rev->mime_boundary = git_version_string;
1235        rev->no_inline = 0;
1236        return 0;
1237}
1238
1239static int header_callback(const struct option *opt, const char *arg, int unset)
1240{
1241        if (unset) {
1242                string_list_clear(&extra_hdr, 0);
1243                string_list_clear(&extra_to, 0);
1244                string_list_clear(&extra_cc, 0);
1245        } else {
1246            add_header(arg);
1247        }
1248        return 0;
1249}
1250
1251static int to_callback(const struct option *opt, const char *arg, int unset)
1252{
1253        if (unset)
1254                string_list_clear(&extra_to, 0);
1255        else
1256                string_list_append(&extra_to, arg);
1257        return 0;
1258}
1259
1260static int cc_callback(const struct option *opt, const char *arg, int unset)
1261{
1262        if (unset)
1263                string_list_clear(&extra_cc, 0);
1264        else
1265                string_list_append(&extra_cc, arg);
1266        return 0;
1267}
1268
1269static int from_callback(const struct option *opt, const char *arg, int unset)
1270{
1271        char **from = opt->value;
1272
1273        free(*from);
1274
1275        if (unset)
1276                *from = NULL;
1277        else if (arg)
1278                *from = xstrdup(arg);
1279        else
1280                *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1281        return 0;
1282}
1283
1284struct base_tree_info {
1285        struct object_id base_commit;
1286        int nr_patch_id, alloc_patch_id;
1287        struct object_id *patch_id;
1288};
1289
1290static struct commit *get_base_commit(const char *base_commit,
1291                                      struct commit **list,
1292                                      int total)
1293{
1294        struct commit *base = NULL;
1295        struct commit **rev;
1296        int i = 0, rev_nr = 0;
1297
1298        if (base_commit && strcmp(base_commit, "auto")) {
1299                base = lookup_commit_reference_by_name(base_commit);
1300                if (!base)
1301                        die(_("Unknown commit %s"), base_commit);
1302        } else if ((base_commit && !strcmp(base_commit, "auto")) || base_auto) {
1303                struct branch *curr_branch = branch_get(NULL);
1304                const char *upstream = branch_get_upstream(curr_branch, NULL);
1305                if (upstream) {
1306                        struct commit_list *base_list;
1307                        struct commit *commit;
1308                        struct object_id oid;
1309
1310                        if (get_oid(upstream, &oid))
1311                                die(_("Failed to resolve '%s' as a valid ref."), upstream);
1312                        commit = lookup_commit_or_die(&oid, "upstream base");
1313                        base_list = get_merge_bases_many(commit, total, list);
1314                        /* There should be one and only one merge base. */
1315                        if (!base_list || base_list->next)
1316                                die(_("Could not find exact merge base."));
1317                        base = base_list->item;
1318                        free_commit_list(base_list);
1319                } else {
1320                        die(_("Failed to get upstream, if you want to record base commit automatically,\n"
1321                              "please use git branch --set-upstream-to to track a remote branch.\n"
1322                              "Or you could specify base commit by --base=<base-commit-id> manually."));
1323                }
1324        }
1325
1326        ALLOC_ARRAY(rev, total);
1327        for (i = 0; i < total; i++)
1328                rev[i] = list[i];
1329
1330        rev_nr = total;
1331        /*
1332         * Get merge base through pair-wise computations
1333         * and store it in rev[0].
1334         */
1335        while (rev_nr > 1) {
1336                for (i = 0; i < rev_nr / 2; i++) {
1337                        struct commit_list *merge_base;
1338                        merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1339                        if (!merge_base || merge_base->next)
1340                                die(_("Failed to find exact merge base"));
1341
1342                        rev[i] = merge_base->item;
1343                }
1344
1345                if (rev_nr % 2)
1346                        rev[i] = rev[2 * i];
1347                rev_nr = DIV_ROUND_UP(rev_nr, 2);
1348        }
1349
1350        if (!in_merge_bases(base, rev[0]))
1351                die(_("base commit should be the ancestor of revision list"));
1352
1353        for (i = 0; i < total; i++) {
1354                if (base == list[i])
1355                        die(_("base commit shouldn't be in revision list"));
1356        }
1357
1358        free(rev);
1359        return base;
1360}
1361
1362define_commit_slab(commit_base, int);
1363
1364static void prepare_bases(struct base_tree_info *bases,
1365                          struct commit *base,
1366                          struct commit **list,
1367                          int total)
1368{
1369        struct commit *commit;
1370        struct rev_info revs;
1371        struct diff_options diffopt;
1372        struct commit_base commit_base;
1373        int i;
1374
1375        if (!base)
1376                return;
1377
1378        init_commit_base(&commit_base);
1379        diff_setup(&diffopt);
1380        diffopt.flags.recursive = 1;
1381        diff_setup_done(&diffopt);
1382
1383        oidcpy(&bases->base_commit, &base->object.oid);
1384
1385        init_revisions(&revs, NULL);
1386        revs.max_parents = 1;
1387        revs.topo_order = 1;
1388        for (i = 0; i < total; i++) {
1389                list[i]->object.flags &= ~UNINTERESTING;
1390                add_pending_object(&revs, &list[i]->object, "rev_list");
1391                *commit_base_at(&commit_base, list[i]) = 1;
1392        }
1393        base->object.flags |= UNINTERESTING;
1394        add_pending_object(&revs, &base->object, "base");
1395
1396        if (prepare_revision_walk(&revs))
1397                die(_("revision walk setup failed"));
1398        /*
1399         * Traverse the commits list, get prerequisite patch ids
1400         * and stuff them in bases structure.
1401         */
1402        while ((commit = get_revision(&revs)) != NULL) {
1403                struct object_id oid;
1404                struct object_id *patch_id;
1405                if (*commit_base_at(&commit_base, commit))
1406                        continue;
1407                if (commit_patch_id(commit, &diffopt, &oid, 0))
1408                        die(_("cannot get patch id"));
1409                ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1410                patch_id = bases->patch_id + bases->nr_patch_id;
1411                oidcpy(patch_id, &oid);
1412                bases->nr_patch_id++;
1413        }
1414        clear_commit_base(&commit_base);
1415}
1416
1417static void print_bases(struct base_tree_info *bases, FILE *file)
1418{
1419        int i;
1420
1421        /* Only do this once, either for the cover or for the first one */
1422        if (is_null_oid(&bases->base_commit))
1423                return;
1424
1425        /* Show the base commit */
1426        fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1427
1428        /* Show the prerequisite patches */
1429        for (i = bases->nr_patch_id - 1; i >= 0; i--)
1430                fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1431
1432        free(bases->patch_id);
1433        bases->nr_patch_id = 0;
1434        bases->alloc_patch_id = 0;
1435        oidclr(&bases->base_commit);
1436}
1437
1438static const char *diff_title(struct strbuf *sb, int reroll_count,
1439                       const char *generic, const char *rerolled)
1440{
1441        if (reroll_count <= 0)
1442                strbuf_addstr(sb, generic);
1443        else /* RFC may be v0, so allow -v1 to diff against v0 */
1444                strbuf_addf(sb, rerolled, reroll_count - 1);
1445        return sb->buf;
1446}
1447
1448static void infer_range_diff_ranges(struct strbuf *r1,
1449                                    struct strbuf *r2,
1450                                    const char *prev,
1451                                    struct commit *head)
1452{
1453        const char *head_oid = oid_to_hex(&head->object.oid);
1454
1455        strbuf_addf(r1, "%s..%s", head_oid, prev);
1456        strbuf_addf(r2, "%s..%s", prev, head_oid);
1457}
1458
1459int cmd_format_patch(int argc, const char **argv, const char *prefix)
1460{
1461        struct commit *commit;
1462        struct commit **list = NULL;
1463        struct rev_info rev;
1464        struct setup_revision_opt s_r_opt;
1465        int nr = 0, total, i;
1466        int use_stdout = 0;
1467        int start_number = -1;
1468        int just_numbers = 0;
1469        int ignore_if_in_upstream = 0;
1470        int cover_letter = -1;
1471        int boundary_count = 0;
1472        int no_binary_diff = 0;
1473        int zero_commit = 0;
1474        struct commit *origin = NULL;
1475        const char *in_reply_to = NULL;
1476        struct patch_ids ids;
1477        struct strbuf buf = STRBUF_INIT;
1478        int use_patch_format = 0;
1479        int quiet = 0;
1480        int reroll_count = -1;
1481        char *branch_name = NULL;
1482        char *base_commit = NULL;
1483        struct base_tree_info bases;
1484        int show_progress = 0;
1485        struct progress *progress = NULL;
1486        struct oid_array idiff_prev = OID_ARRAY_INIT;
1487        struct strbuf idiff_title = STRBUF_INIT;
1488        const char *rdiff_prev = NULL;
1489        struct strbuf rdiff1 = STRBUF_INIT;
1490        struct strbuf rdiff2 = STRBUF_INIT;
1491
1492        const struct option builtin_format_patch_options[] = {
1493                { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1494                            N_("use [PATCH n/m] even with a single patch"),
1495                            PARSE_OPT_NOARG, numbered_callback },
1496                { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1497                            N_("use [PATCH] even with multiple patches"),
1498                            PARSE_OPT_NOARG, no_numbered_callback },
1499                OPT_BOOL('s', "signoff", &do_signoff, N_("add Signed-off-by:")),
1500                OPT_BOOL(0, "stdout", &use_stdout,
1501                            N_("print patches to standard out")),
1502                OPT_BOOL(0, "cover-letter", &cover_letter,
1503                            N_("generate a cover letter")),
1504                OPT_BOOL(0, "numbered-files", &just_numbers,
1505                            N_("use simple number sequence for output file names")),
1506                OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1507                            N_("use <sfx> instead of '.patch'")),
1508                OPT_INTEGER(0, "start-number", &start_number,
1509                            N_("start numbering patches at <n> instead of 1")),
1510                OPT_INTEGER('v', "reroll-count", &reroll_count,
1511                            N_("mark the series as Nth re-roll")),
1512                { OPTION_CALLBACK, 0, "rfc", &rev, NULL,
1513                            N_("Use [RFC PATCH] instead of [PATCH]"),
1514                            PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback },
1515                { OPTION_CALLBACK, 0, "subject-prefix", &rev, N_("prefix"),
1516                            N_("Use [<prefix>] instead of [PATCH]"),
1517                            PARSE_OPT_NONEG, subject_prefix_callback },
1518                { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1519                            N_("dir"), N_("store resulting files in <dir>"),
1520                            PARSE_OPT_NONEG, output_directory_callback },
1521                { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1522                            N_("don't strip/add [PATCH]"),
1523                            PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1524                OPT_BOOL(0, "no-binary", &no_binary_diff,
1525                         N_("don't output binary diffs")),
1526                OPT_BOOL(0, "zero-commit", &zero_commit,
1527                         N_("output all-zero hash in From header")),
1528                OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1529                         N_("don't include a patch matching a commit upstream")),
1530                OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1531                              N_("show patch format instead of default (patch + stat)"),
1532                              1, PARSE_OPT_NONEG),
1533                OPT_GROUP(N_("Messaging")),
1534                { OPTION_CALLBACK, 0, "add-header", NULL, N_("header"),
1535                            N_("add email header"), 0, header_callback },
1536                { OPTION_CALLBACK, 0, "to", NULL, N_("email"), N_("add To: header"),
1537                            0, to_callback },
1538                { OPTION_CALLBACK, 0, "cc", NULL, N_("email"), N_("add Cc: header"),
1539                            0, cc_callback },
1540                { OPTION_CALLBACK, 0, "from", &from, N_("ident"),
1541                            N_("set From address to <ident> (or committer ident if absent)"),
1542                            PARSE_OPT_OPTARG, from_callback },
1543                OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1544                            N_("make first mail a reply to <message-id>")),
1545                { OPTION_CALLBACK, 0, "attach", &rev, N_("boundary"),
1546                            N_("attach the patch"), PARSE_OPT_OPTARG,
1547                            attach_callback },
1548                { OPTION_CALLBACK, 0, "inline", &rev, N_("boundary"),
1549                            N_("inline the patch"),
1550                            PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1551                            inline_callback },
1552                { OPTION_CALLBACK, 0, "thread", &thread, N_("style"),
1553                            N_("enable message threading, styles: shallow, deep"),
1554                            PARSE_OPT_OPTARG, thread_callback },
1555                OPT_STRING(0, "signature", &signature, N_("signature"),
1556                            N_("add a signature")),
1557                OPT_STRING(0, "base", &base_commit, N_("base-commit"),
1558                           N_("add prerequisite tree info to the patch series")),
1559                OPT_FILENAME(0, "signature-file", &signature_file,
1560                                N_("add a signature from a file")),
1561                OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1562                OPT_BOOL(0, "progress", &show_progress,
1563                         N_("show progress while generating patches")),
1564                OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1565                             N_("show changes against <rev> in cover letter or single patch"),
1566                             parse_opt_object_name),
1567                OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1568                           N_("show changes against <refspec> in cover letter")),
1569                OPT_END()
1570        };
1571
1572        extra_hdr.strdup_strings = 1;
1573        extra_to.strdup_strings = 1;
1574        extra_cc.strdup_strings = 1;
1575        init_log_defaults();
1576        git_config(git_format_config, NULL);
1577        init_revisions(&rev, prefix);
1578        rev.commit_format = CMIT_FMT_EMAIL;
1579        rev.expand_tabs_in_log_default = 0;
1580        rev.verbose_header = 1;
1581        rev.diff = 1;
1582        rev.max_parents = 1;
1583        rev.diffopt.flags.recursive = 1;
1584        rev.subject_prefix = fmt_patch_subject_prefix;
1585        memset(&s_r_opt, 0, sizeof(s_r_opt));
1586        s_r_opt.def = "HEAD";
1587        s_r_opt.revarg_opt = REVARG_COMMITTISH;
1588
1589        if (default_attach) {
1590                rev.mime_boundary = default_attach;
1591                rev.no_inline = 1;
1592        }
1593
1594        /*
1595         * Parse the arguments before setup_revisions(), or something
1596         * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1597         * possibly a valid SHA1.
1598         */
1599        argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1600                             builtin_format_patch_usage,
1601                             PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1602                             PARSE_OPT_KEEP_DASHDASH);
1603
1604        if (0 < reroll_count) {
1605                struct strbuf sprefix = STRBUF_INIT;
1606                strbuf_addf(&sprefix, "%s v%d",
1607                            rev.subject_prefix, reroll_count);
1608                rev.reroll_count = reroll_count;
1609                rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1610        }
1611
1612        for (i = 0; i < extra_hdr.nr; i++) {
1613                strbuf_addstr(&buf, extra_hdr.items[i].string);
1614                strbuf_addch(&buf, '\n');
1615        }
1616
1617        if (extra_to.nr)
1618                strbuf_addstr(&buf, "To: ");
1619        for (i = 0; i < extra_to.nr; i++) {
1620                if (i)
1621                        strbuf_addstr(&buf, "    ");
1622                strbuf_addstr(&buf, extra_to.items[i].string);
1623                if (i + 1 < extra_to.nr)
1624                        strbuf_addch(&buf, ',');
1625                strbuf_addch(&buf, '\n');
1626        }
1627
1628        if (extra_cc.nr)
1629                strbuf_addstr(&buf, "Cc: ");
1630        for (i = 0; i < extra_cc.nr; i++) {
1631                if (i)
1632                        strbuf_addstr(&buf, "    ");
1633                strbuf_addstr(&buf, extra_cc.items[i].string);
1634                if (i + 1 < extra_cc.nr)
1635                        strbuf_addch(&buf, ',');
1636                strbuf_addch(&buf, '\n');
1637        }
1638
1639        rev.extra_headers = strbuf_detach(&buf, NULL);
1640
1641        if (from) {
1642                if (split_ident_line(&rev.from_ident, from, strlen(from)))
1643                        die(_("invalid ident line: %s"), from);
1644        }
1645
1646        if (start_number < 0)
1647                start_number = 1;
1648
1649        /*
1650         * If numbered is set solely due to format.numbered in config,
1651         * and it would conflict with --keep-subject (-k) from the
1652         * command line, reset "numbered".
1653         */
1654        if (numbered && keep_subject && !numbered_cmdline_opt)
1655                numbered = 0;
1656
1657        if (numbered && keep_subject)
1658                die (_("-n and -k are mutually exclusive."));
1659        if (keep_subject && subject_prefix)
1660                die (_("--subject-prefix/--rfc and -k are mutually exclusive."));
1661        rev.preserve_subject = keep_subject;
1662
1663        argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1664        if (argc > 1)
1665                die (_("unrecognized argument: %s"), argv[1]);
1666
1667        if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1668                die(_("--name-only does not make sense"));
1669        if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1670                die(_("--name-status does not make sense"));
1671        if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1672                die(_("--check does not make sense"));
1673
1674        if (!use_patch_format &&
1675                (!rev.diffopt.output_format ||
1676                 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1677                rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1678        if (!rev.diffopt.stat_width)
1679                rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1680
1681        /* Always generate a patch */
1682        rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1683
1684        rev.zero_commit = zero_commit;
1685
1686        if (!rev.diffopt.flags.text && !no_binary_diff)
1687                rev.diffopt.flags.binary = 1;
1688
1689        if (rev.show_notes)
1690                init_display_notes(&rev.notes_opt);
1691
1692        if (!output_directory && !use_stdout)
1693                output_directory = config_output_directory;
1694
1695        if (!use_stdout)
1696                output_directory = set_outdir(prefix, output_directory);
1697        else
1698                setup_pager();
1699
1700        if (output_directory) {
1701                if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1702                        rev.diffopt.use_color = GIT_COLOR_NEVER;
1703                if (use_stdout)
1704                        die(_("standard output, or directory, which one?"));
1705                if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1706                        die_errno(_("Could not create directory '%s'"),
1707                                  output_directory);
1708        }
1709
1710        if (rev.pending.nr == 1) {
1711                int check_head = 0;
1712
1713                if (rev.max_count < 0 && !rev.show_root_diff) {
1714                        /*
1715                         * This is traditional behaviour of "git format-patch
1716                         * origin" that prepares what the origin side still
1717                         * does not have.
1718                         */
1719                        rev.pending.objects[0].item->flags |= UNINTERESTING;
1720                        add_head_to_pending(&rev);
1721                        check_head = 1;
1722                }
1723                /*
1724                 * Otherwise, it is "format-patch -22 HEAD", and/or
1725                 * "format-patch --root HEAD".  The user wants
1726                 * get_revision() to do the usual traversal.
1727                 */
1728
1729                if (!strcmp(rev.pending.objects[0].name, "HEAD"))
1730                        check_head = 1;
1731
1732                if (check_head) {
1733                        const char *ref, *v;
1734                        ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1735                                                 NULL, NULL);
1736                        if (ref && skip_prefix(ref, "refs/heads/", &v))
1737                                branch_name = xstrdup(v);
1738                        else
1739                                branch_name = xstrdup(""); /* no branch */
1740                }
1741        }
1742
1743        /*
1744         * We cannot move this anywhere earlier because we do want to
1745         * know if --root was given explicitly from the command line.
1746         */
1747        rev.show_root_diff = 1;
1748
1749        if (ignore_if_in_upstream) {
1750                /* Don't say anything if head and upstream are the same. */
1751                if (rev.pending.nr == 2) {
1752                        struct object_array_entry *o = rev.pending.objects;
1753                        if (oidcmp(&o[0].item->oid, &o[1].item->oid) == 0)
1754                                goto done;
1755                }
1756                get_patch_ids(&rev, &ids);
1757        }
1758
1759        if (prepare_revision_walk(&rev))
1760                die(_("revision walk setup failed"));
1761        rev.boundary = 1;
1762        while ((commit = get_revision(&rev)) != NULL) {
1763                if (commit->object.flags & BOUNDARY) {
1764                        boundary_count++;
1765                        origin = (boundary_count == 1) ? commit : NULL;
1766                        continue;
1767                }
1768
1769                if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
1770                        continue;
1771
1772                nr++;
1773                REALLOC_ARRAY(list, nr);
1774                list[nr - 1] = commit;
1775        }
1776        if (nr == 0)
1777                /* nothing to do */
1778                goto done;
1779        total = nr;
1780        if (cover_letter == -1) {
1781                if (config_cover_letter == COVER_AUTO)
1782                        cover_letter = (total > 1);
1783                else
1784                        cover_letter = (config_cover_letter == COVER_ON);
1785        }
1786        if (!keep_subject && auto_number && (total > 1 || cover_letter))
1787                numbered = 1;
1788        if (numbered)
1789                rev.total = total + start_number - 1;
1790
1791        if (idiff_prev.nr) {
1792                if (!cover_letter && total != 1)
1793                        die(_("--interdiff requires --cover-letter or single patch"));
1794                rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
1795                rev.idiff_oid2 = get_commit_tree_oid(list[0]);
1796                rev.idiff_title = diff_title(&idiff_title, reroll_count,
1797                                             _("Interdiff:"),
1798                                             _("Interdiff against v%d:"));
1799        }
1800
1801        if (rdiff_prev) {
1802                if (!cover_letter)
1803                        die(_("--range-diff requires --cover-letter"));
1804
1805                infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev, list[0]);
1806                rev.rdiff1 = rdiff1.buf;
1807                rev.rdiff2 = rdiff2.buf;
1808                rev.creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
1809        }
1810
1811        if (!signature) {
1812                ; /* --no-signature inhibits all signatures */
1813        } else if (signature && signature != git_version_string) {
1814                ; /* non-default signature already set */
1815        } else if (signature_file) {
1816                struct strbuf buf = STRBUF_INIT;
1817
1818                if (strbuf_read_file(&buf, signature_file, 128) < 0)
1819                        die_errno(_("unable to read signature file '%s'"), signature_file);
1820                signature = strbuf_detach(&buf, NULL);
1821        }
1822
1823        memset(&bases, 0, sizeof(bases));
1824        if (base_commit || base_auto) {
1825                struct commit *base = get_base_commit(base_commit, list, nr);
1826                reset_revision_walk();
1827                clear_object_flags(UNINTERESTING);
1828                prepare_bases(&bases, base, list, nr);
1829        }
1830
1831        if (in_reply_to || thread || cover_letter)
1832                rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1833        if (in_reply_to) {
1834                const char *msgid = clean_message_id(in_reply_to);
1835                string_list_append(rev.ref_message_ids, msgid);
1836        }
1837        rev.numbered_files = just_numbers;
1838        rev.patch_suffix = fmt_patch_suffix;
1839        if (cover_letter) {
1840                if (thread)
1841                        gen_message_id(&rev, "cover");
1842                make_cover_letter(&rev, use_stdout,
1843                                  origin, nr, list, branch_name, quiet);
1844                print_bases(&bases, rev.diffopt.file);
1845                print_signature(rev.diffopt.file);
1846                total++;
1847                start_number--;
1848                /* interdiff in cover-letter; omit from patches */
1849                rev.idiff_oid1 = NULL;
1850        }
1851        rev.add_signoff = do_signoff;
1852
1853        if (show_progress)
1854                progress = start_delayed_progress(_("Generating patches"), total);
1855        while (0 <= --nr) {
1856                int shown;
1857                display_progress(progress, total - nr);
1858                commit = list[nr];
1859                rev.nr = total - nr + (start_number - 1);
1860                /* Make the second and subsequent mails replies to the first */
1861                if (thread) {
1862                        /* Have we already had a message ID? */
1863                        if (rev.message_id) {
1864                                /*
1865                                 * For deep threading: make every mail
1866                                 * a reply to the previous one, no
1867                                 * matter what other options are set.
1868                                 *
1869                                 * For shallow threading:
1870                                 *
1871                                 * Without --cover-letter and
1872                                 * --in-reply-to, make every mail a
1873                                 * reply to the one before.
1874                                 *
1875                                 * With --in-reply-to but no
1876                                 * --cover-letter, make every mail a
1877                                 * reply to the <reply-to>.
1878                                 *
1879                                 * With --cover-letter, make every
1880                                 * mail but the cover letter a reply
1881                                 * to the cover letter.  The cover
1882                                 * letter is a reply to the
1883                                 * --in-reply-to, if specified.
1884                                 */
1885                                if (thread == THREAD_SHALLOW
1886                                    && rev.ref_message_ids->nr > 0
1887                                    && (!cover_letter || rev.nr > 1))
1888                                        free(rev.message_id);
1889                                else
1890                                        string_list_append(rev.ref_message_ids,
1891                                                           rev.message_id);
1892                        }
1893                        gen_message_id(&rev, oid_to_hex(&commit->object.oid));
1894                }
1895
1896                if (!use_stdout &&
1897                    open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
1898                        die(_("Failed to create output files"));
1899                shown = log_tree_commit(&rev, commit);
1900                free_commit_buffer(commit);
1901
1902                /* We put one extra blank line between formatted
1903                 * patches and this flag is used by log-tree code
1904                 * to see if it needs to emit a LF before showing
1905                 * the log; when using one file per patch, we do
1906                 * not want the extra blank line.
1907                 */
1908                if (!use_stdout)
1909                        rev.shown_one = 0;
1910                if (shown) {
1911                        print_bases(&bases, rev.diffopt.file);
1912                        if (rev.mime_boundary)
1913                                fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
1914                                       mime_boundary_leader,
1915                                       rev.mime_boundary);
1916                        else
1917                                print_signature(rev.diffopt.file);
1918                }
1919                if (!use_stdout)
1920                        fclose(rev.diffopt.file);
1921        }
1922        stop_progress(&progress);
1923        free(list);
1924        free(branch_name);
1925        string_list_clear(&extra_to, 0);
1926        string_list_clear(&extra_cc, 0);
1927        string_list_clear(&extra_hdr, 0);
1928        if (ignore_if_in_upstream)
1929                free_patch_ids(&ids);
1930
1931done:
1932        oid_array_clear(&idiff_prev);
1933        strbuf_release(&idiff_title);
1934        strbuf_release(&rdiff1);
1935        strbuf_release(&rdiff2);
1936        return 0;
1937}
1938
1939static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1940{
1941        struct object_id oid;
1942        if (get_oid(arg, &oid) == 0) {
1943                struct commit *commit = lookup_commit_reference(the_repository,
1944                                                                &oid);
1945                if (commit) {
1946                        commit->object.flags |= flags;
1947                        add_pending_object(revs, &commit->object, arg);
1948                        return 0;
1949                }
1950        }
1951        return -1;
1952}
1953
1954static const char * const cherry_usage[] = {
1955        N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
1956        NULL
1957};
1958
1959static void print_commit(char sign, struct commit *commit, int verbose,
1960                         int abbrev, FILE *file)
1961{
1962        if (!verbose) {
1963                fprintf(file, "%c %s\n", sign,
1964                       find_unique_abbrev(&commit->object.oid, abbrev));
1965        } else {
1966                struct strbuf buf = STRBUF_INIT;
1967                pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
1968                fprintf(file, "%c %s %s\n", sign,
1969                       find_unique_abbrev(&commit->object.oid, abbrev),
1970                       buf.buf);
1971                strbuf_release(&buf);
1972        }
1973}
1974
1975int cmd_cherry(int argc, const char **argv, const char *prefix)
1976{
1977        struct rev_info revs;
1978        struct patch_ids ids;
1979        struct commit *commit;
1980        struct commit_list *list = NULL;
1981        struct branch *current_branch;
1982        const char *upstream;
1983        const char *head = "HEAD";
1984        const char *limit = NULL;
1985        int verbose = 0, abbrev = 0;
1986
1987        struct option options[] = {
1988                OPT__ABBREV(&abbrev),
1989                OPT__VERBOSE(&verbose, N_("be verbose")),
1990                OPT_END()
1991        };
1992
1993        argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1994
1995        switch (argc) {
1996        case 3:
1997                limit = argv[2];
1998                /* FALLTHROUGH */
1999        case 2:
2000                head = argv[1];
2001                /* FALLTHROUGH */
2002        case 1:
2003                upstream = argv[0];
2004                break;
2005        default:
2006                current_branch = branch_get(NULL);
2007                upstream = branch_get_upstream(current_branch, NULL);
2008                if (!upstream) {
2009                        fprintf(stderr, _("Could not find a tracked"
2010                                        " remote branch, please"
2011                                        " specify <upstream> manually.\n"));
2012                        usage_with_options(cherry_usage, options);
2013                }
2014        }
2015
2016        init_revisions(&revs, prefix);
2017        revs.max_parents = 1;
2018
2019        if (add_pending_commit(head, &revs, 0))
2020                die(_("Unknown commit %s"), head);
2021        if (add_pending_commit(upstream, &revs, UNINTERESTING))
2022                die(_("Unknown commit %s"), upstream);
2023
2024        /* Don't say anything if head and upstream are the same. */
2025        if (revs.pending.nr == 2) {
2026                struct object_array_entry *o = revs.pending.objects;
2027                if (oidcmp(&o[0].item->oid, &o[1].item->oid) == 0)
2028                        return 0;
2029        }
2030
2031        get_patch_ids(&revs, &ids);
2032
2033        if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2034                die(_("Unknown commit %s"), limit);
2035
2036        /* reverse the list of commits */
2037        if (prepare_revision_walk(&revs))
2038                die(_("revision walk setup failed"));
2039        while ((commit = get_revision(&revs)) != NULL) {
2040                commit_list_insert(commit, &list);
2041        }
2042
2043        while (list) {
2044                char sign = '+';
2045
2046                commit = list->item;
2047                if (has_commit_patch_id(commit, &ids))
2048                        sign = '-';
2049                print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2050                list = list->next;
2051        }
2052
2053        free_patch_ids(&ids);
2054        return 0;
2055}