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