2 * Copyright (C) 2005 Junio C Hamano
11 #include "xdiff-interface.h"
14 #include "run-command.h"
17 #include "submodule-config.h"
18 #include "submodule.h"
21 #include "string-list.h"
22 #include "argv-array.h"
25 #ifdef NO_FAST_WORKING_DIRECTORY
26 #define FAST_WORKING_DIRECTORY 0
28 #define FAST_WORKING_DIRECTORY 1
31 static int diff_detect_rename_default;
32 static int diff_indent_heuristic = 1;
33 static int diff_rename_limit_default = 400;
34 static int diff_suppress_blank_empty;
35 static int diff_use_color_default = -1;
36 static int diff_color_moved_default;
37 static int diff_context_default = 3;
38 static int diff_interhunk_context_default;
39 static const char *diff_word_regex_cfg;
40 static const char *external_diff_cmd_cfg;
41 static const char *diff_order_file_cfg;
42 int diff_auto_refresh_index = 1;
43 static int diff_mnemonic_prefix;
44 static int diff_no_prefix;
45 static int diff_stat_graph_width;
46 static int diff_dirstat_permille_default = 30;
47 static struct diff_options default_diff_options;
48 static long diff_algorithm;
49 static unsigned ws_error_highlight_default = WSEH_NEW;
51 static char diff_colors[][COLOR_MAXLEN] = {
53 GIT_COLOR_NORMAL, /* CONTEXT */
54 GIT_COLOR_BOLD, /* METAINFO */
55 GIT_COLOR_CYAN, /* FRAGINFO */
56 GIT_COLOR_RED, /* OLD */
57 GIT_COLOR_GREEN, /* NEW */
58 GIT_COLOR_YELLOW, /* COMMIT */
59 GIT_COLOR_BG_RED, /* WHITESPACE */
60 GIT_COLOR_NORMAL, /* FUNCINFO */
61 GIT_COLOR_MAGENTA, /* OLD_MOVED */
62 GIT_COLOR_BLUE, /* OLD_MOVED ALTERNATIVE */
63 GIT_COLOR_CYAN, /* NEW_MOVED */
64 GIT_COLOR_YELLOW, /* NEW_MOVED ALTERNATIVE */
67 static NORETURN void die_want_option(const char *option_name)
69 die(_("option '%s' requires a value"), option_name);
72 static int parse_diff_color_slot(const char *var)
74 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
76 if (!strcasecmp(var, "meta"))
78 if (!strcasecmp(var, "frag"))
80 if (!strcasecmp(var, "old"))
82 if (!strcasecmp(var, "new"))
84 if (!strcasecmp(var, "commit"))
86 if (!strcasecmp(var, "whitespace"))
87 return DIFF_WHITESPACE;
88 if (!strcasecmp(var, "func"))
90 if (!strcasecmp(var, "oldmoved"))
91 return DIFF_FILE_OLD_MOVED;
92 if (!strcasecmp(var, "oldmovedalternative"))
93 return DIFF_FILE_OLD_MOVED_ALT;
94 if (!strcasecmp(var, "newmoved"))
95 return DIFF_FILE_NEW_MOVED;
96 if (!strcasecmp(var, "newmovedalternative"))
97 return DIFF_FILE_NEW_MOVED_ALT;
101 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
102 struct strbuf *errmsg)
104 char *params_copy = xstrdup(params_string);
105 struct string_list params = STRING_LIST_INIT_NODUP;
110 string_list_split_in_place(¶ms, params_copy, ',', -1);
111 for (i = 0; i < params.nr; i++) {
112 const char *p = params.items[i].string;
113 if (!strcmp(p, "changes")) {
114 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
115 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
116 } else if (!strcmp(p, "lines")) {
117 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
118 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
119 } else if (!strcmp(p, "files")) {
120 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
121 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
122 } else if (!strcmp(p, "noncumulative")) {
123 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
124 } else if (!strcmp(p, "cumulative")) {
125 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
126 } else if (isdigit(*p)) {
128 int permille = strtoul(p, &end, 10) * 10;
129 if (*end == '.' && isdigit(*++end)) {
130 /* only use first digit */
131 permille += *end - '0';
132 /* .. and ignore any further digits */
133 while (isdigit(*++end))
137 options->dirstat_permille = permille;
139 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
144 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
149 string_list_clear(¶ms, 0);
154 static int parse_submodule_params(struct diff_options *options, const char *value)
156 if (!strcmp(value, "log"))
157 options->submodule_format = DIFF_SUBMODULE_LOG;
158 else if (!strcmp(value, "short"))
159 options->submodule_format = DIFF_SUBMODULE_SHORT;
160 else if (!strcmp(value, "diff"))
161 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
167 static int git_config_rename(const char *var, const char *value)
170 return DIFF_DETECT_RENAME;
171 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
172 return DIFF_DETECT_COPY;
173 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
176 long parse_algorithm_value(const char *value)
180 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
182 else if (!strcasecmp(value, "minimal"))
183 return XDF_NEED_MINIMAL;
184 else if (!strcasecmp(value, "patience"))
185 return XDF_PATIENCE_DIFF;
186 else if (!strcasecmp(value, "histogram"))
187 return XDF_HISTOGRAM_DIFF;
191 static int parse_one_token(const char **arg, const char *token)
194 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
201 static int parse_ws_error_highlight(const char *arg)
203 const char *orig_arg = arg;
207 if (parse_one_token(&arg, "none"))
209 else if (parse_one_token(&arg, "default"))
211 else if (parse_one_token(&arg, "all"))
212 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
213 else if (parse_one_token(&arg, "new"))
215 else if (parse_one_token(&arg, "old"))
217 else if (parse_one_token(&arg, "context"))
220 return -1 - (int)(arg - orig_arg);
229 * These are to give UI layer defaults.
230 * The core-level commands such as git-diff-files should
231 * never be affected by the setting of diff.renames
232 * the user happens to have in the configuration file.
234 void init_diff_ui_defaults(void)
236 diff_detect_rename_default = 1;
239 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
241 if (!strcmp(var, "diff.indentheuristic"))
242 diff_indent_heuristic = git_config_bool(var, value);
246 static int parse_color_moved(const char *arg)
248 switch (git_parse_maybe_bool(arg)) {
250 return COLOR_MOVED_NO;
252 return COLOR_MOVED_DEFAULT;
257 if (!strcmp(arg, "no"))
258 return COLOR_MOVED_NO;
259 else if (!strcmp(arg, "plain"))
260 return COLOR_MOVED_PLAIN;
261 else if (!strcmp(arg, "zebra"))
262 return COLOR_MOVED_ZEBRA;
263 else if (!strcmp(arg, "default"))
264 return COLOR_MOVED_DEFAULT;
266 return error(_("color moved setting must be one of 'no', 'default', 'zebra', 'plain'"));
269 int git_diff_ui_config(const char *var, const char *value, void *cb)
271 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
272 diff_use_color_default = git_config_colorbool(var, value);
275 if (!strcmp(var, "diff.colormoved")) {
276 int cm = parse_color_moved(value);
279 diff_color_moved_default = cm;
282 if (!strcmp(var, "diff.context")) {
283 diff_context_default = git_config_int(var, value);
284 if (diff_context_default < 0)
288 if (!strcmp(var, "diff.interhunkcontext")) {
289 diff_interhunk_context_default = git_config_int(var, value);
290 if (diff_interhunk_context_default < 0)
294 if (!strcmp(var, "diff.renames")) {
295 diff_detect_rename_default = git_config_rename(var, value);
298 if (!strcmp(var, "diff.autorefreshindex")) {
299 diff_auto_refresh_index = git_config_bool(var, value);
302 if (!strcmp(var, "diff.mnemonicprefix")) {
303 diff_mnemonic_prefix = git_config_bool(var, value);
306 if (!strcmp(var, "diff.noprefix")) {
307 diff_no_prefix = git_config_bool(var, value);
310 if (!strcmp(var, "diff.statgraphwidth")) {
311 diff_stat_graph_width = git_config_int(var, value);
314 if (!strcmp(var, "diff.external"))
315 return git_config_string(&external_diff_cmd_cfg, var, value);
316 if (!strcmp(var, "diff.wordregex"))
317 return git_config_string(&diff_word_regex_cfg, var, value);
318 if (!strcmp(var, "diff.orderfile"))
319 return git_config_pathname(&diff_order_file_cfg, var, value);
321 if (!strcmp(var, "diff.ignoresubmodules"))
322 handle_ignore_submodules_arg(&default_diff_options, value);
324 if (!strcmp(var, "diff.submodule")) {
325 if (parse_submodule_params(&default_diff_options, value))
326 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
331 if (!strcmp(var, "diff.algorithm")) {
332 diff_algorithm = parse_algorithm_value(value);
333 if (diff_algorithm < 0)
338 if (!strcmp(var, "diff.wserrorhighlight")) {
339 int val = parse_ws_error_highlight(value);
342 ws_error_highlight_default = val;
346 if (git_color_config(var, value, cb) < 0)
349 return git_diff_basic_config(var, value, cb);
352 int git_diff_basic_config(const char *var, const char *value, void *cb)
356 if (!strcmp(var, "diff.renamelimit")) {
357 diff_rename_limit_default = git_config_int(var, value);
361 if (userdiff_config(var, value) < 0)
364 if (skip_prefix(var, "diff.color.", &name) ||
365 skip_prefix(var, "color.diff.", &name)) {
366 int slot = parse_diff_color_slot(name);
370 return config_error_nonbool(var);
371 return color_parse(value, diff_colors[slot]);
374 /* like GNU diff's --suppress-blank-empty option */
375 if (!strcmp(var, "diff.suppressblankempty") ||
376 /* for backwards compatibility */
377 !strcmp(var, "diff.suppress-blank-empty")) {
378 diff_suppress_blank_empty = git_config_bool(var, value);
382 if (!strcmp(var, "diff.dirstat")) {
383 struct strbuf errmsg = STRBUF_INIT;
384 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
385 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
386 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
388 strbuf_release(&errmsg);
389 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
393 if (starts_with(var, "submodule."))
394 return parse_submodule_config_option(var, value);
396 if (git_diff_heuristic_config(var, value, cb) < 0)
399 return git_default_config(var, value, cb);
402 static char *quote_two(const char *one, const char *two)
404 int need_one = quote_c_style(one, NULL, NULL, 1);
405 int need_two = quote_c_style(two, NULL, NULL, 1);
406 struct strbuf res = STRBUF_INIT;
408 if (need_one + need_two) {
409 strbuf_addch(&res, '"');
410 quote_c_style(one, &res, NULL, 1);
411 quote_c_style(two, &res, NULL, 1);
412 strbuf_addch(&res, '"');
414 strbuf_addstr(&res, one);
415 strbuf_addstr(&res, two);
417 return strbuf_detach(&res, NULL);
420 static const char *external_diff(void)
422 static const char *external_diff_cmd = NULL;
423 static int done_preparing = 0;
426 return external_diff_cmd;
427 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
428 if (!external_diff_cmd)
429 external_diff_cmd = external_diff_cmd_cfg;
431 return external_diff_cmd;
435 * Keep track of files used for diffing. Sometimes such an entry
436 * refers to a temporary file, sometimes to an existing file, and
437 * sometimes to "/dev/null".
439 static struct diff_tempfile {
441 * filename external diff should read from, or NULL if this
442 * entry is currently not in use:
446 char hex[GIT_MAX_HEXSZ + 1];
450 * If this diff_tempfile instance refers to a temporary file,
451 * this tempfile object is used to manage its lifetime.
453 struct tempfile tempfile;
456 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
458 struct emit_callback {
461 int blank_at_eof_in_preimage;
462 int blank_at_eof_in_postimage;
464 int lno_in_postimage;
465 sane_truncate_fn truncate;
466 const char **label_path;
467 struct diff_words_data *diff_words;
468 struct diff_options *opt;
469 struct strbuf *header;
472 static int count_lines(const char *data, int size)
474 int count, ch, completely_empty = 1, nl_just_seen = 0;
481 completely_empty = 0;
485 completely_empty = 0;
488 if (completely_empty)
491 count++; /* no trailing newline */
495 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
497 if (!DIFF_FILE_VALID(one)) {
498 mf->ptr = (char *)""; /* does not matter */
502 else if (diff_populate_filespec(one, 0))
506 mf->size = one->size;
510 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
511 static unsigned long diff_filespec_size(struct diff_filespec *one)
513 if (!DIFF_FILE_VALID(one))
515 diff_populate_filespec(one, CHECK_SIZE_ONLY);
519 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
522 long size = mf->size;
527 ptr += size - 1; /* pointing at the very end */
529 ; /* incomplete line */
531 ptr--; /* skip the last LF */
532 while (mf->ptr < ptr) {
534 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
535 if (*prev_eol == '\n')
537 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
545 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
546 struct emit_callback *ecbdata)
549 unsigned ws_rule = ecbdata->ws_rule;
550 l1 = count_trailing_blank(mf1, ws_rule);
551 l2 = count_trailing_blank(mf2, ws_rule);
553 ecbdata->blank_at_eof_in_preimage = 0;
554 ecbdata->blank_at_eof_in_postimage = 0;
557 at = count_lines(mf1->ptr, mf1->size);
558 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
560 at = count_lines(mf2->ptr, mf2->size);
561 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
564 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
565 int first, const char *line, int len)
567 int has_trailing_newline, has_trailing_carriage_return;
569 FILE *file = o->file;
571 fputs(diff_line_prefix(o), file);
574 has_trailing_newline = (first == '\n');
575 has_trailing_carriage_return = (!has_trailing_newline &&
577 nofirst = has_trailing_newline || has_trailing_carriage_return;
579 has_trailing_newline = (len > 0 && line[len-1] == '\n');
580 if (has_trailing_newline)
582 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
583 if (has_trailing_carriage_return)
588 if (len || !nofirst) {
592 fwrite(line, len, 1, file);
595 if (has_trailing_carriage_return)
597 if (has_trailing_newline)
601 static void emit_line(struct diff_options *o, const char *set, const char *reset,
602 const char *line, int len)
604 emit_line_0(o, set, reset, line[0], line+1, len-1);
608 DIFF_SYMBOL_BINARY_DIFF_HEADER,
609 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
610 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
611 DIFF_SYMBOL_BINARY_DIFF_BODY,
612 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
613 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
614 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
615 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
616 DIFF_SYMBOL_STATS_LINE,
617 DIFF_SYMBOL_WORD_DIFF,
618 DIFF_SYMBOL_STAT_SEP,
620 DIFF_SYMBOL_SUBMODULE_ADD,
621 DIFF_SYMBOL_SUBMODULE_DEL,
622 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
623 DIFF_SYMBOL_SUBMODULE_MODIFIED,
624 DIFF_SYMBOL_SUBMODULE_HEADER,
625 DIFF_SYMBOL_SUBMODULE_ERROR,
626 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
627 DIFF_SYMBOL_REWRITE_DIFF,
628 DIFF_SYMBOL_BINARY_FILES,
630 DIFF_SYMBOL_FILEPAIR_PLUS,
631 DIFF_SYMBOL_FILEPAIR_MINUS,
632 DIFF_SYMBOL_WORDS_PORCELAIN,
635 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
638 DIFF_SYMBOL_NO_LF_EOF,
639 DIFF_SYMBOL_CONTEXT_FRAGINFO,
640 DIFF_SYMBOL_CONTEXT_MARKER,
641 DIFF_SYMBOL_SEPARATOR
644 * Flags for content lines:
645 * 0..12 are whitespace rules
646 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
647 * 16 is marking if the line is blank at EOF
649 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
650 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
651 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
652 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
655 * This struct is used when we need to buffer the output of the diff output.
657 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
658 * into the pre/post image file. This pointer could be a union with the
659 * line pointer. By storing an offset into the file instead of the literal line,
660 * we can decrease the memory footprint for the buffered output. At first we
661 * may want to only have indirection for the content lines, but we could also
662 * enhance the state for emitting prefabricated lines, e.g. the similarity
663 * score line or hunk/file headers would only need to store a number or path
664 * and then the output can be constructed later on depending on state.
666 struct emitted_diff_symbol {
672 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
674 struct emitted_diff_symbols {
675 struct emitted_diff_symbol *buf;
678 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
680 static void append_emitted_diff_symbol(struct diff_options *o,
681 struct emitted_diff_symbol *e)
683 struct emitted_diff_symbol *f;
685 ALLOC_GROW(o->emitted_symbols->buf,
686 o->emitted_symbols->nr + 1,
687 o->emitted_symbols->alloc);
688 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
690 memcpy(f, e, sizeof(struct emitted_diff_symbol));
691 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
695 struct hashmap_entry ent;
696 const struct emitted_diff_symbol *es;
697 struct moved_entry *next_line;
700 static int next_byte(const char **cp, const char **endp,
701 const struct diff_options *diffopt)
708 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE_CHANGE)) {
709 while (*cp < *endp && isspace(**cp))
712 * After skipping a couple of whitespaces, we still have to
713 * account for one space.
718 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE)) {
719 while (*cp < *endp && isspace(**cp))
721 /* return the first non-ws character via the usual below */
724 retval = (unsigned char)(**cp);
729 static int moved_entry_cmp(const struct diff_options *diffopt,
730 const struct moved_entry *a,
731 const struct moved_entry *b,
734 const char *ap = a->es->line, *ae = a->es->line + a->es->len;
735 const char *bp = b->es->line, *be = b->es->line + b->es->len;
737 if (!(diffopt->xdl_opts & XDF_WHITESPACE_FLAGS))
738 return a->es->len != b->es->len || memcmp(ap, bp, a->es->len);
740 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE_AT_EOL)) {
741 while (ae > ap && isspace(*ae))
743 while (be > bp && isspace(*be))
749 ca = next_byte(&ap, &ae, diffopt);
750 cb = next_byte(&bp, &be, diffopt);
758 static unsigned get_string_hash(struct emitted_diff_symbol *es, struct diff_options *o)
760 if (o->xdl_opts & XDF_WHITESPACE_FLAGS) {
761 static struct strbuf sb = STRBUF_INIT;
762 const char *ap = es->line, *ae = es->line + es->len;
766 while (ae > ap && isspace(*ae))
768 while ((c = next_byte(&ap, &ae, o)) > 0)
769 strbuf_addch(&sb, c);
771 return memhash(sb.buf, sb.len);
773 return memhash(es->line, es->len);
777 static struct moved_entry *prepare_entry(struct diff_options *o,
780 struct moved_entry *ret = xmalloc(sizeof(*ret));
781 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
783 ret->ent.hash = get_string_hash(l, o);
785 ret->next_line = NULL;
790 static void add_lines_to_move_detection(struct diff_options *o,
791 struct hashmap *add_lines,
792 struct hashmap *del_lines)
794 struct moved_entry *prev_line = NULL;
797 for (n = 0; n < o->emitted_symbols->nr; n++) {
799 struct moved_entry *key;
801 switch (o->emitted_symbols->buf[n].s) {
802 case DIFF_SYMBOL_PLUS:
805 case DIFF_SYMBOL_MINUS:
813 key = prepare_entry(o, n);
814 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
815 prev_line->next_line = key;
817 hashmap_add(hm, key);
822 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
827 /* Shrink the set of potential block to the remaining running */
828 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
829 while (lp < pmb_nr && pmb[lp])
831 /* lp points at the first NULL now */
833 while (rp > -1 && !pmb[rp])
835 /* rp points at the last non-NULL */
837 if (lp < pmb_nr && rp > -1 && lp < rp) {
845 /* Remember the number of running sets */
849 /* Find blocks of moved code, delegate actual coloring decision to helper */
850 static void mark_color_as_moved(struct diff_options *o,
851 struct hashmap *add_lines,
852 struct hashmap *del_lines)
854 struct moved_entry **pmb = NULL; /* potentially moved blocks */
855 int pmb_nr = 0, pmb_alloc = 0;
856 int n, flipped_block = 1, block_length = 0;
859 for (n = 0; n < o->emitted_symbols->nr; n++) {
860 struct hashmap *hm = NULL;
861 struct moved_entry *key;
862 struct moved_entry *match = NULL;
863 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
867 case DIFF_SYMBOL_PLUS:
869 key = prepare_entry(o, n);
870 match = hashmap_get(hm, key, o);
873 case DIFF_SYMBOL_MINUS:
875 key = prepare_entry(o, n);
876 match = hashmap_get(hm, key, o);
884 if (block_length < COLOR_MOVED_MIN_BLOCK_LENGTH &&
885 o->color_moved != COLOR_MOVED_PLAIN) {
886 for (i = 0; i < block_length + 1; i++) {
887 l = &o->emitted_symbols->buf[n - i];
888 l->flags &= ~DIFF_SYMBOL_MOVED_LINE;
896 l->flags |= DIFF_SYMBOL_MOVED_LINE;
899 if (o->color_moved == COLOR_MOVED_PLAIN)
902 /* Check any potential block runs, advance each or nullify */
903 for (i = 0; i < pmb_nr; i++) {
904 struct moved_entry *p = pmb[i];
905 struct moved_entry *pnext = (p && p->next_line) ?
907 if (pnext && !hm->cmpfn(o, pnext, match, NULL)) {
908 pmb[i] = p->next_line;
914 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
918 * The current line is the start of a new block.
919 * Setup the set of potential blocks.
921 for (; match; match = hashmap_get_next(hm, match)) {
922 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
923 pmb[pmb_nr++] = match;
926 flipped_block = (flipped_block + 1) % 2;
930 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
936 static void emit_line_ws_markup(struct diff_options *o,
937 const char *set, const char *reset,
938 const char *line, int len, char sign,
939 unsigned ws_rule, int blank_at_eof)
941 const char *ws = NULL;
943 if (o->ws_error_highlight & ws_rule) {
944 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
950 emit_line_0(o, set, reset, sign, line, len);
951 else if (blank_at_eof)
952 /* Blank line at EOF - paint '+' as well */
953 emit_line_0(o, ws, reset, sign, line, len);
955 /* Emit just the prefix, then the rest. */
956 emit_line_0(o, set, reset, sign, "", 0);
957 ws_check_emit(line, len, ws_rule,
958 o->file, set, reset, ws);
962 static void emit_diff_symbol_from_struct(struct diff_options *o,
963 struct emitted_diff_symbol *eds)
965 static const char *nneof = " No newline at end of file\n";
966 const char *context, *reset, *set, *meta, *fraginfo;
967 struct strbuf sb = STRBUF_INIT;
969 enum diff_symbol s = eds->s;
970 const char *line = eds->line;
972 unsigned flags = eds->flags;
975 case DIFF_SYMBOL_NO_LF_EOF:
976 context = diff_get_color_opt(o, DIFF_CONTEXT);
977 reset = diff_get_color_opt(o, DIFF_RESET);
979 emit_line_0(o, context, reset, '\\',
980 nneof, strlen(nneof));
982 case DIFF_SYMBOL_SUBMODULE_HEADER:
983 case DIFF_SYMBOL_SUBMODULE_ERROR:
984 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
985 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
986 case DIFF_SYMBOL_SUMMARY:
987 case DIFF_SYMBOL_STATS_LINE:
988 case DIFF_SYMBOL_BINARY_DIFF_BODY:
989 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
990 emit_line(o, "", "", line, len);
992 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
993 case DIFF_SYMBOL_CONTEXT_MARKER:
994 context = diff_get_color_opt(o, DIFF_CONTEXT);
995 reset = diff_get_color_opt(o, DIFF_RESET);
996 emit_line(o, context, reset, line, len);
998 case DIFF_SYMBOL_SEPARATOR:
999 fprintf(o->file, "%s%c",
1000 diff_line_prefix(o),
1001 o->line_termination);
1003 case DIFF_SYMBOL_CONTEXT:
1004 set = diff_get_color_opt(o, DIFF_CONTEXT);
1005 reset = diff_get_color_opt(o, DIFF_RESET);
1006 emit_line_ws_markup(o, set, reset, line, len, ' ',
1007 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1009 case DIFF_SYMBOL_PLUS:
1010 if (flags & DIFF_SYMBOL_MOVED_LINE_ALT)
1011 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1012 else if (flags & DIFF_SYMBOL_MOVED_LINE)
1013 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1015 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1016 reset = diff_get_color_opt(o, DIFF_RESET);
1017 emit_line_ws_markup(o, set, reset, line, len, '+',
1018 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1019 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1021 case DIFF_SYMBOL_MINUS:
1022 if (flags & DIFF_SYMBOL_MOVED_LINE_ALT)
1023 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1024 else if (flags & DIFF_SYMBOL_MOVED_LINE)
1025 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1027 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1028 reset = diff_get_color_opt(o, DIFF_RESET);
1029 emit_line_ws_markup(o, set, reset, line, len, '-',
1030 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1032 case DIFF_SYMBOL_WORDS_PORCELAIN:
1033 context = diff_get_color_opt(o, DIFF_CONTEXT);
1034 reset = diff_get_color_opt(o, DIFF_RESET);
1035 emit_line(o, context, reset, line, len);
1036 fputs("~\n", o->file);
1038 case DIFF_SYMBOL_WORDS:
1039 context = diff_get_color_opt(o, DIFF_CONTEXT);
1040 reset = diff_get_color_opt(o, DIFF_RESET);
1042 * Skip the prefix character, if any. With
1043 * diff_suppress_blank_empty, there may be
1046 if (line[0] != '\n') {
1050 emit_line(o, context, reset, line, len);
1052 case DIFF_SYMBOL_FILEPAIR_PLUS:
1053 meta = diff_get_color_opt(o, DIFF_METAINFO);
1054 reset = diff_get_color_opt(o, DIFF_RESET);
1055 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1057 strchr(line, ' ') ? "\t" : "");
1059 case DIFF_SYMBOL_FILEPAIR_MINUS:
1060 meta = diff_get_color_opt(o, DIFF_METAINFO);
1061 reset = diff_get_color_opt(o, DIFF_RESET);
1062 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1064 strchr(line, ' ') ? "\t" : "");
1066 case DIFF_SYMBOL_BINARY_FILES:
1067 case DIFF_SYMBOL_HEADER:
1068 fprintf(o->file, "%s", line);
1070 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1071 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1073 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1074 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1076 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1077 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1079 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1080 fputs(diff_line_prefix(o), o->file);
1081 fputc('\n', o->file);
1083 case DIFF_SYMBOL_REWRITE_DIFF:
1084 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1085 reset = diff_get_color_opt(o, DIFF_RESET);
1086 emit_line(o, fraginfo, reset, line, len);
1088 case DIFF_SYMBOL_SUBMODULE_ADD:
1089 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1090 reset = diff_get_color_opt(o, DIFF_RESET);
1091 emit_line(o, set, reset, line, len);
1093 case DIFF_SYMBOL_SUBMODULE_DEL:
1094 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1095 reset = diff_get_color_opt(o, DIFF_RESET);
1096 emit_line(o, set, reset, line, len);
1098 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1099 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1100 diff_line_prefix(o), line);
1102 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1103 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1104 diff_line_prefix(o), line);
1106 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1107 emit_line(o, "", "", " 0 files changed\n",
1108 strlen(" 0 files changed\n"));
1110 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1111 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1113 case DIFF_SYMBOL_WORD_DIFF:
1114 fprintf(o->file, "%.*s", len, line);
1116 case DIFF_SYMBOL_STAT_SEP:
1117 fputs(o->stat_sep, o->file);
1120 die("BUG: unknown diff symbol");
1122 strbuf_release(&sb);
1125 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1126 const char *line, int len, unsigned flags)
1128 struct emitted_diff_symbol e = {line, len, flags, s};
1130 if (o->emitted_symbols)
1131 append_emitted_diff_symbol(o, &e);
1133 emit_diff_symbol_from_struct(o, &e);
1136 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1138 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1141 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1143 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1146 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1148 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1149 path, strlen(path), 0);
1152 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1154 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1155 path, strlen(path), 0);
1158 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1160 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1161 header, strlen(header), 0);
1164 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1166 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1169 void diff_emit_submodule_pipethrough(struct diff_options *o,
1170 const char *line, int len)
1172 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1175 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1177 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1178 ecbdata->blank_at_eof_in_preimage &&
1179 ecbdata->blank_at_eof_in_postimage &&
1180 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1181 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1183 return ws_blank_line(line, len, ecbdata->ws_rule);
1186 static void emit_add_line(const char *reset,
1187 struct emit_callback *ecbdata,
1188 const char *line, int len)
1190 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1191 if (new_blank_line_at_eof(ecbdata, line, len))
1192 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1194 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1197 static void emit_del_line(const char *reset,
1198 struct emit_callback *ecbdata,
1199 const char *line, int len)
1201 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1202 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1205 static void emit_context_line(const char *reset,
1206 struct emit_callback *ecbdata,
1207 const char *line, int len)
1209 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1210 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1213 static void emit_hunk_header(struct emit_callback *ecbdata,
1214 const char *line, int len)
1216 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1217 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1218 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1219 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1220 static const char atat[2] = { '@', '@' };
1221 const char *cp, *ep;
1222 struct strbuf msgbuf = STRBUF_INIT;
1227 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1228 * it always is at least 10 bytes long.
1231 memcmp(line, atat, 2) ||
1232 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1233 emit_diff_symbol(ecbdata->opt,
1234 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1237 ep += 2; /* skip over @@ */
1239 /* The hunk header in fraginfo color */
1240 strbuf_addstr(&msgbuf, frag);
1241 strbuf_add(&msgbuf, line, ep - line);
1242 strbuf_addstr(&msgbuf, reset);
1248 if (line[len - i] == '\r' || line[len - i] == '\n')
1251 /* blank before the func header */
1252 for (cp = ep; ep - line < len; ep++)
1253 if (*ep != ' ' && *ep != '\t')
1256 strbuf_addstr(&msgbuf, context);
1257 strbuf_add(&msgbuf, cp, ep - cp);
1258 strbuf_addstr(&msgbuf, reset);
1261 if (ep < line + len) {
1262 strbuf_addstr(&msgbuf, func);
1263 strbuf_add(&msgbuf, ep, line + len - ep);
1264 strbuf_addstr(&msgbuf, reset);
1267 strbuf_add(&msgbuf, line + len, org_len - len);
1268 strbuf_complete_line(&msgbuf);
1269 emit_diff_symbol(ecbdata->opt,
1270 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1271 strbuf_release(&msgbuf);
1274 static struct diff_tempfile *claim_diff_tempfile(void) {
1276 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1277 if (!diff_temp[i].name)
1278 return diff_temp + i;
1279 die("BUG: diff is failing to clean up its tempfiles");
1282 static void remove_tempfile(void)
1285 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1286 if (is_tempfile_active(&diff_temp[i].tempfile))
1287 delete_tempfile(&diff_temp[i].tempfile);
1288 diff_temp[i].name = NULL;
1292 static void add_line_count(struct strbuf *out, int count)
1296 strbuf_addstr(out, "0,0");
1299 strbuf_addstr(out, "1");
1302 strbuf_addf(out, "1,%d", count);
1307 static void emit_rewrite_lines(struct emit_callback *ecb,
1308 int prefix, const char *data, int size)
1310 const char *endp = NULL;
1311 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1316 endp = memchr(data, '\n', size);
1317 len = endp ? (endp - data + 1) : size;
1318 if (prefix != '+') {
1319 ecb->lno_in_preimage++;
1320 emit_del_line(reset, ecb, data, len);
1322 ecb->lno_in_postimage++;
1323 emit_add_line(reset, ecb, data, len);
1329 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1332 static void emit_rewrite_diff(const char *name_a,
1334 struct diff_filespec *one,
1335 struct diff_filespec *two,
1336 struct userdiff_driver *textconv_one,
1337 struct userdiff_driver *textconv_two,
1338 struct diff_options *o)
1341 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1342 const char *a_prefix, *b_prefix;
1343 char *data_one, *data_two;
1344 size_t size_one, size_two;
1345 struct emit_callback ecbdata;
1346 struct strbuf out = STRBUF_INIT;
1348 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
1349 a_prefix = o->b_prefix;
1350 b_prefix = o->a_prefix;
1352 a_prefix = o->a_prefix;
1353 b_prefix = o->b_prefix;
1356 name_a += (*name_a == '/');
1357 name_b += (*name_b == '/');
1359 strbuf_reset(&a_name);
1360 strbuf_reset(&b_name);
1361 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1362 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1364 size_one = fill_textconv(textconv_one, one, &data_one);
1365 size_two = fill_textconv(textconv_two, two, &data_two);
1367 memset(&ecbdata, 0, sizeof(ecbdata));
1368 ecbdata.color_diff = want_color(o->use_color);
1369 ecbdata.ws_rule = whitespace_rule(name_b);
1371 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1373 mf1.ptr = (char *)data_one;
1374 mf2.ptr = (char *)data_two;
1375 mf1.size = size_one;
1376 mf2.size = size_two;
1377 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1379 ecbdata.lno_in_preimage = 1;
1380 ecbdata.lno_in_postimage = 1;
1382 lc_a = count_lines(data_one, size_one);
1383 lc_b = count_lines(data_two, size_two);
1385 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1386 a_name.buf, a_name.len, 0);
1387 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1388 b_name.buf, b_name.len, 0);
1390 strbuf_addstr(&out, "@@ -");
1391 if (!o->irreversible_delete)
1392 add_line_count(&out, lc_a);
1394 strbuf_addstr(&out, "?,?");
1395 strbuf_addstr(&out, " +");
1396 add_line_count(&out, lc_b);
1397 strbuf_addstr(&out, " @@\n");
1398 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1399 strbuf_release(&out);
1401 if (lc_a && !o->irreversible_delete)
1402 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1404 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1406 free((char *)data_one);
1408 free((char *)data_two);
1411 struct diff_words_buffer {
1414 struct diff_words_orig {
1415 const char *begin, *end;
1417 int orig_nr, orig_alloc;
1420 static void diff_words_append(char *line, unsigned long len,
1421 struct diff_words_buffer *buffer)
1423 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1426 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1427 buffer->text.size += len;
1428 buffer->text.ptr[buffer->text.size] = '\0';
1431 struct diff_words_style_elem {
1434 const char *color; /* NULL; filled in by the setup code if
1435 * color is enabled */
1438 struct diff_words_style {
1439 enum diff_words_type type;
1440 struct diff_words_style_elem new, old, ctx;
1441 const char *newline;
1444 static struct diff_words_style diff_words_styles[] = {
1445 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1446 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1447 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1450 struct diff_words_data {
1451 struct diff_words_buffer minus, plus;
1452 const char *current_plus;
1454 struct diff_options *opt;
1455 regex_t *word_regex;
1456 enum diff_words_type type;
1457 struct diff_words_style *style;
1460 static int fn_out_diff_words_write_helper(struct diff_options *o,
1461 struct diff_words_style_elem *st_el,
1462 const char *newline,
1463 size_t count, const char *buf)
1466 struct strbuf sb = STRBUF_INIT;
1469 char *p = memchr(buf, '\n', count);
1471 strbuf_addstr(&sb, diff_line_prefix(o));
1474 const char *reset = st_el->color && *st_el->color ?
1475 GIT_COLOR_RESET : NULL;
1476 if (st_el->color && *st_el->color)
1477 strbuf_addstr(&sb, st_el->color);
1478 strbuf_addstr(&sb, st_el->prefix);
1479 strbuf_add(&sb, buf, p ? p - buf : count);
1480 strbuf_addstr(&sb, st_el->suffix);
1482 strbuf_addstr(&sb, reset);
1487 strbuf_addstr(&sb, newline);
1488 count -= p + 1 - buf;
1492 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1500 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1502 strbuf_release(&sb);
1507 * '--color-words' algorithm can be described as:
1509 * 1. collect the minus/plus lines of a diff hunk, divided into
1510 * minus-lines and plus-lines;
1512 * 2. break both minus-lines and plus-lines into words and
1513 * place them into two mmfile_t with one word for each line;
1515 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1517 * And for the common parts of the both file, we output the plus side text.
1518 * diff_words->current_plus is used to trace the current position of the plus file
1519 * which printed. diff_words->last_minus is used to trace the last minus word
1522 * For '--graph' to work with '--color-words', we need to output the graph prefix
1523 * on each line of color words output. Generally, there are two conditions on
1524 * which we should output the prefix.
1526 * 1. diff_words->last_minus == 0 &&
1527 * diff_words->current_plus == diff_words->plus.text.ptr
1529 * that is: the plus text must start as a new line, and if there is no minus
1530 * word printed, a graph prefix must be printed.
1532 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1533 * *(diff_words->current_plus - 1) == '\n'
1535 * that is: a graph prefix must be printed following a '\n'
1537 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1539 if ((diff_words->last_minus == 0 &&
1540 diff_words->current_plus == diff_words->plus.text.ptr) ||
1541 (diff_words->current_plus > diff_words->plus.text.ptr &&
1542 *(diff_words->current_plus - 1) == '\n')) {
1549 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1551 struct diff_words_data *diff_words = priv;
1552 struct diff_words_style *style = diff_words->style;
1553 int minus_first, minus_len, plus_first, plus_len;
1554 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1555 struct diff_options *opt = diff_words->opt;
1556 const char *line_prefix;
1558 if (line[0] != '@' || parse_hunk_header(line, len,
1559 &minus_first, &minus_len, &plus_first, &plus_len))
1563 line_prefix = diff_line_prefix(opt);
1565 /* POSIX requires that first be decremented by one if len == 0... */
1567 minus_begin = diff_words->minus.orig[minus_first].begin;
1569 diff_words->minus.orig[minus_first + minus_len - 1].end;
1571 minus_begin = minus_end =
1572 diff_words->minus.orig[minus_first].end;
1575 plus_begin = diff_words->plus.orig[plus_first].begin;
1576 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1578 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1580 if (color_words_output_graph_prefix(diff_words)) {
1581 fputs(line_prefix, diff_words->opt->file);
1583 if (diff_words->current_plus != plus_begin) {
1584 fn_out_diff_words_write_helper(diff_words->opt,
1585 &style->ctx, style->newline,
1586 plus_begin - diff_words->current_plus,
1587 diff_words->current_plus);
1589 if (minus_begin != minus_end) {
1590 fn_out_diff_words_write_helper(diff_words->opt,
1591 &style->old, style->newline,
1592 minus_end - minus_begin, minus_begin);
1594 if (plus_begin != plus_end) {
1595 fn_out_diff_words_write_helper(diff_words->opt,
1596 &style->new, style->newline,
1597 plus_end - plus_begin, plus_begin);
1600 diff_words->current_plus = plus_end;
1601 diff_words->last_minus = minus_first;
1604 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1605 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1606 int *begin, int *end)
1608 if (word_regex && *begin < buffer->size) {
1609 regmatch_t match[1];
1610 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1611 buffer->size - *begin, 1, match, 0)) {
1612 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1613 '\n', match[0].rm_eo - match[0].rm_so);
1614 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1615 *begin += match[0].rm_so;
1616 return *begin >= *end;
1621 /* find the next word */
1622 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1624 if (*begin >= buffer->size)
1627 /* find the end of the word */
1629 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1636 * This function splits the words in buffer->text, stores the list with
1637 * newline separator into out, and saves the offsets of the original words
1640 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1641 regex_t *word_regex)
1649 /* fake an empty "0th" word */
1650 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1651 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1652 buffer->orig_nr = 1;
1654 for (i = 0; i < buffer->text.size; i++) {
1655 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1658 /* store original boundaries */
1659 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1660 buffer->orig_alloc);
1661 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1662 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1665 /* store one word */
1666 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1667 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1668 out->ptr[out->size + j - i] = '\n';
1669 out->size += j - i + 1;
1675 /* this executes the word diff on the accumulated buffers */
1676 static void diff_words_show(struct diff_words_data *diff_words)
1680 mmfile_t minus, plus;
1681 struct diff_words_style *style = diff_words->style;
1683 struct diff_options *opt = diff_words->opt;
1684 const char *line_prefix;
1687 line_prefix = diff_line_prefix(opt);
1689 /* special case: only removal */
1690 if (!diff_words->plus.text.size) {
1691 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1692 line_prefix, strlen(line_prefix), 0);
1693 fn_out_diff_words_write_helper(diff_words->opt,
1694 &style->old, style->newline,
1695 diff_words->minus.text.size,
1696 diff_words->minus.text.ptr);
1697 diff_words->minus.text.size = 0;
1701 diff_words->current_plus = diff_words->plus.text.ptr;
1702 diff_words->last_minus = 0;
1704 memset(&xpp, 0, sizeof(xpp));
1705 memset(&xecfg, 0, sizeof(xecfg));
1706 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1707 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1709 /* as only the hunk header will be parsed, we need a 0-context */
1711 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1713 die("unable to generate word diff");
1716 if (diff_words->current_plus != diff_words->plus.text.ptr +
1717 diff_words->plus.text.size) {
1718 if (color_words_output_graph_prefix(diff_words))
1719 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1720 line_prefix, strlen(line_prefix), 0);
1721 fn_out_diff_words_write_helper(diff_words->opt,
1722 &style->ctx, style->newline,
1723 diff_words->plus.text.ptr + diff_words->plus.text.size
1724 - diff_words->current_plus, diff_words->current_plus);
1726 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1729 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1730 static void diff_words_flush(struct emit_callback *ecbdata)
1732 struct diff_options *wo = ecbdata->diff_words->opt;
1734 if (ecbdata->diff_words->minus.text.size ||
1735 ecbdata->diff_words->plus.text.size)
1736 diff_words_show(ecbdata->diff_words);
1738 if (wo->emitted_symbols) {
1739 struct diff_options *o = ecbdata->opt;
1740 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1745 * Instead of appending each, concat all words to a line?
1747 for (i = 0; i < wol->nr; i++)
1748 append_emitted_diff_symbol(o, &wol->buf[i]);
1750 for (i = 0; i < wol->nr; i++)
1751 free((void *)wol->buf[i].line);
1757 static void diff_filespec_load_driver(struct diff_filespec *one)
1759 /* Use already-loaded driver */
1763 if (S_ISREG(one->mode))
1764 one->driver = userdiff_find_by_path(one->path);
1766 /* Fallback to default settings */
1768 one->driver = userdiff_find_by_name("default");
1771 static const char *userdiff_word_regex(struct diff_filespec *one)
1773 diff_filespec_load_driver(one);
1774 return one->driver->word_regex;
1777 static void init_diff_words_data(struct emit_callback *ecbdata,
1778 struct diff_options *orig_opts,
1779 struct diff_filespec *one,
1780 struct diff_filespec *two)
1783 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1784 memcpy(o, orig_opts, sizeof(struct diff_options));
1786 ecbdata->diff_words =
1787 xcalloc(1, sizeof(struct diff_words_data));
1788 ecbdata->diff_words->type = o->word_diff;
1789 ecbdata->diff_words->opt = o;
1791 if (orig_opts->emitted_symbols)
1792 o->emitted_symbols =
1793 xcalloc(1, sizeof(struct emitted_diff_symbols));
1796 o->word_regex = userdiff_word_regex(one);
1798 o->word_regex = userdiff_word_regex(two);
1800 o->word_regex = diff_word_regex_cfg;
1801 if (o->word_regex) {
1802 ecbdata->diff_words->word_regex = (regex_t *)
1803 xmalloc(sizeof(regex_t));
1804 if (regcomp(ecbdata->diff_words->word_regex,
1806 REG_EXTENDED | REG_NEWLINE))
1807 die ("Invalid regular expression: %s",
1810 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1811 if (o->word_diff == diff_words_styles[i].type) {
1812 ecbdata->diff_words->style =
1813 &diff_words_styles[i];
1817 if (want_color(o->use_color)) {
1818 struct diff_words_style *st = ecbdata->diff_words->style;
1819 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1820 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1821 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1825 static void free_diff_words_data(struct emit_callback *ecbdata)
1827 if (ecbdata->diff_words) {
1828 diff_words_flush(ecbdata);
1829 free (ecbdata->diff_words->opt->emitted_symbols);
1830 free (ecbdata->diff_words->opt);
1831 free (ecbdata->diff_words->minus.text.ptr);
1832 free (ecbdata->diff_words->minus.orig);
1833 free (ecbdata->diff_words->plus.text.ptr);
1834 free (ecbdata->diff_words->plus.orig);
1835 if (ecbdata->diff_words->word_regex) {
1836 regfree(ecbdata->diff_words->word_regex);
1837 free(ecbdata->diff_words->word_regex);
1839 FREE_AND_NULL(ecbdata->diff_words);
1843 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1845 if (want_color(diff_use_color))
1846 return diff_colors[ix];
1850 const char *diff_line_prefix(struct diff_options *opt)
1852 struct strbuf *msgbuf;
1853 if (!opt->output_prefix)
1856 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1860 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1863 unsigned long allot;
1867 return ecb->truncate(line, len);
1871 (void) utf8_width(&cp, &l);
1873 break; /* truncated in the middle? */
1878 static void find_lno(const char *line, struct emit_callback *ecbdata)
1881 ecbdata->lno_in_preimage = 0;
1882 ecbdata->lno_in_postimage = 0;
1883 p = strchr(line, '-');
1885 return; /* cannot happen */
1886 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1889 return; /* cannot happen */
1890 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1893 static void fn_out_consume(void *priv, char *line, unsigned long len)
1895 struct emit_callback *ecbdata = priv;
1896 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1897 struct diff_options *o = ecbdata->opt;
1899 o->found_changes = 1;
1901 if (ecbdata->header) {
1902 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1903 ecbdata->header->buf, ecbdata->header->len, 0);
1904 strbuf_reset(ecbdata->header);
1905 ecbdata->header = NULL;
1908 if (ecbdata->label_path[0]) {
1909 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1910 ecbdata->label_path[0],
1911 strlen(ecbdata->label_path[0]), 0);
1912 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1913 ecbdata->label_path[1],
1914 strlen(ecbdata->label_path[1]), 0);
1915 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1918 if (diff_suppress_blank_empty
1919 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1924 if (line[0] == '@') {
1925 if (ecbdata->diff_words)
1926 diff_words_flush(ecbdata);
1927 len = sane_truncate_line(ecbdata, line, len);
1928 find_lno(line, ecbdata);
1929 emit_hunk_header(ecbdata, line, len);
1933 if (ecbdata->diff_words) {
1934 enum diff_symbol s =
1935 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
1936 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
1937 if (line[0] == '-') {
1938 diff_words_append(line, len,
1939 &ecbdata->diff_words->minus);
1941 } else if (line[0] == '+') {
1942 diff_words_append(line, len,
1943 &ecbdata->diff_words->plus);
1945 } else if (starts_with(line, "\\ ")) {
1947 * Eat the "no newline at eof" marker as if we
1948 * saw a "+" or "-" line with nothing on it,
1949 * and return without diff_words_flush() to
1950 * defer processing. If this is the end of
1951 * preimage, more "+" lines may come after it.
1955 diff_words_flush(ecbdata);
1956 emit_diff_symbol(o, s, line, len, 0);
1962 ecbdata->lno_in_postimage++;
1963 emit_add_line(reset, ecbdata, line + 1, len - 1);
1966 ecbdata->lno_in_preimage++;
1967 emit_del_line(reset, ecbdata, line + 1, len - 1);
1970 ecbdata->lno_in_postimage++;
1971 ecbdata->lno_in_preimage++;
1972 emit_context_line(reset, ecbdata, line + 1, len - 1);
1975 /* incomplete line at the end */
1976 ecbdata->lno_in_preimage++;
1977 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1983 static char *pprint_rename(const char *a, const char *b)
1985 const char *old = a;
1986 const char *new = b;
1987 struct strbuf name = STRBUF_INIT;
1988 int pfx_length, sfx_length;
1989 int pfx_adjust_for_slash;
1990 int len_a = strlen(a);
1991 int len_b = strlen(b);
1992 int a_midlen, b_midlen;
1993 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1994 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1996 if (qlen_a || qlen_b) {
1997 quote_c_style(a, &name, NULL, 0);
1998 strbuf_addstr(&name, " => ");
1999 quote_c_style(b, &name, NULL, 0);
2000 return strbuf_detach(&name, NULL);
2003 /* Find common prefix */
2005 while (*old && *new && *old == *new) {
2007 pfx_length = old - a + 1;
2012 /* Find common suffix */
2017 * If there is a common prefix, it must end in a slash. In
2018 * that case we let this loop run 1 into the prefix to see the
2021 * If there is no common prefix, we cannot do this as it would
2022 * underrun the input strings.
2024 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2025 while (a + pfx_length - pfx_adjust_for_slash <= old &&
2026 b + pfx_length - pfx_adjust_for_slash <= new &&
2029 sfx_length = len_a - (old - a);
2035 * pfx{mid-a => mid-b}sfx
2036 * {pfx-a => pfx-b}sfx
2037 * pfx{sfx-a => sfx-b}
2040 a_midlen = len_a - pfx_length - sfx_length;
2041 b_midlen = len_b - pfx_length - sfx_length;
2047 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2048 if (pfx_length + sfx_length) {
2049 strbuf_add(&name, a, pfx_length);
2050 strbuf_addch(&name, '{');
2052 strbuf_add(&name, a + pfx_length, a_midlen);
2053 strbuf_addstr(&name, " => ");
2054 strbuf_add(&name, b + pfx_length, b_midlen);
2055 if (pfx_length + sfx_length) {
2056 strbuf_addch(&name, '}');
2057 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
2059 return strbuf_detach(&name, NULL);
2065 struct diffstat_file {
2069 unsigned is_unmerged:1;
2070 unsigned is_binary:1;
2071 unsigned is_renamed:1;
2072 unsigned is_interesting:1;
2073 uintmax_t added, deleted;
2077 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2081 struct diffstat_file *x;
2082 x = xcalloc(1, sizeof(*x));
2083 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2084 diffstat->files[diffstat->nr++] = x;
2086 x->from_name = xstrdup(name_a);
2087 x->name = xstrdup(name_b);
2091 x->from_name = NULL;
2092 x->name = xstrdup(name_a);
2097 static void diffstat_consume(void *priv, char *line, unsigned long len)
2099 struct diffstat_t *diffstat = priv;
2100 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2104 else if (line[0] == '-')
2108 const char mime_boundary_leader[] = "------------";
2110 static int scale_linear(int it, int width, int max_change)
2115 * make sure that at least one '-' or '+' is printed if
2116 * there is any change to this path. The easiest way is to
2117 * scale linearly as if the alloted width is one column shorter
2118 * than it is, and then add 1 to the result.
2120 return 1 + (it * (width - 1) / max_change);
2123 static void show_graph(struct strbuf *out, char ch, int cnt,
2124 const char *set, const char *reset)
2128 strbuf_addstr(out, set);
2129 strbuf_addchars(out, ch, cnt);
2130 strbuf_addstr(out, reset);
2133 static void fill_print_name(struct diffstat_file *file)
2137 if (file->print_name)
2140 if (!file->is_renamed) {
2141 struct strbuf buf = STRBUF_INIT;
2142 if (quote_c_style(file->name, &buf, NULL, 0)) {
2143 pname = strbuf_detach(&buf, NULL);
2146 strbuf_release(&buf);
2149 pname = pprint_rename(file->from_name, file->name);
2151 file->print_name = pname;
2154 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2155 int files, int insertions, int deletions)
2157 struct strbuf sb = STRBUF_INIT;
2160 assert(insertions == 0 && deletions == 0);
2161 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2167 (files == 1) ? " %d file changed" : " %d files changed",
2171 * For binary diff, the caller may want to print "x files
2172 * changed" with insertions == 0 && deletions == 0.
2174 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2175 * is probably less confusing (i.e skip over "2 files changed
2176 * but nothing about added/removed lines? Is this a bug in Git?").
2178 if (insertions || deletions == 0) {
2180 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2184 if (deletions || insertions == 0) {
2186 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2189 strbuf_addch(&sb, '\n');
2190 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2192 strbuf_release(&sb);
2195 void print_stat_summary(FILE *fp, int files,
2196 int insertions, int deletions)
2198 struct diff_options o;
2199 memset(&o, 0, sizeof(o));
2202 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2205 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2207 int i, len, add, del, adds = 0, dels = 0;
2208 uintmax_t max_change = 0, max_len = 0;
2209 int total_files = data->nr, count;
2210 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2211 const char *reset, *add_c, *del_c;
2212 int extra_shown = 0;
2213 const char *line_prefix = diff_line_prefix(options);
2214 struct strbuf out = STRBUF_INIT;
2219 count = options->stat_count ? options->stat_count : data->nr;
2221 reset = diff_get_color_opt(options, DIFF_RESET);
2222 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2223 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2226 * Find the longest filename and max number of changes
2228 for (i = 0; (i < count) && (i < data->nr); i++) {
2229 struct diffstat_file *file = data->files[i];
2230 uintmax_t change = file->added + file->deleted;
2232 if (!file->is_interesting && (change == 0)) {
2233 count++; /* not shown == room for one more */
2236 fill_print_name(file);
2237 len = strlen(file->print_name);
2241 if (file->is_unmerged) {
2242 /* "Unmerged" is 8 characters */
2243 bin_width = bin_width < 8 ? 8 : bin_width;
2246 if (file->is_binary) {
2247 /* "Bin XXX -> YYY bytes" */
2248 int w = 14 + decimal_width(file->added)
2249 + decimal_width(file->deleted);
2250 bin_width = bin_width < w ? w : bin_width;
2251 /* Display change counts aligned with "Bin" */
2256 if (max_change < change)
2257 max_change = change;
2259 count = i; /* where we can stop scanning in data->files[] */
2262 * We have width = stat_width or term_columns() columns total.
2263 * We want a maximum of min(max_len, stat_name_width) for the name part.
2264 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2265 * We also need 1 for " " and 4 + decimal_width(max_change)
2266 * for " | NNNN " and one the empty column at the end, altogether
2267 * 6 + decimal_width(max_change).
2269 * If there's not enough space, we will use the smaller of
2270 * stat_name_width (if set) and 5/8*width for the filename,
2271 * and the rest for constant elements + graph part, but no more
2272 * than stat_graph_width for the graph part.
2273 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2274 * for the standard terminal size).
2276 * In other words: stat_width limits the maximum width, and
2277 * stat_name_width fixes the maximum width of the filename,
2278 * and is also used to divide available columns if there
2281 * Binary files are displayed with "Bin XXX -> YYY bytes"
2282 * instead of the change count and graph. This part is treated
2283 * similarly to the graph part, except that it is not
2284 * "scaled". If total width is too small to accommodate the
2285 * guaranteed minimum width of the filename part and the
2286 * separators and this message, this message will "overflow"
2287 * making the line longer than the maximum width.
2290 if (options->stat_width == -1)
2291 width = term_columns() - strlen(line_prefix);
2293 width = options->stat_width ? options->stat_width : 80;
2294 number_width = decimal_width(max_change) > number_width ?
2295 decimal_width(max_change) : number_width;
2297 if (options->stat_graph_width == -1)
2298 options->stat_graph_width = diff_stat_graph_width;
2301 * Guarantee 3/8*16==6 for the graph part
2302 * and 5/8*16==10 for the filename part
2304 if (width < 16 + 6 + number_width)
2305 width = 16 + 6 + number_width;
2308 * First assign sizes that are wanted, ignoring available width.
2309 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2310 * starting from "XXX" should fit in graph_width.
2312 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2313 if (options->stat_graph_width &&
2314 options->stat_graph_width < graph_width)
2315 graph_width = options->stat_graph_width;
2317 name_width = (options->stat_name_width > 0 &&
2318 options->stat_name_width < max_len) ?
2319 options->stat_name_width : max_len;
2322 * Adjust adjustable widths not to exceed maximum width
2324 if (name_width + number_width + 6 + graph_width > width) {
2325 if (graph_width > width * 3/8 - number_width - 6) {
2326 graph_width = width * 3/8 - number_width - 6;
2327 if (graph_width < 6)
2331 if (options->stat_graph_width &&
2332 graph_width > options->stat_graph_width)
2333 graph_width = options->stat_graph_width;
2334 if (name_width > width - number_width - 6 - graph_width)
2335 name_width = width - number_width - 6 - graph_width;
2337 graph_width = width - number_width - 6 - name_width;
2341 * From here name_width is the width of the name area,
2342 * and graph_width is the width of the graph area.
2343 * max_change is used to scale graph properly.
2345 for (i = 0; i < count; i++) {
2346 const char *prefix = "";
2347 struct diffstat_file *file = data->files[i];
2348 char *name = file->print_name;
2349 uintmax_t added = file->added;
2350 uintmax_t deleted = file->deleted;
2353 if (!file->is_interesting && (added + deleted == 0))
2357 * "scale" the filename
2360 name_len = strlen(name);
2361 if (name_width < name_len) {
2365 name += name_len - len;
2366 slash = strchr(name, '/');
2371 if (file->is_binary) {
2372 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2373 strbuf_addf(&out, " %*s", number_width, "Bin");
2374 if (!added && !deleted) {
2375 strbuf_addch(&out, '\n');
2376 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2377 out.buf, out.len, 0);
2381 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2382 del_c, deleted, reset);
2383 strbuf_addstr(&out, " -> ");
2384 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2385 add_c, added, reset);
2386 strbuf_addstr(&out, " bytes\n");
2387 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2388 out.buf, out.len, 0);
2392 else if (file->is_unmerged) {
2393 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2394 strbuf_addstr(&out, " Unmerged\n");
2395 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2396 out.buf, out.len, 0);
2402 * scale the add/delete
2407 if (graph_width <= max_change) {
2408 int total = scale_linear(add + del, graph_width, max_change);
2409 if (total < 2 && add && del)
2410 /* width >= 2 due to the sanity check */
2413 add = scale_linear(add, graph_width, max_change);
2416 del = scale_linear(del, graph_width, max_change);
2420 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2421 strbuf_addf(&out, " %*"PRIuMAX"%s",
2422 number_width, added + deleted,
2423 added + deleted ? " " : "");
2424 show_graph(&out, '+', add, add_c, reset);
2425 show_graph(&out, '-', del, del_c, reset);
2426 strbuf_addch(&out, '\n');
2427 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2428 out.buf, out.len, 0);
2432 for (i = 0; i < data->nr; i++) {
2433 struct diffstat_file *file = data->files[i];
2434 uintmax_t added = file->added;
2435 uintmax_t deleted = file->deleted;
2437 if (file->is_unmerged ||
2438 (!file->is_interesting && (added + deleted == 0))) {
2443 if (!file->is_binary) {
2450 emit_diff_symbol(options,
2451 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2456 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2459 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2461 int i, adds = 0, dels = 0, total_files = data->nr;
2466 for (i = 0; i < data->nr; i++) {
2467 int added = data->files[i]->added;
2468 int deleted = data->files[i]->deleted;
2470 if (data->files[i]->is_unmerged ||
2471 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2473 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2478 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2481 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2488 for (i = 0; i < data->nr; i++) {
2489 struct diffstat_file *file = data->files[i];
2491 fprintf(options->file, "%s", diff_line_prefix(options));
2493 if (file->is_binary)
2494 fprintf(options->file, "-\t-\t");
2496 fprintf(options->file,
2497 "%"PRIuMAX"\t%"PRIuMAX"\t",
2498 file->added, file->deleted);
2499 if (options->line_termination) {
2500 fill_print_name(file);
2501 if (!file->is_renamed)
2502 write_name_quoted(file->name, options->file,
2503 options->line_termination);
2505 fputs(file->print_name, options->file);
2506 putc(options->line_termination, options->file);
2509 if (file->is_renamed) {
2510 putc('\0', options->file);
2511 write_name_quoted(file->from_name, options->file, '\0');
2513 write_name_quoted(file->name, options->file, '\0');
2518 struct dirstat_file {
2520 unsigned long changed;
2523 struct dirstat_dir {
2524 struct dirstat_file *files;
2525 int alloc, nr, permille, cumulative;
2528 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2529 unsigned long changed, const char *base, int baselen)
2531 unsigned long this_dir = 0;
2532 unsigned int sources = 0;
2533 const char *line_prefix = diff_line_prefix(opt);
2536 struct dirstat_file *f = dir->files;
2537 int namelen = strlen(f->name);
2541 if (namelen < baselen)
2543 if (memcmp(f->name, base, baselen))
2545 slash = strchr(f->name + baselen, '/');
2547 int newbaselen = slash + 1 - f->name;
2548 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2560 * We don't report dirstat's for
2562 * - or cases where everything came from a single directory
2563 * under this directory (sources == 1).
2565 if (baselen && sources != 1) {
2567 int permille = this_dir * 1000 / changed;
2568 if (permille >= dir->permille) {
2569 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2570 permille / 10, permille % 10, baselen, base);
2571 if (!dir->cumulative)
2579 static int dirstat_compare(const void *_a, const void *_b)
2581 const struct dirstat_file *a = _a;
2582 const struct dirstat_file *b = _b;
2583 return strcmp(a->name, b->name);
2586 static void show_dirstat(struct diff_options *options)
2589 unsigned long changed;
2590 struct dirstat_dir dir;
2591 struct diff_queue_struct *q = &diff_queued_diff;
2596 dir.permille = options->dirstat_permille;
2597 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2600 for (i = 0; i < q->nr; i++) {
2601 struct diff_filepair *p = q->queue[i];
2603 unsigned long copied, added, damage;
2604 int content_changed;
2606 name = p->two->path ? p->two->path : p->one->path;
2608 if (p->one->oid_valid && p->two->oid_valid)
2609 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2611 content_changed = 1;
2613 if (!content_changed) {
2615 * The SHA1 has not changed, so pre-/post-content is
2616 * identical. We can therefore skip looking at the
2617 * file contents altogether.
2623 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2625 * In --dirstat-by-file mode, we don't really need to
2626 * look at the actual file contents at all.
2627 * The fact that the SHA1 changed is enough for us to
2628 * add this file to the list of results
2629 * (with each file contributing equal damage).
2635 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2636 diff_populate_filespec(p->one, 0);
2637 diff_populate_filespec(p->two, 0);
2638 diffcore_count_changes(p->one, p->two, NULL, NULL,
2640 diff_free_filespec_data(p->one);
2641 diff_free_filespec_data(p->two);
2642 } else if (DIFF_FILE_VALID(p->one)) {
2643 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2645 diff_free_filespec_data(p->one);
2646 } else if (DIFF_FILE_VALID(p->two)) {
2647 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2649 added = p->two->size;
2650 diff_free_filespec_data(p->two);
2655 * Original minus copied is the removed material,
2656 * added is the new material. They are both damages
2657 * made to the preimage.
2658 * If the resulting damage is zero, we know that
2659 * diffcore_count_changes() considers the two entries to
2660 * be identical, but since content_changed is true, we
2661 * know that there must have been _some_ kind of change,
2662 * so we force all entries to have damage > 0.
2664 damage = (p->one->size - copied) + added;
2669 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2670 dir.files[dir.nr].name = name;
2671 dir.files[dir.nr].changed = damage;
2676 /* This can happen even with many files, if everything was renames */
2680 /* Show all directories with more than x% of the changes */
2681 QSORT(dir.files, dir.nr, dirstat_compare);
2682 gather_dirstat(options, &dir, changed, "", 0);
2685 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2688 unsigned long changed;
2689 struct dirstat_dir dir;
2697 dir.permille = options->dirstat_permille;
2698 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2701 for (i = 0; i < data->nr; i++) {
2702 struct diffstat_file *file = data->files[i];
2703 unsigned long damage = file->added + file->deleted;
2704 if (file->is_binary)
2706 * binary files counts bytes, not lines. Must find some
2707 * way to normalize binary bytes vs. textual lines.
2708 * The following heuristic assumes that there are 64
2710 * This is stupid and ugly, but very cheap...
2712 damage = (damage + 63) / 64;
2713 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2714 dir.files[dir.nr].name = file->name;
2715 dir.files[dir.nr].changed = damage;
2720 /* This can happen even with many files, if everything was renames */
2724 /* Show all directories with more than x% of the changes */
2725 QSORT(dir.files, dir.nr, dirstat_compare);
2726 gather_dirstat(options, &dir, changed, "", 0);
2729 static void free_diffstat_info(struct diffstat_t *diffstat)
2732 for (i = 0; i < diffstat->nr; i++) {
2733 struct diffstat_file *f = diffstat->files[i];
2734 if (f->name != f->print_name)
2735 free(f->print_name);
2740 free(diffstat->files);
2743 struct checkdiff_t {
2744 const char *filename;
2746 int conflict_marker_size;
2747 struct diff_options *o;
2752 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2757 if (len < marker_size + 1)
2759 firstchar = line[0];
2760 switch (firstchar) {
2761 case '=': case '>': case '<': case '|':
2766 for (cnt = 1; cnt < marker_size; cnt++)
2767 if (line[cnt] != firstchar)
2769 /* line[1] thru line[marker_size-1] are same as firstchar */
2770 if (len < marker_size + 1 || !isspace(line[marker_size]))
2775 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2777 struct checkdiff_t *data = priv;
2778 int marker_size = data->conflict_marker_size;
2779 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2780 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2781 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2783 const char *line_prefix;
2786 line_prefix = diff_line_prefix(data->o);
2788 if (line[0] == '+') {
2791 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2793 fprintf(data->o->file,
2794 "%s%s:%d: leftover conflict marker\n",
2795 line_prefix, data->filename, data->lineno);
2797 bad = ws_check(line + 1, len - 1, data->ws_rule);
2800 data->status |= bad;
2801 err = whitespace_error_string(bad);
2802 fprintf(data->o->file, "%s%s:%d: %s.\n",
2803 line_prefix, data->filename, data->lineno, err);
2805 emit_line(data->o, set, reset, line, 1);
2806 ws_check_emit(line + 1, len - 1, data->ws_rule,
2807 data->o->file, set, reset, ws);
2808 } else if (line[0] == ' ') {
2810 } else if (line[0] == '@') {
2811 char *plus = strchr(line, '+');
2813 data->lineno = strtol(plus, NULL, 10) - 1;
2815 die("invalid diff");
2819 static unsigned char *deflate_it(char *data,
2821 unsigned long *result_size)
2824 unsigned char *deflated;
2827 git_deflate_init(&stream, zlib_compression_level);
2828 bound = git_deflate_bound(&stream, size);
2829 deflated = xmalloc(bound);
2830 stream.next_out = deflated;
2831 stream.avail_out = bound;
2833 stream.next_in = (unsigned char *)data;
2834 stream.avail_in = size;
2835 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2837 git_deflate_end(&stream);
2838 *result_size = stream.total_out;
2842 static void emit_binary_diff_body(struct diff_options *o,
2843 mmfile_t *one, mmfile_t *two)
2849 unsigned long orig_size;
2850 unsigned long delta_size;
2851 unsigned long deflate_size;
2852 unsigned long data_size;
2854 /* We could do deflated delta, or we could do just deflated two,
2855 * whichever is smaller.
2858 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2859 if (one->size && two->size) {
2860 delta = diff_delta(one->ptr, one->size,
2861 two->ptr, two->size,
2862 &delta_size, deflate_size);
2864 void *to_free = delta;
2865 orig_size = delta_size;
2866 delta = deflate_it(delta, delta_size, &delta_size);
2871 if (delta && delta_size < deflate_size) {
2872 char *s = xstrfmt("%lu", orig_size);
2873 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2878 data_size = delta_size;
2880 char *s = xstrfmt("%lu", two->size);
2881 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2886 data_size = deflate_size;
2889 /* emit data encoded in base85 */
2893 int bytes = (52 < data_size) ? 52 : data_size;
2897 line[0] = bytes + 'A' - 1;
2899 line[0] = bytes - 26 + 'a' - 1;
2900 encode_85(line + 1, cp, bytes);
2901 cp = (char *) cp + bytes;
2907 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2910 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2914 static void emit_binary_diff(struct diff_options *o,
2915 mmfile_t *one, mmfile_t *two)
2917 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2918 emit_binary_diff_body(o, one, two);
2919 emit_binary_diff_body(o, two, one);
2922 int diff_filespec_is_binary(struct diff_filespec *one)
2924 if (one->is_binary == -1) {
2925 diff_filespec_load_driver(one);
2926 if (one->driver->binary != -1)
2927 one->is_binary = one->driver->binary;
2929 if (!one->data && DIFF_FILE_VALID(one))
2930 diff_populate_filespec(one, CHECK_BINARY);
2931 if (one->is_binary == -1 && one->data)
2932 one->is_binary = buffer_is_binary(one->data,
2934 if (one->is_binary == -1)
2938 return one->is_binary;
2941 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2943 diff_filespec_load_driver(one);
2944 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2947 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2949 if (!options->a_prefix)
2950 options->a_prefix = a;
2951 if (!options->b_prefix)
2952 options->b_prefix = b;
2955 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2957 if (!DIFF_FILE_VALID(one))
2960 diff_filespec_load_driver(one);
2961 return userdiff_get_textconv(one->driver);
2964 static void builtin_diff(const char *name_a,
2966 struct diff_filespec *one,
2967 struct diff_filespec *two,
2968 const char *xfrm_msg,
2969 int must_show_header,
2970 struct diff_options *o,
2971 int complete_rewrite)
2975 char *a_one, *b_two;
2976 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2977 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2978 const char *a_prefix, *b_prefix;
2979 struct userdiff_driver *textconv_one = NULL;
2980 struct userdiff_driver *textconv_two = NULL;
2981 struct strbuf header = STRBUF_INIT;
2982 const char *line_prefix = diff_line_prefix(o);
2984 diff_set_mnemonic_prefix(o, "a/", "b/");
2985 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2986 a_prefix = o->b_prefix;
2987 b_prefix = o->a_prefix;
2989 a_prefix = o->a_prefix;
2990 b_prefix = o->b_prefix;
2993 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2994 (!one->mode || S_ISGITLINK(one->mode)) &&
2995 (!two->mode || S_ISGITLINK(two->mode))) {
2996 show_submodule_summary(o, one->path ? one->path : two->path,
2997 &one->oid, &two->oid,
2998 two->dirty_submodule);
3000 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3001 (!one->mode || S_ISGITLINK(one->mode)) &&
3002 (!two->mode || S_ISGITLINK(two->mode))) {
3003 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3004 &one->oid, &two->oid,
3005 two->dirty_submodule);
3009 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
3010 textconv_one = get_textconv(one);
3011 textconv_two = get_textconv(two);
3014 /* Never use a non-valid filename anywhere if at all possible */
3015 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3016 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3018 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3019 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3020 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3021 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3022 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3023 if (lbl[0][0] == '/') {
3025 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3027 strbuf_addstr(&header, xfrm_msg);
3028 must_show_header = 1;
3030 else if (lbl[1][0] == '/') {
3031 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3033 strbuf_addstr(&header, xfrm_msg);
3034 must_show_header = 1;
3037 if (one->mode != two->mode) {
3038 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3039 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3040 must_show_header = 1;
3043 strbuf_addstr(&header, xfrm_msg);
3046 * we do not run diff between different kind
3049 if ((one->mode ^ two->mode) & S_IFMT)
3050 goto free_ab_and_return;
3051 if (complete_rewrite &&
3052 (textconv_one || !diff_filespec_is_binary(one)) &&
3053 (textconv_two || !diff_filespec_is_binary(two))) {
3054 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3055 header.buf, header.len, 0);
3056 strbuf_reset(&header);
3057 emit_rewrite_diff(name_a, name_b, one, two,
3058 textconv_one, textconv_two, o);
3059 o->found_changes = 1;
3060 goto free_ab_and_return;
3064 if (o->irreversible_delete && lbl[1][0] == '/') {
3065 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3067 strbuf_reset(&header);
3068 goto free_ab_and_return;
3069 } else if (!DIFF_OPT_TST(o, TEXT) &&
3070 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3071 (!textconv_two && diff_filespec_is_binary(two)) )) {
3072 struct strbuf sb = STRBUF_INIT;
3073 if (!one->data && !two->data &&
3074 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3075 !DIFF_OPT_TST(o, BINARY)) {
3076 if (!oidcmp(&one->oid, &two->oid)) {
3077 if (must_show_header)
3078 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3079 header.buf, header.len,
3081 goto free_ab_and_return;
3083 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3084 header.buf, header.len, 0);
3085 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3086 diff_line_prefix(o), lbl[0], lbl[1]);
3087 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3089 strbuf_release(&sb);
3090 goto free_ab_and_return;
3092 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3093 die("unable to read files to diff");
3094 /* Quite common confusing case */
3095 if (mf1.size == mf2.size &&
3096 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3097 if (must_show_header)
3098 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3099 header.buf, header.len, 0);
3100 goto free_ab_and_return;
3102 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3103 strbuf_reset(&header);
3104 if (DIFF_OPT_TST(o, BINARY))
3105 emit_binary_diff(o, &mf1, &mf2);
3107 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3108 diff_line_prefix(o), lbl[0], lbl[1]);
3109 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3111 strbuf_release(&sb);
3113 o->found_changes = 1;
3115 /* Crazy xdl interfaces.. */
3116 const char *diffopts = getenv("GIT_DIFF_OPTS");
3120 struct emit_callback ecbdata;
3121 const struct userdiff_funcname *pe;
3123 if (must_show_header) {
3124 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3125 header.buf, header.len, 0);
3126 strbuf_reset(&header);
3129 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3130 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3132 pe = diff_funcname_pattern(one);
3134 pe = diff_funcname_pattern(two);
3136 memset(&xpp, 0, sizeof(xpp));
3137 memset(&xecfg, 0, sizeof(xecfg));
3138 memset(&ecbdata, 0, sizeof(ecbdata));
3139 ecbdata.label_path = lbl;
3140 ecbdata.color_diff = want_color(o->use_color);
3141 ecbdata.ws_rule = whitespace_rule(name_b);
3142 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3143 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3145 ecbdata.header = header.len ? &header : NULL;
3146 xpp.flags = o->xdl_opts;
3147 xecfg.ctxlen = o->context;
3148 xecfg.interhunkctxlen = o->interhunkcontext;
3149 xecfg.flags = XDL_EMIT_FUNCNAMES;
3150 if (DIFF_OPT_TST(o, FUNCCONTEXT))
3151 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3153 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3156 else if (skip_prefix(diffopts, "--unified=", &v))
3157 xecfg.ctxlen = strtoul(v, NULL, 10);
3158 else if (skip_prefix(diffopts, "-u", &v))
3159 xecfg.ctxlen = strtoul(v, NULL, 10);
3161 init_diff_words_data(&ecbdata, o, one, two);
3162 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3164 die("unable to generate diff for %s", one->path);
3166 free_diff_words_data(&ecbdata);
3171 xdiff_clear_find_func(&xecfg);
3175 strbuf_release(&header);
3176 diff_free_filespec_data(one);
3177 diff_free_filespec_data(two);
3183 static void builtin_diffstat(const char *name_a, const char *name_b,
3184 struct diff_filespec *one,
3185 struct diff_filespec *two,
3186 struct diffstat_t *diffstat,
3187 struct diff_options *o,
3188 struct diff_filepair *p)
3191 struct diffstat_file *data;
3193 int complete_rewrite = 0;
3195 if (!DIFF_PAIR_UNMERGED(p)) {
3196 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3197 complete_rewrite = 1;
3200 data = diffstat_add(diffstat, name_a, name_b);
3201 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3204 data->is_unmerged = 1;
3208 same_contents = !oidcmp(&one->oid, &two->oid);
3210 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3211 data->is_binary = 1;
3212 if (same_contents) {
3216 data->added = diff_filespec_size(two);
3217 data->deleted = diff_filespec_size(one);
3221 else if (complete_rewrite) {
3222 diff_populate_filespec(one, 0);
3223 diff_populate_filespec(two, 0);
3224 data->deleted = count_lines(one->data, one->size);
3225 data->added = count_lines(two->data, two->size);
3228 else if (!same_contents) {
3229 /* Crazy xdl interfaces.. */
3233 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3234 die("unable to read files to diff");
3236 memset(&xpp, 0, sizeof(xpp));
3237 memset(&xecfg, 0, sizeof(xecfg));
3238 xpp.flags = o->xdl_opts;
3239 xecfg.ctxlen = o->context;
3240 xecfg.interhunkctxlen = o->interhunkcontext;
3241 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3243 die("unable to generate diffstat for %s", one->path);
3246 diff_free_filespec_data(one);
3247 diff_free_filespec_data(two);
3250 static void builtin_checkdiff(const char *name_a, const char *name_b,
3251 const char *attr_path,
3252 struct diff_filespec *one,
3253 struct diff_filespec *two,
3254 struct diff_options *o)
3257 struct checkdiff_t data;
3262 memset(&data, 0, sizeof(data));
3263 data.filename = name_b ? name_b : name_a;
3266 data.ws_rule = whitespace_rule(attr_path);
3267 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3269 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3270 die("unable to read files to diff");
3273 * All the other codepaths check both sides, but not checking
3274 * the "old" side here is deliberate. We are checking the newly
3275 * introduced changes, and as long as the "new" side is text, we
3276 * can and should check what it introduces.
3278 if (diff_filespec_is_binary(two))
3279 goto free_and_return;
3281 /* Crazy xdl interfaces.. */
3285 memset(&xpp, 0, sizeof(xpp));
3286 memset(&xecfg, 0, sizeof(xecfg));
3287 xecfg.ctxlen = 1; /* at least one context line */
3289 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3291 die("unable to generate checkdiff for %s", one->path);
3293 if (data.ws_rule & WS_BLANK_AT_EOF) {
3294 struct emit_callback ecbdata;
3297 ecbdata.ws_rule = data.ws_rule;
3298 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3299 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3304 err = whitespace_error_string(WS_BLANK_AT_EOF);
3305 fprintf(o->file, "%s:%d: %s.\n",
3306 data.filename, blank_at_eof, err);
3307 data.status = 1; /* report errors */
3312 diff_free_filespec_data(one);
3313 diff_free_filespec_data(two);
3315 DIFF_OPT_SET(o, CHECK_FAILED);
3318 struct diff_filespec *alloc_filespec(const char *path)
3320 struct diff_filespec *spec;
3322 FLEXPTR_ALLOC_STR(spec, path, path);
3324 spec->is_binary = -1;
3328 void free_filespec(struct diff_filespec *spec)
3330 if (!--spec->count) {
3331 diff_free_filespec_data(spec);
3336 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3337 int oid_valid, unsigned short mode)
3340 spec->mode = canon_mode(mode);
3341 oidcpy(&spec->oid, oid);
3342 spec->oid_valid = oid_valid;
3347 * Given a name and sha1 pair, if the index tells us the file in
3348 * the work tree has that object contents, return true, so that
3349 * prepare_temp_file() does not have to inflate and extract.
3351 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3353 const struct cache_entry *ce;
3358 * We do not read the cache ourselves here, because the
3359 * benchmark with my previous version that always reads cache
3360 * shows that it makes things worse for diff-tree comparing
3361 * two linux-2.6 kernel trees in an already checked out work
3362 * tree. This is because most diff-tree comparisons deal with
3363 * only a small number of files, while reading the cache is
3364 * expensive for a large project, and its cost outweighs the
3365 * savings we get by not inflating the object to a temporary
3366 * file. Practically, this code only helps when we are used
3367 * by diff-cache --cached, which does read the cache before
3373 /* We want to avoid the working directory if our caller
3374 * doesn't need the data in a normal file, this system
3375 * is rather slow with its stat/open/mmap/close syscalls,
3376 * and the object is contained in a pack file. The pack
3377 * is probably already open and will be faster to obtain
3378 * the data through than the working directory. Loose
3379 * objects however would tend to be slower as they need
3380 * to be individually opened and inflated.
3382 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3386 * Similarly, if we'd have to convert the file contents anyway, that
3387 * makes the optimization not worthwhile.
3389 if (!want_file && would_convert_to_git(&the_index, name))
3393 pos = cache_name_pos(name, len);
3396 ce = active_cache[pos];
3399 * This is not the sha1 we are looking for, or
3400 * unreusable because it is not a regular file.
3402 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3406 * If ce is marked as "assume unchanged", there is no
3407 * guarantee that work tree matches what we are looking for.
3409 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3413 * If ce matches the file in the work tree, we can reuse it.
3415 if (ce_uptodate(ce) ||
3416 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3422 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3424 struct strbuf buf = STRBUF_INIT;
3427 /* Are we looking at the work tree? */
3428 if (s->dirty_submodule)
3431 strbuf_addf(&buf, "Subproject commit %s%s\n",
3432 oid_to_hex(&s->oid), dirty);
3436 strbuf_release(&buf);
3438 s->data = strbuf_detach(&buf, NULL);
3445 * While doing rename detection and pickaxe operation, we may need to
3446 * grab the data for the blob (or file) for our own in-core comparison.
3447 * diff_filespec has data and size fields for this purpose.
3449 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3451 int size_only = flags & CHECK_SIZE_ONLY;
3454 * demote FAIL to WARN to allow inspecting the situation
3455 * instead of refusing.
3457 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3461 if (!DIFF_FILE_VALID(s))
3462 die("internal error: asking to populate invalid file.");
3463 if (S_ISDIR(s->mode))
3469 if (size_only && 0 < s->size)
3472 if (S_ISGITLINK(s->mode))
3473 return diff_populate_gitlink(s, size_only);
3475 if (!s->oid_valid ||
3476 reuse_worktree_file(s->path, &s->oid, 0)) {
3477 struct strbuf buf = STRBUF_INIT;
3481 if (lstat(s->path, &st) < 0) {
3482 if (errno == ENOENT) {
3486 s->data = (char *)"";
3491 s->size = xsize_t(st.st_size);
3494 if (S_ISLNK(st.st_mode)) {
3495 struct strbuf sb = STRBUF_INIT;
3497 if (strbuf_readlink(&sb, s->path, s->size))
3500 s->data = strbuf_detach(&sb, NULL);
3506 * Even if the caller would be happy with getting
3507 * only the size, we cannot return early at this
3508 * point if the path requires us to run the content
3511 if (size_only && !would_convert_to_git(&the_index, s->path))
3515 * Note: this check uses xsize_t(st.st_size) that may
3516 * not be the true size of the blob after it goes
3517 * through convert_to_git(). This may not strictly be
3518 * correct, but the whole point of big_file_threshold
3519 * and is_binary check being that we want to avoid
3520 * opening the file and inspecting the contents, this
3523 if ((flags & CHECK_BINARY) &&
3524 s->size > big_file_threshold && s->is_binary == -1) {
3528 fd = open(s->path, O_RDONLY);
3531 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3533 s->should_munmap = 1;
3536 * Convert from working tree format to canonical git format
3538 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
3540 munmap(s->data, s->size);
3541 s->should_munmap = 0;
3542 s->data = strbuf_detach(&buf, &size);
3548 enum object_type type;
3549 if (size_only || (flags & CHECK_BINARY)) {
3550 type = sha1_object_info(s->oid.hash, &s->size);
3552 die("unable to read %s",
3553 oid_to_hex(&s->oid));
3556 if (s->size > big_file_threshold && s->is_binary == -1) {
3561 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
3563 die("unable to read %s", oid_to_hex(&s->oid));
3569 void diff_free_filespec_blob(struct diff_filespec *s)
3573 else if (s->should_munmap)
3574 munmap(s->data, s->size);
3576 if (s->should_free || s->should_munmap) {
3577 s->should_free = s->should_munmap = 0;
3582 void diff_free_filespec_data(struct diff_filespec *s)
3584 diff_free_filespec_blob(s);
3585 FREE_AND_NULL(s->cnt_data);
3588 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3591 const struct object_id *oid,
3595 struct strbuf buf = STRBUF_INIT;
3596 struct strbuf template = STRBUF_INIT;
3597 char *path_dup = xstrdup(path);
3598 const char *base = basename(path_dup);
3600 /* Generate "XXXXXX_basename.ext" */
3601 strbuf_addstr(&template, "XXXXXX_");
3602 strbuf_addstr(&template, base);
3604 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
3606 die_errno("unable to create temp-file");
3607 if (convert_to_working_tree(path,
3608 (const char *)blob, (size_t)size, &buf)) {
3612 if (write_in_full(fd, blob, size) != size)
3613 die_errno("unable to write temp-file");
3614 close_tempfile(&temp->tempfile);
3615 temp->name = get_tempfile_path(&temp->tempfile);
3616 oid_to_hex_r(temp->hex, oid);
3617 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3618 strbuf_release(&buf);
3619 strbuf_release(&template);
3623 static struct diff_tempfile *prepare_temp_file(const char *name,
3624 struct diff_filespec *one)
3626 struct diff_tempfile *temp = claim_diff_tempfile();
3628 if (!DIFF_FILE_VALID(one)) {
3630 /* A '-' entry produces this for file-2, and
3631 * a '+' entry produces this for file-1.
3633 temp->name = "/dev/null";
3634 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3635 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3639 if (!S_ISGITLINK(one->mode) &&
3641 reuse_worktree_file(name, &one->oid, 1))) {
3643 if (lstat(name, &st) < 0) {
3644 if (errno == ENOENT)
3645 goto not_a_valid_file;
3646 die_errno("stat(%s)", name);
3648 if (S_ISLNK(st.st_mode)) {
3649 struct strbuf sb = STRBUF_INIT;
3650 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3651 die_errno("readlink(%s)", name);
3652 prep_temp_blob(name, temp, sb.buf, sb.len,
3654 &one->oid : &null_oid),
3656 one->mode : S_IFLNK));
3657 strbuf_release(&sb);
3660 /* we can borrow from the file in the work tree */
3662 if (!one->oid_valid)
3663 oid_to_hex_r(temp->hex, &null_oid);
3665 oid_to_hex_r(temp->hex, &one->oid);
3666 /* Even though we may sometimes borrow the
3667 * contents from the work tree, we always want
3668 * one->mode. mode is trustworthy even when
3669 * !(one->oid_valid), as long as
3670 * DIFF_FILE_VALID(one).
3672 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3677 if (diff_populate_filespec(one, 0))
3678 die("cannot read data blob for %s", one->path);
3679 prep_temp_blob(name, temp, one->data, one->size,
3680 &one->oid, one->mode);
3685 static void add_external_diff_name(struct argv_array *argv,
3687 struct diff_filespec *df)
3689 struct diff_tempfile *temp = prepare_temp_file(name, df);
3690 argv_array_push(argv, temp->name);
3691 argv_array_push(argv, temp->hex);
3692 argv_array_push(argv, temp->mode);
3695 /* An external diff command takes:
3697 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3698 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3701 static void run_external_diff(const char *pgm,
3704 struct diff_filespec *one,
3705 struct diff_filespec *two,
3706 const char *xfrm_msg,
3707 int complete_rewrite,
3708 struct diff_options *o)
3710 struct argv_array argv = ARGV_ARRAY_INIT;
3711 struct argv_array env = ARGV_ARRAY_INIT;
3712 struct diff_queue_struct *q = &diff_queued_diff;
3714 argv_array_push(&argv, pgm);
3715 argv_array_push(&argv, name);
3718 add_external_diff_name(&argv, name, one);
3720 add_external_diff_name(&argv, name, two);
3722 add_external_diff_name(&argv, other, two);
3723 argv_array_push(&argv, other);
3724 argv_array_push(&argv, xfrm_msg);
3728 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3729 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3731 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3732 die(_("external diff died, stopping at %s"), name);
3735 argv_array_clear(&argv);
3736 argv_array_clear(&env);
3739 static int similarity_index(struct diff_filepair *p)
3741 return p->score * 100 / MAX_SCORE;
3744 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3746 if (startup_info->have_repository)
3747 return find_unique_abbrev(oid->hash, abbrev);
3749 char *hex = oid_to_hex(oid);
3751 abbrev = FALLBACK_DEFAULT_ABBREV;
3752 if (abbrev > GIT_SHA1_HEXSZ)
3753 die("BUG: oid abbreviation out of range: %d", abbrev);
3760 static void fill_metainfo(struct strbuf *msg,
3763 struct diff_filespec *one,
3764 struct diff_filespec *two,
3765 struct diff_options *o,
3766 struct diff_filepair *p,
3767 int *must_show_header,
3770 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3771 const char *reset = diff_get_color(use_color, DIFF_RESET);
3772 const char *line_prefix = diff_line_prefix(o);
3774 *must_show_header = 1;
3775 strbuf_init(msg, PATH_MAX * 2 + 300);
3776 switch (p->status) {
3777 case DIFF_STATUS_COPIED:
3778 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3779 line_prefix, set, similarity_index(p));
3780 strbuf_addf(msg, "%s\n%s%scopy from ",
3781 reset, line_prefix, set);
3782 quote_c_style(name, msg, NULL, 0);
3783 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3784 quote_c_style(other, msg, NULL, 0);
3785 strbuf_addf(msg, "%s\n", reset);
3787 case DIFF_STATUS_RENAMED:
3788 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3789 line_prefix, set, similarity_index(p));
3790 strbuf_addf(msg, "%s\n%s%srename from ",
3791 reset, line_prefix, set);
3792 quote_c_style(name, msg, NULL, 0);
3793 strbuf_addf(msg, "%s\n%s%srename to ",
3794 reset, line_prefix, set);
3795 quote_c_style(other, msg, NULL, 0);
3796 strbuf_addf(msg, "%s\n", reset);
3798 case DIFF_STATUS_MODIFIED:
3800 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3802 set, similarity_index(p), reset);
3807 *must_show_header = 0;
3809 if (one && two && oidcmp(&one->oid, &two->oid)) {
3810 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3812 if (DIFF_OPT_TST(o, BINARY)) {
3814 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3815 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3818 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3819 diff_abbrev_oid(&one->oid, abbrev),
3820 diff_abbrev_oid(&two->oid, abbrev));
3821 if (one->mode == two->mode)
3822 strbuf_addf(msg, " %06o", one->mode);
3823 strbuf_addf(msg, "%s\n", reset);
3827 static void run_diff_cmd(const char *pgm,
3830 const char *attr_path,
3831 struct diff_filespec *one,
3832 struct diff_filespec *two,
3834 struct diff_options *o,
3835 struct diff_filepair *p)
3837 const char *xfrm_msg = NULL;
3838 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3839 int must_show_header = 0;
3842 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3843 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3844 if (drv && drv->external)
3845 pgm = drv->external;
3850 * don't use colors when the header is intended for an
3851 * external diff driver
3853 fill_metainfo(msg, name, other, one, two, o, p,
3855 want_color(o->use_color) && !pgm);
3856 xfrm_msg = msg->len ? msg->buf : NULL;
3860 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3861 complete_rewrite, o);
3865 builtin_diff(name, other ? other : name,
3866 one, two, xfrm_msg, must_show_header,
3867 o, complete_rewrite);
3869 fprintf(o->file, "* Unmerged path %s\n", name);
3872 static void diff_fill_oid_info(struct diff_filespec *one)
3874 if (DIFF_FILE_VALID(one)) {
3875 if (!one->oid_valid) {
3877 if (one->is_stdin) {
3881 if (lstat(one->path, &st) < 0)
3882 die_errno("stat '%s'", one->path);
3883 if (index_path(one->oid.hash, one->path, &st, 0))
3884 die("cannot hash %s", one->path);
3891 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3893 /* Strip the prefix but do not molest /dev/null and absolute paths */
3894 if (*namep && **namep != '/') {
3895 *namep += prefix_length;
3899 if (*otherp && **otherp != '/') {
3900 *otherp += prefix_length;
3901 if (**otherp == '/')
3906 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3908 const char *pgm = external_diff();
3910 struct diff_filespec *one = p->one;
3911 struct diff_filespec *two = p->two;
3914 const char *attr_path;
3917 other = (strcmp(name, two->path) ? two->path : NULL);
3919 if (o->prefix_length)
3920 strip_prefix(o->prefix_length, &name, &other);
3922 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3925 if (DIFF_PAIR_UNMERGED(p)) {
3926 run_diff_cmd(pgm, name, NULL, attr_path,
3927 NULL, NULL, NULL, o, p);
3931 diff_fill_oid_info(one);
3932 diff_fill_oid_info(two);
3935 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3936 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3938 * a filepair that changes between file and symlink
3939 * needs to be split into deletion and creation.
3941 struct diff_filespec *null = alloc_filespec(two->path);
3942 run_diff_cmd(NULL, name, other, attr_path,
3943 one, null, &msg, o, p);
3945 strbuf_release(&msg);
3947 null = alloc_filespec(one->path);
3948 run_diff_cmd(NULL, name, other, attr_path,
3949 null, two, &msg, o, p);
3953 run_diff_cmd(pgm, name, other, attr_path,
3954 one, two, &msg, o, p);
3956 strbuf_release(&msg);
3959 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3960 struct diffstat_t *diffstat)
3965 if (DIFF_PAIR_UNMERGED(p)) {
3967 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3971 name = p->one->path;
3972 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3974 if (o->prefix_length)
3975 strip_prefix(o->prefix_length, &name, &other);
3977 diff_fill_oid_info(p->one);
3978 diff_fill_oid_info(p->two);
3980 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3983 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3987 const char *attr_path;
3989 if (DIFF_PAIR_UNMERGED(p)) {
3994 name = p->one->path;
3995 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3996 attr_path = other ? other : name;
3998 if (o->prefix_length)
3999 strip_prefix(o->prefix_length, &name, &other);
4001 diff_fill_oid_info(p->one);
4002 diff_fill_oid_info(p->two);
4004 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4007 void diff_setup(struct diff_options *options)
4009 memcpy(options, &default_diff_options, sizeof(*options));
4011 options->file = stdout;
4013 options->abbrev = DEFAULT_ABBREV;
4014 options->line_termination = '\n';
4015 options->break_opt = -1;
4016 options->rename_limit = -1;
4017 options->dirstat_permille = diff_dirstat_permille_default;
4018 options->context = diff_context_default;
4019 options->interhunkcontext = diff_interhunk_context_default;
4020 options->ws_error_highlight = ws_error_highlight_default;
4021 DIFF_OPT_SET(options, RENAME_EMPTY);
4023 /* pathchange left =NULL by default */
4024 options->change = diff_change;
4025 options->add_remove = diff_addremove;
4026 options->use_color = diff_use_color_default;
4027 options->detect_rename = diff_detect_rename_default;
4028 options->xdl_opts |= diff_algorithm;
4029 if (diff_indent_heuristic)
4030 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4032 options->orderfile = diff_order_file_cfg;
4034 if (diff_no_prefix) {
4035 options->a_prefix = options->b_prefix = "";
4036 } else if (!diff_mnemonic_prefix) {
4037 options->a_prefix = "a/";
4038 options->b_prefix = "b/";
4041 options->color_moved = diff_color_moved_default;
4044 void diff_setup_done(struct diff_options *options)
4048 if (options->set_default)
4049 options->set_default(options);
4051 if (options->output_format & DIFF_FORMAT_NAME)
4053 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
4055 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
4057 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
4060 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4063 * Most of the time we can say "there are changes"
4064 * only by checking if there are changed paths, but
4065 * --ignore-whitespace* options force us to look
4069 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
4070 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
4071 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
4072 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
4074 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
4076 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
4077 options->detect_rename = DIFF_DETECT_COPY;
4079 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
4080 options->prefix = NULL;
4081 if (options->prefix)
4082 options->prefix_length = strlen(options->prefix);
4084 options->prefix_length = 0;
4086 if (options->output_format & (DIFF_FORMAT_NAME |
4087 DIFF_FORMAT_NAME_STATUS |
4088 DIFF_FORMAT_CHECKDIFF |
4089 DIFF_FORMAT_NO_OUTPUT))
4090 options->output_format &= ~(DIFF_FORMAT_RAW |
4091 DIFF_FORMAT_NUMSTAT |
4092 DIFF_FORMAT_DIFFSTAT |
4093 DIFF_FORMAT_SHORTSTAT |
4094 DIFF_FORMAT_DIRSTAT |
4095 DIFF_FORMAT_SUMMARY |
4099 * These cases always need recursive; we do not drop caller-supplied
4100 * recursive bits for other formats here.
4102 if (options->output_format & (DIFF_FORMAT_PATCH |
4103 DIFF_FORMAT_NUMSTAT |
4104 DIFF_FORMAT_DIFFSTAT |
4105 DIFF_FORMAT_SHORTSTAT |
4106 DIFF_FORMAT_DIRSTAT |
4107 DIFF_FORMAT_SUMMARY |
4108 DIFF_FORMAT_CHECKDIFF))
4109 DIFF_OPT_SET(options, RECURSIVE);
4111 * Also pickaxe would not work very well if you do not say recursive
4113 if (options->pickaxe)
4114 DIFF_OPT_SET(options, RECURSIVE);
4116 * When patches are generated, submodules diffed against the work tree
4117 * must be checked for dirtiness too so it can be shown in the output
4119 if (options->output_format & DIFF_FORMAT_PATCH)
4120 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
4122 if (options->detect_rename && options->rename_limit < 0)
4123 options->rename_limit = diff_rename_limit_default;
4124 if (options->setup & DIFF_SETUP_USE_CACHE) {
4126 /* read-cache does not die even when it fails
4127 * so it is safe for us to do this here. Also
4128 * it does not smudge active_cache or active_nr
4129 * when it fails, so we do not have to worry about
4130 * cleaning it up ourselves either.
4134 if (40 < options->abbrev)
4135 options->abbrev = 40; /* full */
4138 * It does not make sense to show the first hit we happened
4139 * to have found. It does not make sense not to return with
4140 * exit code in such a case either.
4142 if (DIFF_OPT_TST(options, QUICK)) {
4143 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4144 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4147 options->diff_path_counter = 0;
4149 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
4150 die(_("--follow requires exactly one pathspec"));
4152 if (!options->use_color || external_diff())
4153 options->color_moved = 0;
4156 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4166 if (c == arg_short) {
4170 if (val && isdigit(c)) {
4172 int n = strtoul(arg, &end, 10);
4183 eq = strchrnul(arg, '=');
4185 if (!len || strncmp(arg, arg_long, len))
4190 if (!isdigit(*++eq))
4192 n = strtoul(eq, &end, 10);
4200 static int diff_scoreopt_parse(const char *opt);
4202 static inline int short_opt(char opt, const char **argv,
4203 const char **optarg)
4205 const char *arg = argv[0];
4206 if (arg[0] != '-' || arg[1] != opt)
4208 if (arg[2] != '\0') {
4213 die("Option '%c' requires a value", opt);
4218 int parse_long_opt(const char *opt, const char **argv,
4219 const char **optarg)
4221 const char *arg = argv[0];
4222 if (!skip_prefix(arg, "--", &arg))
4224 if (!skip_prefix(arg, opt, &arg))
4226 if (*arg == '=') { /* stuck form: --option=value */
4232 /* separate form: --option value */
4234 die("Option '--%s' requires a value", opt);
4239 static int stat_opt(struct diff_options *options, const char **av)
4241 const char *arg = av[0];
4243 int width = options->stat_width;
4244 int name_width = options->stat_name_width;
4245 int graph_width = options->stat_graph_width;
4246 int count = options->stat_count;
4249 if (!skip_prefix(arg, "--stat", &arg))
4250 die("BUG: stat option does not begin with --stat: %s", arg);
4255 if (skip_prefix(arg, "-width", &arg)) {
4257 width = strtoul(arg + 1, &end, 10);
4258 else if (!*arg && !av[1])
4259 die_want_option("--stat-width");
4261 width = strtoul(av[1], &end, 10);
4264 } else if (skip_prefix(arg, "-name-width", &arg)) {
4266 name_width = strtoul(arg + 1, &end, 10);
4267 else if (!*arg && !av[1])
4268 die_want_option("--stat-name-width");
4270 name_width = strtoul(av[1], &end, 10);
4273 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4275 graph_width = strtoul(arg + 1, &end, 10);
4276 else if (!*arg && !av[1])
4277 die_want_option("--stat-graph-width");
4279 graph_width = strtoul(av[1], &end, 10);
4282 } else if (skip_prefix(arg, "-count", &arg)) {
4284 count = strtoul(arg + 1, &end, 10);
4285 else if (!*arg && !av[1])
4286 die_want_option("--stat-count");
4288 count = strtoul(av[1], &end, 10);
4294 width = strtoul(arg+1, &end, 10);
4296 name_width = strtoul(end+1, &end, 10);
4298 count = strtoul(end+1, &end, 10);
4301 /* Important! This checks all the error cases! */
4304 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4305 options->stat_name_width = name_width;
4306 options->stat_graph_width = graph_width;
4307 options->stat_width = width;
4308 options->stat_count = count;
4312 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4314 struct strbuf errmsg = STRBUF_INIT;
4315 if (parse_dirstat_params(options, params, &errmsg))
4316 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4318 strbuf_release(&errmsg);
4320 * The caller knows a dirstat-related option is given from the command
4321 * line; allow it to say "return this_function();"
4323 options->output_format |= DIFF_FORMAT_DIRSTAT;
4327 static int parse_submodule_opt(struct diff_options *options, const char *value)
4329 if (parse_submodule_params(options, value))
4330 die(_("Failed to parse --submodule option parameter: '%s'"),
4335 static const char diff_status_letters[] = {
4338 DIFF_STATUS_DELETED,
4339 DIFF_STATUS_MODIFIED,
4340 DIFF_STATUS_RENAMED,
4341 DIFF_STATUS_TYPE_CHANGED,
4342 DIFF_STATUS_UNKNOWN,
4343 DIFF_STATUS_UNMERGED,
4344 DIFF_STATUS_FILTER_AON,
4345 DIFF_STATUS_FILTER_BROKEN,
4349 static unsigned int filter_bit['Z' + 1];
4351 static void prepare_filter_bits(void)
4355 if (!filter_bit[DIFF_STATUS_ADDED]) {
4356 for (i = 0; diff_status_letters[i]; i++)
4357 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4361 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4363 return opt->filter & filter_bit[(int) status];
4366 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4370 prepare_filter_bits();
4373 * If there is a negation e.g. 'd' in the input, and we haven't
4374 * initialized the filter field with another --diff-filter, start
4375 * from full set of bits, except for AON.
4378 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4379 if (optch < 'a' || 'z' < optch)
4381 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4382 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4387 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4391 if ('a' <= optch && optch <= 'z') {
4393 optch = toupper(optch);
4398 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4402 opt->filter &= ~bit;
4409 static void enable_patch_output(int *fmt) {
4410 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4411 *fmt |= DIFF_FORMAT_PATCH;
4414 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4416 int val = parse_ws_error_highlight(arg);
4419 error("unknown value after ws-error-highlight=%.*s",
4423 opt->ws_error_highlight = val;
4427 int diff_opt_parse(struct diff_options *options,
4428 const char **av, int ac, const char *prefix)
4430 const char *arg = av[0];
4437 /* Output format options */
4438 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4439 || opt_arg(arg, 'U', "unified", &options->context))
4440 enable_patch_output(&options->output_format);
4441 else if (!strcmp(arg, "--raw"))
4442 options->output_format |= DIFF_FORMAT_RAW;
4443 else if (!strcmp(arg, "--patch-with-raw")) {
4444 enable_patch_output(&options->output_format);
4445 options->output_format |= DIFF_FORMAT_RAW;
4446 } else if (!strcmp(arg, "--numstat"))
4447 options->output_format |= DIFF_FORMAT_NUMSTAT;
4448 else if (!strcmp(arg, "--shortstat"))
4449 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4450 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
4451 return parse_dirstat_opt(options, "");
4452 else if (skip_prefix(arg, "-X", &arg))
4453 return parse_dirstat_opt(options, arg);
4454 else if (skip_prefix(arg, "--dirstat=", &arg))
4455 return parse_dirstat_opt(options, arg);
4456 else if (!strcmp(arg, "--cumulative"))
4457 return parse_dirstat_opt(options, "cumulative");
4458 else if (!strcmp(arg, "--dirstat-by-file"))
4459 return parse_dirstat_opt(options, "files");
4460 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
4461 parse_dirstat_opt(options, "files");
4462 return parse_dirstat_opt(options, arg);
4464 else if (!strcmp(arg, "--check"))
4465 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4466 else if (!strcmp(arg, "--summary"))
4467 options->output_format |= DIFF_FORMAT_SUMMARY;
4468 else if (!strcmp(arg, "--patch-with-stat")) {
4469 enable_patch_output(&options->output_format);
4470 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4471 } else if (!strcmp(arg, "--name-only"))
4472 options->output_format |= DIFF_FORMAT_NAME;
4473 else if (!strcmp(arg, "--name-status"))
4474 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4475 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4476 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4477 else if (starts_with(arg, "--stat"))
4478 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4479 return stat_opt(options, av);
4481 /* renames options */
4482 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
4483 !strcmp(arg, "--break-rewrites")) {
4484 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4485 return error("invalid argument to -B: %s", arg+2);
4487 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
4488 !strcmp(arg, "--find-renames")) {
4489 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4490 return error("invalid argument to -M: %s", arg+2);
4491 options->detect_rename = DIFF_DETECT_RENAME;
4493 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4494 options->irreversible_delete = 1;
4496 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
4497 !strcmp(arg, "--find-copies")) {
4498 if (options->detect_rename == DIFF_DETECT_COPY)
4499 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4500 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4501 return error("invalid argument to -C: %s", arg+2);
4502 options->detect_rename = DIFF_DETECT_COPY;
4504 else if (!strcmp(arg, "--no-renames"))
4505 options->detect_rename = 0;
4506 else if (!strcmp(arg, "--rename-empty"))
4507 DIFF_OPT_SET(options, RENAME_EMPTY);
4508 else if (!strcmp(arg, "--no-rename-empty"))
4509 DIFF_OPT_CLR(options, RENAME_EMPTY);
4510 else if (!strcmp(arg, "--relative"))
4511 DIFF_OPT_SET(options, RELATIVE_NAME);
4512 else if (skip_prefix(arg, "--relative=", &arg)) {
4513 DIFF_OPT_SET(options, RELATIVE_NAME);
4514 options->prefix = arg;
4518 else if (!strcmp(arg, "--minimal"))
4519 DIFF_XDL_SET(options, NEED_MINIMAL);
4520 else if (!strcmp(arg, "--no-minimal"))
4521 DIFF_XDL_CLR(options, NEED_MINIMAL);
4522 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4523 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4524 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4525 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4526 else if (!strcmp(arg, "--ignore-space-at-eol"))
4527 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4528 else if (!strcmp(arg, "--ignore-blank-lines"))
4529 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4530 else if (!strcmp(arg, "--indent-heuristic"))
4531 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4532 else if (!strcmp(arg, "--no-indent-heuristic"))
4533 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4534 else if (!strcmp(arg, "--patience"))
4535 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4536 else if (!strcmp(arg, "--histogram"))
4537 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4538 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4539 long value = parse_algorithm_value(optarg);
4541 return error("option diff-algorithm accepts \"myers\", "
4542 "\"minimal\", \"patience\" and \"histogram\"");
4543 /* clear out previous settings */
4544 DIFF_XDL_CLR(options, NEED_MINIMAL);
4545 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4546 options->xdl_opts |= value;
4551 else if (!strcmp(arg, "--binary")) {
4552 enable_patch_output(&options->output_format);
4553 DIFF_OPT_SET(options, BINARY);
4555 else if (!strcmp(arg, "--full-index"))
4556 DIFF_OPT_SET(options, FULL_INDEX);
4557 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4558 DIFF_OPT_SET(options, TEXT);
4559 else if (!strcmp(arg, "-R"))
4560 DIFF_OPT_SET(options, REVERSE_DIFF);
4561 else if (!strcmp(arg, "--find-copies-harder"))
4562 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4563 else if (!strcmp(arg, "--follow"))
4564 DIFF_OPT_SET(options, FOLLOW_RENAMES);
4565 else if (!strcmp(arg, "--no-follow")) {
4566 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
4567 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
4568 } else if (!strcmp(arg, "--color"))
4569 options->use_color = 1;
4570 else if (skip_prefix(arg, "--color=", &arg)) {
4571 int value = git_config_colorbool(NULL, arg);
4573 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4574 options->use_color = value;
4576 else if (!strcmp(arg, "--no-color"))
4577 options->use_color = 0;
4578 else if (!strcmp(arg, "--color-moved")) {
4579 if (diff_color_moved_default)
4580 options->color_moved = diff_color_moved_default;
4581 if (options->color_moved == COLOR_MOVED_NO)
4582 options->color_moved = COLOR_MOVED_DEFAULT;
4583 } else if (!strcmp(arg, "--no-color-moved"))
4584 options->color_moved = COLOR_MOVED_NO;
4585 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4586 int cm = parse_color_moved(arg);
4588 die("bad --color-moved argument: %s", arg);
4589 options->color_moved = cm;
4590 } else if (!strcmp(arg, "--color-words")) {
4591 options->use_color = 1;
4592 options->word_diff = DIFF_WORDS_COLOR;
4594 else if (skip_prefix(arg, "--color-words=", &arg)) {
4595 options->use_color = 1;
4596 options->word_diff = DIFF_WORDS_COLOR;
4597 options->word_regex = arg;
4599 else if (!strcmp(arg, "--word-diff")) {
4600 if (options->word_diff == DIFF_WORDS_NONE)
4601 options->word_diff = DIFF_WORDS_PLAIN;
4603 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4604 if (!strcmp(arg, "plain"))
4605 options->word_diff = DIFF_WORDS_PLAIN;
4606 else if (!strcmp(arg, "color")) {
4607 options->use_color = 1;
4608 options->word_diff = DIFF_WORDS_COLOR;
4610 else if (!strcmp(arg, "porcelain"))
4611 options->word_diff = DIFF_WORDS_PORCELAIN;
4612 else if (!strcmp(arg, "none"))
4613 options->word_diff = DIFF_WORDS_NONE;
4615 die("bad --word-diff argument: %s", arg);
4617 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4618 if (options->word_diff == DIFF_WORDS_NONE)
4619 options->word_diff = DIFF_WORDS_PLAIN;
4620 options->word_regex = optarg;
4623 else if (!strcmp(arg, "--exit-code"))
4624 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4625 else if (!strcmp(arg, "--quiet"))
4626 DIFF_OPT_SET(options, QUICK);
4627 else if (!strcmp(arg, "--ext-diff"))
4628 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
4629 else if (!strcmp(arg, "--no-ext-diff"))
4630 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
4631 else if (!strcmp(arg, "--textconv"))
4632 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
4633 else if (!strcmp(arg, "--no-textconv"))
4634 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
4635 else if (!strcmp(arg, "--ignore-submodules")) {
4636 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4637 handle_ignore_submodules_arg(options, "all");
4638 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
4639 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4640 handle_ignore_submodules_arg(options, arg);
4641 } else if (!strcmp(arg, "--submodule"))
4642 options->submodule_format = DIFF_SUBMODULE_LOG;
4643 else if (skip_prefix(arg, "--submodule=", &arg))
4644 return parse_submodule_opt(options, arg);
4645 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4646 return parse_ws_error_highlight_opt(options, arg);
4647 else if (!strcmp(arg, "--ita-invisible-in-index"))
4648 options->ita_invisible_in_index = 1;
4649 else if (!strcmp(arg, "--ita-visible-in-index"))
4650 options->ita_invisible_in_index = 0;
4653 else if (!strcmp(arg, "-z"))
4654 options->line_termination = 0;
4655 else if ((argcount = short_opt('l', av, &optarg))) {
4656 options->rename_limit = strtoul(optarg, NULL, 10);
4659 else if ((argcount = short_opt('S', av, &optarg))) {
4660 options->pickaxe = optarg;
4661 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4663 } else if ((argcount = short_opt('G', av, &optarg))) {
4664 options->pickaxe = optarg;
4665 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4668 else if (!strcmp(arg, "--pickaxe-all"))
4669 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4670 else if (!strcmp(arg, "--pickaxe-regex"))
4671 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4672 else if ((argcount = short_opt('O', av, &optarg))) {
4673 options->orderfile = prefix_filename(prefix, optarg);
4676 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4677 int offending = parse_diff_filter_opt(optarg, options);
4679 die("unknown change class '%c' in --diff-filter=%s",
4683 else if (!strcmp(arg, "--no-abbrev"))
4684 options->abbrev = 0;
4685 else if (!strcmp(arg, "--abbrev"))
4686 options->abbrev = DEFAULT_ABBREV;
4687 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4688 options->abbrev = strtoul(arg, NULL, 10);
4689 if (options->abbrev < MINIMUM_ABBREV)
4690 options->abbrev = MINIMUM_ABBREV;
4691 else if (40 < options->abbrev)
4692 options->abbrev = 40;
4694 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4695 options->a_prefix = optarg;
4698 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4699 options->line_prefix = optarg;
4700 options->line_prefix_length = strlen(options->line_prefix);
4701 graph_setup_line_prefix(options);
4704 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4705 options->b_prefix = optarg;
4708 else if (!strcmp(arg, "--no-prefix"))
4709 options->a_prefix = options->b_prefix = "";
4710 else if (opt_arg(arg, '\0', "inter-hunk-context",
4711 &options->interhunkcontext))
4713 else if (!strcmp(arg, "-W"))
4714 DIFF_OPT_SET(options, FUNCCONTEXT);
4715 else if (!strcmp(arg, "--function-context"))
4716 DIFF_OPT_SET(options, FUNCCONTEXT);
4717 else if (!strcmp(arg, "--no-function-context"))
4718 DIFF_OPT_CLR(options, FUNCCONTEXT);
4719 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4720 char *path = prefix_filename(prefix, optarg);
4721 options->file = xfopen(path, "w");
4722 options->close_file = 1;
4723 if (options->use_color != GIT_COLOR_ALWAYS)
4724 options->use_color = GIT_COLOR_NEVER;
4732 int parse_rename_score(const char **cp_p)
4734 unsigned long num, scale;
4736 const char *cp = *cp_p;
4743 if ( !dot && ch == '.' ) {
4746 } else if ( ch == '%' ) {
4747 scale = dot ? scale*100 : 100;
4748 cp++; /* % is always at the end */
4750 } else if ( ch >= '0' && ch <= '9' ) {
4751 if ( scale < 100000 ) {
4753 num = (num*10) + (ch-'0');
4762 /* user says num divided by scale and we say internally that
4763 * is MAX_SCORE * num / scale.
4765 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4768 static int diff_scoreopt_parse(const char *opt)
4770 int opt1, opt2, cmd;
4776 /* convert the long-form arguments into short-form versions */
4777 if (skip_prefix(opt, "break-rewrites", &opt)) {
4778 if (*opt == 0 || *opt++ == '=')
4780 } else if (skip_prefix(opt, "find-copies", &opt)) {
4781 if (*opt == 0 || *opt++ == '=')
4783 } else if (skip_prefix(opt, "find-renames", &opt)) {
4784 if (*opt == 0 || *opt++ == '=')
4788 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4789 return -1; /* that is not a -M, -C, or -B option */
4791 opt1 = parse_rename_score(&opt);
4797 else if (*opt != '/')
4798 return -1; /* we expect -B80/99 or -B80 */
4801 opt2 = parse_rename_score(&opt);
4806 return opt1 | (opt2 << 16);
4809 struct diff_queue_struct diff_queued_diff;
4811 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4813 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4814 queue->queue[queue->nr++] = dp;
4817 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4818 struct diff_filespec *one,
4819 struct diff_filespec *two)
4821 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4829 void diff_free_filepair(struct diff_filepair *p)
4831 free_filespec(p->one);
4832 free_filespec(p->two);
4836 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4841 if (len == GIT_SHA1_HEXSZ)
4842 return oid_to_hex(oid);
4844 abbrev = diff_abbrev_oid(oid, len);
4845 abblen = strlen(abbrev);
4848 * In well-behaved cases, where the abbbreviated result is the
4849 * same as the requested length, append three dots after the
4850 * abbreviation (hence the whole logic is limited to the case
4851 * where abblen < 37); when the actual abbreviated result is a
4852 * bit longer than the requested length, we reduce the number
4853 * of dots so that they match the well-behaved ones. However,
4854 * if the actual abbreviation is longer than the requested
4855 * length by more than three, we give up on aligning, and add
4856 * three dots anyway, to indicate that the output is not the
4857 * full object name. Yes, this may be suboptimal, but this
4858 * appears only in "diff --raw --abbrev" output and it is not
4859 * worth the effort to change it now. Note that this would
4860 * likely to work fine when the automatic sizing of default
4861 * abbreviation length is used--we would be fed -1 in "len" in
4862 * that case, and will end up always appending three-dots, but
4863 * the automatic sizing is supposed to give abblen that ensures
4864 * uniqueness across all objects (statistically speaking).
4866 if (abblen < GIT_SHA1_HEXSZ - 3) {
4867 static char hex[GIT_MAX_HEXSZ + 1];
4868 if (len < abblen && abblen <= len + 2)
4869 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4871 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4875 return oid_to_hex(oid);
4878 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4880 int line_termination = opt->line_termination;
4881 int inter_name_termination = line_termination ? '\t' : '\0';
4883 fprintf(opt->file, "%s", diff_line_prefix(opt));
4884 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4885 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4886 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4887 fprintf(opt->file, "%s ",
4888 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4891 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4892 inter_name_termination);
4894 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4897 if (p->status == DIFF_STATUS_COPIED ||
4898 p->status == DIFF_STATUS_RENAMED) {
4899 const char *name_a, *name_b;
4900 name_a = p->one->path;
4901 name_b = p->two->path;
4902 strip_prefix(opt->prefix_length, &name_a, &name_b);
4903 write_name_quoted(name_a, opt->file, inter_name_termination);
4904 write_name_quoted(name_b, opt->file, line_termination);
4906 const char *name_a, *name_b;
4907 name_a = p->one->mode ? p->one->path : p->two->path;
4909 strip_prefix(opt->prefix_length, &name_a, &name_b);
4910 write_name_quoted(name_a, opt->file, line_termination);
4914 int diff_unmodified_pair(struct diff_filepair *p)
4916 /* This function is written stricter than necessary to support
4917 * the currently implemented transformers, but the idea is to
4918 * let transformers to produce diff_filepairs any way they want,
4919 * and filter and clean them up here before producing the output.
4921 struct diff_filespec *one = p->one, *two = p->two;
4923 if (DIFF_PAIR_UNMERGED(p))
4924 return 0; /* unmerged is interesting */
4926 /* deletion, addition, mode or type change
4927 * and rename are all interesting.
4929 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4930 DIFF_PAIR_MODE_CHANGED(p) ||
4931 strcmp(one->path, two->path))
4934 /* both are valid and point at the same path. that is, we are
4935 * dealing with a change.
4937 if (one->oid_valid && two->oid_valid &&
4938 !oidcmp(&one->oid, &two->oid) &&
4939 !one->dirty_submodule && !two->dirty_submodule)
4940 return 1; /* no change */
4941 if (!one->oid_valid && !two->oid_valid)
4942 return 1; /* both look at the same file on the filesystem. */
4946 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4948 if (diff_unmodified_pair(p))
4951 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4952 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4953 return; /* no tree diffs in patch format */
4958 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4959 struct diffstat_t *diffstat)
4961 if (diff_unmodified_pair(p))
4964 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4965 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4966 return; /* no useful stat for tree diffs */
4968 run_diffstat(p, o, diffstat);
4971 static void diff_flush_checkdiff(struct diff_filepair *p,
4972 struct diff_options *o)
4974 if (diff_unmodified_pair(p))
4977 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4978 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4979 return; /* nothing to check in tree diffs */
4981 run_checkdiff(p, o);
4984 int diff_queue_is_empty(void)
4986 struct diff_queue_struct *q = &diff_queued_diff;
4988 for (i = 0; i < q->nr; i++)
4989 if (!diff_unmodified_pair(q->queue[i]))
4995 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4997 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5000 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5002 s->oid_valid ? oid_to_hex(&s->oid) : "");
5003 fprintf(stderr, "queue[%d] %s size %lu\n",
5008 void diff_debug_filepair(const struct diff_filepair *p, int i)
5010 diff_debug_filespec(p->one, i, "one");
5011 diff_debug_filespec(p->two, i, "two");
5012 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5013 p->score, p->status ? p->status : '?',
5014 p->one->rename_used, p->broken_pair);
5017 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5021 fprintf(stderr, "%s\n", msg);
5022 fprintf(stderr, "q->nr = %d\n", q->nr);
5023 for (i = 0; i < q->nr; i++) {
5024 struct diff_filepair *p = q->queue[i];
5025 diff_debug_filepair(p, i);
5030 static void diff_resolve_rename_copy(void)
5033 struct diff_filepair *p;
5034 struct diff_queue_struct *q = &diff_queued_diff;
5036 diff_debug_queue("resolve-rename-copy", q);
5038 for (i = 0; i < q->nr; i++) {
5040 p->status = 0; /* undecided */
5041 if (DIFF_PAIR_UNMERGED(p))
5042 p->status = DIFF_STATUS_UNMERGED;
5043 else if (!DIFF_FILE_VALID(p->one))
5044 p->status = DIFF_STATUS_ADDED;
5045 else if (!DIFF_FILE_VALID(p->two))
5046 p->status = DIFF_STATUS_DELETED;
5047 else if (DIFF_PAIR_TYPE_CHANGED(p))
5048 p->status = DIFF_STATUS_TYPE_CHANGED;
5050 /* from this point on, we are dealing with a pair
5051 * whose both sides are valid and of the same type, i.e.
5052 * either in-place edit or rename/copy edit.
5054 else if (DIFF_PAIR_RENAME(p)) {
5056 * A rename might have re-connected a broken
5057 * pair up, causing the pathnames to be the
5058 * same again. If so, that's not a rename at
5059 * all, just a modification..
5061 * Otherwise, see if this source was used for
5062 * multiple renames, in which case we decrement
5063 * the count, and call it a copy.
5065 if (!strcmp(p->one->path, p->two->path))
5066 p->status = DIFF_STATUS_MODIFIED;
5067 else if (--p->one->rename_used > 0)
5068 p->status = DIFF_STATUS_COPIED;
5070 p->status = DIFF_STATUS_RENAMED;
5072 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5073 p->one->mode != p->two->mode ||
5074 p->one->dirty_submodule ||
5075 p->two->dirty_submodule ||
5076 is_null_oid(&p->one->oid))
5077 p->status = DIFF_STATUS_MODIFIED;
5079 /* This is a "no-change" entry and should not
5080 * happen anymore, but prepare for broken callers.
5082 error("feeding unmodified %s to diffcore",
5084 p->status = DIFF_STATUS_UNKNOWN;
5087 diff_debug_queue("resolve-rename-copy done", q);
5090 static int check_pair_status(struct diff_filepair *p)
5092 switch (p->status) {
5093 case DIFF_STATUS_UNKNOWN:
5096 die("internal error in diff-resolve-rename-copy");
5102 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5104 int fmt = opt->output_format;
5106 if (fmt & DIFF_FORMAT_CHECKDIFF)
5107 diff_flush_checkdiff(p, opt);
5108 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5109 diff_flush_raw(p, opt);
5110 else if (fmt & DIFF_FORMAT_NAME) {
5111 const char *name_a, *name_b;
5112 name_a = p->two->path;
5114 strip_prefix(opt->prefix_length, &name_a, &name_b);
5115 fprintf(opt->file, "%s", diff_line_prefix(opt));
5116 write_name_quoted(name_a, opt->file, opt->line_termination);
5120 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5122 struct strbuf sb = STRBUF_INIT;
5124 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5126 strbuf_addf(&sb, " %s ", newdelete);
5128 quote_c_style(fs->path, &sb, NULL, 0);
5129 strbuf_addch(&sb, '\n');
5130 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5132 strbuf_release(&sb);
5135 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5138 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5139 struct strbuf sb = STRBUF_INIT;
5140 strbuf_addf(&sb, " mode change %06o => %06o",
5141 p->one->mode, p->two->mode);
5143 strbuf_addch(&sb, ' ');
5144 quote_c_style(p->two->path, &sb, NULL, 0);
5146 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5148 strbuf_release(&sb);
5152 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5153 struct diff_filepair *p)
5155 struct strbuf sb = STRBUF_INIT;
5156 char *names = pprint_rename(p->one->path, p->two->path);
5157 strbuf_addf(&sb, " %s %s (%d%%)\n",
5158 renamecopy, names, similarity_index(p));
5160 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5162 show_mode_change(opt, p, 0);
5165 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5168 case DIFF_STATUS_DELETED:
5169 show_file_mode_name(opt, "delete", p->one);
5171 case DIFF_STATUS_ADDED:
5172 show_file_mode_name(opt, "create", p->two);
5174 case DIFF_STATUS_COPIED:
5175 show_rename_copy(opt, "copy", p);
5177 case DIFF_STATUS_RENAMED:
5178 show_rename_copy(opt, "rename", p);
5182 struct strbuf sb = STRBUF_INIT;
5183 strbuf_addstr(&sb, " rewrite ");
5184 quote_c_style(p->two->path, &sb, NULL, 0);
5185 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5186 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5189 show_mode_change(opt, p, !p->score);
5199 static int remove_space(char *line, int len)
5205 for (i = 0; i < len; i++)
5206 if (!isspace((c = line[i])))
5212 static void patch_id_consume(void *priv, char *line, unsigned long len)
5214 struct patch_id_t *data = priv;
5217 /* Ignore line numbers when computing the SHA1 of the patch */
5218 if (starts_with(line, "@@ -"))
5221 new_len = remove_space(line, len);
5223 git_SHA1_Update(data->ctx, line, new_len);
5224 data->patchlen += new_len;
5227 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5229 git_SHA1_Update(ctx, str, strlen(str));
5232 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5234 /* large enough for 2^32 in octal */
5236 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5237 git_SHA1_Update(ctx, buf, len);
5240 /* returns 0 upon success, and writes result into sha1 */
5241 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5243 struct diff_queue_struct *q = &diff_queued_diff;
5246 struct patch_id_t data;
5248 git_SHA1_Init(&ctx);
5249 memset(&data, 0, sizeof(struct patch_id_t));
5252 for (i = 0; i < q->nr; i++) {
5256 struct diff_filepair *p = q->queue[i];
5259 memset(&xpp, 0, sizeof(xpp));
5260 memset(&xecfg, 0, sizeof(xecfg));
5262 return error("internal diff status error");
5263 if (p->status == DIFF_STATUS_UNKNOWN)
5265 if (diff_unmodified_pair(p))
5267 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5268 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5270 if (DIFF_PAIR_UNMERGED(p))
5273 diff_fill_oid_info(p->one);
5274 diff_fill_oid_info(p->two);
5276 len1 = remove_space(p->one->path, strlen(p->one->path));
5277 len2 = remove_space(p->two->path, strlen(p->two->path));
5278 patch_id_add_string(&ctx, "diff--git");
5279 patch_id_add_string(&ctx, "a/");
5280 git_SHA1_Update(&ctx, p->one->path, len1);
5281 patch_id_add_string(&ctx, "b/");
5282 git_SHA1_Update(&ctx, p->two->path, len2);
5284 if (p->one->mode == 0) {
5285 patch_id_add_string(&ctx, "newfilemode");
5286 patch_id_add_mode(&ctx, p->two->mode);
5287 patch_id_add_string(&ctx, "---/dev/null");
5288 patch_id_add_string(&ctx, "+++b/");
5289 git_SHA1_Update(&ctx, p->two->path, len2);
5290 } else if (p->two->mode == 0) {
5291 patch_id_add_string(&ctx, "deletedfilemode");
5292 patch_id_add_mode(&ctx, p->one->mode);
5293 patch_id_add_string(&ctx, "---a/");
5294 git_SHA1_Update(&ctx, p->one->path, len1);
5295 patch_id_add_string(&ctx, "+++/dev/null");
5297 patch_id_add_string(&ctx, "---a/");
5298 git_SHA1_Update(&ctx, p->one->path, len1);
5299 patch_id_add_string(&ctx, "+++b/");
5300 git_SHA1_Update(&ctx, p->two->path, len2);
5303 if (diff_header_only)
5306 if (fill_mmfile(&mf1, p->one) < 0 ||
5307 fill_mmfile(&mf2, p->two) < 0)
5308 return error("unable to read files to diff");
5310 if (diff_filespec_is_binary(p->one) ||
5311 diff_filespec_is_binary(p->two)) {
5312 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5314 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5322 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5324 return error("unable to generate patch-id diff for %s",
5328 git_SHA1_Final(oid->hash, &ctx);
5332 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5334 struct diff_queue_struct *q = &diff_queued_diff;
5336 int result = diff_get_patch_id(options, oid, diff_header_only);
5338 for (i = 0; i < q->nr; i++)
5339 diff_free_filepair(q->queue[i]);
5342 DIFF_QUEUE_CLEAR(q);
5347 static int is_summary_empty(const struct diff_queue_struct *q)
5351 for (i = 0; i < q->nr; i++) {
5352 const struct diff_filepair *p = q->queue[i];
5354 switch (p->status) {
5355 case DIFF_STATUS_DELETED:
5356 case DIFF_STATUS_ADDED:
5357 case DIFF_STATUS_COPIED:
5358 case DIFF_STATUS_RENAMED:
5363 if (p->one->mode && p->two->mode &&
5364 p->one->mode != p->two->mode)
5372 static const char rename_limit_warning[] =
5373 N_("inexact rename detection was skipped due to too many files.");
5375 static const char degrade_cc_to_c_warning[] =
5376 N_("only found copies from modified paths due to too many files.");
5378 static const char rename_limit_advice[] =
5379 N_("you may want to set your %s variable to at least "
5380 "%d and retry the command.");
5382 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5385 warning(_(degrade_cc_to_c_warning));
5387 warning(_(rename_limit_warning));
5390 if (0 < needed && needed < 32767)
5391 warning(_(rename_limit_advice), varname, needed);
5394 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5397 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5398 struct diff_queue_struct *q = &diff_queued_diff;
5400 if (WSEH_NEW & WS_RULE_MASK)
5401 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5404 o->emitted_symbols = &esm;
5406 for (i = 0; i < q->nr; i++) {
5407 struct diff_filepair *p = q->queue[i];
5408 if (check_pair_status(p))
5409 diff_flush_patch(p, o);
5412 if (o->emitted_symbols) {
5413 if (o->color_moved) {
5414 struct hashmap add_lines, del_lines;
5416 hashmap_init(&del_lines,
5417 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5418 hashmap_init(&add_lines,
5419 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5421 add_lines_to_move_detection(o, &add_lines, &del_lines);
5422 mark_color_as_moved(o, &add_lines, &del_lines);
5424 hashmap_free(&add_lines, 0);
5425 hashmap_free(&del_lines, 0);
5428 for (i = 0; i < esm.nr; i++)
5429 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5431 for (i = 0; i < esm.nr; i++)
5432 free((void *)esm.buf[i].line);
5437 void diff_flush(struct diff_options *options)
5439 struct diff_queue_struct *q = &diff_queued_diff;
5440 int i, output_format = options->output_format;
5442 int dirstat_by_line = 0;
5445 * Order: raw, stat, summary, patch
5446 * or: name/name-status/checkdiff (other bits clear)
5451 if (output_format & (DIFF_FORMAT_RAW |
5453 DIFF_FORMAT_NAME_STATUS |
5454 DIFF_FORMAT_CHECKDIFF)) {
5455 for (i = 0; i < q->nr; i++) {
5456 struct diff_filepair *p = q->queue[i];
5457 if (check_pair_status(p))
5458 flush_one_pair(p, options);
5463 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
5464 dirstat_by_line = 1;
5466 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5468 struct diffstat_t diffstat;
5470 memset(&diffstat, 0, sizeof(struct diffstat_t));
5471 for (i = 0; i < q->nr; i++) {
5472 struct diff_filepair *p = q->queue[i];
5473 if (check_pair_status(p))
5474 diff_flush_stat(p, options, &diffstat);
5476 if (output_format & DIFF_FORMAT_NUMSTAT)
5477 show_numstat(&diffstat, options);
5478 if (output_format & DIFF_FORMAT_DIFFSTAT)
5479 show_stats(&diffstat, options);
5480 if (output_format & DIFF_FORMAT_SHORTSTAT)
5481 show_shortstats(&diffstat, options);
5482 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5483 show_dirstat_by_line(&diffstat, options);
5484 free_diffstat_info(&diffstat);
5487 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5488 show_dirstat(options);
5490 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5491 for (i = 0; i < q->nr; i++) {
5492 diff_summary(options, q->queue[i]);
5497 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5498 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
5499 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5501 * run diff_flush_patch for the exit status. setting
5502 * options->file to /dev/null should be safe, because we
5503 * aren't supposed to produce any output anyway.
5505 if (options->close_file)
5506 fclose(options->file);
5507 options->file = xfopen("/dev/null", "w");
5508 options->close_file = 1;
5509 options->color_moved = 0;
5510 for (i = 0; i < q->nr; i++) {
5511 struct diff_filepair *p = q->queue[i];
5512 if (check_pair_status(p))
5513 diff_flush_patch(p, options);
5514 if (options->found_changes)
5519 if (output_format & DIFF_FORMAT_PATCH) {
5521 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5522 if (options->stat_sep)
5523 /* attach patch instead of inline */
5524 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5528 diff_flush_patch_all_file_pairs(options);
5531 if (output_format & DIFF_FORMAT_CALLBACK)
5532 options->format_callback(q, options, options->format_callback_data);
5534 for (i = 0; i < q->nr; i++)
5535 diff_free_filepair(q->queue[i]);
5538 DIFF_QUEUE_CLEAR(q);
5539 if (options->close_file)
5540 fclose(options->file);
5543 * Report the content-level differences with HAS_CHANGES;
5544 * diff_addremove/diff_change does not set the bit when
5545 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5547 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5548 if (options->found_changes)
5549 DIFF_OPT_SET(options, HAS_CHANGES);
5551 DIFF_OPT_CLR(options, HAS_CHANGES);
5555 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5557 return (((p->status == DIFF_STATUS_MODIFIED) &&
5559 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5561 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5562 ((p->status != DIFF_STATUS_MODIFIED) &&
5563 filter_bit_tst(p->status, options)));
5566 static void diffcore_apply_filter(struct diff_options *options)
5569 struct diff_queue_struct *q = &diff_queued_diff;
5570 struct diff_queue_struct outq;
5572 DIFF_QUEUE_CLEAR(&outq);
5574 if (!options->filter)
5577 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5579 for (i = found = 0; !found && i < q->nr; i++) {
5580 if (match_filter(options, q->queue[i]))
5586 /* otherwise we will clear the whole queue
5587 * by copying the empty outq at the end of this
5588 * function, but first clear the current entries
5591 for (i = 0; i < q->nr; i++)
5592 diff_free_filepair(q->queue[i]);
5595 /* Only the matching ones */
5596 for (i = 0; i < q->nr; i++) {
5597 struct diff_filepair *p = q->queue[i];
5598 if (match_filter(options, p))
5601 diff_free_filepair(p);
5608 /* Check whether two filespecs with the same mode and size are identical */
5609 static int diff_filespec_is_identical(struct diff_filespec *one,
5610 struct diff_filespec *two)
5612 if (S_ISGITLINK(one->mode))
5614 if (diff_populate_filespec(one, 0))
5616 if (diff_populate_filespec(two, 0))
5618 return !memcmp(one->data, two->data, one->size);
5621 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5623 if (p->done_skip_stat_unmatch)
5624 return p->skip_stat_unmatch_result;
5626 p->done_skip_stat_unmatch = 1;
5627 p->skip_stat_unmatch_result = 0;
5629 * 1. Entries that come from stat info dirtiness
5630 * always have both sides (iow, not create/delete),
5631 * one side of the object name is unknown, with
5632 * the same mode and size. Keep the ones that
5633 * do not match these criteria. They have real
5636 * 2. At this point, the file is known to be modified,
5637 * with the same mode and size, and the object
5638 * name of one side is unknown. Need to inspect
5639 * the identical contents.
5641 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5642 !DIFF_FILE_VALID(p->two) ||
5643 (p->one->oid_valid && p->two->oid_valid) ||
5644 (p->one->mode != p->two->mode) ||
5645 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5646 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5647 (p->one->size != p->two->size) ||
5648 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5649 p->skip_stat_unmatch_result = 1;
5650 return p->skip_stat_unmatch_result;
5653 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5656 struct diff_queue_struct *q = &diff_queued_diff;
5657 struct diff_queue_struct outq;
5658 DIFF_QUEUE_CLEAR(&outq);
5660 for (i = 0; i < q->nr; i++) {
5661 struct diff_filepair *p = q->queue[i];
5663 if (diff_filespec_check_stat_unmatch(p))
5667 * The caller can subtract 1 from skip_stat_unmatch
5668 * to determine how many paths were dirty only
5669 * due to stat info mismatch.
5671 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
5672 diffopt->skip_stat_unmatch++;
5673 diff_free_filepair(p);
5680 static int diffnamecmp(const void *a_, const void *b_)
5682 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5683 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5684 const char *name_a, *name_b;
5686 name_a = a->one ? a->one->path : a->two->path;
5687 name_b = b->one ? b->one->path : b->two->path;
5688 return strcmp(name_a, name_b);
5691 void diffcore_fix_diff_index(struct diff_options *options)
5693 struct diff_queue_struct *q = &diff_queued_diff;
5694 QSORT(q->queue, q->nr, diffnamecmp);
5697 void diffcore_std(struct diff_options *options)
5699 /* NOTE please keep the following in sync with diff_tree_combined() */
5700 if (options->skip_stat_unmatch)
5701 diffcore_skip_stat_unmatch(options);
5702 if (!options->found_follow) {
5703 /* See try_to_follow_renames() in tree-diff.c */
5704 if (options->break_opt != -1)
5705 diffcore_break(options->break_opt);
5706 if (options->detect_rename)
5707 diffcore_rename(options);
5708 if (options->break_opt != -1)
5709 diffcore_merge_broken();
5711 if (options->pickaxe)
5712 diffcore_pickaxe(options);
5713 if (options->orderfile)
5714 diffcore_order(options->orderfile);
5715 if (!options->found_follow)
5716 /* See try_to_follow_renames() in tree-diff.c */
5717 diff_resolve_rename_copy();
5718 diffcore_apply_filter(options);
5720 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5721 DIFF_OPT_SET(options, HAS_CHANGES);
5723 DIFF_OPT_CLR(options, HAS_CHANGES);
5725 options->found_follow = 0;
5728 int diff_result_code(struct diff_options *opt, int status)
5732 diff_warn_rename_limit("diff.renameLimit",
5733 opt->needed_rename_limit,
5734 opt->degraded_cc_to_c);
5735 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5736 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5738 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5739 DIFF_OPT_TST(opt, HAS_CHANGES))
5741 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5742 DIFF_OPT_TST(opt, CHECK_FAILED))
5747 int diff_can_quit_early(struct diff_options *opt)
5749 return (DIFF_OPT_TST(opt, QUICK) &&
5751 DIFF_OPT_TST(opt, HAS_CHANGES));
5755 * Shall changes to this submodule be ignored?
5757 * Submodule changes can be configured to be ignored separately for each path,
5758 * but that configuration can be overridden from the command line.
5760 static int is_submodule_ignored(const char *path, struct diff_options *options)
5763 unsigned orig_flags = options->flags;
5764 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
5765 set_diffopt_flags_from_submodule_config(options, path);
5766 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
5768 options->flags = orig_flags;
5772 void diff_addremove(struct diff_options *options,
5773 int addremove, unsigned mode,
5774 const struct object_id *oid,
5776 const char *concatpath, unsigned dirty_submodule)
5778 struct diff_filespec *one, *two;
5780 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5783 /* This may look odd, but it is a preparation for
5784 * feeding "there are unchanged files which should
5785 * not produce diffs, but when you are doing copy
5786 * detection you would need them, so here they are"
5787 * entries to the diff-core. They will be prefixed
5788 * with something like '=' or '*' (I haven't decided
5789 * which but should not make any difference).
5790 * Feeding the same new and old to diff_change()
5791 * also has the same effect.
5792 * Before the final output happens, they are pruned after
5793 * merged into rename/copy pairs as appropriate.
5795 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5796 addremove = (addremove == '+' ? '-' :
5797 addremove == '-' ? '+' : addremove);
5799 if (options->prefix &&
5800 strncmp(concatpath, options->prefix, options->prefix_length))
5803 one = alloc_filespec(concatpath);
5804 two = alloc_filespec(concatpath);
5806 if (addremove != '+')
5807 fill_filespec(one, oid, oid_valid, mode);
5808 if (addremove != '-') {
5809 fill_filespec(two, oid, oid_valid, mode);
5810 two->dirty_submodule = dirty_submodule;
5813 diff_queue(&diff_queued_diff, one, two);
5814 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5815 DIFF_OPT_SET(options, HAS_CHANGES);
5818 void diff_change(struct diff_options *options,
5819 unsigned old_mode, unsigned new_mode,
5820 const struct object_id *old_oid,
5821 const struct object_id *new_oid,
5822 int old_oid_valid, int new_oid_valid,
5823 const char *concatpath,
5824 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5826 struct diff_filespec *one, *two;
5827 struct diff_filepair *p;
5829 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5830 is_submodule_ignored(concatpath, options))
5833 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5834 SWAP(old_mode, new_mode);
5835 SWAP(old_oid, new_oid);
5836 SWAP(old_oid_valid, new_oid_valid);
5837 SWAP(old_dirty_submodule, new_dirty_submodule);
5840 if (options->prefix &&
5841 strncmp(concatpath, options->prefix, options->prefix_length))
5844 one = alloc_filespec(concatpath);
5845 two = alloc_filespec(concatpath);
5846 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5847 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5848 one->dirty_submodule = old_dirty_submodule;
5849 two->dirty_submodule = new_dirty_submodule;
5850 p = diff_queue(&diff_queued_diff, one, two);
5852 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5855 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5856 !diff_filespec_check_stat_unmatch(p))
5859 DIFF_OPT_SET(options, HAS_CHANGES);
5862 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5864 struct diff_filepair *pair;
5865 struct diff_filespec *one, *two;
5867 if (options->prefix &&
5868 strncmp(path, options->prefix, options->prefix_length))
5871 one = alloc_filespec(path);
5872 two = alloc_filespec(path);
5873 pair = diff_queue(&diff_queued_diff, one, two);
5874 pair->is_unmerged = 1;
5878 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5881 struct diff_tempfile *temp;
5882 const char *argv[3];
5883 const char **arg = argv;
5884 struct child_process child = CHILD_PROCESS_INIT;
5885 struct strbuf buf = STRBUF_INIT;
5888 temp = prepare_temp_file(spec->path, spec);
5890 *arg++ = temp->name;
5893 child.use_shell = 1;
5896 if (start_command(&child)) {
5901 if (strbuf_read(&buf, child.out, 0) < 0)
5902 err = error("error reading from textconv command '%s'", pgm);
5905 if (finish_command(&child) || err) {
5906 strbuf_release(&buf);
5912 return strbuf_detach(&buf, outsize);
5915 size_t fill_textconv(struct userdiff_driver *driver,
5916 struct diff_filespec *df,
5922 if (!DIFF_FILE_VALID(df)) {
5926 if (diff_populate_filespec(df, 0))
5927 die("unable to read files to diff");
5932 if (!driver->textconv)
5933 die("BUG: fill_textconv called with non-textconv driver");
5935 if (driver->textconv_cache && df->oid_valid) {
5936 *outbuf = notes_cache_get(driver->textconv_cache,
5943 *outbuf = run_textconv(driver->textconv, df, &size);
5945 die("unable to read files to diff");
5947 if (driver->textconv_cache && df->oid_valid) {
5948 /* ignore errors, as we might be in a readonly repository */
5949 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
5952 * we could save up changes and flush them all at the end,
5953 * but we would need an extra call after all diffing is done.
5954 * Since generating a cache entry is the slow path anyway,
5955 * this extra overhead probably isn't a big deal.
5957 notes_cache_write(driver->textconv_cache);
5963 int textconv_object(const char *path,
5965 const struct object_id *oid,
5968 unsigned long *buf_size)
5970 struct diff_filespec *df;
5971 struct userdiff_driver *textconv;
5973 df = alloc_filespec(path);
5974 fill_filespec(df, oid, oid_valid, mode);
5975 textconv = get_textconv(df);
5981 *buf_size = fill_textconv(textconv, df, buf);
5986 void setup_diff_pager(struct diff_options *opt)
5989 * If the user asked for our exit code, then either they want --quiet
5990 * or --exit-code. We should definitely not bother with a pager in the
5991 * former case, as we will generate no output. Since we still properly
5992 * report our exit code even when a pager is run, we _could_ run a
5993 * pager with --exit-code. But since we have not done so historically,
5994 * and because it is easy to find people oneline advising "git diff
5995 * --exit-code" in hooks and other scripts, we do not do so.
5997 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5998 check_pager_config("diff") != 0)