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