2 * Copyright (C) 2005 Junio C Hamano
11 #include "xdiff-interface.h"
14 #include "run-command.h"
16 #include "object-store.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
23 #include "string-list.h"
27 #include "parse-options.h"
29 #include "promisor-remote.h"
31 #ifdef NO_FAST_WORKING_DIRECTORY
32 #define FAST_WORKING_DIRECTORY 0
34 #define FAST_WORKING_DIRECTORY 1
37 static int diff_detect_rename_default;
38 static int diff_indent_heuristic = 1;
39 static int diff_rename_limit_default = 400;
40 static int diff_suppress_blank_empty;
41 static int diff_use_color_default = -1;
42 static int diff_color_moved_default;
43 static int diff_color_moved_ws_default;
44 static int diff_context_default = 3;
45 static int diff_interhunk_context_default;
46 static const char *diff_word_regex_cfg;
47 static const char *external_diff_cmd_cfg;
48 static const char *diff_order_file_cfg;
49 int diff_auto_refresh_index = 1;
50 static int diff_mnemonic_prefix;
51 static int diff_no_prefix;
52 static int diff_relative;
53 static int diff_stat_graph_width;
54 static int diff_dirstat_permille_default = 30;
55 static struct diff_options default_diff_options;
56 static long diff_algorithm;
57 static unsigned ws_error_highlight_default = WSEH_NEW;
59 static char diff_colors[][COLOR_MAXLEN] = {
61 GIT_COLOR_NORMAL, /* CONTEXT */
62 GIT_COLOR_BOLD, /* METAINFO */
63 GIT_COLOR_CYAN, /* FRAGINFO */
64 GIT_COLOR_RED, /* OLD */
65 GIT_COLOR_GREEN, /* NEW */
66 GIT_COLOR_YELLOW, /* COMMIT */
67 GIT_COLOR_BG_RED, /* WHITESPACE */
68 GIT_COLOR_NORMAL, /* FUNCINFO */
69 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
70 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
71 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
72 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
73 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
74 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
75 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
76 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
77 GIT_COLOR_FAINT, /* CONTEXT_DIM */
78 GIT_COLOR_FAINT_RED, /* OLD_DIM */
79 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
80 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
81 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
82 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
85 static const char *color_diff_slots[] = {
86 [DIFF_CONTEXT] = "context",
87 [DIFF_METAINFO] = "meta",
88 [DIFF_FRAGINFO] = "frag",
89 [DIFF_FILE_OLD] = "old",
90 [DIFF_FILE_NEW] = "new",
91 [DIFF_COMMIT] = "commit",
92 [DIFF_WHITESPACE] = "whitespace",
93 [DIFF_FUNCINFO] = "func",
94 [DIFF_FILE_OLD_MOVED] = "oldMoved",
95 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
96 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
97 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
98 [DIFF_FILE_NEW_MOVED] = "newMoved",
99 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
100 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
101 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
102 [DIFF_CONTEXT_DIM] = "contextDimmed",
103 [DIFF_FILE_OLD_DIM] = "oldDimmed",
104 [DIFF_FILE_NEW_DIM] = "newDimmed",
105 [DIFF_CONTEXT_BOLD] = "contextBold",
106 [DIFF_FILE_OLD_BOLD] = "oldBold",
107 [DIFF_FILE_NEW_BOLD] = "newBold",
110 define_list_config_array_extra(color_diff_slots, {"plain"});
112 static int parse_diff_color_slot(const char *var)
114 if (!strcasecmp(var, "plain"))
116 return LOOKUP_CONFIG(color_diff_slots, var);
119 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
120 struct strbuf *errmsg)
122 char *params_copy = xstrdup(params_string);
123 struct string_list params = STRING_LIST_INIT_NODUP;
128 string_list_split_in_place(¶ms, params_copy, ',', -1);
129 for (i = 0; i < params.nr; i++) {
130 const char *p = params.items[i].string;
131 if (!strcmp(p, "changes")) {
132 options->flags.dirstat_by_line = 0;
133 options->flags.dirstat_by_file = 0;
134 } else if (!strcmp(p, "lines")) {
135 options->flags.dirstat_by_line = 1;
136 options->flags.dirstat_by_file = 0;
137 } else if (!strcmp(p, "files")) {
138 options->flags.dirstat_by_line = 0;
139 options->flags.dirstat_by_file = 1;
140 } else if (!strcmp(p, "noncumulative")) {
141 options->flags.dirstat_cumulative = 0;
142 } else if (!strcmp(p, "cumulative")) {
143 options->flags.dirstat_cumulative = 1;
144 } else if (isdigit(*p)) {
146 int permille = strtoul(p, &end, 10) * 10;
147 if (*end == '.' && isdigit(*++end)) {
148 /* only use first digit */
149 permille += *end - '0';
150 /* .. and ignore any further digits */
151 while (isdigit(*++end))
155 options->dirstat_permille = permille;
157 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
162 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
167 string_list_clear(¶ms, 0);
172 static int parse_submodule_params(struct diff_options *options, const char *value)
174 if (!strcmp(value, "log"))
175 options->submodule_format = DIFF_SUBMODULE_LOG;
176 else if (!strcmp(value, "short"))
177 options->submodule_format = DIFF_SUBMODULE_SHORT;
178 else if (!strcmp(value, "diff"))
179 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
181 * Please update $__git_diff_submodule_formats in
182 * git-completion.bash when you add new formats.
189 int git_config_rename(const char *var, const char *value)
192 return DIFF_DETECT_RENAME;
193 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
194 return DIFF_DETECT_COPY;
195 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
198 long parse_algorithm_value(const char *value)
202 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
204 else if (!strcasecmp(value, "minimal"))
205 return XDF_NEED_MINIMAL;
206 else if (!strcasecmp(value, "patience"))
207 return XDF_PATIENCE_DIFF;
208 else if (!strcasecmp(value, "histogram"))
209 return XDF_HISTOGRAM_DIFF;
211 * Please update $__git_diff_algorithms in git-completion.bash
212 * when you add new algorithms.
217 static int parse_one_token(const char **arg, const char *token)
220 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
227 static int parse_ws_error_highlight(const char *arg)
229 const char *orig_arg = arg;
233 if (parse_one_token(&arg, "none"))
235 else if (parse_one_token(&arg, "default"))
237 else if (parse_one_token(&arg, "all"))
238 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
239 else if (parse_one_token(&arg, "new"))
241 else if (parse_one_token(&arg, "old"))
243 else if (parse_one_token(&arg, "context"))
246 return -1 - (int)(arg - orig_arg);
255 * These are to give UI layer defaults.
256 * The core-level commands such as git-diff-files should
257 * never be affected by the setting of diff.renames
258 * the user happens to have in the configuration file.
260 void init_diff_ui_defaults(void)
262 diff_detect_rename_default = DIFF_DETECT_RENAME;
265 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
267 if (!strcmp(var, "diff.indentheuristic"))
268 diff_indent_heuristic = git_config_bool(var, value);
272 static int parse_color_moved(const char *arg)
274 switch (git_parse_maybe_bool(arg)) {
276 return COLOR_MOVED_NO;
278 return COLOR_MOVED_DEFAULT;
283 if (!strcmp(arg, "no"))
284 return COLOR_MOVED_NO;
285 else if (!strcmp(arg, "plain"))
286 return COLOR_MOVED_PLAIN;
287 else if (!strcmp(arg, "blocks"))
288 return COLOR_MOVED_BLOCKS;
289 else if (!strcmp(arg, "zebra"))
290 return COLOR_MOVED_ZEBRA;
291 else if (!strcmp(arg, "default"))
292 return COLOR_MOVED_DEFAULT;
293 else if (!strcmp(arg, "dimmed-zebra"))
294 return COLOR_MOVED_ZEBRA_DIM;
295 else if (!strcmp(arg, "dimmed_zebra"))
296 return COLOR_MOVED_ZEBRA_DIM;
298 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
301 static unsigned parse_color_moved_ws(const char *arg)
304 struct string_list l = STRING_LIST_INIT_DUP;
305 struct string_list_item *i;
307 string_list_split(&l, arg, ',', -1);
309 for_each_string_list_item(i, &l) {
310 struct strbuf sb = STRBUF_INIT;
311 strbuf_addstr(&sb, i->string);
314 if (!strcmp(sb.buf, "no"))
316 else if (!strcmp(sb.buf, "ignore-space-change"))
317 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
318 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
319 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
320 else if (!strcmp(sb.buf, "ignore-all-space"))
321 ret |= XDF_IGNORE_WHITESPACE;
322 else if (!strcmp(sb.buf, "allow-indentation-change"))
323 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
325 ret |= COLOR_MOVED_WS_ERROR;
326 error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), sb.buf);
332 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
333 (ret & XDF_WHITESPACE_FLAGS)) {
334 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
335 ret |= COLOR_MOVED_WS_ERROR;
338 string_list_clear(&l, 0);
343 int git_diff_ui_config(const char *var, const char *value, void *cb)
345 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
346 diff_use_color_default = git_config_colorbool(var, value);
349 if (!strcmp(var, "diff.colormoved")) {
350 int cm = parse_color_moved(value);
353 diff_color_moved_default = cm;
356 if (!strcmp(var, "diff.colormovedws")) {
357 unsigned cm = parse_color_moved_ws(value);
358 if (cm & COLOR_MOVED_WS_ERROR)
360 diff_color_moved_ws_default = cm;
363 if (!strcmp(var, "diff.context")) {
364 diff_context_default = git_config_int(var, value);
365 if (diff_context_default < 0)
369 if (!strcmp(var, "diff.interhunkcontext")) {
370 diff_interhunk_context_default = git_config_int(var, value);
371 if (diff_interhunk_context_default < 0)
375 if (!strcmp(var, "diff.renames")) {
376 diff_detect_rename_default = git_config_rename(var, value);
379 if (!strcmp(var, "diff.autorefreshindex")) {
380 diff_auto_refresh_index = git_config_bool(var, value);
383 if (!strcmp(var, "diff.mnemonicprefix")) {
384 diff_mnemonic_prefix = git_config_bool(var, value);
387 if (!strcmp(var, "diff.noprefix")) {
388 diff_no_prefix = git_config_bool(var, value);
391 if (!strcmp(var, "diff.relative")) {
392 diff_relative = git_config_bool(var, value);
395 if (!strcmp(var, "diff.statgraphwidth")) {
396 diff_stat_graph_width = git_config_int(var, value);
399 if (!strcmp(var, "diff.external"))
400 return git_config_string(&external_diff_cmd_cfg, var, value);
401 if (!strcmp(var, "diff.wordregex"))
402 return git_config_string(&diff_word_regex_cfg, var, value);
403 if (!strcmp(var, "diff.orderfile"))
404 return git_config_pathname(&diff_order_file_cfg, var, value);
406 if (!strcmp(var, "diff.ignoresubmodules"))
407 handle_ignore_submodules_arg(&default_diff_options, value);
409 if (!strcmp(var, "diff.submodule")) {
410 if (parse_submodule_params(&default_diff_options, value))
411 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
416 if (!strcmp(var, "diff.algorithm")) {
417 diff_algorithm = parse_algorithm_value(value);
418 if (diff_algorithm < 0)
423 if (git_color_config(var, value, cb) < 0)
426 return git_diff_basic_config(var, value, cb);
429 int git_diff_basic_config(const char *var, const char *value, void *cb)
433 if (!strcmp(var, "diff.renamelimit")) {
434 diff_rename_limit_default = git_config_int(var, value);
438 if (userdiff_config(var, value) < 0)
441 if (skip_prefix(var, "diff.color.", &name) ||
442 skip_prefix(var, "color.diff.", &name)) {
443 int slot = parse_diff_color_slot(name);
447 return config_error_nonbool(var);
448 return color_parse(value, diff_colors[slot]);
451 if (!strcmp(var, "diff.wserrorhighlight")) {
452 int val = parse_ws_error_highlight(value);
455 ws_error_highlight_default = val;
459 /* like GNU diff's --suppress-blank-empty option */
460 if (!strcmp(var, "diff.suppressblankempty") ||
461 /* for backwards compatibility */
462 !strcmp(var, "diff.suppress-blank-empty")) {
463 diff_suppress_blank_empty = git_config_bool(var, value);
467 if (!strcmp(var, "diff.dirstat")) {
468 struct strbuf errmsg = STRBUF_INIT;
469 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
470 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
471 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
473 strbuf_release(&errmsg);
474 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
478 if (git_diff_heuristic_config(var, value, cb) < 0)
481 return git_default_config(var, value, cb);
484 static char *quote_two(const char *one, const char *two)
486 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
487 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
488 struct strbuf res = STRBUF_INIT;
490 if (need_one + need_two) {
491 strbuf_addch(&res, '"');
492 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
493 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
494 strbuf_addch(&res, '"');
496 strbuf_addstr(&res, one);
497 strbuf_addstr(&res, two);
499 return strbuf_detach(&res, NULL);
502 static const char *external_diff(void)
504 static const char *external_diff_cmd = NULL;
505 static int done_preparing = 0;
508 return external_diff_cmd;
509 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
510 if (!external_diff_cmd)
511 external_diff_cmd = external_diff_cmd_cfg;
513 return external_diff_cmd;
517 * Keep track of files used for diffing. Sometimes such an entry
518 * refers to a temporary file, sometimes to an existing file, and
519 * sometimes to "/dev/null".
521 static struct diff_tempfile {
523 * filename external diff should read from, or NULL if this
524 * entry is currently not in use:
528 char hex[GIT_MAX_HEXSZ + 1];
532 * If this diff_tempfile instance refers to a temporary file,
533 * this tempfile object is used to manage its lifetime.
535 struct tempfile *tempfile;
538 struct emit_callback {
541 int blank_at_eof_in_preimage;
542 int blank_at_eof_in_postimage;
544 int lno_in_postimage;
545 const char **label_path;
546 struct diff_words_data *diff_words;
547 struct diff_options *opt;
548 struct strbuf *header;
551 static int count_lines(const char *data, int size)
553 int count, ch, completely_empty = 1, nl_just_seen = 0;
560 completely_empty = 0;
564 completely_empty = 0;
567 if (completely_empty)
570 count++; /* no trailing newline */
574 static int fill_mmfile(struct repository *r, mmfile_t *mf,
575 struct diff_filespec *one)
577 if (!DIFF_FILE_VALID(one)) {
578 mf->ptr = (char *)""; /* does not matter */
582 else if (diff_populate_filespec(r, one, NULL))
586 mf->size = one->size;
590 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
591 static unsigned long diff_filespec_size(struct repository *r,
592 struct diff_filespec *one)
594 struct diff_populate_filespec_options dpf_options = {
595 .check_size_only = 1,
598 if (!DIFF_FILE_VALID(one))
600 diff_populate_filespec(r, one, &dpf_options);
604 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
607 long size = mf->size;
612 ptr += size - 1; /* pointing at the very end */
614 ; /* incomplete line */
616 ptr--; /* skip the last LF */
617 while (mf->ptr < ptr) {
619 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
620 if (*prev_eol == '\n')
622 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
630 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
631 struct emit_callback *ecbdata)
634 unsigned ws_rule = ecbdata->ws_rule;
635 l1 = count_trailing_blank(mf1, ws_rule);
636 l2 = count_trailing_blank(mf2, ws_rule);
638 ecbdata->blank_at_eof_in_preimage = 0;
639 ecbdata->blank_at_eof_in_postimage = 0;
642 at = count_lines(mf1->ptr, mf1->size);
643 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
645 at = count_lines(mf2->ptr, mf2->size);
646 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
649 static void emit_line_0(struct diff_options *o,
650 const char *set_sign, const char *set, unsigned reverse, const char *reset,
651 int first, const char *line, int len)
653 int has_trailing_newline, has_trailing_carriage_return;
654 int needs_reset = 0; /* at the end of the line */
655 FILE *file = o->file;
657 fputs(diff_line_prefix(o), file);
659 has_trailing_newline = (len > 0 && line[len-1] == '\n');
660 if (has_trailing_newline)
663 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
664 if (has_trailing_carriage_return)
670 if (reverse && want_color(o->use_color)) {
671 fputs(GIT_COLOR_REVERSE, file);
676 fputs(set_sign, file);
687 if (set_sign && set != set_sign)
692 fwrite(line, len, 1, file);
693 needs_reset = 1; /* 'line' may contain color codes. */
698 if (has_trailing_carriage_return)
700 if (has_trailing_newline)
704 static void emit_line(struct diff_options *o, const char *set, const char *reset,
705 const char *line, int len)
707 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
711 DIFF_SYMBOL_BINARY_DIFF_HEADER,
712 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
713 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
714 DIFF_SYMBOL_BINARY_DIFF_BODY,
715 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
716 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
717 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
718 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
719 DIFF_SYMBOL_STATS_LINE,
720 DIFF_SYMBOL_WORD_DIFF,
721 DIFF_SYMBOL_STAT_SEP,
723 DIFF_SYMBOL_SUBMODULE_ADD,
724 DIFF_SYMBOL_SUBMODULE_DEL,
725 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
726 DIFF_SYMBOL_SUBMODULE_MODIFIED,
727 DIFF_SYMBOL_SUBMODULE_HEADER,
728 DIFF_SYMBOL_SUBMODULE_ERROR,
729 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
730 DIFF_SYMBOL_REWRITE_DIFF,
731 DIFF_SYMBOL_BINARY_FILES,
733 DIFF_SYMBOL_FILEPAIR_PLUS,
734 DIFF_SYMBOL_FILEPAIR_MINUS,
735 DIFF_SYMBOL_WORDS_PORCELAIN,
738 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
741 DIFF_SYMBOL_NO_LF_EOF,
742 DIFF_SYMBOL_CONTEXT_FRAGINFO,
743 DIFF_SYMBOL_CONTEXT_MARKER,
744 DIFF_SYMBOL_SEPARATOR
747 * Flags for content lines:
748 * 0..12 are whitespace rules
749 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
750 * 16 is marking if the line is blank at EOF
752 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
753 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
754 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
755 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
756 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
759 * This struct is used when we need to buffer the output of the diff output.
761 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
762 * into the pre/post image file. This pointer could be a union with the
763 * line pointer. By storing an offset into the file instead of the literal line,
764 * we can decrease the memory footprint for the buffered output. At first we
765 * may want to only have indirection for the content lines, but we could also
766 * enhance the state for emitting prefabricated lines, e.g. the similarity
767 * score line or hunk/file headers would only need to store a number or path
768 * and then the output can be constructed later on depending on state.
770 struct emitted_diff_symbol {
774 int indent_off; /* Offset to first non-whitespace character */
775 int indent_width; /* The visual width of the indentation */
779 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
781 struct emitted_diff_symbols {
782 struct emitted_diff_symbol *buf;
785 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
787 static void append_emitted_diff_symbol(struct diff_options *o,
788 struct emitted_diff_symbol *e)
790 struct emitted_diff_symbol *f;
792 ALLOC_GROW(o->emitted_symbols->buf,
793 o->emitted_symbols->nr + 1,
794 o->emitted_symbols->alloc);
795 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
797 memcpy(f, e, sizeof(struct emitted_diff_symbol));
798 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
802 const struct emitted_diff_symbol *es;
803 struct moved_entry *next_line;
804 struct moved_entry *next_match;
808 struct moved_entry *match;
809 int wsd; /* The whitespace delta of this block */
812 #define INDENT_BLANKLINE INT_MIN
814 static void fill_es_indent_data(struct emitted_diff_symbol *es)
816 unsigned int off = 0, i;
817 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
818 const char *s = es->line;
819 const int len = es->len;
821 /* skip any \v \f \r at start of indentation */
822 while (s[off] == '\f' || s[off] == '\v' ||
823 (s[off] == '\r' && off < len - 1))
826 /* calculate the visual width of indentation */
831 } else if (s[off] == '\t') {
832 width += tab_width - (width % tab_width);
833 while (s[++off] == '\t')
840 /* check if this line is blank */
841 for (i = off; i < len; i++)
846 es->indent_width = INDENT_BLANKLINE;
847 es->indent_off = len;
849 es->indent_off = off;
850 es->indent_width = width;
854 static int compute_ws_delta(const struct emitted_diff_symbol *a,
855 const struct emitted_diff_symbol *b)
857 int a_width = a->indent_width,
858 b_width = b->indent_width;
860 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
861 return INDENT_BLANKLINE;
863 return a_width - b_width;
866 static int cmp_in_block_with_wsd(const struct diff_options *o,
867 const struct moved_entry *cur,
868 const struct emitted_diff_symbol *l,
869 struct moved_block *pmb)
871 int a_width = cur->es->indent_width, b_width = l->indent_width;
874 /* The text of each line must match */
875 if (cur->es->id != l->id)
879 * If 'l' and 'cur' are both blank then we don't need to check the
880 * indent. We only need to check cur as we know the strings match.
882 if (a_width == INDENT_BLANKLINE)
886 * The indent changes of the block are known and stored in pmb->wsd;
887 * however we need to check if the indent changes of the current line
888 * match those of the current block.
890 delta = b_width - a_width;
893 * If the previous lines of this block were all blank then set its
896 if (pmb->wsd == INDENT_BLANKLINE)
899 return delta != pmb->wsd;
902 struct interned_diff_symbol {
903 struct hashmap_entry ent;
904 struct emitted_diff_symbol *es;
907 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
908 const struct hashmap_entry *eptr,
909 const struct hashmap_entry *entry_or_key,
912 const struct diff_options *diffopt = hashmap_cmp_fn_data;
913 const struct emitted_diff_symbol *a, *b;
914 unsigned flags = diffopt->color_moved_ws_handling
915 & XDF_WHITESPACE_FLAGS;
917 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
918 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
920 return !xdiff_compare_lines(a->line + a->indent_off,
921 a->len - a->indent_off,
922 b->line + b->indent_off,
923 b->len - b->indent_off, flags);
926 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
927 struct interned_diff_symbol *s)
929 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
930 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
931 l->len - l->indent_off, flags);
933 hashmap_entry_init(&s->ent, hash);
937 struct moved_entry_list {
938 struct moved_entry *add, *del;
941 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
942 struct mem_pool *entry_mem_pool)
944 struct moved_entry *prev_line = NULL;
945 struct mem_pool interned_pool;
946 struct hashmap interned_map;
947 struct moved_entry_list *entry_list = NULL;
948 size_t entry_list_alloc = 0;
952 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
953 mem_pool_init(&interned_pool, 1024 * 1024);
955 for (n = 0; n < o->emitted_symbols->nr; n++) {
956 struct interned_diff_symbol key;
957 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
958 struct interned_diff_symbol *s;
959 struct moved_entry *entry;
961 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
966 if (o->color_moved_ws_handling &
967 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
968 fill_es_indent_data(l);
970 prepare_entry(o, l, &key);
971 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
976 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
977 hashmap_add(&interned_map,
978 memcpy(mem_pool_alloc(&interned_pool,
982 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
984 entry->next_line = NULL;
985 if (prev_line && prev_line->es->s == l->s)
986 prev_line->next_line = entry;
988 if (l->s == DIFF_SYMBOL_PLUS) {
989 entry->next_match = entry_list[l->id].add;
990 entry_list[l->id].add = entry;
992 entry->next_match = entry_list[l->id].del;
993 entry_list[l->id].del = entry;
997 hashmap_clear(&interned_map);
998 mem_pool_discard(&interned_pool, 0);
1003 static void pmb_advance_or_null(struct diff_options *o,
1004 struct emitted_diff_symbol *l,
1005 struct moved_block *pmb,
1010 for (i = 0, j = 0; i < *pmb_nr; i++) {
1012 struct moved_entry *prev = pmb[i].match;
1013 struct moved_entry *cur = (prev && prev->next_line) ?
1014 prev->next_line : NULL;
1016 if (o->color_moved_ws_handling &
1017 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1019 !cmp_in_block_with_wsd(o, cur, l, &pmb[i]);
1021 match = cur && cur->es->id == l->id;
1024 pmb[j++].match = cur;
1030 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1032 * Otherwise, if the last block has fewer alphanumeric characters than
1033 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1036 * The last block consists of the (n - block_length)'th line up to but not
1037 * including the nth line.
1039 * Returns 0 if the last block is empty or is unset by this function, non zero
1042 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1043 * Think of a way to unify them.
1045 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1047 int i, alnum_count = 0;
1048 if (o->color_moved == COLOR_MOVED_PLAIN)
1049 return block_length;
1050 for (i = 1; i < block_length + 1; i++) {
1051 const char *c = o->emitted_symbols->buf[n - i].line;
1056 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1060 for (i = 1; i < block_length + 1; i++)
1061 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1065 /* Find blocks of moved code, delegate actual coloring decision to helper */
1066 static void mark_color_as_moved(struct diff_options *o,
1067 struct moved_entry_list *entry_list)
1069 struct moved_block *pmb = NULL; /* potentially moved blocks */
1070 int pmb_nr = 0, pmb_alloc = 0;
1071 int n, flipped_block = 0, block_length = 0;
1072 enum diff_symbol moved_symbol = 0;
1075 for (n = 0; n < o->emitted_symbols->nr; n++) {
1076 struct moved_entry *match = NULL;
1077 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1080 case DIFF_SYMBOL_PLUS:
1081 match = entry_list[l->id].del;
1083 case DIFF_SYMBOL_MINUS:
1084 match = entry_list[l->id].add;
1090 if (pmb_nr && (!match || l->s != moved_symbol)) {
1091 adjust_last_block(o, n, block_length);
1101 if (o->color_moved == COLOR_MOVED_PLAIN) {
1102 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1106 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1110 * The current line is the start of a new block.
1111 * Setup the set of potential blocks.
1113 for (; match; match = match->next_match) {
1114 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1115 if (o->color_moved_ws_handling &
1116 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1117 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1119 pmb[pmb_nr].wsd = 0;
1120 pmb[pmb_nr++].match = match;
1123 if (adjust_last_block(o, n, block_length) &&
1124 pmb_nr && moved_symbol == l->s)
1125 flipped_block = (flipped_block + 1) % 2;
1130 moved_symbol = l->s;
1139 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1140 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1141 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1144 adjust_last_block(o, n, block_length);
1149 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1150 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1151 static void dim_moved_lines(struct diff_options *o)
1154 for (n = 0; n < o->emitted_symbols->nr; n++) {
1155 struct emitted_diff_symbol *prev = (n != 0) ?
1156 &o->emitted_symbols->buf[n - 1] : NULL;
1157 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1158 struct emitted_diff_symbol *next =
1159 (n < o->emitted_symbols->nr - 1) ?
1160 &o->emitted_symbols->buf[n + 1] : NULL;
1162 /* Not a plus or minus line? */
1163 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1166 /* Not a moved line? */
1167 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1171 * If prev or next are not a plus or minus line,
1172 * pretend they don't exist
1174 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1175 prev->s != DIFF_SYMBOL_MINUS)
1177 if (next && next->s != DIFF_SYMBOL_PLUS &&
1178 next->s != DIFF_SYMBOL_MINUS)
1181 /* Inside a block? */
1183 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1184 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1186 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1187 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1188 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1192 /* Check if we are at an interesting bound: */
1193 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1194 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1195 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1197 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1198 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1199 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1203 * The boundary to prev and next are not interesting,
1204 * so this line is not interesting as a whole
1206 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1210 static void emit_line_ws_markup(struct diff_options *o,
1211 const char *set_sign, const char *set,
1213 int sign_index, const char *line, int len,
1214 unsigned ws_rule, int blank_at_eof)
1216 const char *ws = NULL;
1217 int sign = o->output_indicators[sign_index];
1219 if (o->ws_error_highlight & ws_rule) {
1220 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1225 if (!ws && !set_sign)
1226 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1228 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1229 } else if (blank_at_eof)
1230 /* Blank line at EOF - paint '+' as well */
1231 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1233 /* Emit just the prefix, then the rest. */
1234 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1236 ws_check_emit(line, len, ws_rule,
1237 o->file, set, reset, ws);
1241 static void emit_diff_symbol_from_struct(struct diff_options *o,
1242 struct emitted_diff_symbol *eds)
1244 static const char *nneof = " No newline at end of file\n";
1245 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1246 struct strbuf sb = STRBUF_INIT;
1248 enum diff_symbol s = eds->s;
1249 const char *line = eds->line;
1251 unsigned flags = eds->flags;
1254 case DIFF_SYMBOL_NO_LF_EOF:
1255 context = diff_get_color_opt(o, DIFF_CONTEXT);
1256 reset = diff_get_color_opt(o, DIFF_RESET);
1257 putc('\n', o->file);
1258 emit_line_0(o, context, NULL, 0, reset, '\\',
1259 nneof, strlen(nneof));
1261 case DIFF_SYMBOL_SUBMODULE_HEADER:
1262 case DIFF_SYMBOL_SUBMODULE_ERROR:
1263 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1264 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1265 case DIFF_SYMBOL_SUMMARY:
1266 case DIFF_SYMBOL_STATS_LINE:
1267 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1268 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1269 emit_line(o, "", "", line, len);
1271 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1272 case DIFF_SYMBOL_CONTEXT_MARKER:
1273 context = diff_get_color_opt(o, DIFF_CONTEXT);
1274 reset = diff_get_color_opt(o, DIFF_RESET);
1275 emit_line(o, context, reset, line, len);
1277 case DIFF_SYMBOL_SEPARATOR:
1278 fprintf(o->file, "%s%c",
1279 diff_line_prefix(o),
1280 o->line_termination);
1282 case DIFF_SYMBOL_CONTEXT:
1283 set = diff_get_color_opt(o, DIFF_CONTEXT);
1284 reset = diff_get_color_opt(o, DIFF_RESET);
1286 if (o->flags.dual_color_diffed_diffs) {
1287 char c = !len ? 0 : line[0];
1290 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1292 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1294 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1296 emit_line_ws_markup(o, set_sign, set, reset,
1297 OUTPUT_INDICATOR_CONTEXT, line, len,
1298 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1300 case DIFF_SYMBOL_PLUS:
1301 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1302 DIFF_SYMBOL_MOVED_LINE_ALT |
1303 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1304 case DIFF_SYMBOL_MOVED_LINE |
1305 DIFF_SYMBOL_MOVED_LINE_ALT |
1306 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1307 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1309 case DIFF_SYMBOL_MOVED_LINE |
1310 DIFF_SYMBOL_MOVED_LINE_ALT:
1311 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1313 case DIFF_SYMBOL_MOVED_LINE |
1314 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1315 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1317 case DIFF_SYMBOL_MOVED_LINE:
1318 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1321 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1323 reset = diff_get_color_opt(o, DIFF_RESET);
1324 if (!o->flags.dual_color_diffed_diffs)
1327 char c = !len ? 0 : line[0];
1331 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1333 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1335 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1337 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1338 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1340 emit_line_ws_markup(o, set_sign, set, reset,
1341 OUTPUT_INDICATOR_NEW, line, len,
1342 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1343 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1345 case DIFF_SYMBOL_MINUS:
1346 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1347 DIFF_SYMBOL_MOVED_LINE_ALT |
1348 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1349 case DIFF_SYMBOL_MOVED_LINE |
1350 DIFF_SYMBOL_MOVED_LINE_ALT |
1351 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1352 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1354 case DIFF_SYMBOL_MOVED_LINE |
1355 DIFF_SYMBOL_MOVED_LINE_ALT:
1356 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1358 case DIFF_SYMBOL_MOVED_LINE |
1359 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1360 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1362 case DIFF_SYMBOL_MOVED_LINE:
1363 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1366 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1368 reset = diff_get_color_opt(o, DIFF_RESET);
1369 if (!o->flags.dual_color_diffed_diffs)
1372 char c = !len ? 0 : line[0];
1376 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1378 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1380 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1382 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1384 emit_line_ws_markup(o, set_sign, set, reset,
1385 OUTPUT_INDICATOR_OLD, line, len,
1386 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1388 case DIFF_SYMBOL_WORDS_PORCELAIN:
1389 context = diff_get_color_opt(o, DIFF_CONTEXT);
1390 reset = diff_get_color_opt(o, DIFF_RESET);
1391 emit_line(o, context, reset, line, len);
1392 fputs("~\n", o->file);
1394 case DIFF_SYMBOL_WORDS:
1395 context = diff_get_color_opt(o, DIFF_CONTEXT);
1396 reset = diff_get_color_opt(o, DIFF_RESET);
1398 * Skip the prefix character, if any. With
1399 * diff_suppress_blank_empty, there may be
1402 if (line[0] != '\n') {
1406 emit_line(o, context, reset, line, len);
1408 case DIFF_SYMBOL_FILEPAIR_PLUS:
1409 meta = diff_get_color_opt(o, DIFF_METAINFO);
1410 reset = diff_get_color_opt(o, DIFF_RESET);
1411 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1413 strchr(line, ' ') ? "\t" : "");
1415 case DIFF_SYMBOL_FILEPAIR_MINUS:
1416 meta = diff_get_color_opt(o, DIFF_METAINFO);
1417 reset = diff_get_color_opt(o, DIFF_RESET);
1418 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1420 strchr(line, ' ') ? "\t" : "");
1422 case DIFF_SYMBOL_BINARY_FILES:
1423 case DIFF_SYMBOL_HEADER:
1424 fprintf(o->file, "%s", line);
1426 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1427 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1429 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1430 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1432 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1433 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1435 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1436 fputs(diff_line_prefix(o), o->file);
1437 fputc('\n', o->file);
1439 case DIFF_SYMBOL_REWRITE_DIFF:
1440 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1441 reset = diff_get_color_opt(o, DIFF_RESET);
1442 emit_line(o, fraginfo, reset, line, len);
1444 case DIFF_SYMBOL_SUBMODULE_ADD:
1445 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1446 reset = diff_get_color_opt(o, DIFF_RESET);
1447 emit_line(o, set, reset, line, len);
1449 case DIFF_SYMBOL_SUBMODULE_DEL:
1450 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1451 reset = diff_get_color_opt(o, DIFF_RESET);
1452 emit_line(o, set, reset, line, len);
1454 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1455 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1456 diff_line_prefix(o), line);
1458 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1459 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1460 diff_line_prefix(o), line);
1462 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1463 emit_line(o, "", "", " 0 files changed\n",
1464 strlen(" 0 files changed\n"));
1466 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1467 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1469 case DIFF_SYMBOL_WORD_DIFF:
1470 fprintf(o->file, "%.*s", len, line);
1472 case DIFF_SYMBOL_STAT_SEP:
1473 fputs(o->stat_sep, o->file);
1476 BUG("unknown diff symbol");
1478 strbuf_release(&sb);
1481 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1482 const char *line, int len, unsigned flags)
1484 struct emitted_diff_symbol e = {line, len, flags, 0, 0, 0, s};
1486 if (o->emitted_symbols)
1487 append_emitted_diff_symbol(o, &e);
1489 emit_diff_symbol_from_struct(o, &e);
1492 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1494 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1497 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1499 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1502 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1504 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1505 path, strlen(path), 0);
1508 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1510 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1511 path, strlen(path), 0);
1514 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1516 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1517 header, strlen(header), 0);
1520 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1522 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1525 void diff_emit_submodule_pipethrough(struct diff_options *o,
1526 const char *line, int len)
1528 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1531 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1533 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1534 ecbdata->blank_at_eof_in_preimage &&
1535 ecbdata->blank_at_eof_in_postimage &&
1536 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1537 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1539 return ws_blank_line(line, len, ecbdata->ws_rule);
1542 static void emit_add_line(struct emit_callback *ecbdata,
1543 const char *line, int len)
1545 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1546 if (new_blank_line_at_eof(ecbdata, line, len))
1547 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1549 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1552 static void emit_del_line(struct emit_callback *ecbdata,
1553 const char *line, int len)
1555 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1556 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1559 static void emit_context_line(struct emit_callback *ecbdata,
1560 const char *line, int len)
1562 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1563 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1566 static void emit_hunk_header(struct emit_callback *ecbdata,
1567 const char *line, int len)
1569 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1570 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1571 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1572 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1573 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1574 static const char atat[2] = { '@', '@' };
1575 const char *cp, *ep;
1576 struct strbuf msgbuf = STRBUF_INIT;
1581 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1582 * it always is at least 10 bytes long.
1585 memcmp(line, atat, 2) ||
1586 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1587 emit_diff_symbol(ecbdata->opt,
1588 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1591 ep += 2; /* skip over @@ */
1593 /* The hunk header in fraginfo color */
1594 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1595 strbuf_addstr(&msgbuf, reverse);
1596 strbuf_addstr(&msgbuf, frag);
1597 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1598 strbuf_add(&msgbuf, atat, sizeof(atat));
1600 strbuf_add(&msgbuf, line, ep - line);
1601 strbuf_addstr(&msgbuf, reset);
1607 if (line[len - i] == '\r' || line[len - i] == '\n')
1610 /* blank before the func header */
1611 for (cp = ep; ep - line < len; ep++)
1612 if (*ep != ' ' && *ep != '\t')
1615 strbuf_addstr(&msgbuf, context);
1616 strbuf_add(&msgbuf, cp, ep - cp);
1617 strbuf_addstr(&msgbuf, reset);
1620 if (ep < line + len) {
1621 strbuf_addstr(&msgbuf, func);
1622 strbuf_add(&msgbuf, ep, line + len - ep);
1623 strbuf_addstr(&msgbuf, reset);
1626 strbuf_add(&msgbuf, line + len, org_len - len);
1627 strbuf_complete_line(&msgbuf);
1628 emit_diff_symbol(ecbdata->opt,
1629 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1630 strbuf_release(&msgbuf);
1633 static struct diff_tempfile *claim_diff_tempfile(void)
1636 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1637 if (!diff_temp[i].name)
1638 return diff_temp + i;
1639 BUG("diff is failing to clean up its tempfiles");
1642 static void remove_tempfile(void)
1645 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1646 if (is_tempfile_active(diff_temp[i].tempfile))
1647 delete_tempfile(&diff_temp[i].tempfile);
1648 diff_temp[i].name = NULL;
1652 static void add_line_count(struct strbuf *out, int count)
1656 strbuf_addstr(out, "0,0");
1659 strbuf_addstr(out, "1");
1662 strbuf_addf(out, "1,%d", count);
1667 static void emit_rewrite_lines(struct emit_callback *ecb,
1668 int prefix, const char *data, int size)
1670 const char *endp = NULL;
1675 endp = memchr(data, '\n', size);
1676 len = endp ? (endp - data + 1) : size;
1677 if (prefix != '+') {
1678 ecb->lno_in_preimage++;
1679 emit_del_line(ecb, data, len);
1681 ecb->lno_in_postimage++;
1682 emit_add_line(ecb, data, len);
1688 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1691 static void emit_rewrite_diff(const char *name_a,
1693 struct diff_filespec *one,
1694 struct diff_filespec *two,
1695 struct userdiff_driver *textconv_one,
1696 struct userdiff_driver *textconv_two,
1697 struct diff_options *o)
1700 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1701 const char *a_prefix, *b_prefix;
1702 char *data_one, *data_two;
1703 size_t size_one, size_two;
1704 struct emit_callback ecbdata;
1705 struct strbuf out = STRBUF_INIT;
1707 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1708 a_prefix = o->b_prefix;
1709 b_prefix = o->a_prefix;
1711 a_prefix = o->a_prefix;
1712 b_prefix = o->b_prefix;
1715 name_a += (*name_a == '/');
1716 name_b += (*name_b == '/');
1718 strbuf_reset(&a_name);
1719 strbuf_reset(&b_name);
1720 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1721 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1723 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1724 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1726 memset(&ecbdata, 0, sizeof(ecbdata));
1727 ecbdata.color_diff = want_color(o->use_color);
1728 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1730 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1732 mf1.ptr = (char *)data_one;
1733 mf2.ptr = (char *)data_two;
1734 mf1.size = size_one;
1735 mf2.size = size_two;
1736 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1738 ecbdata.lno_in_preimage = 1;
1739 ecbdata.lno_in_postimage = 1;
1741 lc_a = count_lines(data_one, size_one);
1742 lc_b = count_lines(data_two, size_two);
1744 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1745 a_name.buf, a_name.len, 0);
1746 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1747 b_name.buf, b_name.len, 0);
1749 strbuf_addstr(&out, "@@ -");
1750 if (!o->irreversible_delete)
1751 add_line_count(&out, lc_a);
1753 strbuf_addstr(&out, "?,?");
1754 strbuf_addstr(&out, " +");
1755 add_line_count(&out, lc_b);
1756 strbuf_addstr(&out, " @@\n");
1757 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1758 strbuf_release(&out);
1760 if (lc_a && !o->irreversible_delete)
1761 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1763 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1765 free((char *)data_one);
1767 free((char *)data_two);
1770 struct diff_words_buffer {
1772 unsigned long alloc;
1773 struct diff_words_orig {
1774 const char *begin, *end;
1776 int orig_nr, orig_alloc;
1779 static void diff_words_append(char *line, unsigned long len,
1780 struct diff_words_buffer *buffer)
1782 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1785 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1786 buffer->text.size += len;
1787 buffer->text.ptr[buffer->text.size] = '\0';
1790 struct diff_words_style_elem {
1793 const char *color; /* NULL; filled in by the setup code if
1794 * color is enabled */
1797 struct diff_words_style {
1798 enum diff_words_type type;
1799 struct diff_words_style_elem new_word, old_word, ctx;
1800 const char *newline;
1803 static struct diff_words_style diff_words_styles[] = {
1804 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1805 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1806 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1809 struct diff_words_data {
1810 struct diff_words_buffer minus, plus;
1811 const char *current_plus;
1813 struct diff_options *opt;
1814 regex_t *word_regex;
1815 enum diff_words_type type;
1816 struct diff_words_style *style;
1819 static int fn_out_diff_words_write_helper(struct diff_options *o,
1820 struct diff_words_style_elem *st_el,
1821 const char *newline,
1822 size_t count, const char *buf)
1825 struct strbuf sb = STRBUF_INIT;
1828 char *p = memchr(buf, '\n', count);
1830 strbuf_addstr(&sb, diff_line_prefix(o));
1833 const char *reset = st_el->color && *st_el->color ?
1834 GIT_COLOR_RESET : NULL;
1835 if (st_el->color && *st_el->color)
1836 strbuf_addstr(&sb, st_el->color);
1837 strbuf_addstr(&sb, st_el->prefix);
1838 strbuf_add(&sb, buf, p ? p - buf : count);
1839 strbuf_addstr(&sb, st_el->suffix);
1841 strbuf_addstr(&sb, reset);
1846 strbuf_addstr(&sb, newline);
1847 count -= p + 1 - buf;
1851 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1859 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1861 strbuf_release(&sb);
1866 * '--color-words' algorithm can be described as:
1868 * 1. collect the minus/plus lines of a diff hunk, divided into
1869 * minus-lines and plus-lines;
1871 * 2. break both minus-lines and plus-lines into words and
1872 * place them into two mmfile_t with one word for each line;
1874 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1876 * And for the common parts of the both file, we output the plus side text.
1877 * diff_words->current_plus is used to trace the current position of the plus file
1878 * which printed. diff_words->last_minus is used to trace the last minus word
1881 * For '--graph' to work with '--color-words', we need to output the graph prefix
1882 * on each line of color words output. Generally, there are two conditions on
1883 * which we should output the prefix.
1885 * 1. diff_words->last_minus == 0 &&
1886 * diff_words->current_plus == diff_words->plus.text.ptr
1888 * that is: the plus text must start as a new line, and if there is no minus
1889 * word printed, a graph prefix must be printed.
1891 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1892 * *(diff_words->current_plus - 1) == '\n'
1894 * that is: a graph prefix must be printed following a '\n'
1896 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1898 if ((diff_words->last_minus == 0 &&
1899 diff_words->current_plus == diff_words->plus.text.ptr) ||
1900 (diff_words->current_plus > diff_words->plus.text.ptr &&
1901 *(diff_words->current_plus - 1) == '\n')) {
1908 static void fn_out_diff_words_aux(void *priv,
1909 long minus_first, long minus_len,
1910 long plus_first, long plus_len,
1911 const char *func, long funclen)
1913 struct diff_words_data *diff_words = priv;
1914 struct diff_words_style *style = diff_words->style;
1915 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1916 struct diff_options *opt = diff_words->opt;
1917 const char *line_prefix;
1920 line_prefix = diff_line_prefix(opt);
1922 /* POSIX requires that first be decremented by one if len == 0... */
1924 minus_begin = diff_words->minus.orig[minus_first].begin;
1926 diff_words->minus.orig[minus_first + minus_len - 1].end;
1928 minus_begin = minus_end =
1929 diff_words->minus.orig[minus_first].end;
1932 plus_begin = diff_words->plus.orig[plus_first].begin;
1933 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1935 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1937 if (color_words_output_graph_prefix(diff_words)) {
1938 fputs(line_prefix, diff_words->opt->file);
1940 if (diff_words->current_plus != plus_begin) {
1941 fn_out_diff_words_write_helper(diff_words->opt,
1942 &style->ctx, style->newline,
1943 plus_begin - diff_words->current_plus,
1944 diff_words->current_plus);
1946 if (minus_begin != minus_end) {
1947 fn_out_diff_words_write_helper(diff_words->opt,
1948 &style->old_word, style->newline,
1949 minus_end - minus_begin, minus_begin);
1951 if (plus_begin != plus_end) {
1952 fn_out_diff_words_write_helper(diff_words->opt,
1953 &style->new_word, style->newline,
1954 plus_end - plus_begin, plus_begin);
1957 diff_words->current_plus = plus_end;
1958 diff_words->last_minus = minus_first;
1961 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1962 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1963 int *begin, int *end)
1965 while (word_regex && *begin < buffer->size) {
1966 regmatch_t match[1];
1967 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1968 buffer->size - *begin, 1, match, 0)) {
1969 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1970 '\n', match[0].rm_eo - match[0].rm_so);
1971 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1972 *begin += match[0].rm_so;
1976 return *begin > *end;
1982 /* find the next word */
1983 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1985 if (*begin >= buffer->size)
1988 /* find the end of the word */
1990 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1997 * This function splits the words in buffer->text, stores the list with
1998 * newline separator into out, and saves the offsets of the original words
2001 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2002 regex_t *word_regex)
2010 /* fake an empty "0th" word */
2011 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2012 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2013 buffer->orig_nr = 1;
2015 for (i = 0; i < buffer->text.size; i++) {
2016 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2019 /* store original boundaries */
2020 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2021 buffer->orig_alloc);
2022 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2023 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2026 /* store one word */
2027 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2028 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2029 out->ptr[out->size + j - i] = '\n';
2030 out->size += j - i + 1;
2036 /* this executes the word diff on the accumulated buffers */
2037 static void diff_words_show(struct diff_words_data *diff_words)
2041 mmfile_t minus, plus;
2042 struct diff_words_style *style = diff_words->style;
2044 struct diff_options *opt = diff_words->opt;
2045 const char *line_prefix;
2048 line_prefix = diff_line_prefix(opt);
2050 /* special case: only removal */
2051 if (!diff_words->plus.text.size) {
2052 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2053 line_prefix, strlen(line_prefix), 0);
2054 fn_out_diff_words_write_helper(diff_words->opt,
2055 &style->old_word, style->newline,
2056 diff_words->minus.text.size,
2057 diff_words->minus.text.ptr);
2058 diff_words->minus.text.size = 0;
2062 diff_words->current_plus = diff_words->plus.text.ptr;
2063 diff_words->last_minus = 0;
2065 memset(&xpp, 0, sizeof(xpp));
2066 memset(&xecfg, 0, sizeof(xecfg));
2067 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2068 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2070 /* as only the hunk header will be parsed, we need a 0-context */
2072 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2073 diff_words, &xpp, &xecfg))
2074 die("unable to generate word diff");
2077 if (diff_words->current_plus != diff_words->plus.text.ptr +
2078 diff_words->plus.text.size) {
2079 if (color_words_output_graph_prefix(diff_words))
2080 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2081 line_prefix, strlen(line_prefix), 0);
2082 fn_out_diff_words_write_helper(diff_words->opt,
2083 &style->ctx, style->newline,
2084 diff_words->plus.text.ptr + diff_words->plus.text.size
2085 - diff_words->current_plus, diff_words->current_plus);
2087 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2090 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2091 static void diff_words_flush(struct emit_callback *ecbdata)
2093 struct diff_options *wo = ecbdata->diff_words->opt;
2095 if (ecbdata->diff_words->minus.text.size ||
2096 ecbdata->diff_words->plus.text.size)
2097 diff_words_show(ecbdata->diff_words);
2099 if (wo->emitted_symbols) {
2100 struct diff_options *o = ecbdata->opt;
2101 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2106 * Instead of appending each, concat all words to a line?
2108 for (i = 0; i < wol->nr; i++)
2109 append_emitted_diff_symbol(o, &wol->buf[i]);
2111 for (i = 0; i < wol->nr; i++)
2112 free((void *)wol->buf[i].line);
2118 static void diff_filespec_load_driver(struct diff_filespec *one,
2119 struct index_state *istate)
2121 /* Use already-loaded driver */
2125 if (S_ISREG(one->mode))
2126 one->driver = userdiff_find_by_path(istate, one->path);
2128 /* Fallback to default settings */
2130 one->driver = userdiff_find_by_name("default");
2133 static const char *userdiff_word_regex(struct diff_filespec *one,
2134 struct index_state *istate)
2136 diff_filespec_load_driver(one, istate);
2137 return one->driver->word_regex;
2140 static void init_diff_words_data(struct emit_callback *ecbdata,
2141 struct diff_options *orig_opts,
2142 struct diff_filespec *one,
2143 struct diff_filespec *two)
2146 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2147 memcpy(o, orig_opts, sizeof(struct diff_options));
2149 CALLOC_ARRAY(ecbdata->diff_words, 1);
2150 ecbdata->diff_words->type = o->word_diff;
2151 ecbdata->diff_words->opt = o;
2153 if (orig_opts->emitted_symbols)
2154 CALLOC_ARRAY(o->emitted_symbols, 1);
2157 o->word_regex = userdiff_word_regex(one, o->repo->index);
2159 o->word_regex = userdiff_word_regex(two, o->repo->index);
2161 o->word_regex = diff_word_regex_cfg;
2162 if (o->word_regex) {
2163 ecbdata->diff_words->word_regex = (regex_t *)
2164 xmalloc(sizeof(regex_t));
2165 if (regcomp(ecbdata->diff_words->word_regex,
2167 REG_EXTENDED | REG_NEWLINE))
2168 die("invalid regular expression: %s",
2171 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2172 if (o->word_diff == diff_words_styles[i].type) {
2173 ecbdata->diff_words->style =
2174 &diff_words_styles[i];
2178 if (want_color(o->use_color)) {
2179 struct diff_words_style *st = ecbdata->diff_words->style;
2180 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2181 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2182 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2186 static void free_diff_words_data(struct emit_callback *ecbdata)
2188 if (ecbdata->diff_words) {
2189 diff_words_flush(ecbdata);
2190 free (ecbdata->diff_words->opt->emitted_symbols);
2191 free (ecbdata->diff_words->opt);
2192 free (ecbdata->diff_words->minus.text.ptr);
2193 free (ecbdata->diff_words->minus.orig);
2194 free (ecbdata->diff_words->plus.text.ptr);
2195 free (ecbdata->diff_words->plus.orig);
2196 if (ecbdata->diff_words->word_regex) {
2197 regfree(ecbdata->diff_words->word_regex);
2198 free(ecbdata->diff_words->word_regex);
2200 FREE_AND_NULL(ecbdata->diff_words);
2204 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2206 if (want_color(diff_use_color))
2207 return diff_colors[ix];
2211 const char *diff_line_prefix(struct diff_options *opt)
2213 struct strbuf *msgbuf;
2214 if (!opt->output_prefix)
2217 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2221 static unsigned long sane_truncate_line(char *line, unsigned long len)
2224 unsigned long allot;
2230 (void) utf8_width(&cp, &l);
2232 break; /* truncated in the middle? */
2237 static void find_lno(const char *line, struct emit_callback *ecbdata)
2240 ecbdata->lno_in_preimage = 0;
2241 ecbdata->lno_in_postimage = 0;
2242 p = strchr(line, '-');
2244 return; /* cannot happen */
2245 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2248 return; /* cannot happen */
2249 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2252 static int fn_out_consume(void *priv, char *line, unsigned long len)
2254 struct emit_callback *ecbdata = priv;
2255 struct diff_options *o = ecbdata->opt;
2257 o->found_changes = 1;
2259 if (ecbdata->header) {
2260 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2261 ecbdata->header->buf, ecbdata->header->len, 0);
2262 strbuf_reset(ecbdata->header);
2263 ecbdata->header = NULL;
2266 if (ecbdata->label_path[0]) {
2267 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2268 ecbdata->label_path[0],
2269 strlen(ecbdata->label_path[0]), 0);
2270 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2271 ecbdata->label_path[1],
2272 strlen(ecbdata->label_path[1]), 0);
2273 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2276 if (diff_suppress_blank_empty
2277 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2282 if (line[0] == '@') {
2283 if (ecbdata->diff_words)
2284 diff_words_flush(ecbdata);
2285 len = sane_truncate_line(line, len);
2286 find_lno(line, ecbdata);
2287 emit_hunk_header(ecbdata, line, len);
2291 if (ecbdata->diff_words) {
2292 enum diff_symbol s =
2293 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2294 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2295 if (line[0] == '-') {
2296 diff_words_append(line, len,
2297 &ecbdata->diff_words->minus);
2299 } else if (line[0] == '+') {
2300 diff_words_append(line, len,
2301 &ecbdata->diff_words->plus);
2303 } else if (starts_with(line, "\\ ")) {
2305 * Eat the "no newline at eof" marker as if we
2306 * saw a "+" or "-" line with nothing on it,
2307 * and return without diff_words_flush() to
2308 * defer processing. If this is the end of
2309 * preimage, more "+" lines may come after it.
2313 diff_words_flush(ecbdata);
2314 emit_diff_symbol(o, s, line, len, 0);
2320 ecbdata->lno_in_postimage++;
2321 emit_add_line(ecbdata, line + 1, len - 1);
2324 ecbdata->lno_in_preimage++;
2325 emit_del_line(ecbdata, line + 1, len - 1);
2328 ecbdata->lno_in_postimage++;
2329 ecbdata->lno_in_preimage++;
2330 emit_context_line(ecbdata, line + 1, len - 1);
2333 /* incomplete line at the end */
2334 ecbdata->lno_in_preimage++;
2335 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2342 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2344 const char *old_name = a;
2345 const char *new_name = b;
2346 int pfx_length, sfx_length;
2347 int pfx_adjust_for_slash;
2348 int len_a = strlen(a);
2349 int len_b = strlen(b);
2350 int a_midlen, b_midlen;
2351 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2352 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2354 if (qlen_a || qlen_b) {
2355 quote_c_style(a, name, NULL, 0);
2356 strbuf_addstr(name, " => ");
2357 quote_c_style(b, name, NULL, 0);
2361 /* Find common prefix */
2363 while (*old_name && *new_name && *old_name == *new_name) {
2364 if (*old_name == '/')
2365 pfx_length = old_name - a + 1;
2370 /* Find common suffix */
2371 old_name = a + len_a;
2372 new_name = b + len_b;
2375 * If there is a common prefix, it must end in a slash. In
2376 * that case we let this loop run 1 into the prefix to see the
2379 * If there is no common prefix, we cannot do this as it would
2380 * underrun the input strings.
2382 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2383 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2384 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2385 *old_name == *new_name) {
2386 if (*old_name == '/')
2387 sfx_length = len_a - (old_name - a);
2393 * pfx{mid-a => mid-b}sfx
2394 * {pfx-a => pfx-b}sfx
2395 * pfx{sfx-a => sfx-b}
2398 a_midlen = len_a - pfx_length - sfx_length;
2399 b_midlen = len_b - pfx_length - sfx_length;
2405 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2406 if (pfx_length + sfx_length) {
2407 strbuf_add(name, a, pfx_length);
2408 strbuf_addch(name, '{');
2410 strbuf_add(name, a + pfx_length, a_midlen);
2411 strbuf_addstr(name, " => ");
2412 strbuf_add(name, b + pfx_length, b_midlen);
2413 if (pfx_length + sfx_length) {
2414 strbuf_addch(name, '}');
2415 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2419 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2423 struct diffstat_file *x;
2425 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2426 diffstat->files[diffstat->nr++] = x;
2428 x->from_name = xstrdup(name_a);
2429 x->name = xstrdup(name_b);
2433 x->from_name = NULL;
2434 x->name = xstrdup(name_a);
2439 static int diffstat_consume(void *priv, char *line, unsigned long len)
2441 struct diffstat_t *diffstat = priv;
2442 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2446 else if (line[0] == '-')
2451 const char mime_boundary_leader[] = "------------";
2453 static int scale_linear(int it, int width, int max_change)
2458 * make sure that at least one '-' or '+' is printed if
2459 * there is any change to this path. The easiest way is to
2460 * scale linearly as if the allotted width is one column shorter
2461 * than it is, and then add 1 to the result.
2463 return 1 + (it * (width - 1) / max_change);
2466 static void show_graph(struct strbuf *out, char ch, int cnt,
2467 const char *set, const char *reset)
2471 strbuf_addstr(out, set);
2472 strbuf_addchars(out, ch, cnt);
2473 strbuf_addstr(out, reset);
2476 static void fill_print_name(struct diffstat_file *file)
2478 struct strbuf pname = STRBUF_INIT;
2480 if (file->print_name)
2483 if (file->is_renamed)
2484 pprint_rename(&pname, file->from_name, file->name);
2486 quote_c_style(file->name, &pname, NULL, 0);
2489 strbuf_addf(&pname, " (%s)", file->comments);
2491 file->print_name = strbuf_detach(&pname, NULL);
2494 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2495 int files, int insertions, int deletions)
2497 struct strbuf sb = STRBUF_INIT;
2500 assert(insertions == 0 && deletions == 0);
2501 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2507 (files == 1) ? " %d file changed" : " %d files changed",
2511 * For binary diff, the caller may want to print "x files
2512 * changed" with insertions == 0 && deletions == 0.
2514 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2515 * is probably less confusing (i.e skip over "2 files changed
2516 * but nothing about added/removed lines? Is this a bug in Git?").
2518 if (insertions || deletions == 0) {
2520 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2524 if (deletions || insertions == 0) {
2526 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2529 strbuf_addch(&sb, '\n');
2530 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2532 strbuf_release(&sb);
2535 void print_stat_summary(FILE *fp, int files,
2536 int insertions, int deletions)
2538 struct diff_options o;
2539 memset(&o, 0, sizeof(o));
2542 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2545 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2547 int i, len, add, del, adds = 0, dels = 0;
2548 uintmax_t max_change = 0, max_len = 0;
2549 int total_files = data->nr, count;
2550 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2551 const char *reset, *add_c, *del_c;
2552 int extra_shown = 0;
2553 const char *line_prefix = diff_line_prefix(options);
2554 struct strbuf out = STRBUF_INIT;
2559 count = options->stat_count ? options->stat_count : data->nr;
2561 reset = diff_get_color_opt(options, DIFF_RESET);
2562 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2563 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2566 * Find the longest filename and max number of changes
2568 for (i = 0; (i < count) && (i < data->nr); i++) {
2569 struct diffstat_file *file = data->files[i];
2570 uintmax_t change = file->added + file->deleted;
2572 if (!file->is_interesting && (change == 0)) {
2573 count++; /* not shown == room for one more */
2576 fill_print_name(file);
2577 len = strlen(file->print_name);
2581 if (file->is_unmerged) {
2582 /* "Unmerged" is 8 characters */
2583 bin_width = bin_width < 8 ? 8 : bin_width;
2586 if (file->is_binary) {
2587 /* "Bin XXX -> YYY bytes" */
2588 int w = 14 + decimal_width(file->added)
2589 + decimal_width(file->deleted);
2590 bin_width = bin_width < w ? w : bin_width;
2591 /* Display change counts aligned with "Bin" */
2596 if (max_change < change)
2597 max_change = change;
2599 count = i; /* where we can stop scanning in data->files[] */
2602 * We have width = stat_width or term_columns() columns total.
2603 * We want a maximum of min(max_len, stat_name_width) for the name part.
2604 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2605 * We also need 1 for " " and 4 + decimal_width(max_change)
2606 * for " | NNNN " and one the empty column at the end, altogether
2607 * 6 + decimal_width(max_change).
2609 * If there's not enough space, we will use the smaller of
2610 * stat_name_width (if set) and 5/8*width for the filename,
2611 * and the rest for constant elements + graph part, but no more
2612 * than stat_graph_width for the graph part.
2613 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2614 * for the standard terminal size).
2616 * In other words: stat_width limits the maximum width, and
2617 * stat_name_width fixes the maximum width of the filename,
2618 * and is also used to divide available columns if there
2621 * Binary files are displayed with "Bin XXX -> YYY bytes"
2622 * instead of the change count and graph. This part is treated
2623 * similarly to the graph part, except that it is not
2624 * "scaled". If total width is too small to accommodate the
2625 * guaranteed minimum width of the filename part and the
2626 * separators and this message, this message will "overflow"
2627 * making the line longer than the maximum width.
2630 if (options->stat_width == -1)
2631 width = term_columns() - strlen(line_prefix);
2633 width = options->stat_width ? options->stat_width : 80;
2634 number_width = decimal_width(max_change) > number_width ?
2635 decimal_width(max_change) : number_width;
2637 if (options->stat_graph_width == -1)
2638 options->stat_graph_width = diff_stat_graph_width;
2641 * Guarantee 3/8*16==6 for the graph part
2642 * and 5/8*16==10 for the filename part
2644 if (width < 16 + 6 + number_width)
2645 width = 16 + 6 + number_width;
2648 * First assign sizes that are wanted, ignoring available width.
2649 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2650 * starting from "XXX" should fit in graph_width.
2652 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2653 if (options->stat_graph_width &&
2654 options->stat_graph_width < graph_width)
2655 graph_width = options->stat_graph_width;
2657 name_width = (options->stat_name_width > 0 &&
2658 options->stat_name_width < max_len) ?
2659 options->stat_name_width : max_len;
2662 * Adjust adjustable widths not to exceed maximum width
2664 if (name_width + number_width + 6 + graph_width > width) {
2665 if (graph_width > width * 3/8 - number_width - 6) {
2666 graph_width = width * 3/8 - number_width - 6;
2667 if (graph_width < 6)
2671 if (options->stat_graph_width &&
2672 graph_width > options->stat_graph_width)
2673 graph_width = options->stat_graph_width;
2674 if (name_width > width - number_width - 6 - graph_width)
2675 name_width = width - number_width - 6 - graph_width;
2677 graph_width = width - number_width - 6 - name_width;
2681 * From here name_width is the width of the name area,
2682 * and graph_width is the width of the graph area.
2683 * max_change is used to scale graph properly.
2685 for (i = 0; i < count; i++) {
2686 const char *prefix = "";
2687 struct diffstat_file *file = data->files[i];
2688 char *name = file->print_name;
2689 uintmax_t added = file->added;
2690 uintmax_t deleted = file->deleted;
2693 if (!file->is_interesting && (added + deleted == 0))
2697 * "scale" the filename
2700 name_len = strlen(name);
2701 if (name_width < name_len) {
2705 name += name_len - len;
2706 slash = strchr(name, '/');
2711 if (file->is_binary) {
2712 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2713 strbuf_addf(&out, " %*s", number_width, "Bin");
2714 if (!added && !deleted) {
2715 strbuf_addch(&out, '\n');
2716 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2717 out.buf, out.len, 0);
2721 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2722 del_c, deleted, reset);
2723 strbuf_addstr(&out, " -> ");
2724 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2725 add_c, added, reset);
2726 strbuf_addstr(&out, " bytes\n");
2727 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2728 out.buf, out.len, 0);
2732 else if (file->is_unmerged) {
2733 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2734 strbuf_addstr(&out, " Unmerged\n");
2735 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2736 out.buf, out.len, 0);
2742 * scale the add/delete
2747 if (graph_width <= max_change) {
2748 int total = scale_linear(add + del, graph_width, max_change);
2749 if (total < 2 && add && del)
2750 /* width >= 2 due to the sanity check */
2753 add = scale_linear(add, graph_width, max_change);
2756 del = scale_linear(del, graph_width, max_change);
2760 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2761 strbuf_addf(&out, " %*"PRIuMAX"%s",
2762 number_width, added + deleted,
2763 added + deleted ? " " : "");
2764 show_graph(&out, '+', add, add_c, reset);
2765 show_graph(&out, '-', del, del_c, reset);
2766 strbuf_addch(&out, '\n');
2767 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2768 out.buf, out.len, 0);
2772 for (i = 0; i < data->nr; i++) {
2773 struct diffstat_file *file = data->files[i];
2774 uintmax_t added = file->added;
2775 uintmax_t deleted = file->deleted;
2777 if (file->is_unmerged ||
2778 (!file->is_interesting && (added + deleted == 0))) {
2783 if (!file->is_binary) {
2790 emit_diff_symbol(options,
2791 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2796 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2797 strbuf_release(&out);
2800 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2802 int i, adds = 0, dels = 0, total_files = data->nr;
2807 for (i = 0; i < data->nr; i++) {
2808 int added = data->files[i]->added;
2809 int deleted = data->files[i]->deleted;
2811 if (data->files[i]->is_unmerged ||
2812 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2814 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2819 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2822 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2829 for (i = 0; i < data->nr; i++) {
2830 struct diffstat_file *file = data->files[i];
2832 fprintf(options->file, "%s", diff_line_prefix(options));
2834 if (file->is_binary)
2835 fprintf(options->file, "-\t-\t");
2837 fprintf(options->file,
2838 "%"PRIuMAX"\t%"PRIuMAX"\t",
2839 file->added, file->deleted);
2840 if (options->line_termination) {
2841 fill_print_name(file);
2842 if (!file->is_renamed)
2843 write_name_quoted(file->name, options->file,
2844 options->line_termination);
2846 fputs(file->print_name, options->file);
2847 putc(options->line_termination, options->file);
2850 if (file->is_renamed) {
2851 putc('\0', options->file);
2852 write_name_quoted(file->from_name, options->file, '\0');
2854 write_name_quoted(file->name, options->file, '\0');
2859 struct dirstat_file {
2861 unsigned long changed;
2864 struct dirstat_dir {
2865 struct dirstat_file *files;
2866 int alloc, nr, permille, cumulative;
2869 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2870 unsigned long changed, const char *base, int baselen)
2872 unsigned long sum_changes = 0;
2873 unsigned int sources = 0;
2874 const char *line_prefix = diff_line_prefix(opt);
2877 struct dirstat_file *f = dir->files;
2878 int namelen = strlen(f->name);
2879 unsigned long changes;
2882 if (namelen < baselen)
2884 if (memcmp(f->name, base, baselen))
2886 slash = strchr(f->name + baselen, '/');
2888 int newbaselen = slash + 1 - f->name;
2889 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2892 changes = f->changed;
2897 sum_changes += changes;
2901 * We don't report dirstat's for
2903 * - or cases where everything came from a single directory
2904 * under this directory (sources == 1).
2906 if (baselen && sources != 1) {
2908 int permille = sum_changes * 1000 / changed;
2909 if (permille >= dir->permille) {
2910 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2911 permille / 10, permille % 10, baselen, base);
2912 if (!dir->cumulative)
2920 static int dirstat_compare(const void *_a, const void *_b)
2922 const struct dirstat_file *a = _a;
2923 const struct dirstat_file *b = _b;
2924 return strcmp(a->name, b->name);
2927 static void show_dirstat(struct diff_options *options)
2930 unsigned long changed;
2931 struct dirstat_dir dir;
2932 struct diff_queue_struct *q = &diff_queued_diff;
2937 dir.permille = options->dirstat_permille;
2938 dir.cumulative = options->flags.dirstat_cumulative;
2941 for (i = 0; i < q->nr; i++) {
2942 struct diff_filepair *p = q->queue[i];
2944 unsigned long copied, added, damage;
2945 struct diff_populate_filespec_options dpf_options = {
2946 .check_size_only = 1,
2949 name = p->two->path ? p->two->path : p->one->path;
2951 if (p->one->oid_valid && p->two->oid_valid &&
2952 oideq(&p->one->oid, &p->two->oid)) {
2954 * The SHA1 has not changed, so pre-/post-content is
2955 * identical. We can therefore skip looking at the
2956 * file contents altogether.
2962 if (options->flags.dirstat_by_file) {
2964 * In --dirstat-by-file mode, we don't really need to
2965 * look at the actual file contents at all.
2966 * The fact that the SHA1 changed is enough for us to
2967 * add this file to the list of results
2968 * (with each file contributing equal damage).
2974 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2975 diff_populate_filespec(options->repo, p->one, NULL);
2976 diff_populate_filespec(options->repo, p->two, NULL);
2977 diffcore_count_changes(options->repo,
2978 p->one, p->two, NULL, NULL,
2980 diff_free_filespec_data(p->one);
2981 diff_free_filespec_data(p->two);
2982 } else if (DIFF_FILE_VALID(p->one)) {
2983 diff_populate_filespec(options->repo, p->one, &dpf_options);
2985 diff_free_filespec_data(p->one);
2986 } else if (DIFF_FILE_VALID(p->two)) {
2987 diff_populate_filespec(options->repo, p->two, &dpf_options);
2989 added = p->two->size;
2990 diff_free_filespec_data(p->two);
2995 * Original minus copied is the removed material,
2996 * added is the new material. They are both damages
2997 * made to the preimage.
2998 * If the resulting damage is zero, we know that
2999 * diffcore_count_changes() considers the two entries to
3000 * be identical, but since the oid changed, we
3001 * know that there must have been _some_ kind of change,
3002 * so we force all entries to have damage > 0.
3004 damage = (p->one->size - copied) + added;
3009 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3010 dir.files[dir.nr].name = name;
3011 dir.files[dir.nr].changed = damage;
3016 /* This can happen even with many files, if everything was renames */
3020 /* Show all directories with more than x% of the changes */
3021 QSORT(dir.files, dir.nr, dirstat_compare);
3022 gather_dirstat(options, &dir, changed, "", 0);
3025 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3028 unsigned long changed;
3029 struct dirstat_dir dir;
3037 dir.permille = options->dirstat_permille;
3038 dir.cumulative = options->flags.dirstat_cumulative;
3041 for (i = 0; i < data->nr; i++) {
3042 struct diffstat_file *file = data->files[i];
3043 unsigned long damage = file->added + file->deleted;
3044 if (file->is_binary)
3046 * binary files counts bytes, not lines. Must find some
3047 * way to normalize binary bytes vs. textual lines.
3048 * The following heuristic assumes that there are 64
3050 * This is stupid and ugly, but very cheap...
3052 damage = DIV_ROUND_UP(damage, 64);
3053 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3054 dir.files[dir.nr].name = file->name;
3055 dir.files[dir.nr].changed = damage;
3060 /* This can happen even with many files, if everything was renames */
3064 /* Show all directories with more than x% of the changes */
3065 QSORT(dir.files, dir.nr, dirstat_compare);
3066 gather_dirstat(options, &dir, changed, "", 0);
3069 static void free_diffstat_file(struct diffstat_file *f)
3071 free(f->print_name);
3077 void free_diffstat_info(struct diffstat_t *diffstat)
3080 for (i = 0; i < diffstat->nr; i++)
3081 free_diffstat_file(diffstat->files[i]);
3082 free(diffstat->files);
3085 struct checkdiff_t {
3086 const char *filename;
3088 int conflict_marker_size;
3089 struct diff_options *o;
3094 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3099 if (len < marker_size + 1)
3101 firstchar = line[0];
3102 switch (firstchar) {
3103 case '=': case '>': case '<': case '|':
3108 for (cnt = 1; cnt < marker_size; cnt++)
3109 if (line[cnt] != firstchar)
3111 /* line[1] through line[marker_size-1] are same as firstchar */
3112 if (len < marker_size + 1 || !isspace(line[marker_size]))
3117 static void checkdiff_consume_hunk(void *priv,
3118 long ob, long on, long nb, long nn,
3119 const char *func, long funclen)
3122 struct checkdiff_t *data = priv;
3123 data->lineno = nb - 1;
3126 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3128 struct checkdiff_t *data = priv;
3129 int marker_size = data->conflict_marker_size;
3130 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3131 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3132 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3134 const char *line_prefix;
3137 line_prefix = diff_line_prefix(data->o);
3139 if (line[0] == '+') {
3142 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3144 fprintf(data->o->file,
3145 "%s%s:%d: leftover conflict marker\n",
3146 line_prefix, data->filename, data->lineno);
3148 bad = ws_check(line + 1, len - 1, data->ws_rule);
3151 data->status |= bad;
3152 err = whitespace_error_string(bad);
3153 fprintf(data->o->file, "%s%s:%d: %s.\n",
3154 line_prefix, data->filename, data->lineno, err);
3156 emit_line(data->o, set, reset, line, 1);
3157 ws_check_emit(line + 1, len - 1, data->ws_rule,
3158 data->o->file, set, reset, ws);
3159 } else if (line[0] == ' ') {
3165 static unsigned char *deflate_it(char *data,
3167 unsigned long *result_size)
3170 unsigned char *deflated;
3173 git_deflate_init(&stream, zlib_compression_level);
3174 bound = git_deflate_bound(&stream, size);
3175 deflated = xmalloc(bound);
3176 stream.next_out = deflated;
3177 stream.avail_out = bound;
3179 stream.next_in = (unsigned char *)data;
3180 stream.avail_in = size;
3181 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3183 git_deflate_end(&stream);
3184 *result_size = stream.total_out;
3188 static void emit_binary_diff_body(struct diff_options *o,
3189 mmfile_t *one, mmfile_t *two)
3195 unsigned long orig_size;
3196 unsigned long delta_size;
3197 unsigned long deflate_size;
3198 unsigned long data_size;
3200 /* We could do deflated delta, or we could do just deflated two,
3201 * whichever is smaller.
3204 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3205 if (one->size && two->size) {
3206 delta = diff_delta(one->ptr, one->size,
3207 two->ptr, two->size,
3208 &delta_size, deflate_size);
3210 void *to_free = delta;
3211 orig_size = delta_size;
3212 delta = deflate_it(delta, delta_size, &delta_size);
3217 if (delta && delta_size < deflate_size) {
3218 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3219 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3224 data_size = delta_size;
3226 char *s = xstrfmt("%lu", two->size);
3227 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3232 data_size = deflate_size;
3235 /* emit data encoded in base85 */
3239 int bytes = (52 < data_size) ? 52 : data_size;
3243 line[0] = bytes + 'A' - 1;
3245 line[0] = bytes - 26 + 'a' - 1;
3246 encode_85(line + 1, cp, bytes);
3247 cp = (char *) cp + bytes;
3253 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3256 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3260 static void emit_binary_diff(struct diff_options *o,
3261 mmfile_t *one, mmfile_t *two)
3263 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3264 emit_binary_diff_body(o, one, two);
3265 emit_binary_diff_body(o, two, one);
3268 int diff_filespec_is_binary(struct repository *r,
3269 struct diff_filespec *one)
3271 struct diff_populate_filespec_options dpf_options = {
3275 if (one->is_binary == -1) {
3276 diff_filespec_load_driver(one, r->index);
3277 if (one->driver->binary != -1)
3278 one->is_binary = one->driver->binary;
3280 if (!one->data && DIFF_FILE_VALID(one))
3281 diff_populate_filespec(r, one, &dpf_options);
3282 if (one->is_binary == -1 && one->data)
3283 one->is_binary = buffer_is_binary(one->data,
3285 if (one->is_binary == -1)
3289 return one->is_binary;
3292 static const struct userdiff_funcname *
3293 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3295 diff_filespec_load_driver(one, o->repo->index);
3296 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3299 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3301 if (!options->a_prefix)
3302 options->a_prefix = a;
3303 if (!options->b_prefix)
3304 options->b_prefix = b;
3307 struct userdiff_driver *get_textconv(struct repository *r,
3308 struct diff_filespec *one)
3310 if (!DIFF_FILE_VALID(one))
3313 diff_filespec_load_driver(one, r->index);
3314 return userdiff_get_textconv(r, one->driver);
3317 static void builtin_diff(const char *name_a,
3319 struct diff_filespec *one,
3320 struct diff_filespec *two,
3321 const char *xfrm_msg,
3322 int must_show_header,
3323 struct diff_options *o,
3324 int complete_rewrite)
3328 char *a_one, *b_two;
3329 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3330 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3331 const char *a_prefix, *b_prefix;
3332 struct userdiff_driver *textconv_one = NULL;
3333 struct userdiff_driver *textconv_two = NULL;
3334 struct strbuf header = STRBUF_INIT;
3335 const char *line_prefix = diff_line_prefix(o);
3337 diff_set_mnemonic_prefix(o, "a/", "b/");
3338 if (o->flags.reverse_diff) {
3339 a_prefix = o->b_prefix;
3340 b_prefix = o->a_prefix;
3342 a_prefix = o->a_prefix;
3343 b_prefix = o->b_prefix;
3346 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3347 (!one->mode || S_ISGITLINK(one->mode)) &&
3348 (!two->mode || S_ISGITLINK(two->mode))) {
3349 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3350 &one->oid, &two->oid,
3351 two->dirty_submodule);
3353 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3354 (!one->mode || S_ISGITLINK(one->mode)) &&
3355 (!two->mode || S_ISGITLINK(two->mode))) {
3356 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3357 &one->oid, &two->oid,
3358 two->dirty_submodule);
3362 if (o->flags.allow_textconv) {
3363 textconv_one = get_textconv(o->repo, one);
3364 textconv_two = get_textconv(o->repo, two);
3367 /* Never use a non-valid filename anywhere if at all possible */
3368 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3369 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3371 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3372 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3373 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3374 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3375 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3376 if (lbl[0][0] == '/') {
3378 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3380 strbuf_addstr(&header, xfrm_msg);
3381 must_show_header = 1;
3383 else if (lbl[1][0] == '/') {
3384 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3386 strbuf_addstr(&header, xfrm_msg);
3387 must_show_header = 1;
3390 if (one->mode != two->mode) {
3391 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3392 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3393 must_show_header = 1;
3396 strbuf_addstr(&header, xfrm_msg);
3399 * we do not run diff between different kind
3402 if ((one->mode ^ two->mode) & S_IFMT)
3403 goto free_ab_and_return;
3404 if (complete_rewrite &&
3405 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3406 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3407 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3408 header.buf, header.len, 0);
3409 strbuf_reset(&header);
3410 emit_rewrite_diff(name_a, name_b, one, two,
3411 textconv_one, textconv_two, o);
3412 o->found_changes = 1;
3413 goto free_ab_and_return;
3417 if (o->irreversible_delete && lbl[1][0] == '/') {
3418 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3420 strbuf_reset(&header);
3421 goto free_ab_and_return;
3422 } else if (!o->flags.text &&
3423 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3424 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3425 struct strbuf sb = STRBUF_INIT;
3426 if (!one->data && !two->data &&
3427 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3429 if (oideq(&one->oid, &two->oid)) {
3430 if (must_show_header)
3431 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3432 header.buf, header.len,
3434 goto free_ab_and_return;
3436 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3437 header.buf, header.len, 0);
3438 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3439 diff_line_prefix(o), lbl[0], lbl[1]);
3440 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3442 strbuf_release(&sb);
3443 goto free_ab_and_return;
3445 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3446 fill_mmfile(o->repo, &mf2, two) < 0)
3447 die("unable to read files to diff");
3448 /* Quite common confusing case */
3449 if (mf1.size == mf2.size &&
3450 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3451 if (must_show_header)
3452 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3453 header.buf, header.len, 0);
3454 goto free_ab_and_return;
3456 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3457 strbuf_reset(&header);
3458 if (o->flags.binary)
3459 emit_binary_diff(o, &mf1, &mf2);
3461 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3462 diff_line_prefix(o), lbl[0], lbl[1]);
3463 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3465 strbuf_release(&sb);
3467 o->found_changes = 1;
3469 /* Crazy xdl interfaces.. */
3470 const char *diffopts;
3474 struct emit_callback ecbdata;
3475 const struct userdiff_funcname *pe;
3477 if (must_show_header) {
3478 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3479 header.buf, header.len, 0);
3480 strbuf_reset(&header);
3483 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3484 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3486 pe = diff_funcname_pattern(o, one);
3488 pe = diff_funcname_pattern(o, two);
3490 memset(&xpp, 0, sizeof(xpp));
3491 memset(&xecfg, 0, sizeof(xecfg));
3492 memset(&ecbdata, 0, sizeof(ecbdata));
3493 if (o->flags.suppress_diff_headers)
3495 ecbdata.label_path = lbl;
3496 ecbdata.color_diff = want_color(o->use_color);
3497 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3498 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3499 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3501 if (header.len && !o->flags.suppress_diff_headers)
3502 ecbdata.header = &header;
3503 xpp.flags = o->xdl_opts;
3504 xpp.ignore_regex = o->ignore_regex;
3505 xpp.ignore_regex_nr = o->ignore_regex_nr;
3506 xpp.anchors = o->anchors;
3507 xpp.anchors_nr = o->anchors_nr;
3508 xecfg.ctxlen = o->context;
3509 xecfg.interhunkctxlen = o->interhunkcontext;
3510 xecfg.flags = XDL_EMIT_FUNCNAMES;
3511 if (o->flags.funccontext)
3512 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3514 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3516 diffopts = getenv("GIT_DIFF_OPTS");
3519 else if (skip_prefix(diffopts, "--unified=", &v))
3520 xecfg.ctxlen = strtoul(v, NULL, 10);
3521 else if (skip_prefix(diffopts, "-u", &v))
3522 xecfg.ctxlen = strtoul(v, NULL, 10);
3525 init_diff_words_data(&ecbdata, o, one, two);
3526 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3527 &ecbdata, &xpp, &xecfg))
3528 die("unable to generate diff for %s", one->path);
3530 free_diff_words_data(&ecbdata);
3535 xdiff_clear_find_func(&xecfg);
3539 strbuf_release(&header);
3540 diff_free_filespec_data(one);
3541 diff_free_filespec_data(two);
3547 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3550 if (p->status == DIFF_STATUS_ADDED) {
3551 if (S_ISLNK(p->two->mode))
3553 else if ((p->two->mode & 0777) == 0755)
3557 } else if (p->status == DIFF_STATUS_DELETED)
3560 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3562 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3564 else if ((p->one->mode & 0777) == 0644 &&
3565 (p->two->mode & 0777) == 0755)
3567 else if ((p->one->mode & 0777) == 0755 &&
3568 (p->two->mode & 0777) == 0644)
3573 static void builtin_diffstat(const char *name_a, const char *name_b,
3574 struct diff_filespec *one,
3575 struct diff_filespec *two,
3576 struct diffstat_t *diffstat,
3577 struct diff_options *o,
3578 struct diff_filepair *p)
3581 struct diffstat_file *data;
3583 int complete_rewrite = 0;
3585 if (!DIFF_PAIR_UNMERGED(p)) {
3586 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3587 complete_rewrite = 1;
3590 data = diffstat_add(diffstat, name_a, name_b);
3591 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3592 if (o->flags.stat_with_summary)
3593 data->comments = get_compact_summary(p, data->is_renamed);
3596 data->is_unmerged = 1;
3600 /* saves some reads if true, not a guarantee of diff outcome */
3601 may_differ = !(one->oid_valid && two->oid_valid &&
3602 oideq(&one->oid, &two->oid));
3604 if (diff_filespec_is_binary(o->repo, one) ||
3605 diff_filespec_is_binary(o->repo, two)) {
3606 data->is_binary = 1;
3611 data->added = diff_filespec_size(o->repo, two);
3612 data->deleted = diff_filespec_size(o->repo, one);
3616 else if (complete_rewrite) {
3617 diff_populate_filespec(o->repo, one, NULL);
3618 diff_populate_filespec(o->repo, two, NULL);
3619 data->deleted = count_lines(one->data, one->size);
3620 data->added = count_lines(two->data, two->size);
3623 else if (may_differ) {
3624 /* Crazy xdl interfaces.. */
3628 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3629 fill_mmfile(o->repo, &mf2, two) < 0)
3630 die("unable to read files to diff");
3632 memset(&xpp, 0, sizeof(xpp));
3633 memset(&xecfg, 0, sizeof(xecfg));
3634 xpp.flags = o->xdl_opts;
3635 xpp.ignore_regex = o->ignore_regex;
3636 xpp.ignore_regex_nr = o->ignore_regex_nr;
3637 xpp.anchors = o->anchors;
3638 xpp.anchors_nr = o->anchors_nr;
3639 xecfg.ctxlen = o->context;
3640 xecfg.interhunkctxlen = o->interhunkcontext;
3641 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3642 if (xdi_diff_outf(&mf1, &mf2, NULL,
3643 diffstat_consume, diffstat, &xpp, &xecfg))
3644 die("unable to generate diffstat for %s", one->path);
3646 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3647 struct diffstat_file *file =
3648 diffstat->files[diffstat->nr - 1];
3650 * Omit diffstats of modified files where nothing changed.
3651 * Even if may_differ, this might be the case due to
3652 * ignoring whitespace changes, etc.
3654 * But note that we special-case additions, deletions,
3655 * renames, and mode changes as adding an empty file,
3656 * for example is still of interest.
3658 if ((p->status == DIFF_STATUS_MODIFIED)
3661 && one->mode == two->mode) {
3662 free_diffstat_file(file);
3668 diff_free_filespec_data(one);
3669 diff_free_filespec_data(two);
3672 static void builtin_checkdiff(const char *name_a, const char *name_b,
3673 const char *attr_path,
3674 struct diff_filespec *one,
3675 struct diff_filespec *two,
3676 struct diff_options *o)
3679 struct checkdiff_t data;
3684 memset(&data, 0, sizeof(data));
3685 data.filename = name_b ? name_b : name_a;
3688 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3689 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3691 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3692 fill_mmfile(o->repo, &mf2, two) < 0)
3693 die("unable to read files to diff");
3696 * All the other codepaths check both sides, but not checking
3697 * the "old" side here is deliberate. We are checking the newly
3698 * introduced changes, and as long as the "new" side is text, we
3699 * can and should check what it introduces.
3701 if (diff_filespec_is_binary(o->repo, two))
3702 goto free_and_return;
3704 /* Crazy xdl interfaces.. */
3708 memset(&xpp, 0, sizeof(xpp));
3709 memset(&xecfg, 0, sizeof(xecfg));
3710 xecfg.ctxlen = 1; /* at least one context line */
3712 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3713 checkdiff_consume, &data,
3715 die("unable to generate checkdiff for %s", one->path);
3717 if (data.ws_rule & WS_BLANK_AT_EOF) {
3718 struct emit_callback ecbdata;
3721 ecbdata.ws_rule = data.ws_rule;
3722 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3723 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3728 err = whitespace_error_string(WS_BLANK_AT_EOF);
3729 fprintf(o->file, "%s:%d: %s.\n",
3730 data.filename, blank_at_eof, err);
3731 data.status = 1; /* report errors */
3736 diff_free_filespec_data(one);
3737 diff_free_filespec_data(two);
3739 o->flags.check_failed = 1;
3742 struct diff_filespec *alloc_filespec(const char *path)
3744 struct diff_filespec *spec;
3746 FLEXPTR_ALLOC_STR(spec, path, path);
3748 spec->is_binary = -1;
3752 void free_filespec(struct diff_filespec *spec)
3754 if (!--spec->count) {
3755 diff_free_filespec_data(spec);
3760 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3761 int oid_valid, unsigned short mode)
3764 spec->mode = canon_mode(mode);
3765 oidcpy(&spec->oid, oid);
3766 spec->oid_valid = oid_valid;
3771 * Given a name and sha1 pair, if the index tells us the file in
3772 * the work tree has that object contents, return true, so that
3773 * prepare_temp_file() does not have to inflate and extract.
3775 static int reuse_worktree_file(struct index_state *istate,
3777 const struct object_id *oid,
3780 const struct cache_entry *ce;
3785 * We do not read the cache ourselves here, because the
3786 * benchmark with my previous version that always reads cache
3787 * shows that it makes things worse for diff-tree comparing
3788 * two linux-2.6 kernel trees in an already checked out work
3789 * tree. This is because most diff-tree comparisons deal with
3790 * only a small number of files, while reading the cache is
3791 * expensive for a large project, and its cost outweighs the
3792 * savings we get by not inflating the object to a temporary
3793 * file. Practically, this code only helps when we are used
3794 * by diff-cache --cached, which does read the cache before
3800 /* We want to avoid the working directory if our caller
3801 * doesn't need the data in a normal file, this system
3802 * is rather slow with its stat/open/mmap/close syscalls,
3803 * and the object is contained in a pack file. The pack
3804 * is probably already open and will be faster to obtain
3805 * the data through than the working directory. Loose
3806 * objects however would tend to be slower as they need
3807 * to be individually opened and inflated.
3809 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3813 * Similarly, if we'd have to convert the file contents anyway, that
3814 * makes the optimization not worthwhile.
3816 if (!want_file && would_convert_to_git(istate, name))
3820 pos = index_name_pos(istate, name, len);
3823 ce = istate->cache[pos];
3826 * This is not the sha1 we are looking for, or
3827 * unreusable because it is not a regular file.
3829 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3833 * If ce is marked as "assume unchanged", there is no
3834 * guarantee that work tree matches what we are looking for.
3836 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3840 * If ce matches the file in the work tree, we can reuse it.
3842 if (ce_uptodate(ce) ||
3843 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3849 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3851 struct strbuf buf = STRBUF_INIT;
3854 /* Are we looking at the work tree? */
3855 if (s->dirty_submodule)
3858 strbuf_addf(&buf, "Subproject commit %s%s\n",
3859 oid_to_hex(&s->oid), dirty);
3863 strbuf_release(&buf);
3865 s->data = strbuf_detach(&buf, NULL);
3872 * While doing rename detection and pickaxe operation, we may need to
3873 * grab the data for the blob (or file) for our own in-core comparison.
3874 * diff_filespec has data and size fields for this purpose.
3876 int diff_populate_filespec(struct repository *r,
3877 struct diff_filespec *s,
3878 const struct diff_populate_filespec_options *options)
3880 int size_only = options ? options->check_size_only : 0;
3881 int check_binary = options ? options->check_binary : 0;
3883 int conv_flags = global_conv_flags_eol;
3885 * demote FAIL to WARN to allow inspecting the situation
3886 * instead of refusing.
3888 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3889 conv_flags = CONV_EOL_RNDTRP_WARN;
3891 if (!DIFF_FILE_VALID(s))
3892 die("internal error: asking to populate invalid file.");
3893 if (S_ISDIR(s->mode))
3899 if (size_only && 0 < s->size)
3902 if (S_ISGITLINK(s->mode))
3903 return diff_populate_gitlink(s, size_only);
3905 if (!s->oid_valid ||
3906 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3907 struct strbuf buf = STRBUF_INIT;
3911 if (lstat(s->path, &st) < 0) {
3915 s->data = (char *)"";
3919 s->size = xsize_t(st.st_size);
3922 if (S_ISLNK(st.st_mode)) {
3923 struct strbuf sb = STRBUF_INIT;
3925 if (strbuf_readlink(&sb, s->path, s->size))
3928 s->data = strbuf_detach(&sb, NULL);
3934 * Even if the caller would be happy with getting
3935 * only the size, we cannot return early at this
3936 * point if the path requires us to run the content
3939 if (size_only && !would_convert_to_git(r->index, s->path))
3943 * Note: this check uses xsize_t(st.st_size) that may
3944 * not be the true size of the blob after it goes
3945 * through convert_to_git(). This may not strictly be
3946 * correct, but the whole point of big_file_threshold
3947 * and is_binary check being that we want to avoid
3948 * opening the file and inspecting the contents, this
3952 s->size > big_file_threshold && s->is_binary == -1) {
3956 fd = open(s->path, O_RDONLY);
3959 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3961 s->should_munmap = 1;
3964 * Convert from working tree format to canonical git format
3966 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
3968 munmap(s->data, s->size);
3969 s->should_munmap = 0;
3970 s->data = strbuf_detach(&buf, &size);
3976 struct object_info info = {
3980 if (!(size_only || check_binary))
3982 * Set contentp, since there is no chance that merely
3983 * the size is sufficient.
3985 info.contentp = &s->data;
3987 if (options && options->missing_object_cb) {
3988 if (!oid_object_info_extended(r, &s->oid, &info,
3989 OBJECT_INFO_LOOKUP_REPLACE |
3990 OBJECT_INFO_SKIP_FETCH_OBJECT))
3992 options->missing_object_cb(options->missing_object_data);
3994 if (oid_object_info_extended(r, &s->oid, &info,
3995 OBJECT_INFO_LOOKUP_REPLACE))
3996 die("unable to read %s", oid_to_hex(&s->oid));
3999 if (size_only || check_binary) {
4002 if (s->size > big_file_threshold && s->is_binary == -1) {
4007 if (!info.contentp) {
4008 info.contentp = &s->data;
4009 if (oid_object_info_extended(r, &s->oid, &info,
4010 OBJECT_INFO_LOOKUP_REPLACE))
4011 die("unable to read %s", oid_to_hex(&s->oid));
4018 void diff_free_filespec_blob(struct diff_filespec *s)
4022 else if (s->should_munmap)
4023 munmap(s->data, s->size);
4025 if (s->should_free || s->should_munmap) {
4026 s->should_free = s->should_munmap = 0;
4031 void diff_free_filespec_data(struct diff_filespec *s)
4036 diff_free_filespec_blob(s);
4037 FREE_AND_NULL(s->cnt_data);
4040 static void prep_temp_blob(struct index_state *istate,
4041 const char *path, struct diff_tempfile *temp,
4044 const struct object_id *oid,
4047 struct strbuf buf = STRBUF_INIT;
4048 struct strbuf tempfile = STRBUF_INIT;
4049 char *path_dup = xstrdup(path);
4050 const char *base = basename(path_dup);
4051 struct checkout_metadata meta;
4053 init_checkout_metadata(&meta, NULL, NULL, oid);
4055 /* Generate "XXXXXX_basename.ext" */
4056 strbuf_addstr(&tempfile, "XXXXXX_");
4057 strbuf_addstr(&tempfile, base);
4059 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4060 if (!temp->tempfile)
4061 die_errno("unable to create temp-file");
4062 if (convert_to_working_tree(istate, path,
4063 (const char *)blob, (size_t)size, &buf, &meta)) {
4067 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4068 close_tempfile_gently(temp->tempfile))
4069 die_errno("unable to write temp-file");
4070 temp->name = get_tempfile_path(temp->tempfile);
4071 oid_to_hex_r(temp->hex, oid);
4072 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4073 strbuf_release(&buf);
4074 strbuf_release(&tempfile);
4078 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4080 struct diff_filespec *one)
4082 struct diff_tempfile *temp = claim_diff_tempfile();
4084 if (!DIFF_FILE_VALID(one)) {
4086 /* A '-' entry produces this for file-2, and
4087 * a '+' entry produces this for file-1.
4089 temp->name = "/dev/null";
4090 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4091 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4095 if (!S_ISGITLINK(one->mode) &&
4097 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4099 if (lstat(name, &st) < 0) {
4100 if (errno == ENOENT)
4101 goto not_a_valid_file;
4102 die_errno("stat(%s)", name);
4104 if (S_ISLNK(st.st_mode)) {
4105 struct strbuf sb = STRBUF_INIT;
4106 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4107 die_errno("readlink(%s)", name);
4108 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4110 &one->oid : null_oid()),
4112 one->mode : S_IFLNK));
4113 strbuf_release(&sb);
4116 /* we can borrow from the file in the work tree */
4118 if (!one->oid_valid)
4119 oid_to_hex_r(temp->hex, null_oid());
4121 oid_to_hex_r(temp->hex, &one->oid);
4122 /* Even though we may sometimes borrow the
4123 * contents from the work tree, we always want
4124 * one->mode. mode is trustworthy even when
4125 * !(one->oid_valid), as long as
4126 * DIFF_FILE_VALID(one).
4128 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4133 if (diff_populate_filespec(r, one, NULL))
4134 die("cannot read data blob for %s", one->path);
4135 prep_temp_blob(r->index, name, temp,
4136 one->data, one->size,
4137 &one->oid, one->mode);
4142 static void add_external_diff_name(struct repository *r,
4143 struct strvec *argv,
4145 struct diff_filespec *df)
4147 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4148 strvec_push(argv, temp->name);
4149 strvec_push(argv, temp->hex);
4150 strvec_push(argv, temp->mode);
4153 /* An external diff command takes:
4155 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4156 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4159 static void run_external_diff(const char *pgm,
4162 struct diff_filespec *one,
4163 struct diff_filespec *two,
4164 const char *xfrm_msg,
4165 struct diff_options *o)
4167 struct strvec argv = STRVEC_INIT;
4168 struct strvec env = STRVEC_INIT;
4169 struct diff_queue_struct *q = &diff_queued_diff;
4171 strvec_push(&argv, pgm);
4172 strvec_push(&argv, name);
4175 add_external_diff_name(o->repo, &argv, name, one);
4177 add_external_diff_name(o->repo, &argv, name, two);
4179 add_external_diff_name(o->repo, &argv, other, two);
4180 strvec_push(&argv, other);
4181 strvec_push(&argv, xfrm_msg);
4185 strvec_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4186 strvec_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4188 diff_free_filespec_data(one);
4189 diff_free_filespec_data(two);
4190 if (run_command_v_opt_cd_env(argv.v, RUN_USING_SHELL, NULL, env.v))
4191 die(_("external diff died, stopping at %s"), name);
4194 strvec_clear(&argv);
4198 static int similarity_index(struct diff_filepair *p)
4200 return p->score * 100 / MAX_SCORE;
4203 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4205 if (startup_info->have_repository)
4206 return find_unique_abbrev(oid, abbrev);
4208 char *hex = oid_to_hex(oid);
4210 abbrev = FALLBACK_DEFAULT_ABBREV;
4211 if (abbrev > the_hash_algo->hexsz)
4212 BUG("oid abbreviation out of range: %d", abbrev);
4219 static void fill_metainfo(struct strbuf *msg,
4222 struct diff_filespec *one,
4223 struct diff_filespec *two,
4224 struct diff_options *o,
4225 struct diff_filepair *p,
4226 int *must_show_header,
4229 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4230 const char *reset = diff_get_color(use_color, DIFF_RESET);
4231 const char *line_prefix = diff_line_prefix(o);
4233 *must_show_header = 1;
4234 strbuf_init(msg, PATH_MAX * 2 + 300);
4235 switch (p->status) {
4236 case DIFF_STATUS_COPIED:
4237 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4238 line_prefix, set, similarity_index(p));
4239 strbuf_addf(msg, "%s\n%s%scopy from ",
4240 reset, line_prefix, set);
4241 quote_c_style(name, msg, NULL, 0);
4242 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4243 quote_c_style(other, msg, NULL, 0);
4244 strbuf_addf(msg, "%s\n", reset);
4246 case DIFF_STATUS_RENAMED:
4247 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4248 line_prefix, set, similarity_index(p));
4249 strbuf_addf(msg, "%s\n%s%srename from ",
4250 reset, line_prefix, set);
4251 quote_c_style(name, msg, NULL, 0);
4252 strbuf_addf(msg, "%s\n%s%srename to ",
4253 reset, line_prefix, set);
4254 quote_c_style(other, msg, NULL, 0);
4255 strbuf_addf(msg, "%s\n", reset);
4257 case DIFF_STATUS_MODIFIED:
4259 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4261 set, similarity_index(p), reset);
4266 *must_show_header = 0;
4268 if (one && two && !oideq(&one->oid, &two->oid)) {
4269 const unsigned hexsz = the_hash_algo->hexsz;
4270 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4272 if (o->flags.full_index)
4275 if (o->flags.binary) {
4277 if ((!fill_mmfile(o->repo, &mf, one) &&
4278 diff_filespec_is_binary(o->repo, one)) ||
4279 (!fill_mmfile(o->repo, &mf, two) &&
4280 diff_filespec_is_binary(o->repo, two)))
4283 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4284 diff_abbrev_oid(&one->oid, abbrev),
4285 diff_abbrev_oid(&two->oid, abbrev));
4286 if (one->mode == two->mode)
4287 strbuf_addf(msg, " %06o", one->mode);
4288 strbuf_addf(msg, "%s\n", reset);
4292 static void run_diff_cmd(const char *pgm,
4295 const char *attr_path,
4296 struct diff_filespec *one,
4297 struct diff_filespec *two,
4299 struct diff_options *o,
4300 struct diff_filepair *p)
4302 const char *xfrm_msg = NULL;
4303 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4304 int must_show_header = 0;
4307 if (o->flags.allow_external) {
4308 struct userdiff_driver *drv;
4310 drv = userdiff_find_by_path(o->repo->index, attr_path);
4311 if (drv && drv->external)
4312 pgm = drv->external;
4317 * don't use colors when the header is intended for an
4318 * external diff driver
4320 fill_metainfo(msg, name, other, one, two, o, p,
4322 want_color(o->use_color) && !pgm);
4323 xfrm_msg = msg->len ? msg->buf : NULL;
4327 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4331 builtin_diff(name, other ? other : name,
4332 one, two, xfrm_msg, must_show_header,
4333 o, complete_rewrite);
4335 fprintf(o->file, "* Unmerged path %s\n", name);
4338 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4340 if (DIFF_FILE_VALID(one)) {
4341 if (!one->oid_valid) {
4343 if (one->is_stdin) {
4347 if (lstat(one->path, &st) < 0)
4348 die_errno("stat '%s'", one->path);
4349 if (index_path(istate, &one->oid, one->path, &st, 0))
4350 die("cannot hash %s", one->path);
4357 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4359 /* Strip the prefix but do not molest /dev/null and absolute paths */
4360 if (*namep && !is_absolute_path(*namep)) {
4361 *namep += prefix_length;
4365 if (*otherp && !is_absolute_path(*otherp)) {
4366 *otherp += prefix_length;
4367 if (**otherp == '/')
4372 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4374 const char *pgm = external_diff();
4376 struct diff_filespec *one = p->one;
4377 struct diff_filespec *two = p->two;
4380 const char *attr_path;
4383 other = (strcmp(name, two->path) ? two->path : NULL);
4385 if (o->prefix_length)
4386 strip_prefix(o->prefix_length, &name, &other);
4388 if (!o->flags.allow_external)
4391 if (DIFF_PAIR_UNMERGED(p)) {
4392 run_diff_cmd(pgm, name, NULL, attr_path,
4393 NULL, NULL, NULL, o, p);
4397 diff_fill_oid_info(one, o->repo->index);
4398 diff_fill_oid_info(two, o->repo->index);
4401 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4402 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4404 * a filepair that changes between file and symlink
4405 * needs to be split into deletion and creation.
4407 struct diff_filespec *null = alloc_filespec(two->path);
4408 run_diff_cmd(NULL, name, other, attr_path,
4412 strbuf_release(&msg);
4414 null = alloc_filespec(one->path);
4415 run_diff_cmd(NULL, name, other, attr_path,
4416 null, two, &msg, o, p);
4420 run_diff_cmd(pgm, name, other, attr_path,
4421 one, two, &msg, o, p);
4423 strbuf_release(&msg);
4426 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4427 struct diffstat_t *diffstat)
4432 if (DIFF_PAIR_UNMERGED(p)) {
4434 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4439 name = p->one->path;
4440 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4442 if (o->prefix_length)
4443 strip_prefix(o->prefix_length, &name, &other);
4445 diff_fill_oid_info(p->one, o->repo->index);
4446 diff_fill_oid_info(p->two, o->repo->index);
4448 builtin_diffstat(name, other, p->one, p->two,
4452 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4456 const char *attr_path;
4458 if (DIFF_PAIR_UNMERGED(p)) {
4463 name = p->one->path;
4464 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4465 attr_path = other ? other : name;
4467 if (o->prefix_length)
4468 strip_prefix(o->prefix_length, &name, &other);
4470 diff_fill_oid_info(p->one, o->repo->index);
4471 diff_fill_oid_info(p->two, o->repo->index);
4473 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4476 static void prep_parse_options(struct diff_options *options);
4478 void repo_diff_setup(struct repository *r, struct diff_options *options)
4480 memcpy(options, &default_diff_options, sizeof(*options));
4482 options->file = stdout;
4485 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4486 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4487 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4488 options->abbrev = DEFAULT_ABBREV;
4489 options->line_termination = '\n';
4490 options->break_opt = -1;
4491 options->rename_limit = -1;
4492 options->dirstat_permille = diff_dirstat_permille_default;
4493 options->context = diff_context_default;
4494 options->interhunkcontext = diff_interhunk_context_default;
4495 options->ws_error_highlight = ws_error_highlight_default;
4496 options->flags.rename_empty = 1;
4497 options->flags.relative_name = diff_relative;
4498 options->objfind = NULL;
4500 /* pathchange left =NULL by default */
4501 options->change = diff_change;
4502 options->add_remove = diff_addremove;
4503 options->use_color = diff_use_color_default;
4504 options->detect_rename = diff_detect_rename_default;
4505 options->xdl_opts |= diff_algorithm;
4506 if (diff_indent_heuristic)
4507 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4509 options->orderfile = diff_order_file_cfg;
4511 if (!options->flags.ignore_submodule_set)
4512 options->flags.ignore_untracked_in_submodules = 1;
4514 if (diff_no_prefix) {
4515 options->a_prefix = options->b_prefix = "";
4516 } else if (!diff_mnemonic_prefix) {
4517 options->a_prefix = "a/";
4518 options->b_prefix = "b/";
4521 options->color_moved = diff_color_moved_default;
4522 options->color_moved_ws_handling = diff_color_moved_ws_default;
4524 prep_parse_options(options);
4527 void diff_setup_done(struct diff_options *options)
4529 unsigned check_mask = DIFF_FORMAT_NAME |
4530 DIFF_FORMAT_NAME_STATUS |
4531 DIFF_FORMAT_CHECKDIFF |
4532 DIFF_FORMAT_NO_OUTPUT;
4534 * This must be signed because we're comparing against a potentially
4537 const int hexsz = the_hash_algo->hexsz;
4539 if (options->set_default)
4540 options->set_default(options);
4542 if (HAS_MULTI_BITS(options->output_format & check_mask))
4543 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4545 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4546 die(_("-G, -S and --find-object are mutually exclusive"));
4548 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4549 die(_("-G and --pickaxe-regex are mutually exclusive, use --pickaxe-regex with -S"));
4551 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4552 die(_("---pickaxe-all and --find-object are mutually exclusive, use --pickaxe-all with -G and -S"));
4555 * Most of the time we can say "there are changes"
4556 * only by checking if there are changed paths, but
4557 * --ignore-whitespace* options force us to look
4561 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4562 options->ignore_regex_nr)
4563 options->flags.diff_from_contents = 1;
4565 options->flags.diff_from_contents = 0;
4567 if (options->flags.find_copies_harder)
4568 options->detect_rename = DIFF_DETECT_COPY;
4570 if (!options->flags.relative_name)
4571 options->prefix = NULL;
4572 if (options->prefix)
4573 options->prefix_length = strlen(options->prefix);
4575 options->prefix_length = 0;
4577 if (options->output_format & (DIFF_FORMAT_NAME |
4578 DIFF_FORMAT_NAME_STATUS |
4579 DIFF_FORMAT_CHECKDIFF |
4580 DIFF_FORMAT_NO_OUTPUT))
4581 options->output_format &= ~(DIFF_FORMAT_RAW |
4582 DIFF_FORMAT_NUMSTAT |
4583 DIFF_FORMAT_DIFFSTAT |
4584 DIFF_FORMAT_SHORTSTAT |
4585 DIFF_FORMAT_DIRSTAT |
4586 DIFF_FORMAT_SUMMARY |
4590 * These cases always need recursive; we do not drop caller-supplied
4591 * recursive bits for other formats here.
4593 if (options->output_format & (DIFF_FORMAT_PATCH |
4594 DIFF_FORMAT_NUMSTAT |
4595 DIFF_FORMAT_DIFFSTAT |
4596 DIFF_FORMAT_SHORTSTAT |
4597 DIFF_FORMAT_DIRSTAT |
4598 DIFF_FORMAT_SUMMARY |
4599 DIFF_FORMAT_CHECKDIFF))
4600 options->flags.recursive = 1;
4602 * Also pickaxe would not work very well if you do not say recursive
4604 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4605 options->flags.recursive = 1;
4607 * When patches are generated, submodules diffed against the work tree
4608 * must be checked for dirtiness too so it can be shown in the output
4610 if (options->output_format & DIFF_FORMAT_PATCH)
4611 options->flags.dirty_submodules = 1;
4613 if (options->detect_rename && options->rename_limit < 0)
4614 options->rename_limit = diff_rename_limit_default;
4615 if (hexsz < options->abbrev)
4616 options->abbrev = hexsz; /* full */
4619 * It does not make sense to show the first hit we happened
4620 * to have found. It does not make sense not to return with
4621 * exit code in such a case either.
4623 if (options->flags.quick) {
4624 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4625 options->flags.exit_with_status = 1;
4628 options->diff_path_counter = 0;
4630 if (options->flags.follow_renames && options->pathspec.nr != 1)
4631 die(_("--follow requires exactly one pathspec"));
4633 if (!options->use_color || external_diff())
4634 options->color_moved = 0;
4636 FREE_AND_NULL(options->parseopts);
4639 int parse_long_opt(const char *opt, const char **argv,
4640 const char **optarg)
4642 const char *arg = argv[0];
4643 if (!skip_prefix(arg, "--", &arg))
4645 if (!skip_prefix(arg, opt, &arg))
4647 if (*arg == '=') { /* stuck form: --option=value */
4653 /* separate form: --option value */
4655 die("Option '--%s' requires a value", opt);
4660 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4662 struct diff_options *options = opt->value;
4663 int width = options->stat_width;
4664 int name_width = options->stat_name_width;
4665 int graph_width = options->stat_graph_width;
4666 int count = options->stat_count;
4669 BUG_ON_OPT_NEG(unset);
4671 if (!strcmp(opt->long_name, "stat")) {
4673 width = strtoul(value, &end, 10);
4675 name_width = strtoul(end+1, &end, 10);
4677 count = strtoul(end+1, &end, 10);
4679 return error(_("invalid --stat value: %s"), value);
4681 } else if (!strcmp(opt->long_name, "stat-width")) {
4682 width = strtoul(value, &end, 10);
4684 return error(_("%s expects a numerical value"),
4686 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4687 name_width = strtoul(value, &end, 10);
4689 return error(_("%s expects a numerical value"),
4691 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4692 graph_width = strtoul(value, &end, 10);
4694 return error(_("%s expects a numerical value"),
4696 } else if (!strcmp(opt->long_name, "stat-count")) {
4697 count = strtoul(value, &end, 10);
4699 return error(_("%s expects a numerical value"),
4702 BUG("%s should not get here", opt->long_name);
4704 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4705 options->stat_name_width = name_width;
4706 options->stat_graph_width = graph_width;
4707 options->stat_width = width;
4708 options->stat_count = count;
4712 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4714 struct strbuf errmsg = STRBUF_INIT;
4715 if (parse_dirstat_params(options, params, &errmsg))
4716 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4718 strbuf_release(&errmsg);
4720 * The caller knows a dirstat-related option is given from the command
4721 * line; allow it to say "return this_function();"
4723 options->output_format |= DIFF_FORMAT_DIRSTAT;
4727 static const char diff_status_letters[] = {
4730 DIFF_STATUS_DELETED,
4731 DIFF_STATUS_MODIFIED,
4732 DIFF_STATUS_RENAMED,
4733 DIFF_STATUS_TYPE_CHANGED,
4734 DIFF_STATUS_UNKNOWN,
4735 DIFF_STATUS_UNMERGED,
4736 DIFF_STATUS_FILTER_AON,
4737 DIFF_STATUS_FILTER_BROKEN,
4741 static unsigned int filter_bit['Z' + 1];
4743 static void prepare_filter_bits(void)
4747 if (!filter_bit[DIFF_STATUS_ADDED]) {
4748 for (i = 0; diff_status_letters[i]; i++)
4749 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4753 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4755 return opt->filter & filter_bit[(int) status];
4758 unsigned diff_filter_bit(char status)
4760 prepare_filter_bits();
4761 return filter_bit[(int) status];
4764 static int diff_opt_diff_filter(const struct option *option,
4765 const char *optarg, int unset)
4767 struct diff_options *opt = option->value;
4770 BUG_ON_OPT_NEG(unset);
4771 prepare_filter_bits();
4774 * If there is a negation e.g. 'd' in the input, and we haven't
4775 * initialized the filter field with another --diff-filter, start
4776 * from full set of bits, except for AON.
4779 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4780 if (optch < 'a' || 'z' < optch)
4782 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4783 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4788 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4792 if ('a' <= optch && optch <= 'z') {
4794 optch = toupper(optch);
4799 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4801 return error(_("unknown change class '%c' in --diff-filter=%s"),
4804 opt->filter &= ~bit;
4811 static void enable_patch_output(int *fmt)
4813 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4814 *fmt |= DIFF_FORMAT_PATCH;
4817 static int diff_opt_ws_error_highlight(const struct option *option,
4818 const char *arg, int unset)
4820 struct diff_options *opt = option->value;
4821 int val = parse_ws_error_highlight(arg);
4823 BUG_ON_OPT_NEG(unset);
4825 return error(_("unknown value after ws-error-highlight=%.*s"),
4827 opt->ws_error_highlight = val;
4831 static int diff_opt_find_object(const struct option *option,
4832 const char *arg, int unset)
4834 struct diff_options *opt = option->value;
4835 struct object_id oid;
4837 BUG_ON_OPT_NEG(unset);
4838 if (get_oid(arg, &oid))
4839 return error(_("unable to resolve '%s'"), arg);
4842 CALLOC_ARRAY(opt->objfind, 1);
4844 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4845 opt->flags.recursive = 1;
4846 opt->flags.tree_in_recursive = 1;
4847 oidset_insert(opt->objfind, &oid);
4851 static int diff_opt_anchored(const struct option *opt,
4852 const char *arg, int unset)
4854 struct diff_options *options = opt->value;
4856 BUG_ON_OPT_NEG(unset);
4857 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4858 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4859 options->anchors_alloc);
4860 options->anchors[options->anchors_nr++] = xstrdup(arg);
4864 static int diff_opt_binary(const struct option *opt,
4865 const char *arg, int unset)
4867 struct diff_options *options = opt->value;
4869 BUG_ON_OPT_NEG(unset);
4870 BUG_ON_OPT_ARG(arg);
4871 enable_patch_output(&options->output_format);
4872 options->flags.binary = 1;
4876 static int diff_opt_break_rewrites(const struct option *opt,
4877 const char *arg, int unset)
4879 int *break_opt = opt->value;
4882 BUG_ON_OPT_NEG(unset);
4885 opt1 = parse_rename_score(&arg);
4888 else if (*arg != '/')
4889 return error(_("%s expects <n>/<m> form"), opt->long_name);
4892 opt2 = parse_rename_score(&arg);
4895 return error(_("%s expects <n>/<m> form"), opt->long_name);
4896 *break_opt = opt1 | (opt2 << 16);
4900 static int diff_opt_char(const struct option *opt,
4901 const char *arg, int unset)
4903 char *value = opt->value;
4905 BUG_ON_OPT_NEG(unset);
4907 return error(_("%s expects a character, got '%s'"),
4908 opt->long_name, arg);
4913 static int diff_opt_color_moved(const struct option *opt,
4914 const char *arg, int unset)
4916 struct diff_options *options = opt->value;
4919 options->color_moved = COLOR_MOVED_NO;
4921 if (diff_color_moved_default)
4922 options->color_moved = diff_color_moved_default;
4923 if (options->color_moved == COLOR_MOVED_NO)
4924 options->color_moved = COLOR_MOVED_DEFAULT;
4926 int cm = parse_color_moved(arg);
4928 return error(_("bad --color-moved argument: %s"), arg);
4929 options->color_moved = cm;
4934 static int diff_opt_color_moved_ws(const struct option *opt,
4935 const char *arg, int unset)
4937 struct diff_options *options = opt->value;
4941 options->color_moved_ws_handling = 0;
4945 cm = parse_color_moved_ws(arg);
4946 if (cm & COLOR_MOVED_WS_ERROR)
4947 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
4948 options->color_moved_ws_handling = cm;
4952 static int diff_opt_color_words(const struct option *opt,
4953 const char *arg, int unset)
4955 struct diff_options *options = opt->value;
4957 BUG_ON_OPT_NEG(unset);
4958 options->use_color = 1;
4959 options->word_diff = DIFF_WORDS_COLOR;
4960 options->word_regex = arg;
4964 static int diff_opt_compact_summary(const struct option *opt,
4965 const char *arg, int unset)
4967 struct diff_options *options = opt->value;
4969 BUG_ON_OPT_ARG(arg);
4971 options->flags.stat_with_summary = 0;
4973 options->flags.stat_with_summary = 1;
4974 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4979 static int diff_opt_diff_algorithm(const struct option *opt,
4980 const char *arg, int unset)
4982 struct diff_options *options = opt->value;
4983 long value = parse_algorithm_value(arg);
4985 BUG_ON_OPT_NEG(unset);
4987 return error(_("option diff-algorithm accepts \"myers\", "
4988 "\"minimal\", \"patience\" and \"histogram\""));
4990 /* clear out previous settings */
4991 DIFF_XDL_CLR(options, NEED_MINIMAL);
4992 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4993 options->xdl_opts |= value;
4997 static int diff_opt_dirstat(const struct option *opt,
4998 const char *arg, int unset)
5000 struct diff_options *options = opt->value;
5002 BUG_ON_OPT_NEG(unset);
5003 if (!strcmp(opt->long_name, "cumulative")) {
5005 BUG("how come --cumulative take a value?");
5007 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5008 parse_dirstat_opt(options, "files");
5009 parse_dirstat_opt(options, arg ? arg : "");
5013 static int diff_opt_find_copies(const struct option *opt,
5014 const char *arg, int unset)
5016 struct diff_options *options = opt->value;
5018 BUG_ON_OPT_NEG(unset);
5021 options->rename_score = parse_rename_score(&arg);
5023 return error(_("invalid argument to %s"), opt->long_name);
5025 if (options->detect_rename == DIFF_DETECT_COPY)
5026 options->flags.find_copies_harder = 1;
5028 options->detect_rename = DIFF_DETECT_COPY;
5033 static int diff_opt_find_renames(const struct option *opt,
5034 const char *arg, int unset)
5036 struct diff_options *options = opt->value;
5038 BUG_ON_OPT_NEG(unset);
5041 options->rename_score = parse_rename_score(&arg);
5043 return error(_("invalid argument to %s"), opt->long_name);
5045 options->detect_rename = DIFF_DETECT_RENAME;
5049 static int diff_opt_follow(const struct option *opt,
5050 const char *arg, int unset)
5052 struct diff_options *options = opt->value;
5054 BUG_ON_OPT_ARG(arg);
5056 options->flags.follow_renames = 0;
5057 options->flags.default_follow_renames = 0;
5059 options->flags.follow_renames = 1;
5064 static int diff_opt_ignore_submodules(const struct option *opt,
5065 const char *arg, int unset)
5067 struct diff_options *options = opt->value;
5069 BUG_ON_OPT_NEG(unset);
5072 options->flags.override_submodule_config = 1;
5073 handle_ignore_submodules_arg(options, arg);
5077 static int diff_opt_line_prefix(const struct option *opt,
5078 const char *optarg, int unset)
5080 struct diff_options *options = opt->value;
5082 BUG_ON_OPT_NEG(unset);
5083 options->line_prefix = optarg;
5084 options->line_prefix_length = strlen(options->line_prefix);
5085 graph_setup_line_prefix(options);
5089 static int diff_opt_no_prefix(const struct option *opt,
5090 const char *optarg, int unset)
5092 struct diff_options *options = opt->value;
5094 BUG_ON_OPT_NEG(unset);
5095 BUG_ON_OPT_ARG(optarg);
5096 options->a_prefix = "";
5097 options->b_prefix = "";
5101 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5102 const struct option *opt,
5103 const char *arg, int unset)
5105 struct diff_options *options = opt->value;
5108 BUG_ON_OPT_NEG(unset);
5109 path = prefix_filename(ctx->prefix, arg);
5110 options->file = xfopen(path, "w");
5111 options->close_file = 1;
5112 if (options->use_color != GIT_COLOR_ALWAYS)
5113 options->use_color = GIT_COLOR_NEVER;
5118 static int diff_opt_patience(const struct option *opt,
5119 const char *arg, int unset)
5121 struct diff_options *options = opt->value;
5124 BUG_ON_OPT_NEG(unset);
5125 BUG_ON_OPT_ARG(arg);
5126 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5128 * Both --patience and --anchored use PATIENCE_DIFF
5129 * internally, so remove any anchors previously
5132 for (i = 0; i < options->anchors_nr; i++)
5133 free(options->anchors[i]);
5134 options->anchors_nr = 0;
5138 static int diff_opt_ignore_regex(const struct option *opt,
5139 const char *arg, int unset)
5141 struct diff_options *options = opt->value;
5144 BUG_ON_OPT_NEG(unset);
5145 regex = xmalloc(sizeof(*regex));
5146 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5147 return error(_("invalid regex given to -I: '%s'"), arg);
5148 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5149 options->ignore_regex_alloc);
5150 options->ignore_regex[options->ignore_regex_nr++] = regex;
5154 static int diff_opt_pickaxe_regex(const struct option *opt,
5155 const char *arg, int unset)
5157 struct diff_options *options = opt->value;
5159 BUG_ON_OPT_NEG(unset);
5160 options->pickaxe = arg;
5161 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5165 static int diff_opt_pickaxe_string(const struct option *opt,
5166 const char *arg, int unset)
5168 struct diff_options *options = opt->value;
5170 BUG_ON_OPT_NEG(unset);
5171 options->pickaxe = arg;
5172 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5176 static int diff_opt_relative(const struct option *opt,
5177 const char *arg, int unset)
5179 struct diff_options *options = opt->value;
5181 options->flags.relative_name = !unset;
5183 options->prefix = arg;
5187 static int diff_opt_submodule(const struct option *opt,
5188 const char *arg, int unset)
5190 struct diff_options *options = opt->value;
5192 BUG_ON_OPT_NEG(unset);
5195 if (parse_submodule_params(options, arg))
5196 return error(_("failed to parse --submodule option parameter: '%s'"),
5201 static int diff_opt_textconv(const struct option *opt,
5202 const char *arg, int unset)
5204 struct diff_options *options = opt->value;
5206 BUG_ON_OPT_ARG(arg);
5208 options->flags.allow_textconv = 0;
5210 options->flags.allow_textconv = 1;
5211 options->flags.textconv_set_via_cmdline = 1;
5216 static int diff_opt_unified(const struct option *opt,
5217 const char *arg, int unset)
5219 struct diff_options *options = opt->value;
5222 BUG_ON_OPT_NEG(unset);
5225 options->context = strtol(arg, &s, 10);
5227 return error(_("%s expects a numerical value"), "--unified");
5229 enable_patch_output(&options->output_format);
5234 static int diff_opt_word_diff(const struct option *opt,
5235 const char *arg, int unset)
5237 struct diff_options *options = opt->value;
5239 BUG_ON_OPT_NEG(unset);
5241 if (!strcmp(arg, "plain"))
5242 options->word_diff = DIFF_WORDS_PLAIN;
5243 else if (!strcmp(arg, "color")) {
5244 options->use_color = 1;
5245 options->word_diff = DIFF_WORDS_COLOR;
5247 else if (!strcmp(arg, "porcelain"))
5248 options->word_diff = DIFF_WORDS_PORCELAIN;
5249 else if (!strcmp(arg, "none"))
5250 options->word_diff = DIFF_WORDS_NONE;
5252 return error(_("bad --word-diff argument: %s"), arg);
5254 if (options->word_diff == DIFF_WORDS_NONE)
5255 options->word_diff = DIFF_WORDS_PLAIN;
5260 static int diff_opt_word_diff_regex(const struct option *opt,
5261 const char *arg, int unset)
5263 struct diff_options *options = opt->value;
5265 BUG_ON_OPT_NEG(unset);
5266 if (options->word_diff == DIFF_WORDS_NONE)
5267 options->word_diff = DIFF_WORDS_PLAIN;
5268 options->word_regex = arg;
5272 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5274 struct diff_options *options = opt->value;
5276 BUG_ON_OPT_NEG(unset);
5277 if (!strcmp(opt->long_name, "skip-to"))
5278 options->skip_instead_of_rotate = 1;
5280 options->skip_instead_of_rotate = 0;
5281 options->rotate_to = arg;
5285 static void prep_parse_options(struct diff_options *options)
5287 struct option parseopts[] = {
5288 OPT_GROUP(N_("Diff output format options")),
5289 OPT_BITOP('p', "patch", &options->output_format,
5290 N_("generate patch"),
5291 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5292 OPT_BIT_F('s', "no-patch", &options->output_format,
5293 N_("suppress diff output"),
5294 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5295 OPT_BITOP('u', NULL, &options->output_format,
5296 N_("generate patch"),
5297 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5298 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5299 N_("generate diffs with <n> lines context"),
5300 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5301 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5302 N_("generate diffs with <n> lines context")),
5303 OPT_BIT_F(0, "raw", &options->output_format,
5304 N_("generate the diff in raw format"),
5305 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5306 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5307 N_("synonym for '-p --raw'"),
5308 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5309 DIFF_FORMAT_NO_OUTPUT),
5310 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5311 N_("synonym for '-p --stat'"),
5312 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5313 DIFF_FORMAT_NO_OUTPUT),
5314 OPT_BIT_F(0, "numstat", &options->output_format,
5315 N_("machine friendly --stat"),
5316 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5317 OPT_BIT_F(0, "shortstat", &options->output_format,
5318 N_("output only the last line of --stat"),
5319 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5320 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5321 N_("output the distribution of relative amount of changes for each sub-directory"),
5322 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5324 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5325 N_("synonym for --dirstat=cumulative"),
5326 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5328 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5329 N_("synonym for --dirstat=files,param1,param2..."),
5330 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5332 OPT_BIT_F(0, "check", &options->output_format,
5333 N_("warn if changes introduce conflict markers or whitespace errors"),
5334 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5335 OPT_BIT_F(0, "summary", &options->output_format,
5336 N_("condensed summary such as creations, renames and mode changes"),
5337 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5338 OPT_BIT_F(0, "name-only", &options->output_format,
5339 N_("show only names of changed files"),
5340 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5341 OPT_BIT_F(0, "name-status", &options->output_format,
5342 N_("show only names and status of changed files"),
5343 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5344 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5345 N_("generate diffstat"),
5346 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5347 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5348 N_("generate diffstat with a given width"),
5349 PARSE_OPT_NONEG, diff_opt_stat),
5350 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5351 N_("generate diffstat with a given name width"),
5352 PARSE_OPT_NONEG, diff_opt_stat),
5353 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5354 N_("generate diffstat with a given graph width"),
5355 PARSE_OPT_NONEG, diff_opt_stat),
5356 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5357 N_("generate diffstat with limited lines"),
5358 PARSE_OPT_NONEG, diff_opt_stat),
5359 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5360 N_("generate compact summary in diffstat"),
5361 PARSE_OPT_NOARG, diff_opt_compact_summary),
5362 OPT_CALLBACK_F(0, "binary", options, NULL,
5363 N_("output a binary diff that can be applied"),
5364 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5365 OPT_BOOL(0, "full-index", &options->flags.full_index,
5366 N_("show full pre- and post-image object names on the \"index\" lines")),
5367 OPT_COLOR_FLAG(0, "color", &options->use_color,
5368 N_("show colored diff")),
5369 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5370 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5371 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5372 OPT_SET_INT('z', NULL, &options->line_termination,
5373 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5375 OPT__ABBREV(&options->abbrev),
5376 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5377 N_("show the given source prefix instead of \"a/\""),
5379 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5380 N_("show the given destination prefix instead of \"b/\""),
5382 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5383 N_("prepend an additional prefix to every line of output"),
5384 PARSE_OPT_NONEG, diff_opt_line_prefix),
5385 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5386 N_("do not show any source or destination prefix"),
5387 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5388 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5389 N_("show context between diff hunks up to the specified number of lines"),
5391 OPT_CALLBACK_F(0, "output-indicator-new",
5392 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5394 N_("specify the character to indicate a new line instead of '+'"),
5395 PARSE_OPT_NONEG, diff_opt_char),
5396 OPT_CALLBACK_F(0, "output-indicator-old",
5397 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5399 N_("specify the character to indicate an old line instead of '-'"),
5400 PARSE_OPT_NONEG, diff_opt_char),
5401 OPT_CALLBACK_F(0, "output-indicator-context",
5402 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5404 N_("specify the character to indicate a context instead of ' '"),
5405 PARSE_OPT_NONEG, diff_opt_char),
5407 OPT_GROUP(N_("Diff rename options")),
5408 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5409 N_("break complete rewrite changes into pairs of delete and create"),
5410 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5411 diff_opt_break_rewrites),
5412 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5413 N_("detect renames"),
5414 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5415 diff_opt_find_renames),
5416 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5417 N_("omit the preimage for deletes"),
5418 1, PARSE_OPT_NONEG),
5419 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5420 N_("detect copies"),
5421 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5422 diff_opt_find_copies),
5423 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5424 N_("use unmodified files as source to find copies")),
5425 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5426 N_("disable rename detection"),
5427 0, PARSE_OPT_NONEG),
5428 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5429 N_("use empty blobs as rename source")),
5430 OPT_CALLBACK_F(0, "follow", options, NULL,
5431 N_("continue listing the history of a file beyond renames"),
5432 PARSE_OPT_NOARG, diff_opt_follow),
5433 OPT_INTEGER('l', NULL, &options->rename_limit,
5434 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5436 OPT_GROUP(N_("Diff algorithm options")),
5437 OPT_BIT(0, "minimal", &options->xdl_opts,
5438 N_("produce the smallest possible diff"),
5440 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5441 N_("ignore whitespace when comparing lines"),
5442 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5443 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5444 N_("ignore changes in amount of whitespace"),
5445 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5446 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5447 N_("ignore changes in whitespace at EOL"),
5448 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5449 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5450 N_("ignore carrier-return at the end of line"),
5451 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5452 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5453 N_("ignore changes whose lines are all blank"),
5454 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5455 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5456 N_("ignore changes whose all lines match <regex>"),
5457 0, diff_opt_ignore_regex),
5458 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5459 N_("heuristic to shift diff hunk boundaries for easy reading"),
5460 XDF_INDENT_HEURISTIC),
5461 OPT_CALLBACK_F(0, "patience", options, NULL,
5462 N_("generate diff using the \"patience diff\" algorithm"),
5463 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5465 OPT_BITOP(0, "histogram", &options->xdl_opts,
5466 N_("generate diff using the \"histogram diff\" algorithm"),
5467 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5468 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5469 N_("choose a diff algorithm"),
5470 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5471 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5472 N_("generate diff using the \"anchored diff\" algorithm"),
5473 PARSE_OPT_NONEG, diff_opt_anchored),
5474 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5475 N_("show word diff, using <mode> to delimit changed words"),
5476 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5477 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5478 N_("use <regex> to decide what a word is"),
5479 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5480 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5481 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5482 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5483 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5484 N_("moved lines of code are colored differently"),
5485 PARSE_OPT_OPTARG, diff_opt_color_moved),
5486 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5487 N_("how white spaces are ignored in --color-moved"),
5488 0, diff_opt_color_moved_ws),
5490 OPT_GROUP(N_("Other diff options")),
5491 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5492 N_("when run from subdir, exclude changes outside and show relative paths"),
5495 OPT_BOOL('a', "text", &options->flags.text,
5496 N_("treat all files as text")),
5497 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5498 N_("swap two inputs, reverse the diff")),
5499 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5500 N_("exit with 1 if there were differences, 0 otherwise")),
5501 OPT_BOOL(0, "quiet", &options->flags.quick,
5502 N_("disable all output of the program")),
5503 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5504 N_("allow an external diff helper to be executed")),
5505 OPT_CALLBACK_F(0, "textconv", options, NULL,
5506 N_("run external text conversion filters when comparing binary files"),
5507 PARSE_OPT_NOARG, diff_opt_textconv),
5508 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5509 N_("ignore changes to submodules in the diff generation"),
5510 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5511 diff_opt_ignore_submodules),
5512 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5513 N_("specify how differences in submodules are shown"),
5514 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5515 diff_opt_submodule),
5516 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5517 N_("hide 'git add -N' entries from the index"),
5518 1, PARSE_OPT_NONEG),
5519 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5520 N_("treat 'git add -N' entries as real in the index"),
5521 0, PARSE_OPT_NONEG),
5522 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5523 N_("look for differences that change the number of occurrences of the specified string"),
5524 0, diff_opt_pickaxe_string),
5525 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5526 N_("look for differences that change the number of occurrences of the specified regex"),
5527 0, diff_opt_pickaxe_regex),
5528 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5529 N_("show all changes in the changeset with -S or -G"),
5530 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5531 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5532 N_("treat <string> in -S as extended POSIX regular expression"),
5533 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5534 OPT_FILENAME('O', NULL, &options->orderfile,
5535 N_("control the order in which files appear in the output")),
5536 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5537 N_("show the change in the specified path first"),
5538 PARSE_OPT_NONEG, diff_opt_rotate_to),
5539 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5540 N_("skip the output to the specified path"),
5541 PARSE_OPT_NONEG, diff_opt_rotate_to),
5542 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5543 N_("look for differences that change the number of occurrences of the specified object"),
5544 PARSE_OPT_NONEG, diff_opt_find_object),
5545 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5546 N_("select files by diff type"),
5547 PARSE_OPT_NONEG, diff_opt_diff_filter),
5548 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5549 N_("Output to a specific file"),
5550 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5555 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5556 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5559 int diff_opt_parse(struct diff_options *options,
5560 const char **av, int ac, const char *prefix)
5565 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5566 PARSE_OPT_KEEP_DASHDASH |
5567 PARSE_OPT_KEEP_UNKNOWN |
5568 PARSE_OPT_NO_INTERNAL_HELP |
5569 PARSE_OPT_ONE_SHOT |
5570 PARSE_OPT_STOP_AT_NON_OPTION);
5575 int parse_rename_score(const char **cp_p)
5577 unsigned long num, scale;
5579 const char *cp = *cp_p;
5586 if ( !dot && ch == '.' ) {
5589 } else if ( ch == '%' ) {
5590 scale = dot ? scale*100 : 100;
5591 cp++; /* % is always at the end */
5593 } else if ( ch >= '0' && ch <= '9' ) {
5594 if ( scale < 100000 ) {
5596 num = (num*10) + (ch-'0');
5605 /* user says num divided by scale and we say internally that
5606 * is MAX_SCORE * num / scale.
5608 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5611 struct diff_queue_struct diff_queued_diff;
5613 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5615 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5616 queue->queue[queue->nr++] = dp;
5619 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5620 struct diff_filespec *one,
5621 struct diff_filespec *two)
5623 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5631 void diff_free_filepair(struct diff_filepair *p)
5633 free_filespec(p->one);
5634 free_filespec(p->two);
5638 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5643 /* Do we want all 40 hex characters? */
5644 if (len == the_hash_algo->hexsz)
5645 return oid_to_hex(oid);
5647 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5648 abbrev = diff_abbrev_oid(oid, len);
5650 if (!print_sha1_ellipsis())
5653 abblen = strlen(abbrev);
5656 * In well-behaved cases, where the abbreviated result is the
5657 * same as the requested length, append three dots after the
5658 * abbreviation (hence the whole logic is limited to the case
5659 * where abblen < 37); when the actual abbreviated result is a
5660 * bit longer than the requested length, we reduce the number
5661 * of dots so that they match the well-behaved ones. However,
5662 * if the actual abbreviation is longer than the requested
5663 * length by more than three, we give up on aligning, and add
5664 * three dots anyway, to indicate that the output is not the
5665 * full object name. Yes, this may be suboptimal, but this
5666 * appears only in "diff --raw --abbrev" output and it is not
5667 * worth the effort to change it now. Note that this would
5668 * likely to work fine when the automatic sizing of default
5669 * abbreviation length is used--we would be fed -1 in "len" in
5670 * that case, and will end up always appending three-dots, but
5671 * the automatic sizing is supposed to give abblen that ensures
5672 * uniqueness across all objects (statistically speaking).
5674 if (abblen < the_hash_algo->hexsz - 3) {
5675 static char hex[GIT_MAX_HEXSZ + 1];
5676 if (len < abblen && abblen <= len + 2)
5677 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5679 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5683 return oid_to_hex(oid);
5686 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5688 int line_termination = opt->line_termination;
5689 int inter_name_termination = line_termination ? '\t' : '\0';
5691 fprintf(opt->file, "%s", diff_line_prefix(opt));
5692 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5693 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5694 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5695 fprintf(opt->file, "%s ",
5696 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5699 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5700 inter_name_termination);
5702 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5705 if (p->status == DIFF_STATUS_COPIED ||
5706 p->status == DIFF_STATUS_RENAMED) {
5707 const char *name_a, *name_b;
5708 name_a = p->one->path;
5709 name_b = p->two->path;
5710 strip_prefix(opt->prefix_length, &name_a, &name_b);
5711 write_name_quoted(name_a, opt->file, inter_name_termination);
5712 write_name_quoted(name_b, opt->file, line_termination);
5714 const char *name_a, *name_b;
5715 name_a = p->one->mode ? p->one->path : p->two->path;
5717 strip_prefix(opt->prefix_length, &name_a, &name_b);
5718 write_name_quoted(name_a, opt->file, line_termination);
5722 int diff_unmodified_pair(struct diff_filepair *p)
5724 /* This function is written stricter than necessary to support
5725 * the currently implemented transformers, but the idea is to
5726 * let transformers to produce diff_filepairs any way they want,
5727 * and filter and clean them up here before producing the output.
5729 struct diff_filespec *one = p->one, *two = p->two;
5731 if (DIFF_PAIR_UNMERGED(p))
5732 return 0; /* unmerged is interesting */
5734 /* deletion, addition, mode or type change
5735 * and rename are all interesting.
5737 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5738 DIFF_PAIR_MODE_CHANGED(p) ||
5739 strcmp(one->path, two->path))
5742 /* both are valid and point at the same path. that is, we are
5743 * dealing with a change.
5745 if (one->oid_valid && two->oid_valid &&
5746 oideq(&one->oid, &two->oid) &&
5747 !one->dirty_submodule && !two->dirty_submodule)
5748 return 1; /* no change */
5749 if (!one->oid_valid && !two->oid_valid)
5750 return 1; /* both look at the same file on the filesystem. */
5754 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5756 if (diff_unmodified_pair(p))
5759 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5760 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5761 return; /* no tree diffs in patch format */
5766 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5767 struct diffstat_t *diffstat)
5769 if (diff_unmodified_pair(p))
5772 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5773 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5774 return; /* no useful stat for tree diffs */
5776 run_diffstat(p, o, diffstat);
5779 static void diff_flush_checkdiff(struct diff_filepair *p,
5780 struct diff_options *o)
5782 if (diff_unmodified_pair(p))
5785 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5786 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5787 return; /* nothing to check in tree diffs */
5789 run_checkdiff(p, o);
5792 int diff_queue_is_empty(void)
5794 struct diff_queue_struct *q = &diff_queued_diff;
5796 for (i = 0; i < q->nr; i++)
5797 if (!diff_unmodified_pair(q->queue[i]))
5803 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5805 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5808 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5810 s->oid_valid ? oid_to_hex(&s->oid) : "");
5811 fprintf(stderr, "queue[%d] %s size %lu\n",
5816 void diff_debug_filepair(const struct diff_filepair *p, int i)
5818 diff_debug_filespec(p->one, i, "one");
5819 diff_debug_filespec(p->two, i, "two");
5820 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5821 p->score, p->status ? p->status : '?',
5822 p->one->rename_used, p->broken_pair);
5825 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5829 fprintf(stderr, "%s\n", msg);
5830 fprintf(stderr, "q->nr = %d\n", q->nr);
5831 for (i = 0; i < q->nr; i++) {
5832 struct diff_filepair *p = q->queue[i];
5833 diff_debug_filepair(p, i);
5838 static void diff_resolve_rename_copy(void)
5841 struct diff_filepair *p;
5842 struct diff_queue_struct *q = &diff_queued_diff;
5844 diff_debug_queue("resolve-rename-copy", q);
5846 for (i = 0; i < q->nr; i++) {
5848 p->status = 0; /* undecided */
5849 if (DIFF_PAIR_UNMERGED(p))
5850 p->status = DIFF_STATUS_UNMERGED;
5851 else if (!DIFF_FILE_VALID(p->one))
5852 p->status = DIFF_STATUS_ADDED;
5853 else if (!DIFF_FILE_VALID(p->two))
5854 p->status = DIFF_STATUS_DELETED;
5855 else if (DIFF_PAIR_TYPE_CHANGED(p))
5856 p->status = DIFF_STATUS_TYPE_CHANGED;
5858 /* from this point on, we are dealing with a pair
5859 * whose both sides are valid and of the same type, i.e.
5860 * either in-place edit or rename/copy edit.
5862 else if (DIFF_PAIR_RENAME(p)) {
5864 * A rename might have re-connected a broken
5865 * pair up, causing the pathnames to be the
5866 * same again. If so, that's not a rename at
5867 * all, just a modification..
5869 * Otherwise, see if this source was used for
5870 * multiple renames, in which case we decrement
5871 * the count, and call it a copy.
5873 if (!strcmp(p->one->path, p->two->path))
5874 p->status = DIFF_STATUS_MODIFIED;
5875 else if (--p->one->rename_used > 0)
5876 p->status = DIFF_STATUS_COPIED;
5878 p->status = DIFF_STATUS_RENAMED;
5880 else if (!oideq(&p->one->oid, &p->two->oid) ||
5881 p->one->mode != p->two->mode ||
5882 p->one->dirty_submodule ||
5883 p->two->dirty_submodule ||
5884 is_null_oid(&p->one->oid))
5885 p->status = DIFF_STATUS_MODIFIED;
5887 /* This is a "no-change" entry and should not
5888 * happen anymore, but prepare for broken callers.
5890 error("feeding unmodified %s to diffcore",
5892 p->status = DIFF_STATUS_UNKNOWN;
5895 diff_debug_queue("resolve-rename-copy done", q);
5898 static int check_pair_status(struct diff_filepair *p)
5900 switch (p->status) {
5901 case DIFF_STATUS_UNKNOWN:
5904 die("internal error in diff-resolve-rename-copy");
5910 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5912 int fmt = opt->output_format;
5914 if (fmt & DIFF_FORMAT_CHECKDIFF)
5915 diff_flush_checkdiff(p, opt);
5916 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5917 diff_flush_raw(p, opt);
5918 else if (fmt & DIFF_FORMAT_NAME) {
5919 const char *name_a, *name_b;
5920 name_a = p->two->path;
5922 strip_prefix(opt->prefix_length, &name_a, &name_b);
5923 fprintf(opt->file, "%s", diff_line_prefix(opt));
5924 write_name_quoted(name_a, opt->file, opt->line_termination);
5928 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5930 struct strbuf sb = STRBUF_INIT;
5932 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5934 strbuf_addf(&sb, " %s ", newdelete);
5936 quote_c_style(fs->path, &sb, NULL, 0);
5937 strbuf_addch(&sb, '\n');
5938 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5940 strbuf_release(&sb);
5943 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5946 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5947 struct strbuf sb = STRBUF_INIT;
5948 strbuf_addf(&sb, " mode change %06o => %06o",
5949 p->one->mode, p->two->mode);
5951 strbuf_addch(&sb, ' ');
5952 quote_c_style(p->two->path, &sb, NULL, 0);
5954 strbuf_addch(&sb, '\n');
5955 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5957 strbuf_release(&sb);
5961 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5962 struct diff_filepair *p)
5964 struct strbuf sb = STRBUF_INIT;
5965 struct strbuf names = STRBUF_INIT;
5967 pprint_rename(&names, p->one->path, p->two->path);
5968 strbuf_addf(&sb, " %s %s (%d%%)\n",
5969 renamecopy, names.buf, similarity_index(p));
5970 strbuf_release(&names);
5971 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5973 show_mode_change(opt, p, 0);
5974 strbuf_release(&sb);
5977 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5980 case DIFF_STATUS_DELETED:
5981 show_file_mode_name(opt, "delete", p->one);
5983 case DIFF_STATUS_ADDED:
5984 show_file_mode_name(opt, "create", p->two);
5986 case DIFF_STATUS_COPIED:
5987 show_rename_copy(opt, "copy", p);
5989 case DIFF_STATUS_RENAMED:
5990 show_rename_copy(opt, "rename", p);
5994 struct strbuf sb = STRBUF_INIT;
5995 strbuf_addstr(&sb, " rewrite ");
5996 quote_c_style(p->two->path, &sb, NULL, 0);
5997 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5998 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6000 strbuf_release(&sb);
6002 show_mode_change(opt, p, !p->score);
6012 static int remove_space(char *line, int len)
6018 for (i = 0; i < len; i++)
6019 if (!isspace((c = line[i])))
6025 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6027 unsigned char hash[GIT_MAX_RAWSZ];
6028 unsigned short carry = 0;
6031 the_hash_algo->final_fn(hash, ctx);
6032 the_hash_algo->init_fn(ctx);
6033 /* 20-byte sum, with carry */
6034 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6035 carry += result->hash[i] + hash[i];
6036 result->hash[i] = carry;
6041 static int patch_id_consume(void *priv, char *line, unsigned long len)
6043 struct patch_id_t *data = priv;
6046 if (len > 12 && starts_with(line, "\\ "))
6048 new_len = remove_space(line, len);
6050 the_hash_algo->update_fn(data->ctx, line, new_len);
6051 data->patchlen += new_len;
6055 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6057 the_hash_algo->update_fn(ctx, str, strlen(str));
6060 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6062 /* large enough for 2^32 in octal */
6064 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6065 the_hash_algo->update_fn(ctx, buf, len);
6068 /* returns 0 upon success, and writes result into oid */
6069 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6071 struct diff_queue_struct *q = &diff_queued_diff;
6074 struct patch_id_t data;
6076 the_hash_algo->init_fn(&ctx);
6077 memset(&data, 0, sizeof(struct patch_id_t));
6081 for (i = 0; i < q->nr; i++) {
6085 struct diff_filepair *p = q->queue[i];
6088 memset(&xpp, 0, sizeof(xpp));
6089 memset(&xecfg, 0, sizeof(xecfg));
6091 return error("internal diff status error");
6092 if (p->status == DIFF_STATUS_UNKNOWN)
6094 if (diff_unmodified_pair(p))
6096 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6097 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6099 if (DIFF_PAIR_UNMERGED(p))
6102 diff_fill_oid_info(p->one, options->repo->index);
6103 diff_fill_oid_info(p->two, options->repo->index);
6105 len1 = remove_space(p->one->path, strlen(p->one->path));
6106 len2 = remove_space(p->two->path, strlen(p->two->path));
6107 patch_id_add_string(&ctx, "diff--git");
6108 patch_id_add_string(&ctx, "a/");
6109 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6110 patch_id_add_string(&ctx, "b/");
6111 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6113 if (p->one->mode == 0) {
6114 patch_id_add_string(&ctx, "newfilemode");
6115 patch_id_add_mode(&ctx, p->two->mode);
6116 patch_id_add_string(&ctx, "---/dev/null");
6117 patch_id_add_string(&ctx, "+++b/");
6118 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6119 } else if (p->two->mode == 0) {
6120 patch_id_add_string(&ctx, "deletedfilemode");
6121 patch_id_add_mode(&ctx, p->one->mode);
6122 patch_id_add_string(&ctx, "---a/");
6123 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6124 patch_id_add_string(&ctx, "+++/dev/null");
6126 patch_id_add_string(&ctx, "---a/");
6127 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6128 patch_id_add_string(&ctx, "+++b/");
6129 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6132 if (diff_header_only)
6135 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6136 fill_mmfile(options->repo, &mf2, p->two) < 0)
6137 return error("unable to read files to diff");
6139 if (diff_filespec_is_binary(options->repo, p->one) ||
6140 diff_filespec_is_binary(options->repo, p->two)) {
6141 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6142 the_hash_algo->hexsz);
6143 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6144 the_hash_algo->hexsz);
6150 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6151 if (xdi_diff_outf(&mf1, &mf2, NULL,
6152 patch_id_consume, &data, &xpp, &xecfg))
6153 return error("unable to generate patch-id diff for %s",
6157 flush_one_hunk(oid, &ctx);
6161 the_hash_algo->final_oid_fn(oid, &ctx);
6166 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6168 struct diff_queue_struct *q = &diff_queued_diff;
6170 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
6172 for (i = 0; i < q->nr; i++)
6173 diff_free_filepair(q->queue[i]);
6176 DIFF_QUEUE_CLEAR(q);
6181 static int is_summary_empty(const struct diff_queue_struct *q)
6185 for (i = 0; i < q->nr; i++) {
6186 const struct diff_filepair *p = q->queue[i];
6188 switch (p->status) {
6189 case DIFF_STATUS_DELETED:
6190 case DIFF_STATUS_ADDED:
6191 case DIFF_STATUS_COPIED:
6192 case DIFF_STATUS_RENAMED:
6197 if (p->one->mode && p->two->mode &&
6198 p->one->mode != p->two->mode)
6206 static const char rename_limit_warning[] =
6207 N_("inexact rename detection was skipped due to too many files.");
6209 static const char degrade_cc_to_c_warning[] =
6210 N_("only found copies from modified paths due to too many files.");
6212 static const char rename_limit_advice[] =
6213 N_("you may want to set your %s variable to at least "
6214 "%d and retry the command.");
6216 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6220 warning(_(degrade_cc_to_c_warning));
6222 warning(_(rename_limit_warning));
6226 warning(_(rename_limit_advice), varname, needed);
6229 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6232 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6233 struct diff_queue_struct *q = &diff_queued_diff;
6235 if (WSEH_NEW & WS_RULE_MASK)
6236 BUG("WS rules bit mask overlaps with diff symbol flags");
6239 o->emitted_symbols = &esm;
6241 for (i = 0; i < q->nr; i++) {
6242 struct diff_filepair *p = q->queue[i];
6243 if (check_pair_status(p))
6244 diff_flush_patch(p, o);
6247 if (o->emitted_symbols) {
6248 if (o->color_moved) {
6249 struct mem_pool entry_pool;
6250 struct moved_entry_list *entry_list;
6252 mem_pool_init(&entry_pool, 1024 * 1024);
6253 entry_list = add_lines_to_move_detection(o,
6255 mark_color_as_moved(o, entry_list);
6256 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6259 mem_pool_discard(&entry_pool, 0);
6263 for (i = 0; i < esm.nr; i++)
6264 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6266 for (i = 0; i < esm.nr; i++)
6267 free((void *)esm.buf[i].line);
6270 o->emitted_symbols = NULL;
6274 static void diff_free_file(struct diff_options *options)
6276 if (options->close_file)
6277 fclose(options->file);
6280 static void diff_free_ignore_regex(struct diff_options *options)
6284 for (i = 0; i < options->ignore_regex_nr; i++) {
6285 regfree(options->ignore_regex[i]);
6286 free(options->ignore_regex[i]);
6288 free(options->ignore_regex);
6291 void diff_free(struct diff_options *options)
6293 if (options->no_free)
6296 diff_free_file(options);
6297 diff_free_ignore_regex(options);
6300 void diff_flush(struct diff_options *options)
6302 struct diff_queue_struct *q = &diff_queued_diff;
6303 int i, output_format = options->output_format;
6305 int dirstat_by_line = 0;
6308 * Order: raw, stat, summary, patch
6309 * or: name/name-status/checkdiff (other bits clear)
6314 if (output_format & (DIFF_FORMAT_RAW |
6316 DIFF_FORMAT_NAME_STATUS |
6317 DIFF_FORMAT_CHECKDIFF)) {
6318 for (i = 0; i < q->nr; i++) {
6319 struct diff_filepair *p = q->queue[i];
6320 if (check_pair_status(p))
6321 flush_one_pair(p, options);
6326 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6327 dirstat_by_line = 1;
6329 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6331 struct diffstat_t diffstat;
6333 compute_diffstat(options, &diffstat, q);
6334 if (output_format & DIFF_FORMAT_NUMSTAT)
6335 show_numstat(&diffstat, options);
6336 if (output_format & DIFF_FORMAT_DIFFSTAT)
6337 show_stats(&diffstat, options);
6338 if (output_format & DIFF_FORMAT_SHORTSTAT)
6339 show_shortstats(&diffstat, options);
6340 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6341 show_dirstat_by_line(&diffstat, options);
6342 free_diffstat_info(&diffstat);
6345 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6346 show_dirstat(options);
6348 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6349 for (i = 0; i < q->nr; i++) {
6350 diff_summary(options, q->queue[i]);
6355 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6356 options->flags.exit_with_status &&
6357 options->flags.diff_from_contents) {
6359 * run diff_flush_patch for the exit status. setting
6360 * options->file to /dev/null should be safe, because we
6361 * aren't supposed to produce any output anyway.
6363 diff_free_file(options);
6364 options->file = xfopen("/dev/null", "w");
6365 options->close_file = 1;
6366 options->color_moved = 0;
6367 for (i = 0; i < q->nr; i++) {
6368 struct diff_filepair *p = q->queue[i];
6369 if (check_pair_status(p))
6370 diff_flush_patch(p, options);
6371 if (options->found_changes)
6376 if (output_format & DIFF_FORMAT_PATCH) {
6378 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6379 if (options->stat_sep)
6380 /* attach patch instead of inline */
6381 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6385 diff_flush_patch_all_file_pairs(options);
6388 if (output_format & DIFF_FORMAT_CALLBACK)
6389 options->format_callback(q, options, options->format_callback_data);
6391 for (i = 0; i < q->nr; i++)
6392 diff_free_filepair(q->queue[i]);
6395 DIFF_QUEUE_CLEAR(q);
6399 * Report the content-level differences with HAS_CHANGES;
6400 * diff_addremove/diff_change does not set the bit when
6401 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6403 if (options->flags.diff_from_contents) {
6404 if (options->found_changes)
6405 options->flags.has_changes = 1;
6407 options->flags.has_changes = 0;
6411 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6413 return (((p->status == DIFF_STATUS_MODIFIED) &&
6415 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6417 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6418 ((p->status != DIFF_STATUS_MODIFIED) &&
6419 filter_bit_tst(p->status, options)));
6422 static void diffcore_apply_filter(struct diff_options *options)
6425 struct diff_queue_struct *q = &diff_queued_diff;
6426 struct diff_queue_struct outq;
6428 DIFF_QUEUE_CLEAR(&outq);
6430 if (!options->filter)
6433 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6435 for (i = found = 0; !found && i < q->nr; i++) {
6436 if (match_filter(options, q->queue[i]))
6442 /* otherwise we will clear the whole queue
6443 * by copying the empty outq at the end of this
6444 * function, but first clear the current entries
6447 for (i = 0; i < q->nr; i++)
6448 diff_free_filepair(q->queue[i]);
6451 /* Only the matching ones */
6452 for (i = 0; i < q->nr; i++) {
6453 struct diff_filepair *p = q->queue[i];
6454 if (match_filter(options, p))
6457 diff_free_filepair(p);
6464 /* Check whether two filespecs with the same mode and size are identical */
6465 static int diff_filespec_is_identical(struct repository *r,
6466 struct diff_filespec *one,
6467 struct diff_filespec *two)
6469 if (S_ISGITLINK(one->mode))
6471 if (diff_populate_filespec(r, one, NULL))
6473 if (diff_populate_filespec(r, two, NULL))
6475 return !memcmp(one->data, two->data, one->size);
6478 static int diff_filespec_check_stat_unmatch(struct repository *r,
6479 struct diff_filepair *p)
6481 struct diff_populate_filespec_options dpf_options = {
6482 .check_size_only = 1,
6483 .missing_object_cb = diff_queued_diff_prefetch,
6484 .missing_object_data = r,
6487 if (p->done_skip_stat_unmatch)
6488 return p->skip_stat_unmatch_result;
6490 p->done_skip_stat_unmatch = 1;
6491 p->skip_stat_unmatch_result = 0;
6493 * 1. Entries that come from stat info dirtiness
6494 * always have both sides (iow, not create/delete),
6495 * one side of the object name is unknown, with
6496 * the same mode and size. Keep the ones that
6497 * do not match these criteria. They have real
6500 * 2. At this point, the file is known to be modified,
6501 * with the same mode and size, and the object
6502 * name of one side is unknown. Need to inspect
6503 * the identical contents.
6505 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6506 !DIFF_FILE_VALID(p->two) ||
6507 (p->one->oid_valid && p->two->oid_valid) ||
6508 (p->one->mode != p->two->mode) ||
6509 diff_populate_filespec(r, p->one, &dpf_options) ||
6510 diff_populate_filespec(r, p->two, &dpf_options) ||
6511 (p->one->size != p->two->size) ||
6512 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6513 p->skip_stat_unmatch_result = 1;
6514 return p->skip_stat_unmatch_result;
6517 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6520 struct diff_queue_struct *q = &diff_queued_diff;
6521 struct diff_queue_struct outq;
6522 DIFF_QUEUE_CLEAR(&outq);
6524 for (i = 0; i < q->nr; i++) {
6525 struct diff_filepair *p = q->queue[i];
6527 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6531 * The caller can subtract 1 from skip_stat_unmatch
6532 * to determine how many paths were dirty only
6533 * due to stat info mismatch.
6535 if (!diffopt->flags.no_index)
6536 diffopt->skip_stat_unmatch++;
6537 diff_free_filepair(p);
6544 static int diffnamecmp(const void *a_, const void *b_)
6546 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6547 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6548 const char *name_a, *name_b;
6550 name_a = a->one ? a->one->path : a->two->path;
6551 name_b = b->one ? b->one->path : b->two->path;
6552 return strcmp(name_a, name_b);
6555 void diffcore_fix_diff_index(void)
6557 struct diff_queue_struct *q = &diff_queued_diff;
6558 QSORT(q->queue, q->nr, diffnamecmp);
6561 void diff_add_if_missing(struct repository *r,
6562 struct oid_array *to_fetch,
6563 const struct diff_filespec *filespec)
6565 if (filespec && filespec->oid_valid &&
6566 !S_ISGITLINK(filespec->mode) &&
6567 oid_object_info_extended(r, &filespec->oid, NULL,
6568 OBJECT_INFO_FOR_PREFETCH))
6569 oid_array_append(to_fetch, &filespec->oid);
6572 void diff_queued_diff_prefetch(void *repository)
6574 struct repository *repo = repository;
6576 struct diff_queue_struct *q = &diff_queued_diff;
6577 struct oid_array to_fetch = OID_ARRAY_INIT;
6579 for (i = 0; i < q->nr; i++) {
6580 struct diff_filepair *p = q->queue[i];
6581 diff_add_if_missing(repo, &to_fetch, p->one);
6582 diff_add_if_missing(repo, &to_fetch, p->two);
6586 * NEEDSWORK: Consider deduplicating the OIDs sent.
6588 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6590 oid_array_clear(&to_fetch);
6593 void diffcore_std(struct diff_options *options)
6595 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6596 DIFF_FORMAT_NUMSTAT |
6598 DIFF_FORMAT_SHORTSTAT |
6599 DIFF_FORMAT_DIRSTAT;
6602 * Check if the user requested a blob-data-requiring diff output and/or
6603 * break-rewrite detection (which requires blob data). If yes, prefetch
6606 * If no prefetching occurs, diffcore_rename() will prefetch if it
6607 * decides that it needs inexact rename detection.
6609 if (options->repo == the_repository && has_promisor_remote() &&
6610 (options->output_format & output_formats_to_prefetch ||
6611 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6612 diff_queued_diff_prefetch(options->repo);
6614 /* NOTE please keep the following in sync with diff_tree_combined() */
6615 if (options->skip_stat_unmatch)
6616 diffcore_skip_stat_unmatch(options);
6617 if (!options->found_follow) {
6618 /* See try_to_follow_renames() in tree-diff.c */
6619 if (options->break_opt != -1)
6620 diffcore_break(options->repo,
6621 options->break_opt);
6622 if (options->detect_rename)
6623 diffcore_rename(options);
6624 if (options->break_opt != -1)
6625 diffcore_merge_broken();
6627 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6628 diffcore_pickaxe(options);
6629 if (options->orderfile)
6630 diffcore_order(options->orderfile);
6631 if (options->rotate_to)
6632 diffcore_rotate(options);
6633 if (!options->found_follow)
6634 /* See try_to_follow_renames() in tree-diff.c */
6635 diff_resolve_rename_copy();
6636 diffcore_apply_filter(options);
6638 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6639 options->flags.has_changes = 1;
6641 options->flags.has_changes = 0;
6643 options->found_follow = 0;
6646 int diff_result_code(struct diff_options *opt, int status)
6650 diff_warn_rename_limit("diff.renameLimit",
6651 opt->needed_rename_limit,
6652 opt->degraded_cc_to_c);
6653 if (!opt->flags.exit_with_status &&
6654 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6656 if (opt->flags.exit_with_status &&
6657 opt->flags.has_changes)
6659 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6660 opt->flags.check_failed)
6665 int diff_can_quit_early(struct diff_options *opt)
6667 return (opt->flags.quick &&
6669 opt->flags.has_changes);
6673 * Shall changes to this submodule be ignored?
6675 * Submodule changes can be configured to be ignored separately for each path,
6676 * but that configuration can be overridden from the command line.
6678 static int is_submodule_ignored(const char *path, struct diff_options *options)
6681 struct diff_flags orig_flags = options->flags;
6682 if (!options->flags.override_submodule_config)
6683 set_diffopt_flags_from_submodule_config(options, path);
6684 if (options->flags.ignore_submodules)
6686 options->flags = orig_flags;
6690 void compute_diffstat(struct diff_options *options,
6691 struct diffstat_t *diffstat,
6692 struct diff_queue_struct *q)
6696 memset(diffstat, 0, sizeof(struct diffstat_t));
6697 for (i = 0; i < q->nr; i++) {
6698 struct diff_filepair *p = q->queue[i];
6699 if (check_pair_status(p))
6700 diff_flush_stat(p, options, diffstat);
6704 void diff_addremove(struct diff_options *options,
6705 int addremove, unsigned mode,
6706 const struct object_id *oid,
6708 const char *concatpath, unsigned dirty_submodule)
6710 struct diff_filespec *one, *two;
6712 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6715 /* This may look odd, but it is a preparation for
6716 * feeding "there are unchanged files which should
6717 * not produce diffs, but when you are doing copy
6718 * detection you would need them, so here they are"
6719 * entries to the diff-core. They will be prefixed
6720 * with something like '=' or '*' (I haven't decided
6721 * which but should not make any difference).
6722 * Feeding the same new and old to diff_change()
6723 * also has the same effect.
6724 * Before the final output happens, they are pruned after
6725 * merged into rename/copy pairs as appropriate.
6727 if (options->flags.reverse_diff)
6728 addremove = (addremove == '+' ? '-' :
6729 addremove == '-' ? '+' : addremove);
6731 if (options->prefix &&
6732 strncmp(concatpath, options->prefix, options->prefix_length))
6735 one = alloc_filespec(concatpath);
6736 two = alloc_filespec(concatpath);
6738 if (addremove != '+')
6739 fill_filespec(one, oid, oid_valid, mode);
6740 if (addremove != '-') {
6741 fill_filespec(two, oid, oid_valid, mode);
6742 two->dirty_submodule = dirty_submodule;
6745 diff_queue(&diff_queued_diff, one, two);
6746 if (!options->flags.diff_from_contents)
6747 options->flags.has_changes = 1;
6750 void diff_change(struct diff_options *options,
6751 unsigned old_mode, unsigned new_mode,
6752 const struct object_id *old_oid,
6753 const struct object_id *new_oid,
6754 int old_oid_valid, int new_oid_valid,
6755 const char *concatpath,
6756 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6758 struct diff_filespec *one, *two;
6759 struct diff_filepair *p;
6761 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6762 is_submodule_ignored(concatpath, options))
6765 if (options->flags.reverse_diff) {
6766 SWAP(old_mode, new_mode);
6767 SWAP(old_oid, new_oid);
6768 SWAP(old_oid_valid, new_oid_valid);
6769 SWAP(old_dirty_submodule, new_dirty_submodule);
6772 if (options->prefix &&
6773 strncmp(concatpath, options->prefix, options->prefix_length))
6776 one = alloc_filespec(concatpath);
6777 two = alloc_filespec(concatpath);
6778 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6779 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6780 one->dirty_submodule = old_dirty_submodule;
6781 two->dirty_submodule = new_dirty_submodule;
6782 p = diff_queue(&diff_queued_diff, one, two);
6784 if (options->flags.diff_from_contents)
6787 if (options->flags.quick && options->skip_stat_unmatch &&
6788 !diff_filespec_check_stat_unmatch(options->repo, p)) {
6789 diff_free_filespec_data(p->one);
6790 diff_free_filespec_data(p->two);
6794 options->flags.has_changes = 1;
6797 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6799 struct diff_filepair *pair;
6800 struct diff_filespec *one, *two;
6802 if (options->prefix &&
6803 strncmp(path, options->prefix, options->prefix_length))
6806 one = alloc_filespec(path);
6807 two = alloc_filespec(path);
6808 pair = diff_queue(&diff_queued_diff, one, two);
6809 pair->is_unmerged = 1;
6813 static char *run_textconv(struct repository *r,
6815 struct diff_filespec *spec,
6818 struct diff_tempfile *temp;
6819 const char *argv[3];
6820 const char **arg = argv;
6821 struct child_process child = CHILD_PROCESS_INIT;
6822 struct strbuf buf = STRBUF_INIT;
6825 temp = prepare_temp_file(r, spec->path, spec);
6827 *arg++ = temp->name;
6830 child.use_shell = 1;
6833 if (start_command(&child)) {
6838 if (strbuf_read(&buf, child.out, 0) < 0)
6839 err = error("error reading from textconv command '%s'", pgm);
6842 if (finish_command(&child) || err) {
6843 strbuf_release(&buf);
6849 return strbuf_detach(&buf, outsize);
6852 size_t fill_textconv(struct repository *r,
6853 struct userdiff_driver *driver,
6854 struct diff_filespec *df,
6860 if (!DIFF_FILE_VALID(df)) {
6864 if (diff_populate_filespec(r, df, NULL))
6865 die("unable to read files to diff");
6870 if (!driver->textconv)
6871 BUG("fill_textconv called with non-textconv driver");
6873 if (driver->textconv_cache && df->oid_valid) {
6874 *outbuf = notes_cache_get(driver->textconv_cache,
6881 *outbuf = run_textconv(r, driver->textconv, df, &size);
6883 die("unable to read files to diff");
6885 if (driver->textconv_cache && df->oid_valid) {
6886 /* ignore errors, as we might be in a readonly repository */
6887 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6890 * we could save up changes and flush them all at the end,
6891 * but we would need an extra call after all diffing is done.
6892 * Since generating a cache entry is the slow path anyway,
6893 * this extra overhead probably isn't a big deal.
6895 notes_cache_write(driver->textconv_cache);
6901 int textconv_object(struct repository *r,
6904 const struct object_id *oid,
6907 unsigned long *buf_size)
6909 struct diff_filespec *df;
6910 struct userdiff_driver *textconv;
6912 df = alloc_filespec(path);
6913 fill_filespec(df, oid, oid_valid, mode);
6914 textconv = get_textconv(r, df);
6920 *buf_size = fill_textconv(r, textconv, df, buf);
6925 void setup_diff_pager(struct diff_options *opt)
6928 * If the user asked for our exit code, then either they want --quiet
6929 * or --exit-code. We should definitely not bother with a pager in the
6930 * former case, as we will generate no output. Since we still properly
6931 * report our exit code even when a pager is run, we _could_ run a
6932 * pager with --exit-code. But since we have not done so historically,
6933 * and because it is easy to find people oneline advising "git diff
6934 * --exit-code" in hooks and other scripts, we do not do so.
6936 if (!opt->flags.exit_with_status &&
6937 check_pager_config("diff") != 0)