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