builtin-log.con commit format-patch: migrate to parse-options API (fff02ee)
   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 "color.h"
   9#include "commit.h"
  10#include "diff.h"
  11#include "revision.h"
  12#include "log-tree.h"
  13#include "builtin.h"
  14#include "tag.h"
  15#include "reflog-walk.h"
  16#include "patch-ids.h"
  17#include "run-command.h"
  18#include "shortlog.h"
  19#include "remote.h"
  20#include "string-list.h"
  21#include "parse-options.h"
  22
  23/* Set a default date-time format for git log ("log.date" config variable) */
  24static const char *default_date_mode = NULL;
  25
  26static int default_show_root = 1;
  27static const char *fmt_patch_subject_prefix = "PATCH";
  28static const char *fmt_pretty;
  29
  30static void cmd_log_init(int argc, const char **argv, const char *prefix,
  31                      struct rev_info *rev)
  32{
  33        int i;
  34
  35        rev->abbrev = DEFAULT_ABBREV;
  36        rev->commit_format = CMIT_FMT_DEFAULT;
  37        if (fmt_pretty)
  38                get_commit_format(fmt_pretty, rev);
  39        rev->verbose_header = 1;
  40        DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
  41        rev->show_root_diff = default_show_root;
  42        rev->subject_prefix = fmt_patch_subject_prefix;
  43        DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
  44
  45        if (default_date_mode)
  46                rev->date_mode = parse_date_format(default_date_mode);
  47
  48        argc = setup_revisions(argc, argv, rev, "HEAD");
  49
  50        if (rev->diffopt.pickaxe || rev->diffopt.filter)
  51                rev->always_show_header = 0;
  52        if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
  53                rev->always_show_header = 0;
  54                if (rev->diffopt.nr_paths != 1)
  55                        usage("git logs can only follow renames on one pathname at a time");
  56        }
  57        for (i = 1; i < argc; i++) {
  58                const char *arg = argv[i];
  59                if (!strcmp(arg, "--decorate")) {
  60                        load_ref_decorations();
  61                        rev->show_decorations = 1;
  62                } else if (!strcmp(arg, "--source")) {
  63                        rev->show_source = 1;
  64                } else
  65                        die("unrecognized argument: %s", arg);
  66        }
  67}
  68
  69/*
  70 * This gives a rough estimate for how many commits we
  71 * will print out in the list.
  72 */
  73static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
  74{
  75        int n = 0;
  76
  77        while (list) {
  78                struct commit *commit = list->item;
  79                unsigned int flags = commit->object.flags;
  80                list = list->next;
  81                if (!(flags & (TREESAME | UNINTERESTING)))
  82                        n++;
  83        }
  84        return n;
  85}
  86
  87static void show_early_header(struct rev_info *rev, const char *stage, int nr)
  88{
  89        if (rev->shown_one) {
  90                rev->shown_one = 0;
  91                if (rev->commit_format != CMIT_FMT_ONELINE)
  92                        putchar(rev->diffopt.line_termination);
  93        }
  94        printf("Final output: %d %s\n", nr, stage);
  95}
  96
  97struct itimerval early_output_timer;
  98
  99static void log_show_early(struct rev_info *revs, struct commit_list *list)
 100{
 101        int i = revs->early_output;
 102        int show_header = 1;
 103
 104        sort_in_topological_order(&list, revs->lifo);
 105        while (list && i) {
 106                struct commit *commit = list->item;
 107                switch (simplify_commit(revs, commit)) {
 108                case commit_show:
 109                        if (show_header) {
 110                                int n = estimate_commit_count(revs, list);
 111                                show_early_header(revs, "incomplete", n);
 112                                show_header = 0;
 113                        }
 114                        log_tree_commit(revs, commit);
 115                        i--;
 116                        break;
 117                case commit_ignore:
 118                        break;
 119                case commit_error:
 120                        return;
 121                }
 122                list = list->next;
 123        }
 124
 125        /* Did we already get enough commits for the early output? */
 126        if (!i)
 127                return;
 128
 129        /*
 130         * ..if no, then repeat it twice a second until we
 131         * do.
 132         *
 133         * NOTE! We don't use "it_interval", because if the
 134         * reader isn't listening, we want our output to be
 135         * throttled by the writing, and not have the timer
 136         * trigger every second even if we're blocked on a
 137         * reader!
 138         */
 139        early_output_timer.it_value.tv_sec = 0;
 140        early_output_timer.it_value.tv_usec = 500000;
 141        setitimer(ITIMER_REAL, &early_output_timer, NULL);
 142}
 143
 144static void early_output(int signal)
 145{
 146        show_early_output = log_show_early;
 147}
 148
 149static void setup_early_output(struct rev_info *rev)
 150{
 151        struct sigaction sa;
 152
 153        /*
 154         * Set up the signal handler, minimally intrusively:
 155         * we only set a single volatile integer word (not
 156         * using sigatomic_t - trying to avoid unnecessary
 157         * system dependencies and headers), and using
 158         * SA_RESTART.
 159         */
 160        memset(&sa, 0, sizeof(sa));
 161        sa.sa_handler = early_output;
 162        sigemptyset(&sa.sa_mask);
 163        sa.sa_flags = SA_RESTART;
 164        sigaction(SIGALRM, &sa, NULL);
 165
 166        /*
 167         * If we can get the whole output in less than a
 168         * tenth of a second, don't even bother doing the
 169         * early-output thing..
 170         *
 171         * This is a one-time-only trigger.
 172         */
 173        early_output_timer.it_value.tv_sec = 0;
 174        early_output_timer.it_value.tv_usec = 100000;
 175        setitimer(ITIMER_REAL, &early_output_timer, NULL);
 176}
 177
 178static void finish_early_output(struct rev_info *rev)
 179{
 180        int n = estimate_commit_count(rev, rev->commits);
 181        signal(SIGALRM, SIG_IGN);
 182        show_early_header(rev, "done", n);
 183}
 184
 185static int cmd_log_walk(struct rev_info *rev)
 186{
 187        struct commit *commit;
 188
 189        if (rev->early_output)
 190                setup_early_output(rev);
 191
 192        if (prepare_revision_walk(rev))
 193                die("revision walk setup failed");
 194
 195        if (rev->early_output)
 196                finish_early_output(rev);
 197
 198        /*
 199         * For --check and --exit-code, the exit code is based on CHECK_FAILED
 200         * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
 201         * retain that state information if replacing rev->diffopt in this loop
 202         */
 203        while ((commit = get_revision(rev)) != NULL) {
 204                log_tree_commit(rev, commit);
 205                if (!rev->reflog_info) {
 206                        /* we allow cycles in reflog ancestry */
 207                        free(commit->buffer);
 208                        commit->buffer = NULL;
 209                }
 210                free_commit_list(commit->parents);
 211                commit->parents = NULL;
 212        }
 213        if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
 214            DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
 215                return 02;
 216        }
 217        return diff_result_code(&rev->diffopt, 0);
 218}
 219
 220static int git_log_config(const char *var, const char *value, void *cb)
 221{
 222        if (!strcmp(var, "format.pretty"))
 223                return git_config_string(&fmt_pretty, var, value);
 224        if (!strcmp(var, "format.subjectprefix"))
 225                return git_config_string(&fmt_patch_subject_prefix, var, value);
 226        if (!strcmp(var, "log.date"))
 227                return git_config_string(&default_date_mode, var, value);
 228        if (!strcmp(var, "log.showroot")) {
 229                default_show_root = git_config_bool(var, value);
 230                return 0;
 231        }
 232        return git_diff_ui_config(var, value, cb);
 233}
 234
 235int cmd_whatchanged(int argc, const char **argv, const char *prefix)
 236{
 237        struct rev_info rev;
 238
 239        git_config(git_log_config, NULL);
 240
 241        if (diff_use_color_default == -1)
 242                diff_use_color_default = git_use_color_default;
 243
 244        init_revisions(&rev, prefix);
 245        rev.diff = 1;
 246        rev.simplify_history = 0;
 247        cmd_log_init(argc, argv, prefix, &rev);
 248        if (!rev.diffopt.output_format)
 249                rev.diffopt.output_format = DIFF_FORMAT_RAW;
 250        return cmd_log_walk(&rev);
 251}
 252
 253static void show_tagger(char *buf, int len, struct rev_info *rev)
 254{
 255        struct strbuf out = STRBUF_INIT;
 256
 257        pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
 258                git_log_output_encoding ?
 259                git_log_output_encoding: git_commit_encoding);
 260        printf("%s\n", out.buf);
 261        strbuf_release(&out);
 262}
 263
 264static int show_object(const unsigned char *sha1, int show_tag_object,
 265        struct rev_info *rev)
 266{
 267        unsigned long size;
 268        enum object_type type;
 269        char *buf = read_sha1_file(sha1, &type, &size);
 270        int offset = 0;
 271
 272        if (!buf)
 273                return error("Could not read object %s", sha1_to_hex(sha1));
 274
 275        if (show_tag_object)
 276                while (offset < size && buf[offset] != '\n') {
 277                        int new_offset = offset + 1;
 278                        while (new_offset < size && buf[new_offset++] != '\n')
 279                                ; /* do nothing */
 280                        if (!prefixcmp(buf + offset, "tagger "))
 281                                show_tagger(buf + offset + 7,
 282                                            new_offset - offset - 7, rev);
 283                        offset = new_offset;
 284                }
 285
 286        if (offset < size)
 287                fwrite(buf + offset, size - offset, 1, stdout);
 288        free(buf);
 289        return 0;
 290}
 291
 292static int show_tree_object(const unsigned char *sha1,
 293                const char *base, int baselen,
 294                const char *pathname, unsigned mode, int stage, void *context)
 295{
 296        printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
 297        return 0;
 298}
 299
 300int cmd_show(int argc, const char **argv, const char *prefix)
 301{
 302        struct rev_info rev;
 303        struct object_array_entry *objects;
 304        int i, count, ret = 0;
 305
 306        git_config(git_log_config, NULL);
 307
 308        if (diff_use_color_default == -1)
 309                diff_use_color_default = git_use_color_default;
 310
 311        init_revisions(&rev, prefix);
 312        rev.diff = 1;
 313        rev.combine_merges = 1;
 314        rev.dense_combined_merges = 1;
 315        rev.always_show_header = 1;
 316        rev.ignore_merges = 0;
 317        rev.no_walk = 1;
 318        cmd_log_init(argc, argv, prefix, &rev);
 319
 320        count = rev.pending.nr;
 321        objects = rev.pending.objects;
 322        for (i = 0; i < count && !ret; i++) {
 323                struct object *o = objects[i].item;
 324                const char *name = objects[i].name;
 325                switch (o->type) {
 326                case OBJ_BLOB:
 327                        ret = show_object(o->sha1, 0, NULL);
 328                        break;
 329                case OBJ_TAG: {
 330                        struct tag *t = (struct tag *)o;
 331
 332                        printf("%stag %s%s\n",
 333                                        diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
 334                                        t->tag,
 335                                        diff_get_color_opt(&rev.diffopt, DIFF_RESET));
 336                        ret = show_object(o->sha1, 1, &rev);
 337                        if (ret)
 338                                break;
 339                        o = parse_object(t->tagged->sha1);
 340                        if (!o)
 341                                ret = error("Could not read object %s",
 342                                            sha1_to_hex(t->tagged->sha1));
 343                        objects[i].item = o;
 344                        i--;
 345                        break;
 346                }
 347                case OBJ_TREE:
 348                        printf("%stree %s%s\n\n",
 349                                        diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
 350                                        name,
 351                                        diff_get_color_opt(&rev.diffopt, DIFF_RESET));
 352                        read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
 353                                        show_tree_object, NULL);
 354                        break;
 355                case OBJ_COMMIT:
 356                        rev.pending.nr = rev.pending.alloc = 0;
 357                        rev.pending.objects = NULL;
 358                        add_object_array(o, name, &rev.pending);
 359                        ret = cmd_log_walk(&rev);
 360                        break;
 361                default:
 362                        ret = error("Unknown type: %d", o->type);
 363                }
 364        }
 365        free(objects);
 366        return ret;
 367}
 368
 369/*
 370 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
 371 */
 372int cmd_log_reflog(int argc, const char **argv, const char *prefix)
 373{
 374        struct rev_info rev;
 375
 376        git_config(git_log_config, NULL);
 377
 378        if (diff_use_color_default == -1)
 379                diff_use_color_default = git_use_color_default;
 380
 381        init_revisions(&rev, prefix);
 382        init_reflog_walk(&rev.reflog_info);
 383        rev.abbrev_commit = 1;
 384        rev.verbose_header = 1;
 385        cmd_log_init(argc, argv, prefix, &rev);
 386
 387        /*
 388         * This means that we override whatever commit format the user gave
 389         * on the cmd line.  Sad, but cmd_log_init() currently doesn't
 390         * allow us to set a different default.
 391         */
 392        rev.commit_format = CMIT_FMT_ONELINE;
 393        rev.use_terminator = 1;
 394        rev.always_show_header = 1;
 395
 396        /*
 397         * We get called through "git reflog", so unlike the other log
 398         * routines, we need to set up our pager manually..
 399         */
 400        setup_pager();
 401
 402        return cmd_log_walk(&rev);
 403}
 404
 405int cmd_log(int argc, const char **argv, const char *prefix)
 406{
 407        struct rev_info rev;
 408
 409        git_config(git_log_config, NULL);
 410
 411        if (diff_use_color_default == -1)
 412                diff_use_color_default = git_use_color_default;
 413
 414        init_revisions(&rev, prefix);
 415        rev.always_show_header = 1;
 416        cmd_log_init(argc, argv, prefix, &rev);
 417        return cmd_log_walk(&rev);
 418}
 419
 420/* format-patch */
 421
 422static const char *fmt_patch_suffix = ".patch";
 423static int numbered = 0;
 424static int auto_number = 1;
 425
 426static char *default_attach = NULL;
 427
 428static char **extra_hdr;
 429static int extra_hdr_nr;
 430static int extra_hdr_alloc;
 431
 432static char **extra_to;
 433static int extra_to_nr;
 434static int extra_to_alloc;
 435
 436static char **extra_cc;
 437static int extra_cc_nr;
 438static int extra_cc_alloc;
 439
 440static void add_header(const char *value)
 441{
 442        int len = strlen(value);
 443        while (len && value[len - 1] == '\n')
 444                len--;
 445        if (!strncasecmp(value, "to: ", 4)) {
 446                ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
 447                extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
 448                return;
 449        }
 450        if (!strncasecmp(value, "cc: ", 4)) {
 451                ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
 452                extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
 453                return;
 454        }
 455        ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
 456        extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
 457}
 458
 459#define THREAD_SHALLOW 1
 460#define THREAD_DEEP 2
 461static int thread = 0;
 462static int do_signoff = 0;
 463
 464static int git_format_config(const char *var, const char *value, void *cb)
 465{
 466        if (!strcmp(var, "format.headers")) {
 467                if (!value)
 468                        die("format.headers without value");
 469                add_header(value);
 470                return 0;
 471        }
 472        if (!strcmp(var, "format.suffix"))
 473                return git_config_string(&fmt_patch_suffix, var, value);
 474        if (!strcmp(var, "format.cc")) {
 475                if (!value)
 476                        return config_error_nonbool(var);
 477                ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
 478                extra_cc[extra_cc_nr++] = xstrdup(value);
 479                return 0;
 480        }
 481        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
 482                return 0;
 483        }
 484        if (!strcmp(var, "format.numbered")) {
 485                if (value && !strcasecmp(value, "auto")) {
 486                        auto_number = 1;
 487                        return 0;
 488                }
 489                numbered = git_config_bool(var, value);
 490                auto_number = auto_number && numbered;
 491                return 0;
 492        }
 493        if (!strcmp(var, "format.attach")) {
 494                if (value && *value)
 495                        default_attach = xstrdup(value);
 496                else
 497                        default_attach = xstrdup(git_version_string);
 498                return 0;
 499        }
 500        if (!strcmp(var, "format.thread")) {
 501                if (value && !strcasecmp(value, "deep")) {
 502                        thread = THREAD_DEEP;
 503                        return 0;
 504                }
 505                if (value && !strcasecmp(value, "shallow")) {
 506                        thread = THREAD_SHALLOW;
 507                        return 0;
 508                }
 509                thread = git_config_bool(var, value) && THREAD_SHALLOW;
 510                return 0;
 511        }
 512        if (!strcmp(var, "format.signoff")) {
 513                do_signoff = git_config_bool(var, value);
 514                return 0;
 515        }
 516
 517        return git_log_config(var, value, cb);
 518}
 519
 520static FILE *realstdout = NULL;
 521static const char *output_directory = NULL;
 522static int outdir_offset;
 523
 524static int reopen_stdout(struct commit *commit, struct rev_info *rev)
 525{
 526        struct strbuf filename = STRBUF_INIT;
 527        int suffix_len = strlen(fmt_patch_suffix) + 1;
 528
 529        if (output_directory) {
 530                strbuf_addstr(&filename, output_directory);
 531                if (filename.len >=
 532                    PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
 533                        return error("name of output directory is too long");
 534                if (filename.buf[filename.len - 1] != '/')
 535                        strbuf_addch(&filename, '/');
 536        }
 537
 538        get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
 539
 540        if (!DIFF_OPT_TST(&rev->diffopt, QUIET))
 541                fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
 542
 543        if (freopen(filename.buf, "w", stdout) == NULL)
 544                return error("Cannot open patch file %s", filename.buf);
 545
 546        strbuf_release(&filename);
 547        return 0;
 548}
 549
 550static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
 551{
 552        struct rev_info check_rev;
 553        struct commit *commit;
 554        struct object *o1, *o2;
 555        unsigned flags1, flags2;
 556
 557        if (rev->pending.nr != 2)
 558                die("Need exactly one range.");
 559
 560        o1 = rev->pending.objects[0].item;
 561        flags1 = o1->flags;
 562        o2 = rev->pending.objects[1].item;
 563        flags2 = o2->flags;
 564
 565        if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
 566                die("Not a range.");
 567
 568        init_patch_ids(ids);
 569
 570        /* given a range a..b get all patch ids for b..a */
 571        init_revisions(&check_rev, prefix);
 572        o1->flags ^= UNINTERESTING;
 573        o2->flags ^= UNINTERESTING;
 574        add_pending_object(&check_rev, o1, "o1");
 575        add_pending_object(&check_rev, o2, "o2");
 576        if (prepare_revision_walk(&check_rev))
 577                die("revision walk setup failed");
 578
 579        while ((commit = get_revision(&check_rev)) != NULL) {
 580                /* ignore merges */
 581                if (commit->parents && commit->parents->next)
 582                        continue;
 583
 584                add_commit_patch_id(commit, ids);
 585        }
 586
 587        /* reset for next revision walk */
 588        clear_commit_marks((struct commit *)o1,
 589                        SEEN | UNINTERESTING | SHOWN | ADDED);
 590        clear_commit_marks((struct commit *)o2,
 591                        SEEN | UNINTERESTING | SHOWN | ADDED);
 592        o1->flags = flags1;
 593        o2->flags = flags2;
 594}
 595
 596static void gen_message_id(struct rev_info *info, char *base)
 597{
 598        const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
 599        const char *email_start = strrchr(committer, '<');
 600        const char *email_end = strrchr(committer, '>');
 601        struct strbuf buf = STRBUF_INIT;
 602        if (!email_start || !email_end || email_start > email_end - 1)
 603                die("Could not extract email from committer identity.");
 604        strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
 605                    (unsigned long) time(NULL),
 606                    (int)(email_end - email_start - 1), email_start + 1);
 607        info->message_id = strbuf_detach(&buf, NULL);
 608}
 609
 610static void make_cover_letter(struct rev_info *rev, int use_stdout,
 611                              int numbered, int numbered_files,
 612                              struct commit *origin,
 613                              int nr, struct commit **list, struct commit *head)
 614{
 615        const char *committer;
 616        const char *subject_start = NULL;
 617        const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
 618        const char *msg;
 619        const char *extra_headers = rev->extra_headers;
 620        struct shortlog log;
 621        struct strbuf sb = STRBUF_INIT;
 622        int i;
 623        const char *encoding = "utf-8";
 624        struct diff_options opts;
 625        int need_8bit_cte = 0;
 626        struct commit *commit = NULL;
 627
 628        if (rev->commit_format != CMIT_FMT_EMAIL)
 629                die("Cover letter needs email format");
 630
 631        committer = git_committer_info(0);
 632
 633        if (!numbered_files) {
 634                /*
 635                 * We fake a commit for the cover letter so we get the filename
 636                 * desired.
 637                 */
 638                commit = xcalloc(1, sizeof(*commit));
 639                commit->buffer = xmalloc(400);
 640                snprintf(commit->buffer, 400,
 641                        "tree 0000000000000000000000000000000000000000\n"
 642                        "parent %s\n"
 643                        "author %s\n"
 644                        "committer %s\n\n"
 645                        "cover letter\n",
 646                        sha1_to_hex(head->object.sha1), committer, committer);
 647        }
 648
 649        if (!use_stdout && reopen_stdout(commit, rev))
 650                return;
 651
 652        if (commit) {
 653
 654                free(commit->buffer);
 655                free(commit);
 656        }
 657
 658        log_write_email_headers(rev, head, &subject_start, &extra_headers,
 659                                &need_8bit_cte);
 660
 661        msg = body;
 662        pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
 663                     encoding);
 664        pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
 665                      encoding, need_8bit_cte);
 666        pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
 667        printf("%s\n", sb.buf);
 668
 669        strbuf_release(&sb);
 670
 671        shortlog_init(&log);
 672        log.wrap_lines = 1;
 673        log.wrap = 72;
 674        log.in1 = 2;
 675        log.in2 = 4;
 676        for (i = 0; i < nr; i++)
 677                shortlog_add_commit(&log, list[i]);
 678
 679        shortlog_output(&log);
 680
 681        /*
 682         * We can only do diffstat with a unique reference point
 683         */
 684        if (!origin)
 685                return;
 686
 687        memcpy(&opts, &rev->diffopt, sizeof(opts));
 688        opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 689
 690        diff_setup_done(&opts);
 691
 692        diff_tree_sha1(origin->tree->object.sha1,
 693                       head->tree->object.sha1,
 694                       "", &opts);
 695        diffcore_std(&opts);
 696        diff_flush(&opts);
 697
 698        printf("\n");
 699}
 700
 701static const char *clean_message_id(const char *msg_id)
 702{
 703        char ch;
 704        const char *a, *z, *m;
 705
 706        m = msg_id;
 707        while ((ch = *m) && (isspace(ch) || (ch == '<')))
 708                m++;
 709        a = m;
 710        z = NULL;
 711        while ((ch = *m)) {
 712                if (!isspace(ch) && (ch != '>'))
 713                        z = m;
 714                m++;
 715        }
 716        if (!z)
 717                die("insane in-reply-to: %s", msg_id);
 718        if (++z == m)
 719                return a;
 720        return xmemdupz(a, z - a);
 721}
 722
 723static const char *set_outdir(const char *prefix, const char *output_directory)
 724{
 725        if (output_directory && is_absolute_path(output_directory))
 726                return output_directory;
 727
 728        if (!prefix || !*prefix) {
 729                if (output_directory)
 730                        return output_directory;
 731                /* The user did not explicitly ask for "./" */
 732                outdir_offset = 2;
 733                return "./";
 734        }
 735
 736        outdir_offset = strlen(prefix);
 737        if (!output_directory)
 738                return prefix;
 739
 740        return xstrdup(prefix_filename(prefix, outdir_offset,
 741                                       output_directory));
 742}
 743
 744static const char * const builtin_format_patch_usage[] = {
 745        "git format-patch [options] [<since> | <revision range>]",
 746        NULL
 747};
 748
 749static int keep_subject = 0;
 750
 751static int keep_callback(const struct option *opt, const char *arg, int unset)
 752{
 753        ((struct rev_info *)opt->value)->total = -1;
 754        keep_subject = 1;
 755        return 0;
 756}
 757
 758static int subject_prefix = 0;
 759
 760static int subject_prefix_callback(const struct option *opt, const char *arg,
 761                            int unset)
 762{
 763        subject_prefix = 1;
 764        ((struct rev_info *)opt->value)->subject_prefix = arg;
 765        return 0;
 766}
 767
 768static int numbered_callback(const struct option *opt, const char *arg,
 769                             int unset)
 770{
 771        *(int *)opt->value = unset ? 0 : 1;
 772        if (unset)
 773                auto_number =  0;
 774        return 0;
 775}
 776
 777static int no_numbered_callback(const struct option *opt, const char *arg,
 778                                int unset)
 779{
 780        return numbered_callback(opt, arg, 1);
 781}
 782
 783static int output_directory_callback(const struct option *opt, const char *arg,
 784                              int unset)
 785{
 786        const char **dir = (const char **)opt->value;
 787        if (*dir)
 788                die("Two output directories?");
 789        *dir = arg;
 790        return 0;
 791}
 792
 793static int thread_callback(const struct option *opt, const char *arg, int unset)
 794{
 795        int *thread = (int *)opt->value;
 796        if (unset)
 797                *thread = 0;
 798        else if (!arg || !strcmp(arg, "shallow"))
 799                *thread = THREAD_SHALLOW;
 800        else if (!strcmp(arg, "deep"))
 801                *thread = THREAD_DEEP;
 802        else
 803                return 1;
 804        return 0;
 805}
 806
 807static int attach_callback(const struct option *opt, const char *arg, int unset)
 808{
 809        struct rev_info *rev = (struct rev_info *)opt->value;
 810        if (unset)
 811                rev->mime_boundary = NULL;
 812        else if (arg)
 813                rev->mime_boundary = arg;
 814        else
 815                rev->mime_boundary = git_version_string;
 816        rev->no_inline = unset ? 0 : 1;
 817        return 0;
 818}
 819
 820static int inline_callback(const struct option *opt, const char *arg, int unset)
 821{
 822        struct rev_info *rev = (struct rev_info *)opt->value;
 823        if (unset)
 824                rev->mime_boundary = NULL;
 825        else if (arg)
 826                rev->mime_boundary = arg;
 827        else
 828                rev->mime_boundary = git_version_string;
 829        rev->no_inline = 0;
 830        return 0;
 831}
 832
 833static int header_callback(const struct option *opt, const char *arg, int unset)
 834{
 835        add_header(arg);
 836        return 0;
 837}
 838
 839static int cc_callback(const struct option *opt, const char *arg, int unset)
 840{
 841        ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
 842        extra_cc[extra_cc_nr++] = xstrdup(arg);
 843        return 0;
 844}
 845
 846int cmd_format_patch(int argc, const char **argv, const char *prefix)
 847{
 848        struct commit *commit;
 849        struct commit **list = NULL;
 850        struct rev_info rev;
 851        int nr = 0, total, i;
 852        int use_stdout = 0;
 853        int start_number = -1;
 854        int numbered_files = 0;         /* _just_ numbers */
 855        int ignore_if_in_upstream = 0;
 856        int cover_letter = 0;
 857        int boundary_count = 0;
 858        int no_binary_diff = 0;
 859        struct commit *origin = NULL, *head = NULL;
 860        const char *in_reply_to = NULL;
 861        struct patch_ids ids;
 862        char *add_signoff = NULL;
 863        struct strbuf buf = STRBUF_INIT;
 864        const struct option builtin_format_patch_options[] = {
 865                { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
 866                            "use [PATCH n/m] even with a single patch",
 867                            PARSE_OPT_NOARG, numbered_callback },
 868                { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
 869                            "use [PATCH] even with multiple patches",
 870                            PARSE_OPT_NOARG, no_numbered_callback },
 871                OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
 872                OPT_BOOLEAN(0, "stdout", &use_stdout,
 873                            "print patches to standard out"),
 874                OPT_BOOLEAN(0, "cover-letter", &cover_letter,
 875                            "generate a cover letter"),
 876                OPT_BOOLEAN(0, "numbered-files", &numbered_files,
 877                            "use simple number sequence for output file names"),
 878                OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
 879                            "use <sfx> instead of '.patch'"),
 880                OPT_INTEGER(0, "start-number", &start_number,
 881                            "start numbering patches at <n> instead of 1"),
 882                { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
 883                            "Use [<prefix>] instead of [PATCH]",
 884                            PARSE_OPT_NONEG, subject_prefix_callback },
 885                { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
 886                            "dir", "store resulting files in <dir>",
 887                            PARSE_OPT_NONEG, output_directory_callback },
 888                { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
 889                            "don't strip/add [PATCH]",
 890                            PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
 891                OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
 892                            "don't output binary diffs"),
 893                OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
 894                            "don't include a patch matching a commit upstream"),
 895                OPT_GROUP("Messaging"),
 896                { OPTION_CALLBACK, 0, "add-header", NULL, "header",
 897                            "add email header", PARSE_OPT_NONEG,
 898                            header_callback },
 899                { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
 900                            PARSE_OPT_NONEG, cc_callback },
 901                OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
 902                            "make first mail a reply to <message-id>"),
 903                { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
 904                            "attach the patch", PARSE_OPT_OPTARG,
 905                            attach_callback },
 906                { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
 907                            "inline the patch",
 908                            PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
 909                            inline_callback },
 910                { OPTION_CALLBACK, 0, "thread", &thread, "style",
 911                            "enable message threading, styles: shallow, deep",
 912                            PARSE_OPT_OPTARG, thread_callback },
 913                OPT_END()
 914        };
 915
 916        git_config(git_format_config, NULL);
 917        init_revisions(&rev, prefix);
 918        rev.commit_format = CMIT_FMT_EMAIL;
 919        rev.verbose_header = 1;
 920        rev.diff = 1;
 921        rev.combine_merges = 0;
 922        rev.ignore_merges = 1;
 923        DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
 924
 925        rev.subject_prefix = fmt_patch_subject_prefix;
 926
 927        if (default_attach) {
 928                rev.mime_boundary = default_attach;
 929                rev.no_inline = 1;
 930        }
 931
 932        /*
 933         * Parse the arguments before setup_revisions(), or something
 934         * like "git format-patch -o a123 HEAD^.." may fail; a123 is
 935         * possibly a valid SHA1.
 936         */
 937        argc = parse_options(argc, argv, builtin_format_patch_options,
 938                             builtin_format_patch_usage,
 939                             PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN);
 940
 941        if (do_signoff) {
 942                const char *committer;
 943                const char *endpos;
 944                committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
 945                endpos = strchr(committer, '>');
 946                if (!endpos)
 947                        die("bogus committer info %s", committer);
 948                add_signoff = xmemdupz(committer, endpos - committer + 1);
 949        }
 950
 951        for (i = 0; i < extra_hdr_nr; i++) {
 952                strbuf_addstr(&buf, extra_hdr[i]);
 953                strbuf_addch(&buf, '\n');
 954        }
 955
 956        if (extra_to_nr)
 957                strbuf_addstr(&buf, "To: ");
 958        for (i = 0; i < extra_to_nr; i++) {
 959                if (i)
 960                        strbuf_addstr(&buf, "    ");
 961                strbuf_addstr(&buf, extra_to[i]);
 962                if (i + 1 < extra_to_nr)
 963                        strbuf_addch(&buf, ',');
 964                strbuf_addch(&buf, '\n');
 965        }
 966
 967        if (extra_cc_nr)
 968                strbuf_addstr(&buf, "Cc: ");
 969        for (i = 0; i < extra_cc_nr; i++) {
 970                if (i)
 971                        strbuf_addstr(&buf, "    ");
 972                strbuf_addstr(&buf, extra_cc[i]);
 973                if (i + 1 < extra_cc_nr)
 974                        strbuf_addch(&buf, ',');
 975                strbuf_addch(&buf, '\n');
 976        }
 977
 978        rev.extra_headers = strbuf_detach(&buf, 0);
 979
 980        if (start_number < 0)
 981                start_number = 1;
 982        if (numbered && keep_subject)
 983                die ("-n and -k are mutually exclusive.");
 984        if (keep_subject && subject_prefix)
 985                die ("--subject-prefix and -k are mutually exclusive.");
 986
 987        argc = setup_revisions(argc, argv, &rev, "HEAD");
 988        if (argc > 1)
 989                die ("unrecognized argument: %s", argv[1]);
 990
 991        if (!rev.diffopt.output_format
 992                || rev.diffopt.output_format == DIFF_FORMAT_PATCH)
 993                rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
 994
 995        if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
 996                DIFF_OPT_SET(&rev.diffopt, BINARY);
 997
 998        if (!use_stdout)
 999                output_directory = set_outdir(prefix, output_directory);
1000
1001        if (output_directory) {
1002                if (use_stdout)
1003                        die("standard output, or directory, which one?");
1004                if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1005                        die("Could not create directory %s",
1006                            output_directory);
1007        }
1008
1009        if (rev.pending.nr == 1) {
1010                if (rev.max_count < 0 && !rev.show_root_diff) {
1011                        /*
1012                         * This is traditional behaviour of "git format-patch
1013                         * origin" that prepares what the origin side still
1014                         * does not have.
1015                         */
1016                        rev.pending.objects[0].item->flags |= UNINTERESTING;
1017                        add_head_to_pending(&rev);
1018                }
1019                /*
1020                 * Otherwise, it is "format-patch -22 HEAD", and/or
1021                 * "format-patch --root HEAD".  The user wants
1022                 * get_revision() to do the usual traversal.
1023                 */
1024        }
1025
1026        /*
1027         * We cannot move this anywhere earlier because we do want to
1028         * know if --root was given explicitly from the comand line.
1029         */
1030        rev.show_root_diff = 1;
1031
1032        if (cover_letter) {
1033                /* remember the range */
1034                int i;
1035                for (i = 0; i < rev.pending.nr; i++) {
1036                        struct object *o = rev.pending.objects[i].item;
1037                        if (!(o->flags & UNINTERESTING))
1038                                head = (struct commit *)o;
1039                }
1040                /* We can't generate a cover letter without any patches */
1041                if (!head)
1042                        return 0;
1043        }
1044
1045        if (ignore_if_in_upstream)
1046                get_patch_ids(&rev, &ids, prefix);
1047
1048        if (!use_stdout)
1049                realstdout = xfdopen(xdup(1), "w");
1050
1051        if (prepare_revision_walk(&rev))
1052                die("revision walk setup failed");
1053        rev.boundary = 1;
1054        while ((commit = get_revision(&rev)) != NULL) {
1055                if (commit->object.flags & BOUNDARY) {
1056                        boundary_count++;
1057                        origin = (boundary_count == 1) ? commit : NULL;
1058                        continue;
1059                }
1060
1061                /* ignore merges */
1062                if (commit->parents && commit->parents->next)
1063                        continue;
1064
1065                if (ignore_if_in_upstream &&
1066                                has_commit_patch_id(commit, &ids))
1067                        continue;
1068
1069                nr++;
1070                list = xrealloc(list, nr * sizeof(list[0]));
1071                list[nr - 1] = commit;
1072        }
1073        total = nr;
1074        if (!keep_subject && auto_number && total > 1)
1075                numbered = 1;
1076        if (numbered)
1077                rev.total = total + start_number - 1;
1078        if (in_reply_to || thread || cover_letter)
1079                rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1080        if (in_reply_to) {
1081                const char *msgid = clean_message_id(in_reply_to);
1082                string_list_append(msgid, rev.ref_message_ids);
1083        }
1084        rev.numbered_files = numbered_files;
1085        rev.patch_suffix = fmt_patch_suffix;
1086        if (cover_letter) {
1087                if (thread)
1088                        gen_message_id(&rev, "cover");
1089                make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1090                                  origin, nr, list, head);
1091                total++;
1092                start_number--;
1093        }
1094        rev.add_signoff = add_signoff;
1095        while (0 <= --nr) {
1096                int shown;
1097                commit = list[nr];
1098                rev.nr = total - nr + (start_number - 1);
1099                /* Make the second and subsequent mails replies to the first */
1100                if (thread) {
1101                        /* Have we already had a message ID? */
1102                        if (rev.message_id) {
1103                                /*
1104                                 * For deep threading: make every mail
1105                                 * a reply to the previous one, no
1106                                 * matter what other options are set.
1107                                 *
1108                                 * For shallow threading:
1109                                 *
1110                                 * Without --cover-letter and
1111                                 * --in-reply-to, make every mail a
1112                                 * reply to the one before.
1113                                 *
1114                                 * With --in-reply-to but no
1115                                 * --cover-letter, make every mail a
1116                                 * reply to the <reply-to>.
1117                                 *
1118                                 * With --cover-letter, make every
1119                                 * mail but the cover letter a reply
1120                                 * to the cover letter.  The cover
1121                                 * letter is a reply to the
1122                                 * --in-reply-to, if specified.
1123                                 */
1124                                if (thread == THREAD_SHALLOW
1125                                    && rev.ref_message_ids->nr > 0
1126                                    && (!cover_letter || rev.nr > 1))
1127                                        free(rev.message_id);
1128                                else
1129                                        string_list_append(rev.message_id,
1130                                                           rev.ref_message_ids);
1131                        }
1132                        gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1133                }
1134
1135                if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1136                                                 &rev))
1137                        die("Failed to create output files");
1138                shown = log_tree_commit(&rev, commit);
1139                free(commit->buffer);
1140                commit->buffer = NULL;
1141
1142                /* We put one extra blank line between formatted
1143                 * patches and this flag is used by log-tree code
1144                 * to see if it needs to emit a LF before showing
1145                 * the log; when using one file per patch, we do
1146                 * not want the extra blank line.
1147                 */
1148                if (!use_stdout)
1149                        rev.shown_one = 0;
1150                if (shown) {
1151                        if (rev.mime_boundary)
1152                                printf("\n--%s%s--\n\n\n",
1153                                       mime_boundary_leader,
1154                                       rev.mime_boundary);
1155                        else
1156                                printf("-- \n%s\n\n", git_version_string);
1157                }
1158                if (!use_stdout)
1159                        fclose(stdout);
1160        }
1161        free(list);
1162        if (ignore_if_in_upstream)
1163                free_patch_ids(&ids);
1164        return 0;
1165}
1166
1167static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1168{
1169        unsigned char sha1[20];
1170        if (get_sha1(arg, sha1) == 0) {
1171                struct commit *commit = lookup_commit_reference(sha1);
1172                if (commit) {
1173                        commit->object.flags |= flags;
1174                        add_pending_object(revs, &commit->object, arg);
1175                        return 0;
1176                }
1177        }
1178        return -1;
1179}
1180
1181static const char cherry_usage[] =
1182"git cherry [-v] [<upstream> [<head> [<limit>]]]";
1183int cmd_cherry(int argc, const char **argv, const char *prefix)
1184{
1185        struct rev_info revs;
1186        struct patch_ids ids;
1187        struct commit *commit;
1188        struct commit_list *list = NULL;
1189        struct branch *current_branch;
1190        const char *upstream;
1191        const char *head = "HEAD";
1192        const char *limit = NULL;
1193        int verbose = 0;
1194
1195        if (argc > 1 && !strcmp(argv[1], "-v")) {
1196                verbose = 1;
1197                argc--;
1198                argv++;
1199        }
1200
1201        switch (argc) {
1202        case 4:
1203                limit = argv[3];
1204                /* FALLTHROUGH */
1205        case 3:
1206                head = argv[2];
1207                /* FALLTHROUGH */
1208        case 2:
1209                upstream = argv[1];
1210                break;
1211        default:
1212                current_branch = branch_get(NULL);
1213                if (!current_branch || !current_branch->merge
1214                                        || !current_branch->merge[0]
1215                                        || !current_branch->merge[0]->dst) {
1216                        fprintf(stderr, "Could not find a tracked"
1217                                        " remote branch, please"
1218                                        " specify <upstream> manually.\n");
1219                        usage(cherry_usage);
1220                }
1221
1222                upstream = current_branch->merge[0]->dst;
1223        }
1224
1225        init_revisions(&revs, prefix);
1226        revs.diff = 1;
1227        revs.combine_merges = 0;
1228        revs.ignore_merges = 1;
1229        DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1230
1231        if (add_pending_commit(head, &revs, 0))
1232                die("Unknown commit %s", head);
1233        if (add_pending_commit(upstream, &revs, UNINTERESTING))
1234                die("Unknown commit %s", upstream);
1235
1236        /* Don't say anything if head and upstream are the same. */
1237        if (revs.pending.nr == 2) {
1238                struct object_array_entry *o = revs.pending.objects;
1239                if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1240                        return 0;
1241        }
1242
1243        get_patch_ids(&revs, &ids, prefix);
1244
1245        if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1246                die("Unknown commit %s", limit);
1247
1248        /* reverse the list of commits */
1249        if (prepare_revision_walk(&revs))
1250                die("revision walk setup failed");
1251        while ((commit = get_revision(&revs)) != NULL) {
1252                /* ignore merges */
1253                if (commit->parents && commit->parents->next)
1254                        continue;
1255
1256                commit_list_insert(commit, &list);
1257        }
1258
1259        while (list) {
1260                char sign = '+';
1261
1262                commit = list->item;
1263                if (has_commit_patch_id(commit, &ids))
1264                        sign = '-';
1265
1266                if (verbose) {
1267                        struct strbuf buf = STRBUF_INIT;
1268                        pretty_print_commit(CMIT_FMT_ONELINE, commit,
1269                                            &buf, 0, NULL, NULL, 0, 0);
1270                        printf("%c %s %s\n", sign,
1271                               sha1_to_hex(commit->object.sha1), buf.buf);
1272                        strbuf_release(&buf);
1273                }
1274                else {
1275                        printf("%c %s\n", sign,
1276                               sha1_to_hex(commit->object.sha1));
1277                }
1278
1279                list = list->next;
1280        }
1281
1282        free_patch_ids(&ids);
1283        return 0;
1284}