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