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_BOLD_MAGENTA, /* OLD_MOVED */
62 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
63 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
64 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
65 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
66 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
67 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
68 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
71 static NORETURN void die_want_option(const char *option_name)
73 die(_("option '%s' requires a value"), option_name);
76 static int parse_diff_color_slot(const char *var)
78 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
80 if (!strcasecmp(var, "meta"))
82 if (!strcasecmp(var, "frag"))
84 if (!strcasecmp(var, "old"))
86 if (!strcasecmp(var, "new"))
88 if (!strcasecmp(var, "commit"))
90 if (!strcasecmp(var, "whitespace"))
91 return DIFF_WHITESPACE;
92 if (!strcasecmp(var, "func"))
94 if (!strcasecmp(var, "oldmoved"))
95 return DIFF_FILE_OLD_MOVED;
96 if (!strcasecmp(var, "oldmovedalternative"))
97 return DIFF_FILE_OLD_MOVED_ALT;
98 if (!strcasecmp(var, "oldmoveddimmed"))
99 return DIFF_FILE_OLD_MOVED_DIM;
100 if (!strcasecmp(var, "oldmovedalternativedimmed"))
101 return DIFF_FILE_OLD_MOVED_ALT_DIM;
102 if (!strcasecmp(var, "newmoved"))
103 return DIFF_FILE_NEW_MOVED;
104 if (!strcasecmp(var, "newmovedalternative"))
105 return DIFF_FILE_NEW_MOVED_ALT;
106 if (!strcasecmp(var, "newmoveddimmed"))
107 return DIFF_FILE_NEW_MOVED_DIM;
108 if (!strcasecmp(var, "newmovedalternativedimmed"))
109 return DIFF_FILE_NEW_MOVED_ALT_DIM;
113 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
114 struct strbuf *errmsg)
116 char *params_copy = xstrdup(params_string);
117 struct string_list params = STRING_LIST_INIT_NODUP;
122 string_list_split_in_place(¶ms, params_copy, ',', -1);
123 for (i = 0; i < params.nr; i++) {
124 const char *p = params.items[i].string;
125 if (!strcmp(p, "changes")) {
126 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
127 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
128 } else if (!strcmp(p, "lines")) {
129 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
130 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
131 } else if (!strcmp(p, "files")) {
132 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
133 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
134 } else if (!strcmp(p, "noncumulative")) {
135 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
136 } else if (!strcmp(p, "cumulative")) {
137 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
138 } else if (isdigit(*p)) {
140 int permille = strtoul(p, &end, 10) * 10;
141 if (*end == '.' && isdigit(*++end)) {
142 /* only use first digit */
143 permille += *end - '0';
144 /* .. and ignore any further digits */
145 while (isdigit(*++end))
149 options->dirstat_permille = permille;
151 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
156 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
161 string_list_clear(¶ms, 0);
166 static int parse_submodule_params(struct diff_options *options, const char *value)
168 if (!strcmp(value, "log"))
169 options->submodule_format = DIFF_SUBMODULE_LOG;
170 else if (!strcmp(value, "short"))
171 options->submodule_format = DIFF_SUBMODULE_SHORT;
172 else if (!strcmp(value, "diff"))
173 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
179 static int git_config_rename(const char *var, const char *value)
182 return DIFF_DETECT_RENAME;
183 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
184 return DIFF_DETECT_COPY;
185 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
188 long parse_algorithm_value(const char *value)
192 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
194 else if (!strcasecmp(value, "minimal"))
195 return XDF_NEED_MINIMAL;
196 else if (!strcasecmp(value, "patience"))
197 return XDF_PATIENCE_DIFF;
198 else if (!strcasecmp(value, "histogram"))
199 return XDF_HISTOGRAM_DIFF;
203 static int parse_one_token(const char **arg, const char *token)
206 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
213 static int parse_ws_error_highlight(const char *arg)
215 const char *orig_arg = arg;
219 if (parse_one_token(&arg, "none"))
221 else if (parse_one_token(&arg, "default"))
223 else if (parse_one_token(&arg, "all"))
224 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
225 else if (parse_one_token(&arg, "new"))
227 else if (parse_one_token(&arg, "old"))
229 else if (parse_one_token(&arg, "context"))
232 return -1 - (int)(arg - orig_arg);
241 * These are to give UI layer defaults.
242 * The core-level commands such as git-diff-files should
243 * never be affected by the setting of diff.renames
244 * the user happens to have in the configuration file.
246 void init_diff_ui_defaults(void)
248 diff_detect_rename_default = 1;
251 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
253 if (!strcmp(var, "diff.indentheuristic"))
254 diff_indent_heuristic = git_config_bool(var, value);
258 static int parse_color_moved(const char *arg)
260 switch (git_parse_maybe_bool(arg)) {
262 return COLOR_MOVED_NO;
264 return COLOR_MOVED_DEFAULT;
269 if (!strcmp(arg, "no"))
270 return COLOR_MOVED_NO;
271 else if (!strcmp(arg, "plain"))
272 return COLOR_MOVED_PLAIN;
273 else if (!strcmp(arg, "zebra"))
274 return COLOR_MOVED_ZEBRA;
275 else if (!strcmp(arg, "default"))
276 return COLOR_MOVED_DEFAULT;
277 else if (!strcmp(arg, "dimmed_zebra"))
278 return COLOR_MOVED_ZEBRA_DIM;
280 return error(_("color moved setting must be one of 'no', 'default', 'zebra', 'dimmed_zebra', 'plain'"));
283 int git_diff_ui_config(const char *var, const char *value, void *cb)
285 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
286 diff_use_color_default = git_config_colorbool(var, value);
289 if (!strcmp(var, "diff.colormoved")) {
290 int cm = parse_color_moved(value);
293 diff_color_moved_default = cm;
296 if (!strcmp(var, "diff.context")) {
297 diff_context_default = git_config_int(var, value);
298 if (diff_context_default < 0)
302 if (!strcmp(var, "diff.interhunkcontext")) {
303 diff_interhunk_context_default = git_config_int(var, value);
304 if (diff_interhunk_context_default < 0)
308 if (!strcmp(var, "diff.renames")) {
309 diff_detect_rename_default = git_config_rename(var, value);
312 if (!strcmp(var, "diff.autorefreshindex")) {
313 diff_auto_refresh_index = git_config_bool(var, value);
316 if (!strcmp(var, "diff.mnemonicprefix")) {
317 diff_mnemonic_prefix = git_config_bool(var, value);
320 if (!strcmp(var, "diff.noprefix")) {
321 diff_no_prefix = git_config_bool(var, value);
324 if (!strcmp(var, "diff.statgraphwidth")) {
325 diff_stat_graph_width = git_config_int(var, value);
328 if (!strcmp(var, "diff.external"))
329 return git_config_string(&external_diff_cmd_cfg, var, value);
330 if (!strcmp(var, "diff.wordregex"))
331 return git_config_string(&diff_word_regex_cfg, var, value);
332 if (!strcmp(var, "diff.orderfile"))
333 return git_config_pathname(&diff_order_file_cfg, var, value);
335 if (!strcmp(var, "diff.ignoresubmodules"))
336 handle_ignore_submodules_arg(&default_diff_options, value);
338 if (!strcmp(var, "diff.submodule")) {
339 if (parse_submodule_params(&default_diff_options, value))
340 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
345 if (!strcmp(var, "diff.algorithm")) {
346 diff_algorithm = parse_algorithm_value(value);
347 if (diff_algorithm < 0)
352 if (!strcmp(var, "diff.wserrorhighlight")) {
353 int val = parse_ws_error_highlight(value);
356 ws_error_highlight_default = val;
360 return git_diff_basic_config(var, value, cb);
363 int git_diff_basic_config(const char *var, const char *value, void *cb)
367 if (!strcmp(var, "diff.renamelimit")) {
368 diff_rename_limit_default = git_config_int(var, value);
372 if (userdiff_config(var, value) < 0)
375 if (skip_prefix(var, "diff.color.", &name) ||
376 skip_prefix(var, "color.diff.", &name)) {
377 int slot = parse_diff_color_slot(name);
381 return config_error_nonbool(var);
382 return color_parse(value, diff_colors[slot]);
385 /* like GNU diff's --suppress-blank-empty option */
386 if (!strcmp(var, "diff.suppressblankempty") ||
387 /* for backwards compatibility */
388 !strcmp(var, "diff.suppress-blank-empty")) {
389 diff_suppress_blank_empty = git_config_bool(var, value);
393 if (!strcmp(var, "diff.dirstat")) {
394 struct strbuf errmsg = STRBUF_INIT;
395 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
396 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
397 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
399 strbuf_release(&errmsg);
400 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
404 if (starts_with(var, "submodule."))
405 return parse_submodule_config_option(var, value);
407 if (git_diff_heuristic_config(var, value, cb) < 0)
410 return git_default_config(var, value, cb);
413 static char *quote_two(const char *one, const char *two)
415 int need_one = quote_c_style(one, NULL, NULL, 1);
416 int need_two = quote_c_style(two, NULL, NULL, 1);
417 struct strbuf res = STRBUF_INIT;
419 if (need_one + need_two) {
420 strbuf_addch(&res, '"');
421 quote_c_style(one, &res, NULL, 1);
422 quote_c_style(two, &res, NULL, 1);
423 strbuf_addch(&res, '"');
425 strbuf_addstr(&res, one);
426 strbuf_addstr(&res, two);
428 return strbuf_detach(&res, NULL);
431 static const char *external_diff(void)
433 static const char *external_diff_cmd = NULL;
434 static int done_preparing = 0;
437 return external_diff_cmd;
438 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
439 if (!external_diff_cmd)
440 external_diff_cmd = external_diff_cmd_cfg;
442 return external_diff_cmd;
446 * Keep track of files used for diffing. Sometimes such an entry
447 * refers to a temporary file, sometimes to an existing file, and
448 * sometimes to "/dev/null".
450 static struct diff_tempfile {
452 * filename external diff should read from, or NULL if this
453 * entry is currently not in use:
457 char hex[GIT_MAX_HEXSZ + 1];
461 * If this diff_tempfile instance refers to a temporary file,
462 * this tempfile object is used to manage its lifetime.
464 struct tempfile tempfile;
467 struct emit_callback {
470 int blank_at_eof_in_preimage;
471 int blank_at_eof_in_postimage;
473 int lno_in_postimage;
474 const char **label_path;
475 struct diff_words_data *diff_words;
476 struct diff_options *opt;
477 struct strbuf *header;
480 static int count_lines(const char *data, int size)
482 int count, ch, completely_empty = 1, nl_just_seen = 0;
489 completely_empty = 0;
493 completely_empty = 0;
496 if (completely_empty)
499 count++; /* no trailing newline */
503 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
505 if (!DIFF_FILE_VALID(one)) {
506 mf->ptr = (char *)""; /* does not matter */
510 else if (diff_populate_filespec(one, 0))
514 mf->size = one->size;
518 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
519 static unsigned long diff_filespec_size(struct diff_filespec *one)
521 if (!DIFF_FILE_VALID(one))
523 diff_populate_filespec(one, CHECK_SIZE_ONLY);
527 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
530 long size = mf->size;
535 ptr += size - 1; /* pointing at the very end */
537 ; /* incomplete line */
539 ptr--; /* skip the last LF */
540 while (mf->ptr < ptr) {
542 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
543 if (*prev_eol == '\n')
545 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
553 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
554 struct emit_callback *ecbdata)
557 unsigned ws_rule = ecbdata->ws_rule;
558 l1 = count_trailing_blank(mf1, ws_rule);
559 l2 = count_trailing_blank(mf2, ws_rule);
561 ecbdata->blank_at_eof_in_preimage = 0;
562 ecbdata->blank_at_eof_in_postimage = 0;
565 at = count_lines(mf1->ptr, mf1->size);
566 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
568 at = count_lines(mf2->ptr, mf2->size);
569 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
572 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
573 int first, const char *line, int len)
575 int has_trailing_newline, has_trailing_carriage_return;
577 FILE *file = o->file;
579 fputs(diff_line_prefix(o), file);
582 has_trailing_newline = (first == '\n');
583 has_trailing_carriage_return = (!has_trailing_newline &&
585 nofirst = has_trailing_newline || has_trailing_carriage_return;
587 has_trailing_newline = (len > 0 && line[len-1] == '\n');
588 if (has_trailing_newline)
590 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
591 if (has_trailing_carriage_return)
596 if (len || !nofirst) {
600 fwrite(line, len, 1, file);
603 if (has_trailing_carriage_return)
605 if (has_trailing_newline)
609 static void emit_line(struct diff_options *o, const char *set, const char *reset,
610 const char *line, int len)
612 emit_line_0(o, set, reset, line[0], line+1, len-1);
616 DIFF_SYMBOL_BINARY_DIFF_HEADER,
617 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
618 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
619 DIFF_SYMBOL_BINARY_DIFF_BODY,
620 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
621 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
622 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
623 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
624 DIFF_SYMBOL_STATS_LINE,
625 DIFF_SYMBOL_WORD_DIFF,
626 DIFF_SYMBOL_STAT_SEP,
628 DIFF_SYMBOL_SUBMODULE_ADD,
629 DIFF_SYMBOL_SUBMODULE_DEL,
630 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
631 DIFF_SYMBOL_SUBMODULE_MODIFIED,
632 DIFF_SYMBOL_SUBMODULE_HEADER,
633 DIFF_SYMBOL_SUBMODULE_ERROR,
634 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
635 DIFF_SYMBOL_REWRITE_DIFF,
636 DIFF_SYMBOL_BINARY_FILES,
638 DIFF_SYMBOL_FILEPAIR_PLUS,
639 DIFF_SYMBOL_FILEPAIR_MINUS,
640 DIFF_SYMBOL_WORDS_PORCELAIN,
643 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
646 DIFF_SYMBOL_NO_LF_EOF,
647 DIFF_SYMBOL_CONTEXT_FRAGINFO,
648 DIFF_SYMBOL_CONTEXT_MARKER,
649 DIFF_SYMBOL_SEPARATOR
652 * Flags for content lines:
653 * 0..12 are whitespace rules
654 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
655 * 16 is marking if the line is blank at EOF
657 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
658 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
659 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
660 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
661 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
664 * This struct is used when we need to buffer the output of the diff output.
666 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
667 * into the pre/post image file. This pointer could be a union with the
668 * line pointer. By storing an offset into the file instead of the literal line,
669 * we can decrease the memory footprint for the buffered output. At first we
670 * may want to only have indirection for the content lines, but we could also
671 * enhance the state for emitting prefabricated lines, e.g. the similarity
672 * score line or hunk/file headers would only need to store a number or path
673 * and then the output can be constructed later on depending on state.
675 struct emitted_diff_symbol {
681 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
683 struct emitted_diff_symbols {
684 struct emitted_diff_symbol *buf;
687 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
689 static void append_emitted_diff_symbol(struct diff_options *o,
690 struct emitted_diff_symbol *e)
692 struct emitted_diff_symbol *f;
694 ALLOC_GROW(o->emitted_symbols->buf,
695 o->emitted_symbols->nr + 1,
696 o->emitted_symbols->alloc);
697 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
699 memcpy(f, e, sizeof(struct emitted_diff_symbol));
700 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
704 struct hashmap_entry ent;
705 const struct emitted_diff_symbol *es;
706 struct moved_entry *next_line;
709 static int next_byte(const char **cp, const char **endp,
710 const struct diff_options *diffopt)
717 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE_CHANGE)) {
718 while (*cp < *endp && isspace(**cp))
721 * After skipping a couple of whitespaces, we still have to
722 * account for one space.
727 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE)) {
728 while (*cp < *endp && isspace(**cp))
730 /* return the first non-ws character via the usual below */
733 retval = (unsigned char)(**cp);
738 static int moved_entry_cmp(const struct diff_options *diffopt,
739 const struct moved_entry *a,
740 const struct moved_entry *b,
743 const char *ap = a->es->line, *ae = a->es->line + a->es->len;
744 const char *bp = b->es->line, *be = b->es->line + b->es->len;
746 if (!(diffopt->xdl_opts & XDF_WHITESPACE_FLAGS))
747 return a->es->len != b->es->len || memcmp(ap, bp, a->es->len);
749 if (DIFF_XDL_TST(diffopt, IGNORE_WHITESPACE_AT_EOL)) {
750 while (ae > ap && isspace(*ae))
752 while (be > bp && isspace(*be))
758 ca = next_byte(&ap, &ae, diffopt);
759 cb = next_byte(&bp, &be, diffopt);
767 static unsigned get_string_hash(struct emitted_diff_symbol *es, struct diff_options *o)
769 if (o->xdl_opts & XDF_WHITESPACE_FLAGS) {
770 static struct strbuf sb = STRBUF_INIT;
771 const char *ap = es->line, *ae = es->line + es->len;
775 while (ae > ap && isspace(*ae))
777 while ((c = next_byte(&ap, &ae, o)) > 0)
778 strbuf_addch(&sb, c);
780 return memhash(sb.buf, sb.len);
782 return memhash(es->line, es->len);
786 static struct moved_entry *prepare_entry(struct diff_options *o,
789 struct moved_entry *ret = xmalloc(sizeof(*ret));
790 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
792 ret->ent.hash = get_string_hash(l, o);
794 ret->next_line = NULL;
799 static void add_lines_to_move_detection(struct diff_options *o,
800 struct hashmap *add_lines,
801 struct hashmap *del_lines)
803 struct moved_entry *prev_line = NULL;
806 for (n = 0; n < o->emitted_symbols->nr; n++) {
808 struct moved_entry *key;
810 switch (o->emitted_symbols->buf[n].s) {
811 case DIFF_SYMBOL_PLUS:
814 case DIFF_SYMBOL_MINUS:
822 key = prepare_entry(o, n);
823 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
824 prev_line->next_line = key;
826 hashmap_add(hm, key);
831 static int shrink_potential_moved_blocks(struct moved_entry **pmb,
836 /* Shrink the set of potential block to the remaining running */
837 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
838 while (lp < pmb_nr && pmb[lp])
840 /* lp points at the first NULL now */
842 while (rp > -1 && !pmb[rp])
844 /* rp points at the last non-NULL */
846 if (lp < pmb_nr && rp > -1 && lp < rp) {
854 /* Remember the number of running sets */
858 /* Find blocks of moved code, delegate actual coloring decision to helper */
859 static void mark_color_as_moved(struct diff_options *o,
860 struct hashmap *add_lines,
861 struct hashmap *del_lines)
863 struct moved_entry **pmb = NULL; /* potentially moved blocks */
864 int pmb_nr = 0, pmb_alloc = 0;
865 int n, flipped_block = 1, block_length = 0;
868 for (n = 0; n < o->emitted_symbols->nr; n++) {
869 struct hashmap *hm = NULL;
870 struct moved_entry *key;
871 struct moved_entry *match = NULL;
872 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
876 case DIFF_SYMBOL_PLUS:
878 key = prepare_entry(o, n);
879 match = hashmap_get(hm, key, o);
882 case DIFF_SYMBOL_MINUS:
884 key = prepare_entry(o, n);
885 match = hashmap_get(hm, key, o);
893 if (block_length < COLOR_MOVED_MIN_BLOCK_LENGTH &&
894 o->color_moved != COLOR_MOVED_PLAIN) {
895 for (i = 0; i < block_length + 1; i++) {
896 l = &o->emitted_symbols->buf[n - i];
897 l->flags &= ~DIFF_SYMBOL_MOVED_LINE;
905 l->flags |= DIFF_SYMBOL_MOVED_LINE;
908 if (o->color_moved == COLOR_MOVED_PLAIN)
911 /* Check any potential block runs, advance each or nullify */
912 for (i = 0; i < pmb_nr; i++) {
913 struct moved_entry *p = pmb[i];
914 struct moved_entry *pnext = (p && p->next_line) ?
916 if (pnext && !hm->cmpfn(o, pnext, match, NULL)) {
917 pmb[i] = p->next_line;
923 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
927 * The current line is the start of a new block.
928 * Setup the set of potential blocks.
930 for (; match; match = hashmap_get_next(hm, match)) {
931 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
932 pmb[pmb_nr++] = match;
935 flipped_block = (flipped_block + 1) % 2;
939 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
945 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
946 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
947 static void dim_moved_lines(struct diff_options *o)
950 for (n = 0; n < o->emitted_symbols->nr; n++) {
951 struct emitted_diff_symbol *prev = (n != 0) ?
952 &o->emitted_symbols->buf[n - 1] : NULL;
953 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
954 struct emitted_diff_symbol *next =
955 (n < o->emitted_symbols->nr - 1) ?
956 &o->emitted_symbols->buf[n + 1] : NULL;
958 /* Not a plus or minus line? */
959 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
962 /* Not a moved line? */
963 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
967 * If prev or next are not a plus or minus line,
968 * pretend they don't exist
970 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
971 prev->s != DIFF_SYMBOL_MINUS)
973 if (next && next->s != DIFF_SYMBOL_PLUS &&
974 next->s != DIFF_SYMBOL_MINUS)
977 /* Inside a block? */
979 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
980 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
982 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
983 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
984 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
988 /* Check if we are at an interesting bound: */
989 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
990 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
991 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
993 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
994 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
995 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
999 * The boundary to prev and next are not interesting,
1000 * so this line is not interesting as a whole
1002 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1006 static void emit_line_ws_markup(struct diff_options *o,
1007 const char *set, const char *reset,
1008 const char *line, int len, char sign,
1009 unsigned ws_rule, int blank_at_eof)
1011 const char *ws = NULL;
1013 if (o->ws_error_highlight & ws_rule) {
1014 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1020 emit_line_0(o, set, reset, sign, line, len);
1021 else if (blank_at_eof)
1022 /* Blank line at EOF - paint '+' as well */
1023 emit_line_0(o, ws, reset, sign, line, len);
1025 /* Emit just the prefix, then the rest. */
1026 emit_line_0(o, set, reset, sign, "", 0);
1027 ws_check_emit(line, len, ws_rule,
1028 o->file, set, reset, ws);
1032 static void emit_diff_symbol_from_struct(struct diff_options *o,
1033 struct emitted_diff_symbol *eds)
1035 static const char *nneof = " No newline at end of file\n";
1036 const char *context, *reset, *set, *meta, *fraginfo;
1037 struct strbuf sb = STRBUF_INIT;
1039 enum diff_symbol s = eds->s;
1040 const char *line = eds->line;
1042 unsigned flags = eds->flags;
1045 case DIFF_SYMBOL_NO_LF_EOF:
1046 context = diff_get_color_opt(o, DIFF_CONTEXT);
1047 reset = diff_get_color_opt(o, DIFF_RESET);
1048 putc('\n', o->file);
1049 emit_line_0(o, context, reset, '\\',
1050 nneof, strlen(nneof));
1052 case DIFF_SYMBOL_SUBMODULE_HEADER:
1053 case DIFF_SYMBOL_SUBMODULE_ERROR:
1054 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1055 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1056 case DIFF_SYMBOL_SUMMARY:
1057 case DIFF_SYMBOL_STATS_LINE:
1058 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1059 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1060 emit_line(o, "", "", line, len);
1062 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1063 case DIFF_SYMBOL_CONTEXT_MARKER:
1064 context = diff_get_color_opt(o, DIFF_CONTEXT);
1065 reset = diff_get_color_opt(o, DIFF_RESET);
1066 emit_line(o, context, reset, line, len);
1068 case DIFF_SYMBOL_SEPARATOR:
1069 fprintf(o->file, "%s%c",
1070 diff_line_prefix(o),
1071 o->line_termination);
1073 case DIFF_SYMBOL_CONTEXT:
1074 set = diff_get_color_opt(o, DIFF_CONTEXT);
1075 reset = diff_get_color_opt(o, DIFF_RESET);
1076 emit_line_ws_markup(o, set, reset, line, len, ' ',
1077 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1079 case DIFF_SYMBOL_PLUS:
1080 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1081 DIFF_SYMBOL_MOVED_LINE_ALT |
1082 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1083 case DIFF_SYMBOL_MOVED_LINE |
1084 DIFF_SYMBOL_MOVED_LINE_ALT |
1085 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1086 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1088 case DIFF_SYMBOL_MOVED_LINE |
1089 DIFF_SYMBOL_MOVED_LINE_ALT:
1090 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1092 case DIFF_SYMBOL_MOVED_LINE |
1093 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1094 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1096 case DIFF_SYMBOL_MOVED_LINE:
1097 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1100 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1102 reset = diff_get_color_opt(o, DIFF_RESET);
1103 emit_line_ws_markup(o, set, reset, line, len, '+',
1104 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1105 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1107 case DIFF_SYMBOL_MINUS:
1108 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1109 DIFF_SYMBOL_MOVED_LINE_ALT |
1110 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1111 case DIFF_SYMBOL_MOVED_LINE |
1112 DIFF_SYMBOL_MOVED_LINE_ALT |
1113 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1114 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1116 case DIFF_SYMBOL_MOVED_LINE |
1117 DIFF_SYMBOL_MOVED_LINE_ALT:
1118 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1120 case DIFF_SYMBOL_MOVED_LINE |
1121 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1122 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1124 case DIFF_SYMBOL_MOVED_LINE:
1125 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1128 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1130 reset = diff_get_color_opt(o, DIFF_RESET);
1131 emit_line_ws_markup(o, set, reset, line, len, '-',
1132 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1134 case DIFF_SYMBOL_WORDS_PORCELAIN:
1135 context = diff_get_color_opt(o, DIFF_CONTEXT);
1136 reset = diff_get_color_opt(o, DIFF_RESET);
1137 emit_line(o, context, reset, line, len);
1138 fputs("~\n", o->file);
1140 case DIFF_SYMBOL_WORDS:
1141 context = diff_get_color_opt(o, DIFF_CONTEXT);
1142 reset = diff_get_color_opt(o, DIFF_RESET);
1144 * Skip the prefix character, if any. With
1145 * diff_suppress_blank_empty, there may be
1148 if (line[0] != '\n') {
1152 emit_line(o, context, reset, line, len);
1154 case DIFF_SYMBOL_FILEPAIR_PLUS:
1155 meta = diff_get_color_opt(o, DIFF_METAINFO);
1156 reset = diff_get_color_opt(o, DIFF_RESET);
1157 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1159 strchr(line, ' ') ? "\t" : "");
1161 case DIFF_SYMBOL_FILEPAIR_MINUS:
1162 meta = diff_get_color_opt(o, DIFF_METAINFO);
1163 reset = diff_get_color_opt(o, DIFF_RESET);
1164 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1166 strchr(line, ' ') ? "\t" : "");
1168 case DIFF_SYMBOL_BINARY_FILES:
1169 case DIFF_SYMBOL_HEADER:
1170 fprintf(o->file, "%s", line);
1172 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1173 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1175 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1176 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1178 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1179 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1181 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1182 fputs(diff_line_prefix(o), o->file);
1183 fputc('\n', o->file);
1185 case DIFF_SYMBOL_REWRITE_DIFF:
1186 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1187 reset = diff_get_color_opt(o, DIFF_RESET);
1188 emit_line(o, fraginfo, reset, line, len);
1190 case DIFF_SYMBOL_SUBMODULE_ADD:
1191 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1192 reset = diff_get_color_opt(o, DIFF_RESET);
1193 emit_line(o, set, reset, line, len);
1195 case DIFF_SYMBOL_SUBMODULE_DEL:
1196 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1197 reset = diff_get_color_opt(o, DIFF_RESET);
1198 emit_line(o, set, reset, line, len);
1200 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1201 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1202 diff_line_prefix(o), line);
1204 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1205 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1206 diff_line_prefix(o), line);
1208 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1209 emit_line(o, "", "", " 0 files changed\n",
1210 strlen(" 0 files changed\n"));
1212 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1213 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1215 case DIFF_SYMBOL_WORD_DIFF:
1216 fprintf(o->file, "%.*s", len, line);
1218 case DIFF_SYMBOL_STAT_SEP:
1219 fputs(o->stat_sep, o->file);
1222 die("BUG: unknown diff symbol");
1224 strbuf_release(&sb);
1227 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1228 const char *line, int len, unsigned flags)
1230 struct emitted_diff_symbol e = {line, len, flags, s};
1232 if (o->emitted_symbols)
1233 append_emitted_diff_symbol(o, &e);
1235 emit_diff_symbol_from_struct(o, &e);
1238 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1240 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1243 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1245 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1248 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1250 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1251 path, strlen(path), 0);
1254 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1256 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1257 path, strlen(path), 0);
1260 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1262 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1263 header, strlen(header), 0);
1266 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1268 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1271 void diff_emit_submodule_pipethrough(struct diff_options *o,
1272 const char *line, int len)
1274 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1277 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1279 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1280 ecbdata->blank_at_eof_in_preimage &&
1281 ecbdata->blank_at_eof_in_postimage &&
1282 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1283 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1285 return ws_blank_line(line, len, ecbdata->ws_rule);
1288 static void emit_add_line(const char *reset,
1289 struct emit_callback *ecbdata,
1290 const char *line, int len)
1292 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1293 if (new_blank_line_at_eof(ecbdata, line, len))
1294 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1296 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1299 static void emit_del_line(const char *reset,
1300 struct emit_callback *ecbdata,
1301 const char *line, int len)
1303 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1304 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1307 static void emit_context_line(const char *reset,
1308 struct emit_callback *ecbdata,
1309 const char *line, int len)
1311 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1312 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1315 static void emit_hunk_header(struct emit_callback *ecbdata,
1316 const char *line, int len)
1318 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1319 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1320 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1321 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1322 static const char atat[2] = { '@', '@' };
1323 const char *cp, *ep;
1324 struct strbuf msgbuf = STRBUF_INIT;
1329 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1330 * it always is at least 10 bytes long.
1333 memcmp(line, atat, 2) ||
1334 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1335 emit_diff_symbol(ecbdata->opt,
1336 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1339 ep += 2; /* skip over @@ */
1341 /* The hunk header in fraginfo color */
1342 strbuf_addstr(&msgbuf, frag);
1343 strbuf_add(&msgbuf, line, ep - line);
1344 strbuf_addstr(&msgbuf, reset);
1350 if (line[len - i] == '\r' || line[len - i] == '\n')
1353 /* blank before the func header */
1354 for (cp = ep; ep - line < len; ep++)
1355 if (*ep != ' ' && *ep != '\t')
1358 strbuf_addstr(&msgbuf, context);
1359 strbuf_add(&msgbuf, cp, ep - cp);
1360 strbuf_addstr(&msgbuf, reset);
1363 if (ep < line + len) {
1364 strbuf_addstr(&msgbuf, func);
1365 strbuf_add(&msgbuf, ep, line + len - ep);
1366 strbuf_addstr(&msgbuf, reset);
1369 strbuf_add(&msgbuf, line + len, org_len - len);
1370 strbuf_complete_line(&msgbuf);
1371 emit_diff_symbol(ecbdata->opt,
1372 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1373 strbuf_release(&msgbuf);
1376 static struct diff_tempfile *claim_diff_tempfile(void) {
1378 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1379 if (!diff_temp[i].name)
1380 return diff_temp + i;
1381 die("BUG: diff is failing to clean up its tempfiles");
1384 static void remove_tempfile(void)
1387 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1388 if (is_tempfile_active(&diff_temp[i].tempfile))
1389 delete_tempfile(&diff_temp[i].tempfile);
1390 diff_temp[i].name = NULL;
1394 static void add_line_count(struct strbuf *out, int count)
1398 strbuf_addstr(out, "0,0");
1401 strbuf_addstr(out, "1");
1404 strbuf_addf(out, "1,%d", count);
1409 static void emit_rewrite_lines(struct emit_callback *ecb,
1410 int prefix, const char *data, int size)
1412 const char *endp = NULL;
1413 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1418 endp = memchr(data, '\n', size);
1419 len = endp ? (endp - data + 1) : size;
1420 if (prefix != '+') {
1421 ecb->lno_in_preimage++;
1422 emit_del_line(reset, ecb, data, len);
1424 ecb->lno_in_postimage++;
1425 emit_add_line(reset, ecb, data, len);
1431 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1434 static void emit_rewrite_diff(const char *name_a,
1436 struct diff_filespec *one,
1437 struct diff_filespec *two,
1438 struct userdiff_driver *textconv_one,
1439 struct userdiff_driver *textconv_two,
1440 struct diff_options *o)
1443 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1444 const char *a_prefix, *b_prefix;
1445 char *data_one, *data_two;
1446 size_t size_one, size_two;
1447 struct emit_callback ecbdata;
1448 struct strbuf out = STRBUF_INIT;
1450 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
1451 a_prefix = o->b_prefix;
1452 b_prefix = o->a_prefix;
1454 a_prefix = o->a_prefix;
1455 b_prefix = o->b_prefix;
1458 name_a += (*name_a == '/');
1459 name_b += (*name_b == '/');
1461 strbuf_reset(&a_name);
1462 strbuf_reset(&b_name);
1463 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1464 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1466 size_one = fill_textconv(textconv_one, one, &data_one);
1467 size_two = fill_textconv(textconv_two, two, &data_two);
1469 memset(&ecbdata, 0, sizeof(ecbdata));
1470 ecbdata.color_diff = want_color(o->use_color);
1471 ecbdata.ws_rule = whitespace_rule(name_b);
1473 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1475 mf1.ptr = (char *)data_one;
1476 mf2.ptr = (char *)data_two;
1477 mf1.size = size_one;
1478 mf2.size = size_two;
1479 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1481 ecbdata.lno_in_preimage = 1;
1482 ecbdata.lno_in_postimage = 1;
1484 lc_a = count_lines(data_one, size_one);
1485 lc_b = count_lines(data_two, size_two);
1487 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1488 a_name.buf, a_name.len, 0);
1489 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1490 b_name.buf, b_name.len, 0);
1492 strbuf_addstr(&out, "@@ -");
1493 if (!o->irreversible_delete)
1494 add_line_count(&out, lc_a);
1496 strbuf_addstr(&out, "?,?");
1497 strbuf_addstr(&out, " +");
1498 add_line_count(&out, lc_b);
1499 strbuf_addstr(&out, " @@\n");
1500 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1501 strbuf_release(&out);
1503 if (lc_a && !o->irreversible_delete)
1504 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1506 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1508 free((char *)data_one);
1510 free((char *)data_two);
1513 struct diff_words_buffer {
1516 struct diff_words_orig {
1517 const char *begin, *end;
1519 int orig_nr, orig_alloc;
1522 static void diff_words_append(char *line, unsigned long len,
1523 struct diff_words_buffer *buffer)
1525 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1528 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1529 buffer->text.size += len;
1530 buffer->text.ptr[buffer->text.size] = '\0';
1533 struct diff_words_style_elem {
1536 const char *color; /* NULL; filled in by the setup code if
1537 * color is enabled */
1540 struct diff_words_style {
1541 enum diff_words_type type;
1542 struct diff_words_style_elem new, old, ctx;
1543 const char *newline;
1546 static struct diff_words_style diff_words_styles[] = {
1547 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1548 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1549 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1552 struct diff_words_data {
1553 struct diff_words_buffer minus, plus;
1554 const char *current_plus;
1556 struct diff_options *opt;
1557 regex_t *word_regex;
1558 enum diff_words_type type;
1559 struct diff_words_style *style;
1562 static int fn_out_diff_words_write_helper(struct diff_options *o,
1563 struct diff_words_style_elem *st_el,
1564 const char *newline,
1565 size_t count, const char *buf)
1568 struct strbuf sb = STRBUF_INIT;
1571 char *p = memchr(buf, '\n', count);
1573 strbuf_addstr(&sb, diff_line_prefix(o));
1576 const char *reset = st_el->color && *st_el->color ?
1577 GIT_COLOR_RESET : NULL;
1578 if (st_el->color && *st_el->color)
1579 strbuf_addstr(&sb, st_el->color);
1580 strbuf_addstr(&sb, st_el->prefix);
1581 strbuf_add(&sb, buf, p ? p - buf : count);
1582 strbuf_addstr(&sb, st_el->suffix);
1584 strbuf_addstr(&sb, reset);
1589 strbuf_addstr(&sb, newline);
1590 count -= p + 1 - buf;
1594 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1602 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1604 strbuf_release(&sb);
1609 * '--color-words' algorithm can be described as:
1611 * 1. collect the minus/plus lines of a diff hunk, divided into
1612 * minus-lines and plus-lines;
1614 * 2. break both minus-lines and plus-lines into words and
1615 * place them into two mmfile_t with one word for each line;
1617 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1619 * And for the common parts of the both file, we output the plus side text.
1620 * diff_words->current_plus is used to trace the current position of the plus file
1621 * which printed. diff_words->last_minus is used to trace the last minus word
1624 * For '--graph' to work with '--color-words', we need to output the graph prefix
1625 * on each line of color words output. Generally, there are two conditions on
1626 * which we should output the prefix.
1628 * 1. diff_words->last_minus == 0 &&
1629 * diff_words->current_plus == diff_words->plus.text.ptr
1631 * that is: the plus text must start as a new line, and if there is no minus
1632 * word printed, a graph prefix must be printed.
1634 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1635 * *(diff_words->current_plus - 1) == '\n'
1637 * that is: a graph prefix must be printed following a '\n'
1639 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1641 if ((diff_words->last_minus == 0 &&
1642 diff_words->current_plus == diff_words->plus.text.ptr) ||
1643 (diff_words->current_plus > diff_words->plus.text.ptr &&
1644 *(diff_words->current_plus - 1) == '\n')) {
1651 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1653 struct diff_words_data *diff_words = priv;
1654 struct diff_words_style *style = diff_words->style;
1655 int minus_first, minus_len, plus_first, plus_len;
1656 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1657 struct diff_options *opt = diff_words->opt;
1658 const char *line_prefix;
1660 if (line[0] != '@' || parse_hunk_header(line, len,
1661 &minus_first, &minus_len, &plus_first, &plus_len))
1665 line_prefix = diff_line_prefix(opt);
1667 /* POSIX requires that first be decremented by one if len == 0... */
1669 minus_begin = diff_words->minus.orig[minus_first].begin;
1671 diff_words->minus.orig[minus_first + minus_len - 1].end;
1673 minus_begin = minus_end =
1674 diff_words->minus.orig[minus_first].end;
1677 plus_begin = diff_words->plus.orig[plus_first].begin;
1678 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1680 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1682 if (color_words_output_graph_prefix(diff_words)) {
1683 fputs(line_prefix, diff_words->opt->file);
1685 if (diff_words->current_plus != plus_begin) {
1686 fn_out_diff_words_write_helper(diff_words->opt,
1687 &style->ctx, style->newline,
1688 plus_begin - diff_words->current_plus,
1689 diff_words->current_plus);
1691 if (minus_begin != minus_end) {
1692 fn_out_diff_words_write_helper(diff_words->opt,
1693 &style->old, style->newline,
1694 minus_end - minus_begin, minus_begin);
1696 if (plus_begin != plus_end) {
1697 fn_out_diff_words_write_helper(diff_words->opt,
1698 &style->new, style->newline,
1699 plus_end - plus_begin, plus_begin);
1702 diff_words->current_plus = plus_end;
1703 diff_words->last_minus = minus_first;
1706 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1707 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1708 int *begin, int *end)
1710 if (word_regex && *begin < buffer->size) {
1711 regmatch_t match[1];
1712 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1713 buffer->size - *begin, 1, match, 0)) {
1714 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1715 '\n', match[0].rm_eo - match[0].rm_so);
1716 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1717 *begin += match[0].rm_so;
1718 return *begin >= *end;
1723 /* find the next word */
1724 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1726 if (*begin >= buffer->size)
1729 /* find the end of the word */
1731 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1738 * This function splits the words in buffer->text, stores the list with
1739 * newline separator into out, and saves the offsets of the original words
1742 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1743 regex_t *word_regex)
1751 /* fake an empty "0th" word */
1752 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1753 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1754 buffer->orig_nr = 1;
1756 for (i = 0; i < buffer->text.size; i++) {
1757 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1760 /* store original boundaries */
1761 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1762 buffer->orig_alloc);
1763 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1764 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1767 /* store one word */
1768 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1769 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1770 out->ptr[out->size + j - i] = '\n';
1771 out->size += j - i + 1;
1777 /* this executes the word diff on the accumulated buffers */
1778 static void diff_words_show(struct diff_words_data *diff_words)
1782 mmfile_t minus, plus;
1783 struct diff_words_style *style = diff_words->style;
1785 struct diff_options *opt = diff_words->opt;
1786 const char *line_prefix;
1789 line_prefix = diff_line_prefix(opt);
1791 /* special case: only removal */
1792 if (!diff_words->plus.text.size) {
1793 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1794 line_prefix, strlen(line_prefix), 0);
1795 fn_out_diff_words_write_helper(diff_words->opt,
1796 &style->old, style->newline,
1797 diff_words->minus.text.size,
1798 diff_words->minus.text.ptr);
1799 diff_words->minus.text.size = 0;
1803 diff_words->current_plus = diff_words->plus.text.ptr;
1804 diff_words->last_minus = 0;
1806 memset(&xpp, 0, sizeof(xpp));
1807 memset(&xecfg, 0, sizeof(xecfg));
1808 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1809 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1811 /* as only the hunk header will be parsed, we need a 0-context */
1813 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1815 die("unable to generate word diff");
1818 if (diff_words->current_plus != diff_words->plus.text.ptr +
1819 diff_words->plus.text.size) {
1820 if (color_words_output_graph_prefix(diff_words))
1821 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1822 line_prefix, strlen(line_prefix), 0);
1823 fn_out_diff_words_write_helper(diff_words->opt,
1824 &style->ctx, style->newline,
1825 diff_words->plus.text.ptr + diff_words->plus.text.size
1826 - diff_words->current_plus, diff_words->current_plus);
1828 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1831 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1832 static void diff_words_flush(struct emit_callback *ecbdata)
1834 struct diff_options *wo = ecbdata->diff_words->opt;
1836 if (ecbdata->diff_words->minus.text.size ||
1837 ecbdata->diff_words->plus.text.size)
1838 diff_words_show(ecbdata->diff_words);
1840 if (wo->emitted_symbols) {
1841 struct diff_options *o = ecbdata->opt;
1842 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1847 * Instead of appending each, concat all words to a line?
1849 for (i = 0; i < wol->nr; i++)
1850 append_emitted_diff_symbol(o, &wol->buf[i]);
1852 for (i = 0; i < wol->nr; i++)
1853 free((void *)wol->buf[i].line);
1859 static void diff_filespec_load_driver(struct diff_filespec *one)
1861 /* Use already-loaded driver */
1865 if (S_ISREG(one->mode))
1866 one->driver = userdiff_find_by_path(one->path);
1868 /* Fallback to default settings */
1870 one->driver = userdiff_find_by_name("default");
1873 static const char *userdiff_word_regex(struct diff_filespec *one)
1875 diff_filespec_load_driver(one);
1876 return one->driver->word_regex;
1879 static void init_diff_words_data(struct emit_callback *ecbdata,
1880 struct diff_options *orig_opts,
1881 struct diff_filespec *one,
1882 struct diff_filespec *two)
1885 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1886 memcpy(o, orig_opts, sizeof(struct diff_options));
1888 ecbdata->diff_words =
1889 xcalloc(1, sizeof(struct diff_words_data));
1890 ecbdata->diff_words->type = o->word_diff;
1891 ecbdata->diff_words->opt = o;
1893 if (orig_opts->emitted_symbols)
1894 o->emitted_symbols =
1895 xcalloc(1, sizeof(struct emitted_diff_symbols));
1898 o->word_regex = userdiff_word_regex(one);
1900 o->word_regex = userdiff_word_regex(two);
1902 o->word_regex = diff_word_regex_cfg;
1903 if (o->word_regex) {
1904 ecbdata->diff_words->word_regex = (regex_t *)
1905 xmalloc(sizeof(regex_t));
1906 if (regcomp(ecbdata->diff_words->word_regex,
1908 REG_EXTENDED | REG_NEWLINE))
1909 die ("Invalid regular expression: %s",
1912 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1913 if (o->word_diff == diff_words_styles[i].type) {
1914 ecbdata->diff_words->style =
1915 &diff_words_styles[i];
1919 if (want_color(o->use_color)) {
1920 struct diff_words_style *st = ecbdata->diff_words->style;
1921 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1922 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1923 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1927 static void free_diff_words_data(struct emit_callback *ecbdata)
1929 if (ecbdata->diff_words) {
1930 diff_words_flush(ecbdata);
1931 free (ecbdata->diff_words->opt->emitted_symbols);
1932 free (ecbdata->diff_words->opt);
1933 free (ecbdata->diff_words->minus.text.ptr);
1934 free (ecbdata->diff_words->minus.orig);
1935 free (ecbdata->diff_words->plus.text.ptr);
1936 free (ecbdata->diff_words->plus.orig);
1937 if (ecbdata->diff_words->word_regex) {
1938 regfree(ecbdata->diff_words->word_regex);
1939 free(ecbdata->diff_words->word_regex);
1941 FREE_AND_NULL(ecbdata->diff_words);
1945 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1947 if (want_color(diff_use_color))
1948 return diff_colors[ix];
1952 const char *diff_line_prefix(struct diff_options *opt)
1954 struct strbuf *msgbuf;
1955 if (!opt->output_prefix)
1958 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1962 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1965 unsigned long allot;
1971 (void) utf8_width(&cp, &l);
1973 break; /* truncated in the middle? */
1978 static void find_lno(const char *line, struct emit_callback *ecbdata)
1981 ecbdata->lno_in_preimage = 0;
1982 ecbdata->lno_in_postimage = 0;
1983 p = strchr(line, '-');
1985 return; /* cannot happen */
1986 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1989 return; /* cannot happen */
1990 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1993 static void fn_out_consume(void *priv, char *line, unsigned long len)
1995 struct emit_callback *ecbdata = priv;
1996 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1997 struct diff_options *o = ecbdata->opt;
1999 o->found_changes = 1;
2001 if (ecbdata->header) {
2002 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2003 ecbdata->header->buf, ecbdata->header->len, 0);
2004 strbuf_reset(ecbdata->header);
2005 ecbdata->header = NULL;
2008 if (ecbdata->label_path[0]) {
2009 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2010 ecbdata->label_path[0],
2011 strlen(ecbdata->label_path[0]), 0);
2012 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2013 ecbdata->label_path[1],
2014 strlen(ecbdata->label_path[1]), 0);
2015 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2018 if (diff_suppress_blank_empty
2019 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2024 if (line[0] == '@') {
2025 if (ecbdata->diff_words)
2026 diff_words_flush(ecbdata);
2027 len = sane_truncate_line(ecbdata, line, len);
2028 find_lno(line, ecbdata);
2029 emit_hunk_header(ecbdata, line, len);
2033 if (ecbdata->diff_words) {
2034 enum diff_symbol s =
2035 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2036 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2037 if (line[0] == '-') {
2038 diff_words_append(line, len,
2039 &ecbdata->diff_words->minus);
2041 } else if (line[0] == '+') {
2042 diff_words_append(line, len,
2043 &ecbdata->diff_words->plus);
2045 } else if (starts_with(line, "\\ ")) {
2047 * Eat the "no newline at eof" marker as if we
2048 * saw a "+" or "-" line with nothing on it,
2049 * and return without diff_words_flush() to
2050 * defer processing. If this is the end of
2051 * preimage, more "+" lines may come after it.
2055 diff_words_flush(ecbdata);
2056 emit_diff_symbol(o, s, line, len, 0);
2062 ecbdata->lno_in_postimage++;
2063 emit_add_line(reset, ecbdata, line + 1, len - 1);
2066 ecbdata->lno_in_preimage++;
2067 emit_del_line(reset, ecbdata, line + 1, len - 1);
2070 ecbdata->lno_in_postimage++;
2071 ecbdata->lno_in_preimage++;
2072 emit_context_line(reset, ecbdata, line + 1, len - 1);
2075 /* incomplete line at the end */
2076 ecbdata->lno_in_preimage++;
2077 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2083 static char *pprint_rename(const char *a, const char *b)
2085 const char *old = a;
2086 const char *new = b;
2087 struct strbuf name = STRBUF_INIT;
2088 int pfx_length, sfx_length;
2089 int pfx_adjust_for_slash;
2090 int len_a = strlen(a);
2091 int len_b = strlen(b);
2092 int a_midlen, b_midlen;
2093 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2094 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2096 if (qlen_a || qlen_b) {
2097 quote_c_style(a, &name, NULL, 0);
2098 strbuf_addstr(&name, " => ");
2099 quote_c_style(b, &name, NULL, 0);
2100 return strbuf_detach(&name, NULL);
2103 /* Find common prefix */
2105 while (*old && *new && *old == *new) {
2107 pfx_length = old - a + 1;
2112 /* Find common suffix */
2117 * If there is a common prefix, it must end in a slash. In
2118 * that case we let this loop run 1 into the prefix to see the
2121 * If there is no common prefix, we cannot do this as it would
2122 * underrun the input strings.
2124 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2125 while (a + pfx_length - pfx_adjust_for_slash <= old &&
2126 b + pfx_length - pfx_adjust_for_slash <= new &&
2129 sfx_length = len_a - (old - a);
2135 * pfx{mid-a => mid-b}sfx
2136 * {pfx-a => pfx-b}sfx
2137 * pfx{sfx-a => sfx-b}
2140 a_midlen = len_a - pfx_length - sfx_length;
2141 b_midlen = len_b - pfx_length - sfx_length;
2147 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2148 if (pfx_length + sfx_length) {
2149 strbuf_add(&name, a, pfx_length);
2150 strbuf_addch(&name, '{');
2152 strbuf_add(&name, a + pfx_length, a_midlen);
2153 strbuf_addstr(&name, " => ");
2154 strbuf_add(&name, b + pfx_length, b_midlen);
2155 if (pfx_length + sfx_length) {
2156 strbuf_addch(&name, '}');
2157 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
2159 return strbuf_detach(&name, NULL);
2165 struct diffstat_file {
2169 unsigned is_unmerged:1;
2170 unsigned is_binary:1;
2171 unsigned is_renamed:1;
2172 unsigned is_interesting:1;
2173 uintmax_t added, deleted;
2177 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2181 struct diffstat_file *x;
2182 x = xcalloc(1, sizeof(*x));
2183 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2184 diffstat->files[diffstat->nr++] = x;
2186 x->from_name = xstrdup(name_a);
2187 x->name = xstrdup(name_b);
2191 x->from_name = NULL;
2192 x->name = xstrdup(name_a);
2197 static void diffstat_consume(void *priv, char *line, unsigned long len)
2199 struct diffstat_t *diffstat = priv;
2200 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2204 else if (line[0] == '-')
2208 const char mime_boundary_leader[] = "------------";
2210 static int scale_linear(int it, int width, int max_change)
2215 * make sure that at least one '-' or '+' is printed if
2216 * there is any change to this path. The easiest way is to
2217 * scale linearly as if the alloted width is one column shorter
2218 * than it is, and then add 1 to the result.
2220 return 1 + (it * (width - 1) / max_change);
2223 static void show_graph(struct strbuf *out, char ch, int cnt,
2224 const char *set, const char *reset)
2228 strbuf_addstr(out, set);
2229 strbuf_addchars(out, ch, cnt);
2230 strbuf_addstr(out, reset);
2233 static void fill_print_name(struct diffstat_file *file)
2237 if (file->print_name)
2240 if (!file->is_renamed) {
2241 struct strbuf buf = STRBUF_INIT;
2242 if (quote_c_style(file->name, &buf, NULL, 0)) {
2243 pname = strbuf_detach(&buf, NULL);
2246 strbuf_release(&buf);
2249 pname = pprint_rename(file->from_name, file->name);
2251 file->print_name = pname;
2254 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2255 int files, int insertions, int deletions)
2257 struct strbuf sb = STRBUF_INIT;
2260 assert(insertions == 0 && deletions == 0);
2261 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2267 (files == 1) ? " %d file changed" : " %d files changed",
2271 * For binary diff, the caller may want to print "x files
2272 * changed" with insertions == 0 && deletions == 0.
2274 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2275 * is probably less confusing (i.e skip over "2 files changed
2276 * but nothing about added/removed lines? Is this a bug in Git?").
2278 if (insertions || deletions == 0) {
2280 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2284 if (deletions || insertions == 0) {
2286 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2289 strbuf_addch(&sb, '\n');
2290 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2292 strbuf_release(&sb);
2295 void print_stat_summary(FILE *fp, int files,
2296 int insertions, int deletions)
2298 struct diff_options o;
2299 memset(&o, 0, sizeof(o));
2302 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2305 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2307 int i, len, add, del, adds = 0, dels = 0;
2308 uintmax_t max_change = 0, max_len = 0;
2309 int total_files = data->nr, count;
2310 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2311 const char *reset, *add_c, *del_c;
2312 int extra_shown = 0;
2313 const char *line_prefix = diff_line_prefix(options);
2314 struct strbuf out = STRBUF_INIT;
2319 count = options->stat_count ? options->stat_count : data->nr;
2321 reset = diff_get_color_opt(options, DIFF_RESET);
2322 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2323 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2326 * Find the longest filename and max number of changes
2328 for (i = 0; (i < count) && (i < data->nr); i++) {
2329 struct diffstat_file *file = data->files[i];
2330 uintmax_t change = file->added + file->deleted;
2332 if (!file->is_interesting && (change == 0)) {
2333 count++; /* not shown == room for one more */
2336 fill_print_name(file);
2337 len = strlen(file->print_name);
2341 if (file->is_unmerged) {
2342 /* "Unmerged" is 8 characters */
2343 bin_width = bin_width < 8 ? 8 : bin_width;
2346 if (file->is_binary) {
2347 /* "Bin XXX -> YYY bytes" */
2348 int w = 14 + decimal_width(file->added)
2349 + decimal_width(file->deleted);
2350 bin_width = bin_width < w ? w : bin_width;
2351 /* Display change counts aligned with "Bin" */
2356 if (max_change < change)
2357 max_change = change;
2359 count = i; /* where we can stop scanning in data->files[] */
2362 * We have width = stat_width or term_columns() columns total.
2363 * We want a maximum of min(max_len, stat_name_width) for the name part.
2364 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2365 * We also need 1 for " " and 4 + decimal_width(max_change)
2366 * for " | NNNN " and one the empty column at the end, altogether
2367 * 6 + decimal_width(max_change).
2369 * If there's not enough space, we will use the smaller of
2370 * stat_name_width (if set) and 5/8*width for the filename,
2371 * and the rest for constant elements + graph part, but no more
2372 * than stat_graph_width for the graph part.
2373 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2374 * for the standard terminal size).
2376 * In other words: stat_width limits the maximum width, and
2377 * stat_name_width fixes the maximum width of the filename,
2378 * and is also used to divide available columns if there
2381 * Binary files are displayed with "Bin XXX -> YYY bytes"
2382 * instead of the change count and graph. This part is treated
2383 * similarly to the graph part, except that it is not
2384 * "scaled". If total width is too small to accommodate the
2385 * guaranteed minimum width of the filename part and the
2386 * separators and this message, this message will "overflow"
2387 * making the line longer than the maximum width.
2390 if (options->stat_width == -1)
2391 width = term_columns() - strlen(line_prefix);
2393 width = options->stat_width ? options->stat_width : 80;
2394 number_width = decimal_width(max_change) > number_width ?
2395 decimal_width(max_change) : number_width;
2397 if (options->stat_graph_width == -1)
2398 options->stat_graph_width = diff_stat_graph_width;
2401 * Guarantee 3/8*16==6 for the graph part
2402 * and 5/8*16==10 for the filename part
2404 if (width < 16 + 6 + number_width)
2405 width = 16 + 6 + number_width;
2408 * First assign sizes that are wanted, ignoring available width.
2409 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2410 * starting from "XXX" should fit in graph_width.
2412 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2413 if (options->stat_graph_width &&
2414 options->stat_graph_width < graph_width)
2415 graph_width = options->stat_graph_width;
2417 name_width = (options->stat_name_width > 0 &&
2418 options->stat_name_width < max_len) ?
2419 options->stat_name_width : max_len;
2422 * Adjust adjustable widths not to exceed maximum width
2424 if (name_width + number_width + 6 + graph_width > width) {
2425 if (graph_width > width * 3/8 - number_width - 6) {
2426 graph_width = width * 3/8 - number_width - 6;
2427 if (graph_width < 6)
2431 if (options->stat_graph_width &&
2432 graph_width > options->stat_graph_width)
2433 graph_width = options->stat_graph_width;
2434 if (name_width > width - number_width - 6 - graph_width)
2435 name_width = width - number_width - 6 - graph_width;
2437 graph_width = width - number_width - 6 - name_width;
2441 * From here name_width is the width of the name area,
2442 * and graph_width is the width of the graph area.
2443 * max_change is used to scale graph properly.
2445 for (i = 0; i < count; i++) {
2446 const char *prefix = "";
2447 struct diffstat_file *file = data->files[i];
2448 char *name = file->print_name;
2449 uintmax_t added = file->added;
2450 uintmax_t deleted = file->deleted;
2453 if (!file->is_interesting && (added + deleted == 0))
2457 * "scale" the filename
2460 name_len = strlen(name);
2461 if (name_width < name_len) {
2465 name += name_len - len;
2466 slash = strchr(name, '/');
2471 if (file->is_binary) {
2472 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2473 strbuf_addf(&out, " %*s", number_width, "Bin");
2474 if (!added && !deleted) {
2475 strbuf_addch(&out, '\n');
2476 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2477 out.buf, out.len, 0);
2481 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2482 del_c, deleted, reset);
2483 strbuf_addstr(&out, " -> ");
2484 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2485 add_c, added, reset);
2486 strbuf_addstr(&out, " bytes\n");
2487 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2488 out.buf, out.len, 0);
2492 else if (file->is_unmerged) {
2493 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2494 strbuf_addstr(&out, " Unmerged\n");
2495 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2496 out.buf, out.len, 0);
2502 * scale the add/delete
2507 if (graph_width <= max_change) {
2508 int total = scale_linear(add + del, graph_width, max_change);
2509 if (total < 2 && add && del)
2510 /* width >= 2 due to the sanity check */
2513 add = scale_linear(add, graph_width, max_change);
2516 del = scale_linear(del, graph_width, max_change);
2520 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2521 strbuf_addf(&out, " %*"PRIuMAX"%s",
2522 number_width, added + deleted,
2523 added + deleted ? " " : "");
2524 show_graph(&out, '+', add, add_c, reset);
2525 show_graph(&out, '-', del, del_c, reset);
2526 strbuf_addch(&out, '\n');
2527 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2528 out.buf, out.len, 0);
2532 for (i = 0; i < data->nr; i++) {
2533 struct diffstat_file *file = data->files[i];
2534 uintmax_t added = file->added;
2535 uintmax_t deleted = file->deleted;
2537 if (file->is_unmerged ||
2538 (!file->is_interesting && (added + deleted == 0))) {
2543 if (!file->is_binary) {
2550 emit_diff_symbol(options,
2551 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2556 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2559 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2561 int i, adds = 0, dels = 0, total_files = data->nr;
2566 for (i = 0; i < data->nr; i++) {
2567 int added = data->files[i]->added;
2568 int deleted = data->files[i]->deleted;
2570 if (data->files[i]->is_unmerged ||
2571 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2573 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2578 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2581 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2588 for (i = 0; i < data->nr; i++) {
2589 struct diffstat_file *file = data->files[i];
2591 fprintf(options->file, "%s", diff_line_prefix(options));
2593 if (file->is_binary)
2594 fprintf(options->file, "-\t-\t");
2596 fprintf(options->file,
2597 "%"PRIuMAX"\t%"PRIuMAX"\t",
2598 file->added, file->deleted);
2599 if (options->line_termination) {
2600 fill_print_name(file);
2601 if (!file->is_renamed)
2602 write_name_quoted(file->name, options->file,
2603 options->line_termination);
2605 fputs(file->print_name, options->file);
2606 putc(options->line_termination, options->file);
2609 if (file->is_renamed) {
2610 putc('\0', options->file);
2611 write_name_quoted(file->from_name, options->file, '\0');
2613 write_name_quoted(file->name, options->file, '\0');
2618 struct dirstat_file {
2620 unsigned long changed;
2623 struct dirstat_dir {
2624 struct dirstat_file *files;
2625 int alloc, nr, permille, cumulative;
2628 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2629 unsigned long changed, const char *base, int baselen)
2631 unsigned long this_dir = 0;
2632 unsigned int sources = 0;
2633 const char *line_prefix = diff_line_prefix(opt);
2636 struct dirstat_file *f = dir->files;
2637 int namelen = strlen(f->name);
2641 if (namelen < baselen)
2643 if (memcmp(f->name, base, baselen))
2645 slash = strchr(f->name + baselen, '/');
2647 int newbaselen = slash + 1 - f->name;
2648 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2660 * We don't report dirstat's for
2662 * - or cases where everything came from a single directory
2663 * under this directory (sources == 1).
2665 if (baselen && sources != 1) {
2667 int permille = this_dir * 1000 / changed;
2668 if (permille >= dir->permille) {
2669 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2670 permille / 10, permille % 10, baselen, base);
2671 if (!dir->cumulative)
2679 static int dirstat_compare(const void *_a, const void *_b)
2681 const struct dirstat_file *a = _a;
2682 const struct dirstat_file *b = _b;
2683 return strcmp(a->name, b->name);
2686 static void show_dirstat(struct diff_options *options)
2689 unsigned long changed;
2690 struct dirstat_dir dir;
2691 struct diff_queue_struct *q = &diff_queued_diff;
2696 dir.permille = options->dirstat_permille;
2697 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2700 for (i = 0; i < q->nr; i++) {
2701 struct diff_filepair *p = q->queue[i];
2703 unsigned long copied, added, damage;
2704 int content_changed;
2706 name = p->two->path ? p->two->path : p->one->path;
2708 if (p->one->oid_valid && p->two->oid_valid)
2709 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2711 content_changed = 1;
2713 if (!content_changed) {
2715 * The SHA1 has not changed, so pre-/post-content is
2716 * identical. We can therefore skip looking at the
2717 * file contents altogether.
2723 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2725 * In --dirstat-by-file mode, we don't really need to
2726 * look at the actual file contents at all.
2727 * The fact that the SHA1 changed is enough for us to
2728 * add this file to the list of results
2729 * (with each file contributing equal damage).
2735 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2736 diff_populate_filespec(p->one, 0);
2737 diff_populate_filespec(p->two, 0);
2738 diffcore_count_changes(p->one, p->two, NULL, NULL,
2740 diff_free_filespec_data(p->one);
2741 diff_free_filespec_data(p->two);
2742 } else if (DIFF_FILE_VALID(p->one)) {
2743 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2745 diff_free_filespec_data(p->one);
2746 } else if (DIFF_FILE_VALID(p->two)) {
2747 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2749 added = p->two->size;
2750 diff_free_filespec_data(p->two);
2755 * Original minus copied is the removed material,
2756 * added is the new material. They are both damages
2757 * made to the preimage.
2758 * If the resulting damage is zero, we know that
2759 * diffcore_count_changes() considers the two entries to
2760 * be identical, but since content_changed is true, we
2761 * know that there must have been _some_ kind of change,
2762 * so we force all entries to have damage > 0.
2764 damage = (p->one->size - copied) + added;
2769 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2770 dir.files[dir.nr].name = name;
2771 dir.files[dir.nr].changed = damage;
2776 /* This can happen even with many files, if everything was renames */
2780 /* Show all directories with more than x% of the changes */
2781 QSORT(dir.files, dir.nr, dirstat_compare);
2782 gather_dirstat(options, &dir, changed, "", 0);
2785 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2788 unsigned long changed;
2789 struct dirstat_dir dir;
2797 dir.permille = options->dirstat_permille;
2798 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2801 for (i = 0; i < data->nr; i++) {
2802 struct diffstat_file *file = data->files[i];
2803 unsigned long damage = file->added + file->deleted;
2804 if (file->is_binary)
2806 * binary files counts bytes, not lines. Must find some
2807 * way to normalize binary bytes vs. textual lines.
2808 * The following heuristic assumes that there are 64
2810 * This is stupid and ugly, but very cheap...
2812 damage = DIV_ROUND_UP(damage, 64);
2813 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2814 dir.files[dir.nr].name = file->name;
2815 dir.files[dir.nr].changed = damage;
2820 /* This can happen even with many files, if everything was renames */
2824 /* Show all directories with more than x% of the changes */
2825 QSORT(dir.files, dir.nr, dirstat_compare);
2826 gather_dirstat(options, &dir, changed, "", 0);
2829 static void free_diffstat_info(struct diffstat_t *diffstat)
2832 for (i = 0; i < diffstat->nr; i++) {
2833 struct diffstat_file *f = diffstat->files[i];
2834 if (f->name != f->print_name)
2835 free(f->print_name);
2840 free(diffstat->files);
2843 struct checkdiff_t {
2844 const char *filename;
2846 int conflict_marker_size;
2847 struct diff_options *o;
2852 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2857 if (len < marker_size + 1)
2859 firstchar = line[0];
2860 switch (firstchar) {
2861 case '=': case '>': case '<': case '|':
2866 for (cnt = 1; cnt < marker_size; cnt++)
2867 if (line[cnt] != firstchar)
2869 /* line[1] thru line[marker_size-1] are same as firstchar */
2870 if (len < marker_size + 1 || !isspace(line[marker_size]))
2875 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2877 struct checkdiff_t *data = priv;
2878 int marker_size = data->conflict_marker_size;
2879 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2880 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2881 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2883 const char *line_prefix;
2886 line_prefix = diff_line_prefix(data->o);
2888 if (line[0] == '+') {
2891 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2893 fprintf(data->o->file,
2894 "%s%s:%d: leftover conflict marker\n",
2895 line_prefix, data->filename, data->lineno);
2897 bad = ws_check(line + 1, len - 1, data->ws_rule);
2900 data->status |= bad;
2901 err = whitespace_error_string(bad);
2902 fprintf(data->o->file, "%s%s:%d: %s.\n",
2903 line_prefix, data->filename, data->lineno, err);
2905 emit_line(data->o, set, reset, line, 1);
2906 ws_check_emit(line + 1, len - 1, data->ws_rule,
2907 data->o->file, set, reset, ws);
2908 } else if (line[0] == ' ') {
2910 } else if (line[0] == '@') {
2911 char *plus = strchr(line, '+');
2913 data->lineno = strtol(plus, NULL, 10) - 1;
2915 die("invalid diff");
2919 static unsigned char *deflate_it(char *data,
2921 unsigned long *result_size)
2924 unsigned char *deflated;
2927 git_deflate_init(&stream, zlib_compression_level);
2928 bound = git_deflate_bound(&stream, size);
2929 deflated = xmalloc(bound);
2930 stream.next_out = deflated;
2931 stream.avail_out = bound;
2933 stream.next_in = (unsigned char *)data;
2934 stream.avail_in = size;
2935 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2937 git_deflate_end(&stream);
2938 *result_size = stream.total_out;
2942 static void emit_binary_diff_body(struct diff_options *o,
2943 mmfile_t *one, mmfile_t *two)
2949 unsigned long orig_size;
2950 unsigned long delta_size;
2951 unsigned long deflate_size;
2952 unsigned long data_size;
2954 /* We could do deflated delta, or we could do just deflated two,
2955 * whichever is smaller.
2958 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2959 if (one->size && two->size) {
2960 delta = diff_delta(one->ptr, one->size,
2961 two->ptr, two->size,
2962 &delta_size, deflate_size);
2964 void *to_free = delta;
2965 orig_size = delta_size;
2966 delta = deflate_it(delta, delta_size, &delta_size);
2971 if (delta && delta_size < deflate_size) {
2972 char *s = xstrfmt("%lu", orig_size);
2973 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2978 data_size = delta_size;
2980 char *s = xstrfmt("%lu", two->size);
2981 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2986 data_size = deflate_size;
2989 /* emit data encoded in base85 */
2993 int bytes = (52 < data_size) ? 52 : data_size;
2997 line[0] = bytes + 'A' - 1;
2999 line[0] = bytes - 26 + 'a' - 1;
3000 encode_85(line + 1, cp, bytes);
3001 cp = (char *) cp + bytes;
3007 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3010 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3014 static void emit_binary_diff(struct diff_options *o,
3015 mmfile_t *one, mmfile_t *two)
3017 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3018 emit_binary_diff_body(o, one, two);
3019 emit_binary_diff_body(o, two, one);
3022 int diff_filespec_is_binary(struct diff_filespec *one)
3024 if (one->is_binary == -1) {
3025 diff_filespec_load_driver(one);
3026 if (one->driver->binary != -1)
3027 one->is_binary = one->driver->binary;
3029 if (!one->data && DIFF_FILE_VALID(one))
3030 diff_populate_filespec(one, CHECK_BINARY);
3031 if (one->is_binary == -1 && one->data)
3032 one->is_binary = buffer_is_binary(one->data,
3034 if (one->is_binary == -1)
3038 return one->is_binary;
3041 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
3043 diff_filespec_load_driver(one);
3044 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3047 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3049 if (!options->a_prefix)
3050 options->a_prefix = a;
3051 if (!options->b_prefix)
3052 options->b_prefix = b;
3055 struct userdiff_driver *get_textconv(struct diff_filespec *one)
3057 if (!DIFF_FILE_VALID(one))
3060 diff_filespec_load_driver(one);
3061 return userdiff_get_textconv(one->driver);
3064 static void builtin_diff(const char *name_a,
3066 struct diff_filespec *one,
3067 struct diff_filespec *two,
3068 const char *xfrm_msg,
3069 int must_show_header,
3070 struct diff_options *o,
3071 int complete_rewrite)
3075 char *a_one, *b_two;
3076 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3077 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3078 const char *a_prefix, *b_prefix;
3079 struct userdiff_driver *textconv_one = NULL;
3080 struct userdiff_driver *textconv_two = NULL;
3081 struct strbuf header = STRBUF_INIT;
3082 const char *line_prefix = diff_line_prefix(o);
3084 diff_set_mnemonic_prefix(o, "a/", "b/");
3085 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
3086 a_prefix = o->b_prefix;
3087 b_prefix = o->a_prefix;
3089 a_prefix = o->a_prefix;
3090 b_prefix = o->b_prefix;
3093 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3094 (!one->mode || S_ISGITLINK(one->mode)) &&
3095 (!two->mode || S_ISGITLINK(two->mode))) {
3096 show_submodule_summary(o, one->path ? one->path : two->path,
3097 &one->oid, &two->oid,
3098 two->dirty_submodule);
3100 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3101 (!one->mode || S_ISGITLINK(one->mode)) &&
3102 (!two->mode || S_ISGITLINK(two->mode))) {
3103 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3104 &one->oid, &two->oid,
3105 two->dirty_submodule);
3109 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
3110 textconv_one = get_textconv(one);
3111 textconv_two = get_textconv(two);
3114 /* Never use a non-valid filename anywhere if at all possible */
3115 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3116 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3118 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3119 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3120 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3121 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3122 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3123 if (lbl[0][0] == '/') {
3125 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3127 strbuf_addstr(&header, xfrm_msg);
3128 must_show_header = 1;
3130 else if (lbl[1][0] == '/') {
3131 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3133 strbuf_addstr(&header, xfrm_msg);
3134 must_show_header = 1;
3137 if (one->mode != two->mode) {
3138 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3139 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3140 must_show_header = 1;
3143 strbuf_addstr(&header, xfrm_msg);
3146 * we do not run diff between different kind
3149 if ((one->mode ^ two->mode) & S_IFMT)
3150 goto free_ab_and_return;
3151 if (complete_rewrite &&
3152 (textconv_one || !diff_filespec_is_binary(one)) &&
3153 (textconv_two || !diff_filespec_is_binary(two))) {
3154 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3155 header.buf, header.len, 0);
3156 strbuf_reset(&header);
3157 emit_rewrite_diff(name_a, name_b, one, two,
3158 textconv_one, textconv_two, o);
3159 o->found_changes = 1;
3160 goto free_ab_and_return;
3164 if (o->irreversible_delete && lbl[1][0] == '/') {
3165 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3167 strbuf_reset(&header);
3168 goto free_ab_and_return;
3169 } else if (!DIFF_OPT_TST(o, TEXT) &&
3170 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3171 (!textconv_two && diff_filespec_is_binary(two)) )) {
3172 struct strbuf sb = STRBUF_INIT;
3173 if (!one->data && !two->data &&
3174 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3175 !DIFF_OPT_TST(o, BINARY)) {
3176 if (!oidcmp(&one->oid, &two->oid)) {
3177 if (must_show_header)
3178 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3179 header.buf, header.len,
3181 goto free_ab_and_return;
3183 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3184 header.buf, header.len, 0);
3185 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3186 diff_line_prefix(o), lbl[0], lbl[1]);
3187 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3189 strbuf_release(&sb);
3190 goto free_ab_and_return;
3192 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3193 die("unable to read files to diff");
3194 /* Quite common confusing case */
3195 if (mf1.size == mf2.size &&
3196 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3197 if (must_show_header)
3198 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3199 header.buf, header.len, 0);
3200 goto free_ab_and_return;
3202 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3203 strbuf_reset(&header);
3204 if (DIFF_OPT_TST(o, BINARY))
3205 emit_binary_diff(o, &mf1, &mf2);
3207 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3208 diff_line_prefix(o), lbl[0], lbl[1]);
3209 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3211 strbuf_release(&sb);
3213 o->found_changes = 1;
3215 /* Crazy xdl interfaces.. */
3216 const char *diffopts = getenv("GIT_DIFF_OPTS");
3220 struct emit_callback ecbdata;
3221 const struct userdiff_funcname *pe;
3223 if (must_show_header) {
3224 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3225 header.buf, header.len, 0);
3226 strbuf_reset(&header);
3229 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3230 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
3232 pe = diff_funcname_pattern(one);
3234 pe = diff_funcname_pattern(two);
3236 memset(&xpp, 0, sizeof(xpp));
3237 memset(&xecfg, 0, sizeof(xecfg));
3238 memset(&ecbdata, 0, sizeof(ecbdata));
3239 ecbdata.label_path = lbl;
3240 ecbdata.color_diff = want_color(o->use_color);
3241 ecbdata.ws_rule = whitespace_rule(name_b);
3242 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3243 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3245 ecbdata.header = header.len ? &header : NULL;
3246 xpp.flags = o->xdl_opts;
3247 xecfg.ctxlen = o->context;
3248 xecfg.interhunkctxlen = o->interhunkcontext;
3249 xecfg.flags = XDL_EMIT_FUNCNAMES;
3250 if (DIFF_OPT_TST(o, FUNCCONTEXT))
3251 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3253 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3256 else if (skip_prefix(diffopts, "--unified=", &v))
3257 xecfg.ctxlen = strtoul(v, NULL, 10);
3258 else if (skip_prefix(diffopts, "-u", &v))
3259 xecfg.ctxlen = strtoul(v, NULL, 10);
3261 init_diff_words_data(&ecbdata, o, one, two);
3262 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3264 die("unable to generate diff for %s", one->path);
3266 free_diff_words_data(&ecbdata);
3271 xdiff_clear_find_func(&xecfg);
3275 strbuf_release(&header);
3276 diff_free_filespec_data(one);
3277 diff_free_filespec_data(two);
3283 static void builtin_diffstat(const char *name_a, const char *name_b,
3284 struct diff_filespec *one,
3285 struct diff_filespec *two,
3286 struct diffstat_t *diffstat,
3287 struct diff_options *o,
3288 struct diff_filepair *p)
3291 struct diffstat_file *data;
3293 int complete_rewrite = 0;
3295 if (!DIFF_PAIR_UNMERGED(p)) {
3296 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3297 complete_rewrite = 1;
3300 data = diffstat_add(diffstat, name_a, name_b);
3301 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3304 data->is_unmerged = 1;
3308 same_contents = !oidcmp(&one->oid, &two->oid);
3310 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
3311 data->is_binary = 1;
3312 if (same_contents) {
3316 data->added = diff_filespec_size(two);
3317 data->deleted = diff_filespec_size(one);
3321 else if (complete_rewrite) {
3322 diff_populate_filespec(one, 0);
3323 diff_populate_filespec(two, 0);
3324 data->deleted = count_lines(one->data, one->size);
3325 data->added = count_lines(two->data, two->size);
3328 else if (!same_contents) {
3329 /* Crazy xdl interfaces.. */
3333 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3334 die("unable to read files to diff");
3336 memset(&xpp, 0, sizeof(xpp));
3337 memset(&xecfg, 0, sizeof(xecfg));
3338 xpp.flags = o->xdl_opts;
3339 xecfg.ctxlen = o->context;
3340 xecfg.interhunkctxlen = o->interhunkcontext;
3341 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3343 die("unable to generate diffstat for %s", one->path);
3346 diff_free_filespec_data(one);
3347 diff_free_filespec_data(two);
3350 static void builtin_checkdiff(const char *name_a, const char *name_b,
3351 const char *attr_path,
3352 struct diff_filespec *one,
3353 struct diff_filespec *two,
3354 struct diff_options *o)
3357 struct checkdiff_t data;
3362 memset(&data, 0, sizeof(data));
3363 data.filename = name_b ? name_b : name_a;
3366 data.ws_rule = whitespace_rule(attr_path);
3367 data.conflict_marker_size = ll_merge_marker_size(attr_path);
3369 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3370 die("unable to read files to diff");
3373 * All the other codepaths check both sides, but not checking
3374 * the "old" side here is deliberate. We are checking the newly
3375 * introduced changes, and as long as the "new" side is text, we
3376 * can and should check what it introduces.
3378 if (diff_filespec_is_binary(two))
3379 goto free_and_return;
3381 /* Crazy xdl interfaces.. */
3385 memset(&xpp, 0, sizeof(xpp));
3386 memset(&xecfg, 0, sizeof(xecfg));
3387 xecfg.ctxlen = 1; /* at least one context line */
3389 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3391 die("unable to generate checkdiff for %s", one->path);
3393 if (data.ws_rule & WS_BLANK_AT_EOF) {
3394 struct emit_callback ecbdata;
3397 ecbdata.ws_rule = data.ws_rule;
3398 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3399 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3404 err = whitespace_error_string(WS_BLANK_AT_EOF);
3405 fprintf(o->file, "%s:%d: %s.\n",
3406 data.filename, blank_at_eof, err);
3407 data.status = 1; /* report errors */
3412 diff_free_filespec_data(one);
3413 diff_free_filespec_data(two);
3415 DIFF_OPT_SET(o, CHECK_FAILED);
3418 struct diff_filespec *alloc_filespec(const char *path)
3420 struct diff_filespec *spec;
3422 FLEXPTR_ALLOC_STR(spec, path, path);
3424 spec->is_binary = -1;
3428 void free_filespec(struct diff_filespec *spec)
3430 if (!--spec->count) {
3431 diff_free_filespec_data(spec);
3436 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3437 int oid_valid, unsigned short mode)
3440 spec->mode = canon_mode(mode);
3441 oidcpy(&spec->oid, oid);
3442 spec->oid_valid = oid_valid;
3447 * Given a name and sha1 pair, if the index tells us the file in
3448 * the work tree has that object contents, return true, so that
3449 * prepare_temp_file() does not have to inflate and extract.
3451 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3453 const struct cache_entry *ce;
3458 * We do not read the cache ourselves here, because the
3459 * benchmark with my previous version that always reads cache
3460 * shows that it makes things worse for diff-tree comparing
3461 * two linux-2.6 kernel trees in an already checked out work
3462 * tree. This is because most diff-tree comparisons deal with
3463 * only a small number of files, while reading the cache is
3464 * expensive for a large project, and its cost outweighs the
3465 * savings we get by not inflating the object to a temporary
3466 * file. Practically, this code only helps when we are used
3467 * by diff-cache --cached, which does read the cache before
3473 /* We want to avoid the working directory if our caller
3474 * doesn't need the data in a normal file, this system
3475 * is rather slow with its stat/open/mmap/close syscalls,
3476 * and the object is contained in a pack file. The pack
3477 * is probably already open and will be faster to obtain
3478 * the data through than the working directory. Loose
3479 * objects however would tend to be slower as they need
3480 * to be individually opened and inflated.
3482 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3486 * Similarly, if we'd have to convert the file contents anyway, that
3487 * makes the optimization not worthwhile.
3489 if (!want_file && would_convert_to_git(&the_index, name))
3493 pos = cache_name_pos(name, len);
3496 ce = active_cache[pos];
3499 * This is not the sha1 we are looking for, or
3500 * unreusable because it is not a regular file.
3502 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3506 * If ce is marked as "assume unchanged", there is no
3507 * guarantee that work tree matches what we are looking for.
3509 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3513 * If ce matches the file in the work tree, we can reuse it.
3515 if (ce_uptodate(ce) ||
3516 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3522 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3524 struct strbuf buf = STRBUF_INIT;
3527 /* Are we looking at the work tree? */
3528 if (s->dirty_submodule)
3531 strbuf_addf(&buf, "Subproject commit %s%s\n",
3532 oid_to_hex(&s->oid), dirty);
3536 strbuf_release(&buf);
3538 s->data = strbuf_detach(&buf, NULL);
3545 * While doing rename detection and pickaxe operation, we may need to
3546 * grab the data for the blob (or file) for our own in-core comparison.
3547 * diff_filespec has data and size fields for this purpose.
3549 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3551 int size_only = flags & CHECK_SIZE_ONLY;
3554 * demote FAIL to WARN to allow inspecting the situation
3555 * instead of refusing.
3557 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3561 if (!DIFF_FILE_VALID(s))
3562 die("internal error: asking to populate invalid file.");
3563 if (S_ISDIR(s->mode))
3569 if (size_only && 0 < s->size)
3572 if (S_ISGITLINK(s->mode))
3573 return diff_populate_gitlink(s, size_only);
3575 if (!s->oid_valid ||
3576 reuse_worktree_file(s->path, &s->oid, 0)) {
3577 struct strbuf buf = STRBUF_INIT;
3581 if (lstat(s->path, &st) < 0) {
3582 if (errno == ENOENT) {
3586 s->data = (char *)"";
3591 s->size = xsize_t(st.st_size);
3594 if (S_ISLNK(st.st_mode)) {
3595 struct strbuf sb = STRBUF_INIT;
3597 if (strbuf_readlink(&sb, s->path, s->size))
3600 s->data = strbuf_detach(&sb, NULL);
3606 * Even if the caller would be happy with getting
3607 * only the size, we cannot return early at this
3608 * point if the path requires us to run the content
3611 if (size_only && !would_convert_to_git(&the_index, s->path))
3615 * Note: this check uses xsize_t(st.st_size) that may
3616 * not be the true size of the blob after it goes
3617 * through convert_to_git(). This may not strictly be
3618 * correct, but the whole point of big_file_threshold
3619 * and is_binary check being that we want to avoid
3620 * opening the file and inspecting the contents, this
3623 if ((flags & CHECK_BINARY) &&
3624 s->size > big_file_threshold && s->is_binary == -1) {
3628 fd = open(s->path, O_RDONLY);
3631 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3633 s->should_munmap = 1;
3636 * Convert from working tree format to canonical git format
3638 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
3640 munmap(s->data, s->size);
3641 s->should_munmap = 0;
3642 s->data = strbuf_detach(&buf, &size);
3648 enum object_type type;
3649 if (size_only || (flags & CHECK_BINARY)) {
3650 type = sha1_object_info(s->oid.hash, &s->size);
3652 die("unable to read %s",
3653 oid_to_hex(&s->oid));
3656 if (s->size > big_file_threshold && s->is_binary == -1) {
3661 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
3663 die("unable to read %s", oid_to_hex(&s->oid));
3669 void diff_free_filespec_blob(struct diff_filespec *s)
3673 else if (s->should_munmap)
3674 munmap(s->data, s->size);
3676 if (s->should_free || s->should_munmap) {
3677 s->should_free = s->should_munmap = 0;
3682 void diff_free_filespec_data(struct diff_filespec *s)
3684 diff_free_filespec_blob(s);
3685 FREE_AND_NULL(s->cnt_data);
3688 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3691 const struct object_id *oid,
3695 struct strbuf buf = STRBUF_INIT;
3696 struct strbuf template = STRBUF_INIT;
3697 char *path_dup = xstrdup(path);
3698 const char *base = basename(path_dup);
3700 /* Generate "XXXXXX_basename.ext" */
3701 strbuf_addstr(&template, "XXXXXX_");
3702 strbuf_addstr(&template, base);
3704 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
3706 die_errno("unable to create temp-file");
3707 if (convert_to_working_tree(path,
3708 (const char *)blob, (size_t)size, &buf)) {
3712 if (write_in_full(fd, blob, size) != size)
3713 die_errno("unable to write temp-file");
3714 close_tempfile(&temp->tempfile);
3715 temp->name = get_tempfile_path(&temp->tempfile);
3716 oid_to_hex_r(temp->hex, oid);
3717 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3718 strbuf_release(&buf);
3719 strbuf_release(&template);
3723 static struct diff_tempfile *prepare_temp_file(const char *name,
3724 struct diff_filespec *one)
3726 struct diff_tempfile *temp = claim_diff_tempfile();
3728 if (!DIFF_FILE_VALID(one)) {
3730 /* A '-' entry produces this for file-2, and
3731 * a '+' entry produces this for file-1.
3733 temp->name = "/dev/null";
3734 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3735 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3739 if (!S_ISGITLINK(one->mode) &&
3741 reuse_worktree_file(name, &one->oid, 1))) {
3743 if (lstat(name, &st) < 0) {
3744 if (errno == ENOENT)
3745 goto not_a_valid_file;
3746 die_errno("stat(%s)", name);
3748 if (S_ISLNK(st.st_mode)) {
3749 struct strbuf sb = STRBUF_INIT;
3750 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3751 die_errno("readlink(%s)", name);
3752 prep_temp_blob(name, temp, sb.buf, sb.len,
3754 &one->oid : &null_oid),
3756 one->mode : S_IFLNK));
3757 strbuf_release(&sb);
3760 /* we can borrow from the file in the work tree */
3762 if (!one->oid_valid)
3763 oid_to_hex_r(temp->hex, &null_oid);
3765 oid_to_hex_r(temp->hex, &one->oid);
3766 /* Even though we may sometimes borrow the
3767 * contents from the work tree, we always want
3768 * one->mode. mode is trustworthy even when
3769 * !(one->oid_valid), as long as
3770 * DIFF_FILE_VALID(one).
3772 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3777 if (diff_populate_filespec(one, 0))
3778 die("cannot read data blob for %s", one->path);
3779 prep_temp_blob(name, temp, one->data, one->size,
3780 &one->oid, one->mode);
3785 static void add_external_diff_name(struct argv_array *argv,
3787 struct diff_filespec *df)
3789 struct diff_tempfile *temp = prepare_temp_file(name, df);
3790 argv_array_push(argv, temp->name);
3791 argv_array_push(argv, temp->hex);
3792 argv_array_push(argv, temp->mode);
3795 /* An external diff command takes:
3797 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3798 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3801 static void run_external_diff(const char *pgm,
3804 struct diff_filespec *one,
3805 struct diff_filespec *two,
3806 const char *xfrm_msg,
3807 int complete_rewrite,
3808 struct diff_options *o)
3810 struct argv_array argv = ARGV_ARRAY_INIT;
3811 struct argv_array env = ARGV_ARRAY_INIT;
3812 struct diff_queue_struct *q = &diff_queued_diff;
3814 argv_array_push(&argv, pgm);
3815 argv_array_push(&argv, name);
3818 add_external_diff_name(&argv, name, one);
3820 add_external_diff_name(&argv, name, two);
3822 add_external_diff_name(&argv, other, two);
3823 argv_array_push(&argv, other);
3824 argv_array_push(&argv, xfrm_msg);
3828 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3829 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3831 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3832 die(_("external diff died, stopping at %s"), name);
3835 argv_array_clear(&argv);
3836 argv_array_clear(&env);
3839 static int similarity_index(struct diff_filepair *p)
3841 return p->score * 100 / MAX_SCORE;
3844 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3846 if (startup_info->have_repository)
3847 return find_unique_abbrev(oid->hash, abbrev);
3849 char *hex = oid_to_hex(oid);
3851 abbrev = FALLBACK_DEFAULT_ABBREV;
3852 if (abbrev > GIT_SHA1_HEXSZ)
3853 die("BUG: oid abbreviation out of range: %d", abbrev);
3860 static void fill_metainfo(struct strbuf *msg,
3863 struct diff_filespec *one,
3864 struct diff_filespec *two,
3865 struct diff_options *o,
3866 struct diff_filepair *p,
3867 int *must_show_header,
3870 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3871 const char *reset = diff_get_color(use_color, DIFF_RESET);
3872 const char *line_prefix = diff_line_prefix(o);
3874 *must_show_header = 1;
3875 strbuf_init(msg, PATH_MAX * 2 + 300);
3876 switch (p->status) {
3877 case DIFF_STATUS_COPIED:
3878 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3879 line_prefix, set, similarity_index(p));
3880 strbuf_addf(msg, "%s\n%s%scopy from ",
3881 reset, line_prefix, set);
3882 quote_c_style(name, msg, NULL, 0);
3883 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3884 quote_c_style(other, msg, NULL, 0);
3885 strbuf_addf(msg, "%s\n", reset);
3887 case DIFF_STATUS_RENAMED:
3888 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3889 line_prefix, set, similarity_index(p));
3890 strbuf_addf(msg, "%s\n%s%srename from ",
3891 reset, line_prefix, set);
3892 quote_c_style(name, msg, NULL, 0);
3893 strbuf_addf(msg, "%s\n%s%srename to ",
3894 reset, line_prefix, set);
3895 quote_c_style(other, msg, NULL, 0);
3896 strbuf_addf(msg, "%s\n", reset);
3898 case DIFF_STATUS_MODIFIED:
3900 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3902 set, similarity_index(p), reset);
3907 *must_show_header = 0;
3909 if (one && two && oidcmp(&one->oid, &two->oid)) {
3910 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3912 if (DIFF_OPT_TST(o, BINARY)) {
3914 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3915 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3918 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3919 diff_abbrev_oid(&one->oid, abbrev),
3920 diff_abbrev_oid(&two->oid, abbrev));
3921 if (one->mode == two->mode)
3922 strbuf_addf(msg, " %06o", one->mode);
3923 strbuf_addf(msg, "%s\n", reset);
3927 static void run_diff_cmd(const char *pgm,
3930 const char *attr_path,
3931 struct diff_filespec *one,
3932 struct diff_filespec *two,
3934 struct diff_options *o,
3935 struct diff_filepair *p)
3937 const char *xfrm_msg = NULL;
3938 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3939 int must_show_header = 0;
3942 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3943 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3944 if (drv && drv->external)
3945 pgm = drv->external;
3950 * don't use colors when the header is intended for an
3951 * external diff driver
3953 fill_metainfo(msg, name, other, one, two, o, p,
3955 want_color(o->use_color) && !pgm);
3956 xfrm_msg = msg->len ? msg->buf : NULL;
3960 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3961 complete_rewrite, o);
3965 builtin_diff(name, other ? other : name,
3966 one, two, xfrm_msg, must_show_header,
3967 o, complete_rewrite);
3969 fprintf(o->file, "* Unmerged path %s\n", name);
3972 static void diff_fill_oid_info(struct diff_filespec *one)
3974 if (DIFF_FILE_VALID(one)) {
3975 if (!one->oid_valid) {
3977 if (one->is_stdin) {
3981 if (lstat(one->path, &st) < 0)
3982 die_errno("stat '%s'", one->path);
3983 if (index_path(one->oid.hash, one->path, &st, 0))
3984 die("cannot hash %s", one->path);
3991 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3993 /* Strip the prefix but do not molest /dev/null and absolute paths */
3994 if (*namep && **namep != '/') {
3995 *namep += prefix_length;
3999 if (*otherp && **otherp != '/') {
4000 *otherp += prefix_length;
4001 if (**otherp == '/')
4006 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4008 const char *pgm = external_diff();
4010 struct diff_filespec *one = p->one;
4011 struct diff_filespec *two = p->two;
4014 const char *attr_path;
4017 other = (strcmp(name, two->path) ? two->path : NULL);
4019 if (o->prefix_length)
4020 strip_prefix(o->prefix_length, &name, &other);
4022 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
4025 if (DIFF_PAIR_UNMERGED(p)) {
4026 run_diff_cmd(pgm, name, NULL, attr_path,
4027 NULL, NULL, NULL, o, p);
4031 diff_fill_oid_info(one);
4032 diff_fill_oid_info(two);
4035 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4036 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4038 * a filepair that changes between file and symlink
4039 * needs to be split into deletion and creation.
4041 struct diff_filespec *null = alloc_filespec(two->path);
4042 run_diff_cmd(NULL, name, other, attr_path,
4043 one, null, &msg, o, p);
4045 strbuf_release(&msg);
4047 null = alloc_filespec(one->path);
4048 run_diff_cmd(NULL, name, other, attr_path,
4049 null, two, &msg, o, p);
4053 run_diff_cmd(pgm, name, other, attr_path,
4054 one, two, &msg, o, p);
4056 strbuf_release(&msg);
4059 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4060 struct diffstat_t *diffstat)
4065 if (DIFF_PAIR_UNMERGED(p)) {
4067 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
4071 name = p->one->path;
4072 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4074 if (o->prefix_length)
4075 strip_prefix(o->prefix_length, &name, &other);
4077 diff_fill_oid_info(p->one);
4078 diff_fill_oid_info(p->two);
4080 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
4083 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4087 const char *attr_path;
4089 if (DIFF_PAIR_UNMERGED(p)) {
4094 name = p->one->path;
4095 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4096 attr_path = other ? other : name;
4098 if (o->prefix_length)
4099 strip_prefix(o->prefix_length, &name, &other);
4101 diff_fill_oid_info(p->one);
4102 diff_fill_oid_info(p->two);
4104 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4107 void diff_setup(struct diff_options *options)
4109 memcpy(options, &default_diff_options, sizeof(*options));
4111 options->file = stdout;
4113 options->abbrev = DEFAULT_ABBREV;
4114 options->line_termination = '\n';
4115 options->break_opt = -1;
4116 options->rename_limit = -1;
4117 options->dirstat_permille = diff_dirstat_permille_default;
4118 options->context = diff_context_default;
4119 options->interhunkcontext = diff_interhunk_context_default;
4120 options->ws_error_highlight = ws_error_highlight_default;
4121 DIFF_OPT_SET(options, RENAME_EMPTY);
4123 /* pathchange left =NULL by default */
4124 options->change = diff_change;
4125 options->add_remove = diff_addremove;
4126 options->use_color = diff_use_color_default;
4127 options->detect_rename = diff_detect_rename_default;
4128 options->xdl_opts |= diff_algorithm;
4129 if (diff_indent_heuristic)
4130 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4132 options->orderfile = diff_order_file_cfg;
4134 if (diff_no_prefix) {
4135 options->a_prefix = options->b_prefix = "";
4136 } else if (!diff_mnemonic_prefix) {
4137 options->a_prefix = "a/";
4138 options->b_prefix = "b/";
4141 options->color_moved = diff_color_moved_default;
4144 void diff_setup_done(struct diff_options *options)
4148 if (options->set_default)
4149 options->set_default(options);
4151 if (options->output_format & DIFF_FORMAT_NAME)
4153 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
4155 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
4157 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
4160 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4163 * Most of the time we can say "there are changes"
4164 * only by checking if there are changed paths, but
4165 * --ignore-whitespace* options force us to look
4169 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
4170 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
4171 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
4172 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
4174 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
4176 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
4177 options->detect_rename = DIFF_DETECT_COPY;
4179 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
4180 options->prefix = NULL;
4181 if (options->prefix)
4182 options->prefix_length = strlen(options->prefix);
4184 options->prefix_length = 0;
4186 if (options->output_format & (DIFF_FORMAT_NAME |
4187 DIFF_FORMAT_NAME_STATUS |
4188 DIFF_FORMAT_CHECKDIFF |
4189 DIFF_FORMAT_NO_OUTPUT))
4190 options->output_format &= ~(DIFF_FORMAT_RAW |
4191 DIFF_FORMAT_NUMSTAT |
4192 DIFF_FORMAT_DIFFSTAT |
4193 DIFF_FORMAT_SHORTSTAT |
4194 DIFF_FORMAT_DIRSTAT |
4195 DIFF_FORMAT_SUMMARY |
4199 * These cases always need recursive; we do not drop caller-supplied
4200 * recursive bits for other formats here.
4202 if (options->output_format & (DIFF_FORMAT_PATCH |
4203 DIFF_FORMAT_NUMSTAT |
4204 DIFF_FORMAT_DIFFSTAT |
4205 DIFF_FORMAT_SHORTSTAT |
4206 DIFF_FORMAT_DIRSTAT |
4207 DIFF_FORMAT_SUMMARY |
4208 DIFF_FORMAT_CHECKDIFF))
4209 DIFF_OPT_SET(options, RECURSIVE);
4211 * Also pickaxe would not work very well if you do not say recursive
4213 if (options->pickaxe)
4214 DIFF_OPT_SET(options, RECURSIVE);
4216 * When patches are generated, submodules diffed against the work tree
4217 * must be checked for dirtiness too so it can be shown in the output
4219 if (options->output_format & DIFF_FORMAT_PATCH)
4220 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
4222 if (options->detect_rename && options->rename_limit < 0)
4223 options->rename_limit = diff_rename_limit_default;
4224 if (options->setup & DIFF_SETUP_USE_CACHE) {
4226 /* read-cache does not die even when it fails
4227 * so it is safe for us to do this here. Also
4228 * it does not smudge active_cache or active_nr
4229 * when it fails, so we do not have to worry about
4230 * cleaning it up ourselves either.
4234 if (40 < options->abbrev)
4235 options->abbrev = 40; /* full */
4238 * It does not make sense to show the first hit we happened
4239 * to have found. It does not make sense not to return with
4240 * exit code in such a case either.
4242 if (DIFF_OPT_TST(options, QUICK)) {
4243 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4244 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4247 options->diff_path_counter = 0;
4249 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
4250 die(_("--follow requires exactly one pathspec"));
4252 if (!options->use_color || external_diff())
4253 options->color_moved = 0;
4256 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4266 if (c == arg_short) {
4270 if (val && isdigit(c)) {
4272 int n = strtoul(arg, &end, 10);
4283 eq = strchrnul(arg, '=');
4285 if (!len || strncmp(arg, arg_long, len))
4290 if (!isdigit(*++eq))
4292 n = strtoul(eq, &end, 10);
4300 static int diff_scoreopt_parse(const char *opt);
4302 static inline int short_opt(char opt, const char **argv,
4303 const char **optarg)
4305 const char *arg = argv[0];
4306 if (arg[0] != '-' || arg[1] != opt)
4308 if (arg[2] != '\0') {
4313 die("Option '%c' requires a value", opt);
4318 int parse_long_opt(const char *opt, const char **argv,
4319 const char **optarg)
4321 const char *arg = argv[0];
4322 if (!skip_prefix(arg, "--", &arg))
4324 if (!skip_prefix(arg, opt, &arg))
4326 if (*arg == '=') { /* stuck form: --option=value */
4332 /* separate form: --option value */
4334 die("Option '--%s' requires a value", opt);
4339 static int stat_opt(struct diff_options *options, const char **av)
4341 const char *arg = av[0];
4343 int width = options->stat_width;
4344 int name_width = options->stat_name_width;
4345 int graph_width = options->stat_graph_width;
4346 int count = options->stat_count;
4349 if (!skip_prefix(arg, "--stat", &arg))
4350 die("BUG: stat option does not begin with --stat: %s", arg);
4355 if (skip_prefix(arg, "-width", &arg)) {
4357 width = strtoul(arg + 1, &end, 10);
4358 else if (!*arg && !av[1])
4359 die_want_option("--stat-width");
4361 width = strtoul(av[1], &end, 10);
4364 } else if (skip_prefix(arg, "-name-width", &arg)) {
4366 name_width = strtoul(arg + 1, &end, 10);
4367 else if (!*arg && !av[1])
4368 die_want_option("--stat-name-width");
4370 name_width = strtoul(av[1], &end, 10);
4373 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4375 graph_width = strtoul(arg + 1, &end, 10);
4376 else if (!*arg && !av[1])
4377 die_want_option("--stat-graph-width");
4379 graph_width = strtoul(av[1], &end, 10);
4382 } else if (skip_prefix(arg, "-count", &arg)) {
4384 count = strtoul(arg + 1, &end, 10);
4385 else if (!*arg && !av[1])
4386 die_want_option("--stat-count");
4388 count = strtoul(av[1], &end, 10);
4394 width = strtoul(arg+1, &end, 10);
4396 name_width = strtoul(end+1, &end, 10);
4398 count = strtoul(end+1, &end, 10);
4401 /* Important! This checks all the error cases! */
4404 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4405 options->stat_name_width = name_width;
4406 options->stat_graph_width = graph_width;
4407 options->stat_width = width;
4408 options->stat_count = count;
4412 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4414 struct strbuf errmsg = STRBUF_INIT;
4415 if (parse_dirstat_params(options, params, &errmsg))
4416 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4418 strbuf_release(&errmsg);
4420 * The caller knows a dirstat-related option is given from the command
4421 * line; allow it to say "return this_function();"
4423 options->output_format |= DIFF_FORMAT_DIRSTAT;
4427 static int parse_submodule_opt(struct diff_options *options, const char *value)
4429 if (parse_submodule_params(options, value))
4430 die(_("Failed to parse --submodule option parameter: '%s'"),
4435 static const char diff_status_letters[] = {
4438 DIFF_STATUS_DELETED,
4439 DIFF_STATUS_MODIFIED,
4440 DIFF_STATUS_RENAMED,
4441 DIFF_STATUS_TYPE_CHANGED,
4442 DIFF_STATUS_UNKNOWN,
4443 DIFF_STATUS_UNMERGED,
4444 DIFF_STATUS_FILTER_AON,
4445 DIFF_STATUS_FILTER_BROKEN,
4449 static unsigned int filter_bit['Z' + 1];
4451 static void prepare_filter_bits(void)
4455 if (!filter_bit[DIFF_STATUS_ADDED]) {
4456 for (i = 0; diff_status_letters[i]; i++)
4457 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4461 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4463 return opt->filter & filter_bit[(int) status];
4466 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4470 prepare_filter_bits();
4473 * If there is a negation e.g. 'd' in the input, and we haven't
4474 * initialized the filter field with another --diff-filter, start
4475 * from full set of bits, except for AON.
4478 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4479 if (optch < 'a' || 'z' < optch)
4481 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4482 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4487 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4491 if ('a' <= optch && optch <= 'z') {
4493 optch = toupper(optch);
4498 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4502 opt->filter &= ~bit;
4509 static void enable_patch_output(int *fmt) {
4510 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4511 *fmt |= DIFF_FORMAT_PATCH;
4514 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4516 int val = parse_ws_error_highlight(arg);
4519 error("unknown value after ws-error-highlight=%.*s",
4523 opt->ws_error_highlight = val;
4527 int diff_opt_parse(struct diff_options *options,
4528 const char **av, int ac, const char *prefix)
4530 const char *arg = av[0];
4537 /* Output format options */
4538 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4539 || opt_arg(arg, 'U', "unified", &options->context))
4540 enable_patch_output(&options->output_format);
4541 else if (!strcmp(arg, "--raw"))
4542 options->output_format |= DIFF_FORMAT_RAW;
4543 else if (!strcmp(arg, "--patch-with-raw")) {
4544 enable_patch_output(&options->output_format);
4545 options->output_format |= DIFF_FORMAT_RAW;
4546 } else if (!strcmp(arg, "--numstat"))
4547 options->output_format |= DIFF_FORMAT_NUMSTAT;
4548 else if (!strcmp(arg, "--shortstat"))
4549 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4550 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
4551 return parse_dirstat_opt(options, "");
4552 else if (skip_prefix(arg, "-X", &arg))
4553 return parse_dirstat_opt(options, arg);
4554 else if (skip_prefix(arg, "--dirstat=", &arg))
4555 return parse_dirstat_opt(options, arg);
4556 else if (!strcmp(arg, "--cumulative"))
4557 return parse_dirstat_opt(options, "cumulative");
4558 else if (!strcmp(arg, "--dirstat-by-file"))
4559 return parse_dirstat_opt(options, "files");
4560 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
4561 parse_dirstat_opt(options, "files");
4562 return parse_dirstat_opt(options, arg);
4564 else if (!strcmp(arg, "--check"))
4565 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4566 else if (!strcmp(arg, "--summary"))
4567 options->output_format |= DIFF_FORMAT_SUMMARY;
4568 else if (!strcmp(arg, "--patch-with-stat")) {
4569 enable_patch_output(&options->output_format);
4570 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4571 } else if (!strcmp(arg, "--name-only"))
4572 options->output_format |= DIFF_FORMAT_NAME;
4573 else if (!strcmp(arg, "--name-status"))
4574 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4575 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4576 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4577 else if (starts_with(arg, "--stat"))
4578 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4579 return stat_opt(options, av);
4581 /* renames options */
4582 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
4583 !strcmp(arg, "--break-rewrites")) {
4584 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4585 return error("invalid argument to -B: %s", arg+2);
4587 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
4588 !strcmp(arg, "--find-renames")) {
4589 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4590 return error("invalid argument to -M: %s", arg+2);
4591 options->detect_rename = DIFF_DETECT_RENAME;
4593 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4594 options->irreversible_delete = 1;
4596 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
4597 !strcmp(arg, "--find-copies")) {
4598 if (options->detect_rename == DIFF_DETECT_COPY)
4599 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4600 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4601 return error("invalid argument to -C: %s", arg+2);
4602 options->detect_rename = DIFF_DETECT_COPY;
4604 else if (!strcmp(arg, "--no-renames"))
4605 options->detect_rename = 0;
4606 else if (!strcmp(arg, "--rename-empty"))
4607 DIFF_OPT_SET(options, RENAME_EMPTY);
4608 else if (!strcmp(arg, "--no-rename-empty"))
4609 DIFF_OPT_CLR(options, RENAME_EMPTY);
4610 else if (!strcmp(arg, "--relative"))
4611 DIFF_OPT_SET(options, RELATIVE_NAME);
4612 else if (skip_prefix(arg, "--relative=", &arg)) {
4613 DIFF_OPT_SET(options, RELATIVE_NAME);
4614 options->prefix = arg;
4618 else if (!strcmp(arg, "--minimal"))
4619 DIFF_XDL_SET(options, NEED_MINIMAL);
4620 else if (!strcmp(arg, "--no-minimal"))
4621 DIFF_XDL_CLR(options, NEED_MINIMAL);
4622 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4623 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4624 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4625 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4626 else if (!strcmp(arg, "--ignore-space-at-eol"))
4627 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4628 else if (!strcmp(arg, "--ignore-blank-lines"))
4629 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4630 else if (!strcmp(arg, "--indent-heuristic"))
4631 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4632 else if (!strcmp(arg, "--no-indent-heuristic"))
4633 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4634 else if (!strcmp(arg, "--patience"))
4635 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4636 else if (!strcmp(arg, "--histogram"))
4637 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4638 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4639 long value = parse_algorithm_value(optarg);
4641 return error("option diff-algorithm accepts \"myers\", "
4642 "\"minimal\", \"patience\" and \"histogram\"");
4643 /* clear out previous settings */
4644 DIFF_XDL_CLR(options, NEED_MINIMAL);
4645 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4646 options->xdl_opts |= value;
4651 else if (!strcmp(arg, "--binary")) {
4652 enable_patch_output(&options->output_format);
4653 DIFF_OPT_SET(options, BINARY);
4655 else if (!strcmp(arg, "--full-index"))
4656 DIFF_OPT_SET(options, FULL_INDEX);
4657 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4658 DIFF_OPT_SET(options, TEXT);
4659 else if (!strcmp(arg, "-R"))
4660 DIFF_OPT_SET(options, REVERSE_DIFF);
4661 else if (!strcmp(arg, "--find-copies-harder"))
4662 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4663 else if (!strcmp(arg, "--follow"))
4664 DIFF_OPT_SET(options, FOLLOW_RENAMES);
4665 else if (!strcmp(arg, "--no-follow")) {
4666 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
4667 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
4668 } else if (!strcmp(arg, "--color"))
4669 options->use_color = 1;
4670 else if (skip_prefix(arg, "--color=", &arg)) {
4671 int value = git_config_colorbool(NULL, arg);
4673 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4674 options->use_color = value;
4676 else if (!strcmp(arg, "--no-color"))
4677 options->use_color = 0;
4678 else if (!strcmp(arg, "--color-moved")) {
4679 if (diff_color_moved_default)
4680 options->color_moved = diff_color_moved_default;
4681 if (options->color_moved == COLOR_MOVED_NO)
4682 options->color_moved = COLOR_MOVED_DEFAULT;
4683 } else if (!strcmp(arg, "--no-color-moved"))
4684 options->color_moved = COLOR_MOVED_NO;
4685 else if (skip_prefix(arg, "--color-moved=", &arg)) {
4686 int cm = parse_color_moved(arg);
4688 die("bad --color-moved argument: %s", arg);
4689 options->color_moved = cm;
4690 } else if (!strcmp(arg, "--color-words")) {
4691 options->use_color = 1;
4692 options->word_diff = DIFF_WORDS_COLOR;
4694 else if (skip_prefix(arg, "--color-words=", &arg)) {
4695 options->use_color = 1;
4696 options->word_diff = DIFF_WORDS_COLOR;
4697 options->word_regex = arg;
4699 else if (!strcmp(arg, "--word-diff")) {
4700 if (options->word_diff == DIFF_WORDS_NONE)
4701 options->word_diff = DIFF_WORDS_PLAIN;
4703 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4704 if (!strcmp(arg, "plain"))
4705 options->word_diff = DIFF_WORDS_PLAIN;
4706 else if (!strcmp(arg, "color")) {
4707 options->use_color = 1;
4708 options->word_diff = DIFF_WORDS_COLOR;
4710 else if (!strcmp(arg, "porcelain"))
4711 options->word_diff = DIFF_WORDS_PORCELAIN;
4712 else if (!strcmp(arg, "none"))
4713 options->word_diff = DIFF_WORDS_NONE;
4715 die("bad --word-diff argument: %s", arg);
4717 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4718 if (options->word_diff == DIFF_WORDS_NONE)
4719 options->word_diff = DIFF_WORDS_PLAIN;
4720 options->word_regex = optarg;
4723 else if (!strcmp(arg, "--exit-code"))
4724 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4725 else if (!strcmp(arg, "--quiet"))
4726 DIFF_OPT_SET(options, QUICK);
4727 else if (!strcmp(arg, "--ext-diff"))
4728 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
4729 else if (!strcmp(arg, "--no-ext-diff"))
4730 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
4731 else if (!strcmp(arg, "--textconv"))
4732 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
4733 else if (!strcmp(arg, "--no-textconv"))
4734 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
4735 else if (!strcmp(arg, "--ignore-submodules")) {
4736 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4737 handle_ignore_submodules_arg(options, "all");
4738 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
4739 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4740 handle_ignore_submodules_arg(options, arg);
4741 } else if (!strcmp(arg, "--submodule"))
4742 options->submodule_format = DIFF_SUBMODULE_LOG;
4743 else if (skip_prefix(arg, "--submodule=", &arg))
4744 return parse_submodule_opt(options, arg);
4745 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4746 return parse_ws_error_highlight_opt(options, arg);
4747 else if (!strcmp(arg, "--ita-invisible-in-index"))
4748 options->ita_invisible_in_index = 1;
4749 else if (!strcmp(arg, "--ita-visible-in-index"))
4750 options->ita_invisible_in_index = 0;
4753 else if (!strcmp(arg, "-z"))
4754 options->line_termination = 0;
4755 else if ((argcount = short_opt('l', av, &optarg))) {
4756 options->rename_limit = strtoul(optarg, NULL, 10);
4759 else if ((argcount = short_opt('S', av, &optarg))) {
4760 options->pickaxe = optarg;
4761 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4763 } else if ((argcount = short_opt('G', av, &optarg))) {
4764 options->pickaxe = optarg;
4765 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4768 else if (!strcmp(arg, "--pickaxe-all"))
4769 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4770 else if (!strcmp(arg, "--pickaxe-regex"))
4771 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4772 else if ((argcount = short_opt('O', av, &optarg))) {
4773 options->orderfile = prefix_filename(prefix, optarg);
4776 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4777 int offending = parse_diff_filter_opt(optarg, options);
4779 die("unknown change class '%c' in --diff-filter=%s",
4783 else if (!strcmp(arg, "--no-abbrev"))
4784 options->abbrev = 0;
4785 else if (!strcmp(arg, "--abbrev"))
4786 options->abbrev = DEFAULT_ABBREV;
4787 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4788 options->abbrev = strtoul(arg, NULL, 10);
4789 if (options->abbrev < MINIMUM_ABBREV)
4790 options->abbrev = MINIMUM_ABBREV;
4791 else if (40 < options->abbrev)
4792 options->abbrev = 40;
4794 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4795 options->a_prefix = optarg;
4798 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4799 options->line_prefix = optarg;
4800 options->line_prefix_length = strlen(options->line_prefix);
4801 graph_setup_line_prefix(options);
4804 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4805 options->b_prefix = optarg;
4808 else if (!strcmp(arg, "--no-prefix"))
4809 options->a_prefix = options->b_prefix = "";
4810 else if (opt_arg(arg, '\0', "inter-hunk-context",
4811 &options->interhunkcontext))
4813 else if (!strcmp(arg, "-W"))
4814 DIFF_OPT_SET(options, FUNCCONTEXT);
4815 else if (!strcmp(arg, "--function-context"))
4816 DIFF_OPT_SET(options, FUNCCONTEXT);
4817 else if (!strcmp(arg, "--no-function-context"))
4818 DIFF_OPT_CLR(options, FUNCCONTEXT);
4819 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4820 char *path = prefix_filename(prefix, optarg);
4821 options->file = xfopen(path, "w");
4822 options->close_file = 1;
4823 if (options->use_color != GIT_COLOR_ALWAYS)
4824 options->use_color = GIT_COLOR_NEVER;
4832 int parse_rename_score(const char **cp_p)
4834 unsigned long num, scale;
4836 const char *cp = *cp_p;
4843 if ( !dot && ch == '.' ) {
4846 } else if ( ch == '%' ) {
4847 scale = dot ? scale*100 : 100;
4848 cp++; /* % is always at the end */
4850 } else if ( ch >= '0' && ch <= '9' ) {
4851 if ( scale < 100000 ) {
4853 num = (num*10) + (ch-'0');
4862 /* user says num divided by scale and we say internally that
4863 * is MAX_SCORE * num / scale.
4865 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4868 static int diff_scoreopt_parse(const char *opt)
4870 int opt1, opt2, cmd;
4876 /* convert the long-form arguments into short-form versions */
4877 if (skip_prefix(opt, "break-rewrites", &opt)) {
4878 if (*opt == 0 || *opt++ == '=')
4880 } else if (skip_prefix(opt, "find-copies", &opt)) {
4881 if (*opt == 0 || *opt++ == '=')
4883 } else if (skip_prefix(opt, "find-renames", &opt)) {
4884 if (*opt == 0 || *opt++ == '=')
4888 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4889 return -1; /* that is not a -M, -C, or -B option */
4891 opt1 = parse_rename_score(&opt);
4897 else if (*opt != '/')
4898 return -1; /* we expect -B80/99 or -B80 */
4901 opt2 = parse_rename_score(&opt);
4906 return opt1 | (opt2 << 16);
4909 struct diff_queue_struct diff_queued_diff;
4911 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4913 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4914 queue->queue[queue->nr++] = dp;
4917 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4918 struct diff_filespec *one,
4919 struct diff_filespec *two)
4921 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4929 void diff_free_filepair(struct diff_filepair *p)
4931 free_filespec(p->one);
4932 free_filespec(p->two);
4936 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4941 if (len == GIT_SHA1_HEXSZ)
4942 return oid_to_hex(oid);
4944 abbrev = diff_abbrev_oid(oid, len);
4945 abblen = strlen(abbrev);
4948 * In well-behaved cases, where the abbbreviated result is the
4949 * same as the requested length, append three dots after the
4950 * abbreviation (hence the whole logic is limited to the case
4951 * where abblen < 37); when the actual abbreviated result is a
4952 * bit longer than the requested length, we reduce the number
4953 * of dots so that they match the well-behaved ones. However,
4954 * if the actual abbreviation is longer than the requested
4955 * length by more than three, we give up on aligning, and add
4956 * three dots anyway, to indicate that the output is not the
4957 * full object name. Yes, this may be suboptimal, but this
4958 * appears only in "diff --raw --abbrev" output and it is not
4959 * worth the effort to change it now. Note that this would
4960 * likely to work fine when the automatic sizing of default
4961 * abbreviation length is used--we would be fed -1 in "len" in
4962 * that case, and will end up always appending three-dots, but
4963 * the automatic sizing is supposed to give abblen that ensures
4964 * uniqueness across all objects (statistically speaking).
4966 if (abblen < GIT_SHA1_HEXSZ - 3) {
4967 static char hex[GIT_MAX_HEXSZ + 1];
4968 if (len < abblen && abblen <= len + 2)
4969 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4971 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4975 return oid_to_hex(oid);
4978 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4980 int line_termination = opt->line_termination;
4981 int inter_name_termination = line_termination ? '\t' : '\0';
4983 fprintf(opt->file, "%s", diff_line_prefix(opt));
4984 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4985 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4986 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4987 fprintf(opt->file, "%s ",
4988 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4991 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4992 inter_name_termination);
4994 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4997 if (p->status == DIFF_STATUS_COPIED ||
4998 p->status == DIFF_STATUS_RENAMED) {
4999 const char *name_a, *name_b;
5000 name_a = p->one->path;
5001 name_b = p->two->path;
5002 strip_prefix(opt->prefix_length, &name_a, &name_b);
5003 write_name_quoted(name_a, opt->file, inter_name_termination);
5004 write_name_quoted(name_b, opt->file, line_termination);
5006 const char *name_a, *name_b;
5007 name_a = p->one->mode ? p->one->path : p->two->path;
5009 strip_prefix(opt->prefix_length, &name_a, &name_b);
5010 write_name_quoted(name_a, opt->file, line_termination);
5014 int diff_unmodified_pair(struct diff_filepair *p)
5016 /* This function is written stricter than necessary to support
5017 * the currently implemented transformers, but the idea is to
5018 * let transformers to produce diff_filepairs any way they want,
5019 * and filter and clean them up here before producing the output.
5021 struct diff_filespec *one = p->one, *two = p->two;
5023 if (DIFF_PAIR_UNMERGED(p))
5024 return 0; /* unmerged is interesting */
5026 /* deletion, addition, mode or type change
5027 * and rename are all interesting.
5029 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5030 DIFF_PAIR_MODE_CHANGED(p) ||
5031 strcmp(one->path, two->path))
5034 /* both are valid and point at the same path. that is, we are
5035 * dealing with a change.
5037 if (one->oid_valid && two->oid_valid &&
5038 !oidcmp(&one->oid, &two->oid) &&
5039 !one->dirty_submodule && !two->dirty_submodule)
5040 return 1; /* no change */
5041 if (!one->oid_valid && !two->oid_valid)
5042 return 1; /* both look at the same file on the filesystem. */
5046 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5048 if (diff_unmodified_pair(p))
5051 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5052 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5053 return; /* no tree diffs in patch format */
5058 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5059 struct diffstat_t *diffstat)
5061 if (diff_unmodified_pair(p))
5064 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5065 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5066 return; /* no useful stat for tree diffs */
5068 run_diffstat(p, o, diffstat);
5071 static void diff_flush_checkdiff(struct diff_filepair *p,
5072 struct diff_options *o)
5074 if (diff_unmodified_pair(p))
5077 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5078 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5079 return; /* nothing to check in tree diffs */
5081 run_checkdiff(p, o);
5084 int diff_queue_is_empty(void)
5086 struct diff_queue_struct *q = &diff_queued_diff;
5088 for (i = 0; i < q->nr; i++)
5089 if (!diff_unmodified_pair(q->queue[i]))
5095 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5097 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5100 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5102 s->oid_valid ? oid_to_hex(&s->oid) : "");
5103 fprintf(stderr, "queue[%d] %s size %lu\n",
5108 void diff_debug_filepair(const struct diff_filepair *p, int i)
5110 diff_debug_filespec(p->one, i, "one");
5111 diff_debug_filespec(p->two, i, "two");
5112 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5113 p->score, p->status ? p->status : '?',
5114 p->one->rename_used, p->broken_pair);
5117 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5121 fprintf(stderr, "%s\n", msg);
5122 fprintf(stderr, "q->nr = %d\n", q->nr);
5123 for (i = 0; i < q->nr; i++) {
5124 struct diff_filepair *p = q->queue[i];
5125 diff_debug_filepair(p, i);
5130 static void diff_resolve_rename_copy(void)
5133 struct diff_filepair *p;
5134 struct diff_queue_struct *q = &diff_queued_diff;
5136 diff_debug_queue("resolve-rename-copy", q);
5138 for (i = 0; i < q->nr; i++) {
5140 p->status = 0; /* undecided */
5141 if (DIFF_PAIR_UNMERGED(p))
5142 p->status = DIFF_STATUS_UNMERGED;
5143 else if (!DIFF_FILE_VALID(p->one))
5144 p->status = DIFF_STATUS_ADDED;
5145 else if (!DIFF_FILE_VALID(p->two))
5146 p->status = DIFF_STATUS_DELETED;
5147 else if (DIFF_PAIR_TYPE_CHANGED(p))
5148 p->status = DIFF_STATUS_TYPE_CHANGED;
5150 /* from this point on, we are dealing with a pair
5151 * whose both sides are valid and of the same type, i.e.
5152 * either in-place edit or rename/copy edit.
5154 else if (DIFF_PAIR_RENAME(p)) {
5156 * A rename might have re-connected a broken
5157 * pair up, causing the pathnames to be the
5158 * same again. If so, that's not a rename at
5159 * all, just a modification..
5161 * Otherwise, see if this source was used for
5162 * multiple renames, in which case we decrement
5163 * the count, and call it a copy.
5165 if (!strcmp(p->one->path, p->two->path))
5166 p->status = DIFF_STATUS_MODIFIED;
5167 else if (--p->one->rename_used > 0)
5168 p->status = DIFF_STATUS_COPIED;
5170 p->status = DIFF_STATUS_RENAMED;
5172 else if (oidcmp(&p->one->oid, &p->two->oid) ||
5173 p->one->mode != p->two->mode ||
5174 p->one->dirty_submodule ||
5175 p->two->dirty_submodule ||
5176 is_null_oid(&p->one->oid))
5177 p->status = DIFF_STATUS_MODIFIED;
5179 /* This is a "no-change" entry and should not
5180 * happen anymore, but prepare for broken callers.
5182 error("feeding unmodified %s to diffcore",
5184 p->status = DIFF_STATUS_UNKNOWN;
5187 diff_debug_queue("resolve-rename-copy done", q);
5190 static int check_pair_status(struct diff_filepair *p)
5192 switch (p->status) {
5193 case DIFF_STATUS_UNKNOWN:
5196 die("internal error in diff-resolve-rename-copy");
5202 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5204 int fmt = opt->output_format;
5206 if (fmt & DIFF_FORMAT_CHECKDIFF)
5207 diff_flush_checkdiff(p, opt);
5208 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5209 diff_flush_raw(p, opt);
5210 else if (fmt & DIFF_FORMAT_NAME) {
5211 const char *name_a, *name_b;
5212 name_a = p->two->path;
5214 strip_prefix(opt->prefix_length, &name_a, &name_b);
5215 fprintf(opt->file, "%s", diff_line_prefix(opt));
5216 write_name_quoted(name_a, opt->file, opt->line_termination);
5220 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5222 struct strbuf sb = STRBUF_INIT;
5224 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5226 strbuf_addf(&sb, " %s ", newdelete);
5228 quote_c_style(fs->path, &sb, NULL, 0);
5229 strbuf_addch(&sb, '\n');
5230 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5232 strbuf_release(&sb);
5235 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5238 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5239 struct strbuf sb = STRBUF_INIT;
5240 strbuf_addf(&sb, " mode change %06o => %06o",
5241 p->one->mode, p->two->mode);
5243 strbuf_addch(&sb, ' ');
5244 quote_c_style(p->two->path, &sb, NULL, 0);
5246 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5248 strbuf_release(&sb);
5252 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5253 struct diff_filepair *p)
5255 struct strbuf sb = STRBUF_INIT;
5256 char *names = pprint_rename(p->one->path, p->two->path);
5257 strbuf_addf(&sb, " %s %s (%d%%)\n",
5258 renamecopy, names, similarity_index(p));
5260 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5262 show_mode_change(opt, p, 0);
5265 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5268 case DIFF_STATUS_DELETED:
5269 show_file_mode_name(opt, "delete", p->one);
5271 case DIFF_STATUS_ADDED:
5272 show_file_mode_name(opt, "create", p->two);
5274 case DIFF_STATUS_COPIED:
5275 show_rename_copy(opt, "copy", p);
5277 case DIFF_STATUS_RENAMED:
5278 show_rename_copy(opt, "rename", p);
5282 struct strbuf sb = STRBUF_INIT;
5283 strbuf_addstr(&sb, " rewrite ");
5284 quote_c_style(p->two->path, &sb, NULL, 0);
5285 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5286 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5289 show_mode_change(opt, p, !p->score);
5299 static int remove_space(char *line, int len)
5305 for (i = 0; i < len; i++)
5306 if (!isspace((c = line[i])))
5312 static void patch_id_consume(void *priv, char *line, unsigned long len)
5314 struct patch_id_t *data = priv;
5317 /* Ignore line numbers when computing the SHA1 of the patch */
5318 if (starts_with(line, "@@ -"))
5321 new_len = remove_space(line, len);
5323 git_SHA1_Update(data->ctx, line, new_len);
5324 data->patchlen += new_len;
5327 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5329 git_SHA1_Update(ctx, str, strlen(str));
5332 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5334 /* large enough for 2^32 in octal */
5336 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5337 git_SHA1_Update(ctx, buf, len);
5340 /* returns 0 upon success, and writes result into sha1 */
5341 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5343 struct diff_queue_struct *q = &diff_queued_diff;
5346 struct patch_id_t data;
5348 git_SHA1_Init(&ctx);
5349 memset(&data, 0, sizeof(struct patch_id_t));
5352 for (i = 0; i < q->nr; i++) {
5356 struct diff_filepair *p = q->queue[i];
5359 memset(&xpp, 0, sizeof(xpp));
5360 memset(&xecfg, 0, sizeof(xecfg));
5362 return error("internal diff status error");
5363 if (p->status == DIFF_STATUS_UNKNOWN)
5365 if (diff_unmodified_pair(p))
5367 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5368 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5370 if (DIFF_PAIR_UNMERGED(p))
5373 diff_fill_oid_info(p->one);
5374 diff_fill_oid_info(p->two);
5376 len1 = remove_space(p->one->path, strlen(p->one->path));
5377 len2 = remove_space(p->two->path, strlen(p->two->path));
5378 patch_id_add_string(&ctx, "diff--git");
5379 patch_id_add_string(&ctx, "a/");
5380 git_SHA1_Update(&ctx, p->one->path, len1);
5381 patch_id_add_string(&ctx, "b/");
5382 git_SHA1_Update(&ctx, p->two->path, len2);
5384 if (p->one->mode == 0) {
5385 patch_id_add_string(&ctx, "newfilemode");
5386 patch_id_add_mode(&ctx, p->two->mode);
5387 patch_id_add_string(&ctx, "---/dev/null");
5388 patch_id_add_string(&ctx, "+++b/");
5389 git_SHA1_Update(&ctx, p->two->path, len2);
5390 } else if (p->two->mode == 0) {
5391 patch_id_add_string(&ctx, "deletedfilemode");
5392 patch_id_add_mode(&ctx, p->one->mode);
5393 patch_id_add_string(&ctx, "---a/");
5394 git_SHA1_Update(&ctx, p->one->path, len1);
5395 patch_id_add_string(&ctx, "+++/dev/null");
5397 patch_id_add_string(&ctx, "---a/");
5398 git_SHA1_Update(&ctx, p->one->path, len1);
5399 patch_id_add_string(&ctx, "+++b/");
5400 git_SHA1_Update(&ctx, p->two->path, len2);
5403 if (diff_header_only)
5406 if (fill_mmfile(&mf1, p->one) < 0 ||
5407 fill_mmfile(&mf2, p->two) < 0)
5408 return error("unable to read files to diff");
5410 if (diff_filespec_is_binary(p->one) ||
5411 diff_filespec_is_binary(p->two)) {
5412 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5414 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5422 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5424 return error("unable to generate patch-id diff for %s",
5428 git_SHA1_Final(oid->hash, &ctx);
5432 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5434 struct diff_queue_struct *q = &diff_queued_diff;
5436 int result = diff_get_patch_id(options, oid, diff_header_only);
5438 for (i = 0; i < q->nr; i++)
5439 diff_free_filepair(q->queue[i]);
5442 DIFF_QUEUE_CLEAR(q);
5447 static int is_summary_empty(const struct diff_queue_struct *q)
5451 for (i = 0; i < q->nr; i++) {
5452 const struct diff_filepair *p = q->queue[i];
5454 switch (p->status) {
5455 case DIFF_STATUS_DELETED:
5456 case DIFF_STATUS_ADDED:
5457 case DIFF_STATUS_COPIED:
5458 case DIFF_STATUS_RENAMED:
5463 if (p->one->mode && p->two->mode &&
5464 p->one->mode != p->two->mode)
5472 static const char rename_limit_warning[] =
5473 N_("inexact rename detection was skipped due to too many files.");
5475 static const char degrade_cc_to_c_warning[] =
5476 N_("only found copies from modified paths due to too many files.");
5478 static const char rename_limit_advice[] =
5479 N_("you may want to set your %s variable to at least "
5480 "%d and retry the command.");
5482 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5485 warning(_(degrade_cc_to_c_warning));
5487 warning(_(rename_limit_warning));
5490 if (0 < needed && needed < 32767)
5491 warning(_(rename_limit_advice), varname, needed);
5494 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5497 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5498 struct diff_queue_struct *q = &diff_queued_diff;
5500 if (WSEH_NEW & WS_RULE_MASK)
5501 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5504 o->emitted_symbols = &esm;
5506 for (i = 0; i < q->nr; i++) {
5507 struct diff_filepair *p = q->queue[i];
5508 if (check_pair_status(p))
5509 diff_flush_patch(p, o);
5512 if (o->emitted_symbols) {
5513 if (o->color_moved) {
5514 struct hashmap add_lines, del_lines;
5516 hashmap_init(&del_lines,
5517 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5518 hashmap_init(&add_lines,
5519 (hashmap_cmp_fn)moved_entry_cmp, o, 0);
5521 add_lines_to_move_detection(o, &add_lines, &del_lines);
5522 mark_color_as_moved(o, &add_lines, &del_lines);
5523 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5526 hashmap_free(&add_lines, 0);
5527 hashmap_free(&del_lines, 0);
5530 for (i = 0; i < esm.nr; i++)
5531 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5533 for (i = 0; i < esm.nr; i++)
5534 free((void *)esm.buf[i].line);
5539 void diff_flush(struct diff_options *options)
5541 struct diff_queue_struct *q = &diff_queued_diff;
5542 int i, output_format = options->output_format;
5544 int dirstat_by_line = 0;
5547 * Order: raw, stat, summary, patch
5548 * or: name/name-status/checkdiff (other bits clear)
5553 if (output_format & (DIFF_FORMAT_RAW |
5555 DIFF_FORMAT_NAME_STATUS |
5556 DIFF_FORMAT_CHECKDIFF)) {
5557 for (i = 0; i < q->nr; i++) {
5558 struct diff_filepair *p = q->queue[i];
5559 if (check_pair_status(p))
5560 flush_one_pair(p, options);
5565 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
5566 dirstat_by_line = 1;
5568 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5570 struct diffstat_t diffstat;
5572 memset(&diffstat, 0, sizeof(struct diffstat_t));
5573 for (i = 0; i < q->nr; i++) {
5574 struct diff_filepair *p = q->queue[i];
5575 if (check_pair_status(p))
5576 diff_flush_stat(p, options, &diffstat);
5578 if (output_format & DIFF_FORMAT_NUMSTAT)
5579 show_numstat(&diffstat, options);
5580 if (output_format & DIFF_FORMAT_DIFFSTAT)
5581 show_stats(&diffstat, options);
5582 if (output_format & DIFF_FORMAT_SHORTSTAT)
5583 show_shortstats(&diffstat, options);
5584 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5585 show_dirstat_by_line(&diffstat, options);
5586 free_diffstat_info(&diffstat);
5589 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5590 show_dirstat(options);
5592 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5593 for (i = 0; i < q->nr; i++) {
5594 diff_summary(options, q->queue[i]);
5599 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5600 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
5601 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5603 * run diff_flush_patch for the exit status. setting
5604 * options->file to /dev/null should be safe, because we
5605 * aren't supposed to produce any output anyway.
5607 if (options->close_file)
5608 fclose(options->file);
5609 options->file = xfopen("/dev/null", "w");
5610 options->close_file = 1;
5611 options->color_moved = 0;
5612 for (i = 0; i < q->nr; i++) {
5613 struct diff_filepair *p = q->queue[i];
5614 if (check_pair_status(p))
5615 diff_flush_patch(p, options);
5616 if (options->found_changes)
5621 if (output_format & DIFF_FORMAT_PATCH) {
5623 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5624 if (options->stat_sep)
5625 /* attach patch instead of inline */
5626 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5630 diff_flush_patch_all_file_pairs(options);
5633 if (output_format & DIFF_FORMAT_CALLBACK)
5634 options->format_callback(q, options, options->format_callback_data);
5636 for (i = 0; i < q->nr; i++)
5637 diff_free_filepair(q->queue[i]);
5640 DIFF_QUEUE_CLEAR(q);
5641 if (options->close_file)
5642 fclose(options->file);
5645 * Report the content-level differences with HAS_CHANGES;
5646 * diff_addremove/diff_change does not set the bit when
5647 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5649 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5650 if (options->found_changes)
5651 DIFF_OPT_SET(options, HAS_CHANGES);
5653 DIFF_OPT_CLR(options, HAS_CHANGES);
5657 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5659 return (((p->status == DIFF_STATUS_MODIFIED) &&
5661 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5663 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5664 ((p->status != DIFF_STATUS_MODIFIED) &&
5665 filter_bit_tst(p->status, options)));
5668 static void diffcore_apply_filter(struct diff_options *options)
5671 struct diff_queue_struct *q = &diff_queued_diff;
5672 struct diff_queue_struct outq;
5674 DIFF_QUEUE_CLEAR(&outq);
5676 if (!options->filter)
5679 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5681 for (i = found = 0; !found && i < q->nr; i++) {
5682 if (match_filter(options, q->queue[i]))
5688 /* otherwise we will clear the whole queue
5689 * by copying the empty outq at the end of this
5690 * function, but first clear the current entries
5693 for (i = 0; i < q->nr; i++)
5694 diff_free_filepair(q->queue[i]);
5697 /* Only the matching ones */
5698 for (i = 0; i < q->nr; i++) {
5699 struct diff_filepair *p = q->queue[i];
5700 if (match_filter(options, p))
5703 diff_free_filepair(p);
5710 /* Check whether two filespecs with the same mode and size are identical */
5711 static int diff_filespec_is_identical(struct diff_filespec *one,
5712 struct diff_filespec *two)
5714 if (S_ISGITLINK(one->mode))
5716 if (diff_populate_filespec(one, 0))
5718 if (diff_populate_filespec(two, 0))
5720 return !memcmp(one->data, two->data, one->size);
5723 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5725 if (p->done_skip_stat_unmatch)
5726 return p->skip_stat_unmatch_result;
5728 p->done_skip_stat_unmatch = 1;
5729 p->skip_stat_unmatch_result = 0;
5731 * 1. Entries that come from stat info dirtiness
5732 * always have both sides (iow, not create/delete),
5733 * one side of the object name is unknown, with
5734 * the same mode and size. Keep the ones that
5735 * do not match these criteria. They have real
5738 * 2. At this point, the file is known to be modified,
5739 * with the same mode and size, and the object
5740 * name of one side is unknown. Need to inspect
5741 * the identical contents.
5743 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5744 !DIFF_FILE_VALID(p->two) ||
5745 (p->one->oid_valid && p->two->oid_valid) ||
5746 (p->one->mode != p->two->mode) ||
5747 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5748 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5749 (p->one->size != p->two->size) ||
5750 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5751 p->skip_stat_unmatch_result = 1;
5752 return p->skip_stat_unmatch_result;
5755 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5758 struct diff_queue_struct *q = &diff_queued_diff;
5759 struct diff_queue_struct outq;
5760 DIFF_QUEUE_CLEAR(&outq);
5762 for (i = 0; i < q->nr; i++) {
5763 struct diff_filepair *p = q->queue[i];
5765 if (diff_filespec_check_stat_unmatch(p))
5769 * The caller can subtract 1 from skip_stat_unmatch
5770 * to determine how many paths were dirty only
5771 * due to stat info mismatch.
5773 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
5774 diffopt->skip_stat_unmatch++;
5775 diff_free_filepair(p);
5782 static int diffnamecmp(const void *a_, const void *b_)
5784 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5785 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5786 const char *name_a, *name_b;
5788 name_a = a->one ? a->one->path : a->two->path;
5789 name_b = b->one ? b->one->path : b->two->path;
5790 return strcmp(name_a, name_b);
5793 void diffcore_fix_diff_index(struct diff_options *options)
5795 struct diff_queue_struct *q = &diff_queued_diff;
5796 QSORT(q->queue, q->nr, diffnamecmp);
5799 void diffcore_std(struct diff_options *options)
5801 /* NOTE please keep the following in sync with diff_tree_combined() */
5802 if (options->skip_stat_unmatch)
5803 diffcore_skip_stat_unmatch(options);
5804 if (!options->found_follow) {
5805 /* See try_to_follow_renames() in tree-diff.c */
5806 if (options->break_opt != -1)
5807 diffcore_break(options->break_opt);
5808 if (options->detect_rename)
5809 diffcore_rename(options);
5810 if (options->break_opt != -1)
5811 diffcore_merge_broken();
5813 if (options->pickaxe)
5814 diffcore_pickaxe(options);
5815 if (options->orderfile)
5816 diffcore_order(options->orderfile);
5817 if (!options->found_follow)
5818 /* See try_to_follow_renames() in tree-diff.c */
5819 diff_resolve_rename_copy();
5820 diffcore_apply_filter(options);
5822 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5823 DIFF_OPT_SET(options, HAS_CHANGES);
5825 DIFF_OPT_CLR(options, HAS_CHANGES);
5827 options->found_follow = 0;
5830 int diff_result_code(struct diff_options *opt, int status)
5834 diff_warn_rename_limit("diff.renameLimit",
5835 opt->needed_rename_limit,
5836 opt->degraded_cc_to_c);
5837 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5838 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5840 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5841 DIFF_OPT_TST(opt, HAS_CHANGES))
5843 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5844 DIFF_OPT_TST(opt, CHECK_FAILED))
5849 int diff_can_quit_early(struct diff_options *opt)
5851 return (DIFF_OPT_TST(opt, QUICK) &&
5853 DIFF_OPT_TST(opt, HAS_CHANGES));
5857 * Shall changes to this submodule be ignored?
5859 * Submodule changes can be configured to be ignored separately for each path,
5860 * but that configuration can be overridden from the command line.
5862 static int is_submodule_ignored(const char *path, struct diff_options *options)
5865 unsigned orig_flags = options->flags;
5866 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
5867 set_diffopt_flags_from_submodule_config(options, path);
5868 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
5870 options->flags = orig_flags;
5874 void diff_addremove(struct diff_options *options,
5875 int addremove, unsigned mode,
5876 const struct object_id *oid,
5878 const char *concatpath, unsigned dirty_submodule)
5880 struct diff_filespec *one, *two;
5882 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5885 /* This may look odd, but it is a preparation for
5886 * feeding "there are unchanged files which should
5887 * not produce diffs, but when you are doing copy
5888 * detection you would need them, so here they are"
5889 * entries to the diff-core. They will be prefixed
5890 * with something like '=' or '*' (I haven't decided
5891 * which but should not make any difference).
5892 * Feeding the same new and old to diff_change()
5893 * also has the same effect.
5894 * Before the final output happens, they are pruned after
5895 * merged into rename/copy pairs as appropriate.
5897 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5898 addremove = (addremove == '+' ? '-' :
5899 addremove == '-' ? '+' : addremove);
5901 if (options->prefix &&
5902 strncmp(concatpath, options->prefix, options->prefix_length))
5905 one = alloc_filespec(concatpath);
5906 two = alloc_filespec(concatpath);
5908 if (addremove != '+')
5909 fill_filespec(one, oid, oid_valid, mode);
5910 if (addremove != '-') {
5911 fill_filespec(two, oid, oid_valid, mode);
5912 two->dirty_submodule = dirty_submodule;
5915 diff_queue(&diff_queued_diff, one, two);
5916 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5917 DIFF_OPT_SET(options, HAS_CHANGES);
5920 void diff_change(struct diff_options *options,
5921 unsigned old_mode, unsigned new_mode,
5922 const struct object_id *old_oid,
5923 const struct object_id *new_oid,
5924 int old_oid_valid, int new_oid_valid,
5925 const char *concatpath,
5926 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5928 struct diff_filespec *one, *two;
5929 struct diff_filepair *p;
5931 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5932 is_submodule_ignored(concatpath, options))
5935 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5936 SWAP(old_mode, new_mode);
5937 SWAP(old_oid, new_oid);
5938 SWAP(old_oid_valid, new_oid_valid);
5939 SWAP(old_dirty_submodule, new_dirty_submodule);
5942 if (options->prefix &&
5943 strncmp(concatpath, options->prefix, options->prefix_length))
5946 one = alloc_filespec(concatpath);
5947 two = alloc_filespec(concatpath);
5948 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5949 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5950 one->dirty_submodule = old_dirty_submodule;
5951 two->dirty_submodule = new_dirty_submodule;
5952 p = diff_queue(&diff_queued_diff, one, two);
5954 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5957 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5958 !diff_filespec_check_stat_unmatch(p))
5961 DIFF_OPT_SET(options, HAS_CHANGES);
5964 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5966 struct diff_filepair *pair;
5967 struct diff_filespec *one, *two;
5969 if (options->prefix &&
5970 strncmp(path, options->prefix, options->prefix_length))
5973 one = alloc_filespec(path);
5974 two = alloc_filespec(path);
5975 pair = diff_queue(&diff_queued_diff, one, two);
5976 pair->is_unmerged = 1;
5980 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5983 struct diff_tempfile *temp;
5984 const char *argv[3];
5985 const char **arg = argv;
5986 struct child_process child = CHILD_PROCESS_INIT;
5987 struct strbuf buf = STRBUF_INIT;
5990 temp = prepare_temp_file(spec->path, spec);
5992 *arg++ = temp->name;
5995 child.use_shell = 1;
5998 if (start_command(&child)) {
6003 if (strbuf_read(&buf, child.out, 0) < 0)
6004 err = error("error reading from textconv command '%s'", pgm);
6007 if (finish_command(&child) || err) {
6008 strbuf_release(&buf);
6014 return strbuf_detach(&buf, outsize);
6017 size_t fill_textconv(struct userdiff_driver *driver,
6018 struct diff_filespec *df,
6024 if (!DIFF_FILE_VALID(df)) {
6028 if (diff_populate_filespec(df, 0))
6029 die("unable to read files to diff");
6034 if (!driver->textconv)
6035 die("BUG: fill_textconv called with non-textconv driver");
6037 if (driver->textconv_cache && df->oid_valid) {
6038 *outbuf = notes_cache_get(driver->textconv_cache,
6045 *outbuf = run_textconv(driver->textconv, df, &size);
6047 die("unable to read files to diff");
6049 if (driver->textconv_cache && df->oid_valid) {
6050 /* ignore errors, as we might be in a readonly repository */
6051 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6054 * we could save up changes and flush them all at the end,
6055 * but we would need an extra call after all diffing is done.
6056 * Since generating a cache entry is the slow path anyway,
6057 * this extra overhead probably isn't a big deal.
6059 notes_cache_write(driver->textconv_cache);
6065 int textconv_object(const char *path,
6067 const struct object_id *oid,
6070 unsigned long *buf_size)
6072 struct diff_filespec *df;
6073 struct userdiff_driver *textconv;
6075 df = alloc_filespec(path);
6076 fill_filespec(df, oid, oid_valid, mode);
6077 textconv = get_textconv(df);
6083 *buf_size = fill_textconv(textconv, df, buf);
6088 void setup_diff_pager(struct diff_options *opt)
6091 * If the user asked for our exit code, then either they want --quiet
6092 * or --exit-code. We should definitely not bother with a pager in the
6093 * former case, as we will generate no output. Since we still properly
6094 * report our exit code even when a pager is run, we _could_ run a
6095 * pager with --exit-code. But since we have not done so historically,
6096 * and because it is easy to find people oneline advising "git diff
6097 * --exit-code" in hooks and other scripts, we do not do so.
6099 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
6100 check_pager_config("diff") != 0)