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