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