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