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