Merge branch 'sb/diff-color-moved-config-option-fixup'
[git.git] / diff.c
blobf1e901a5fc3f4d4bd61fd1ce0ed69bb261424c15
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "tempfile.h"
7 #include "quote.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "delta.h"
11 #include "xdiff-interface.h"
12 #include "color.h"
13 #include "attr.h"
14 #include "run-command.h"
15 #include "utf8.h"
16 #include "object-store.h"
17 #include "userdiff.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
20 #include "hashmap.h"
21 #include "ll-merge.h"
22 #include "string-list.h"
23 #include "argv-array.h"
24 #include "graph.h"
25 #include "packfile.h"
26 #include "help.h"
28 #ifdef NO_FAST_WORKING_DIRECTORY
29 #define FAST_WORKING_DIRECTORY 0
30 #else
31 #define FAST_WORKING_DIRECTORY 1
32 #endif
34 static int diff_detect_rename_default;
35 static int diff_indent_heuristic = 1;
36 static int diff_rename_limit_default = 400;
37 static int diff_suppress_blank_empty;
38 static int diff_use_color_default = -1;
39 static int diff_color_moved_default;
40 static int diff_color_moved_ws_default;
41 static int diff_context_default = 3;
42 static int diff_interhunk_context_default;
43 static const char *diff_word_regex_cfg;
44 static const char *external_diff_cmd_cfg;
45 static const char *diff_order_file_cfg;
46 int diff_auto_refresh_index = 1;
47 static int diff_mnemonic_prefix;
48 static int diff_no_prefix;
49 static int diff_stat_graph_width;
50 static int diff_dirstat_permille_default = 30;
51 static struct diff_options default_diff_options;
52 static long diff_algorithm;
53 static unsigned ws_error_highlight_default = WSEH_NEW;
55 static char diff_colors[][COLOR_MAXLEN] = {
56 GIT_COLOR_RESET,
57 GIT_COLOR_NORMAL, /* CONTEXT */
58 GIT_COLOR_BOLD, /* METAINFO */
59 GIT_COLOR_CYAN, /* FRAGINFO */
60 GIT_COLOR_RED, /* OLD */
61 GIT_COLOR_GREEN, /* NEW */
62 GIT_COLOR_YELLOW, /* COMMIT */
63 GIT_COLOR_BG_RED, /* WHITESPACE */
64 GIT_COLOR_NORMAL, /* FUNCINFO */
65 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
66 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
67 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
68 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
69 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
70 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
71 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
72 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
73 GIT_COLOR_FAINT, /* CONTEXT_DIM */
74 GIT_COLOR_FAINT_RED, /* OLD_DIM */
75 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
76 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
77 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
78 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
81 static const char *color_diff_slots[] = {
82 [DIFF_CONTEXT] = "context",
83 [DIFF_METAINFO] = "meta",
84 [DIFF_FRAGINFO] = "frag",
85 [DIFF_FILE_OLD] = "old",
86 [DIFF_FILE_NEW] = "new",
87 [DIFF_COMMIT] = "commit",
88 [DIFF_WHITESPACE] = "whitespace",
89 [DIFF_FUNCINFO] = "func",
90 [DIFF_FILE_OLD_MOVED] = "oldMoved",
91 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
92 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
93 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
94 [DIFF_FILE_NEW_MOVED] = "newMoved",
95 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
96 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
97 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
98 [DIFF_CONTEXT_DIM] = "contextDimmed",
99 [DIFF_FILE_OLD_DIM] = "oldDimmed",
100 [DIFF_FILE_NEW_DIM] = "newDimmed",
101 [DIFF_CONTEXT_BOLD] = "contextBold",
102 [DIFF_FILE_OLD_BOLD] = "oldBold",
103 [DIFF_FILE_NEW_BOLD] = "newBold",
106 static NORETURN void die_want_option(const char *option_name)
108 die(_("option '%s' requires a value"), option_name);
111 define_list_config_array_extra(color_diff_slots, {"plain"});
113 static int parse_diff_color_slot(const char *var)
115 if (!strcasecmp(var, "plain"))
116 return DIFF_CONTEXT;
117 return LOOKUP_CONFIG(color_diff_slots, var);
120 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
121 struct strbuf *errmsg)
123 char *params_copy = xstrdup(params_string);
124 struct string_list params = STRING_LIST_INIT_NODUP;
125 int ret = 0;
126 int i;
128 if (*params_copy)
129 string_list_split_in_place(&params, params_copy, ',', -1);
130 for (i = 0; i < params.nr; i++) {
131 const char *p = params.items[i].string;
132 if (!strcmp(p, "changes")) {
133 options->flags.dirstat_by_line = 0;
134 options->flags.dirstat_by_file = 0;
135 } else if (!strcmp(p, "lines")) {
136 options->flags.dirstat_by_line = 1;
137 options->flags.dirstat_by_file = 0;
138 } else if (!strcmp(p, "files")) {
139 options->flags.dirstat_by_line = 0;
140 options->flags.dirstat_by_file = 1;
141 } else if (!strcmp(p, "noncumulative")) {
142 options->flags.dirstat_cumulative = 0;
143 } else if (!strcmp(p, "cumulative")) {
144 options->flags.dirstat_cumulative = 1;
145 } else if (isdigit(*p)) {
146 char *end;
147 int permille = strtoul(p, &end, 10) * 10;
148 if (*end == '.' && isdigit(*++end)) {
149 /* only use first digit */
150 permille += *end - '0';
151 /* .. and ignore any further digits */
152 while (isdigit(*++end))
153 ; /* nothing */
155 if (!*end)
156 options->dirstat_permille = permille;
157 else {
158 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
160 ret++;
162 } else {
163 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
164 ret++;
168 string_list_clear(&params, 0);
169 free(params_copy);
170 return ret;
173 static int parse_submodule_params(struct diff_options *options, const char *value)
175 if (!strcmp(value, "log"))
176 options->submodule_format = DIFF_SUBMODULE_LOG;
177 else if (!strcmp(value, "short"))
178 options->submodule_format = DIFF_SUBMODULE_SHORT;
179 else if (!strcmp(value, "diff"))
180 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
181 else
182 return -1;
183 return 0;
186 int git_config_rename(const char *var, const char *value)
188 if (!value)
189 return DIFF_DETECT_RENAME;
190 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
191 return DIFF_DETECT_COPY;
192 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
195 long parse_algorithm_value(const char *value)
197 if (!value)
198 return -1;
199 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
200 return 0;
201 else if (!strcasecmp(value, "minimal"))
202 return XDF_NEED_MINIMAL;
203 else if (!strcasecmp(value, "patience"))
204 return XDF_PATIENCE_DIFF;
205 else if (!strcasecmp(value, "histogram"))
206 return XDF_HISTOGRAM_DIFF;
207 return -1;
210 static int parse_one_token(const char **arg, const char *token)
212 const char *rest;
213 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
214 *arg = rest;
215 return 1;
217 return 0;
220 static int parse_ws_error_highlight(const char *arg)
222 const char *orig_arg = arg;
223 unsigned val = 0;
225 while (*arg) {
226 if (parse_one_token(&arg, "none"))
227 val = 0;
228 else if (parse_one_token(&arg, "default"))
229 val = WSEH_NEW;
230 else if (parse_one_token(&arg, "all"))
231 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
232 else if (parse_one_token(&arg, "new"))
233 val |= WSEH_NEW;
234 else if (parse_one_token(&arg, "old"))
235 val |= WSEH_OLD;
236 else if (parse_one_token(&arg, "context"))
237 val |= WSEH_CONTEXT;
238 else {
239 return -1 - (int)(arg - orig_arg);
241 if (*arg)
242 arg++;
244 return val;
248 * These are to give UI layer defaults.
249 * The core-level commands such as git-diff-files should
250 * never be affected by the setting of diff.renames
251 * the user happens to have in the configuration file.
253 void init_diff_ui_defaults(void)
255 diff_detect_rename_default = DIFF_DETECT_RENAME;
258 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
260 if (!strcmp(var, "diff.indentheuristic"))
261 diff_indent_heuristic = git_config_bool(var, value);
262 return 0;
265 static int parse_color_moved(const char *arg)
267 switch (git_parse_maybe_bool(arg)) {
268 case 0:
269 return COLOR_MOVED_NO;
270 case 1:
271 return COLOR_MOVED_DEFAULT;
272 default:
273 break;
276 if (!strcmp(arg, "no"))
277 return COLOR_MOVED_NO;
278 else if (!strcmp(arg, "plain"))
279 return COLOR_MOVED_PLAIN;
280 else if (!strcmp(arg, "blocks"))
281 return COLOR_MOVED_BLOCKS;
282 else if (!strcmp(arg, "zebra"))
283 return COLOR_MOVED_ZEBRA;
284 else if (!strcmp(arg, "default"))
285 return COLOR_MOVED_DEFAULT;
286 else if (!strcmp(arg, "dimmed-zebra"))
287 return COLOR_MOVED_ZEBRA_DIM;
288 else if (!strcmp(arg, "dimmed_zebra"))
289 return COLOR_MOVED_ZEBRA_DIM;
290 else
291 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
294 static unsigned parse_color_moved_ws(const char *arg)
296 int ret = 0;
297 struct string_list l = STRING_LIST_INIT_DUP;
298 struct string_list_item *i;
300 string_list_split(&l, arg, ',', -1);
302 for_each_string_list_item(i, &l) {
303 struct strbuf sb = STRBUF_INIT;
304 strbuf_addstr(&sb, i->string);
305 strbuf_trim(&sb);
307 if (!strcmp(sb.buf, "ignore-space-change"))
308 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
309 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
310 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
311 else if (!strcmp(sb.buf, "ignore-all-space"))
312 ret |= XDF_IGNORE_WHITESPACE;
313 else if (!strcmp(sb.buf, "allow-indentation-change"))
314 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
315 else {
316 ret |= COLOR_MOVED_WS_ERROR;
317 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);
320 strbuf_release(&sb);
323 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
324 (ret & XDF_WHITESPACE_FLAGS)) {
325 error(_("color-moved-ws: allow-indentation-change cannot be combined with other white space modes"));
326 ret |= COLOR_MOVED_WS_ERROR;
329 string_list_clear(&l, 0);
331 return ret;
334 int git_diff_ui_config(const char *var, const char *value, void *cb)
336 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
337 diff_use_color_default = git_config_colorbool(var, value);
338 return 0;
340 if (!strcmp(var, "diff.colormoved")) {
341 int cm = parse_color_moved(value);
342 if (cm < 0)
343 return -1;
344 diff_color_moved_default = cm;
345 return 0;
347 if (!strcmp(var, "diff.colormovedws")) {
348 unsigned cm = parse_color_moved_ws(value);
349 if (cm & COLOR_MOVED_WS_ERROR)
350 return -1;
351 diff_color_moved_ws_default = cm;
352 return 0;
354 if (!strcmp(var, "diff.context")) {
355 diff_context_default = git_config_int(var, value);
356 if (diff_context_default < 0)
357 return -1;
358 return 0;
360 if (!strcmp(var, "diff.interhunkcontext")) {
361 diff_interhunk_context_default = git_config_int(var, value);
362 if (diff_interhunk_context_default < 0)
363 return -1;
364 return 0;
366 if (!strcmp(var, "diff.renames")) {
367 diff_detect_rename_default = git_config_rename(var, value);
368 return 0;
370 if (!strcmp(var, "diff.autorefreshindex")) {
371 diff_auto_refresh_index = git_config_bool(var, value);
372 return 0;
374 if (!strcmp(var, "diff.mnemonicprefix")) {
375 diff_mnemonic_prefix = git_config_bool(var, value);
376 return 0;
378 if (!strcmp(var, "diff.noprefix")) {
379 diff_no_prefix = git_config_bool(var, value);
380 return 0;
382 if (!strcmp(var, "diff.statgraphwidth")) {
383 diff_stat_graph_width = git_config_int(var, value);
384 return 0;
386 if (!strcmp(var, "diff.external"))
387 return git_config_string(&external_diff_cmd_cfg, var, value);
388 if (!strcmp(var, "diff.wordregex"))
389 return git_config_string(&diff_word_regex_cfg, var, value);
390 if (!strcmp(var, "diff.orderfile"))
391 return git_config_pathname(&diff_order_file_cfg, var, value);
393 if (!strcmp(var, "diff.ignoresubmodules"))
394 handle_ignore_submodules_arg(&default_diff_options, value);
396 if (!strcmp(var, "diff.submodule")) {
397 if (parse_submodule_params(&default_diff_options, value))
398 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
399 value);
400 return 0;
403 if (!strcmp(var, "diff.algorithm")) {
404 diff_algorithm = parse_algorithm_value(value);
405 if (diff_algorithm < 0)
406 return -1;
407 return 0;
410 if (!strcmp(var, "diff.wserrorhighlight")) {
411 int val = parse_ws_error_highlight(value);
412 if (val < 0)
413 return -1;
414 ws_error_highlight_default = val;
415 return 0;
418 if (git_color_config(var, value, cb) < 0)
419 return -1;
421 return git_diff_basic_config(var, value, cb);
424 int git_diff_basic_config(const char *var, const char *value, void *cb)
426 const char *name;
428 if (!strcmp(var, "diff.renamelimit")) {
429 diff_rename_limit_default = git_config_int(var, value);
430 return 0;
433 if (userdiff_config(var, value) < 0)
434 return -1;
436 if (skip_prefix(var, "diff.color.", &name) ||
437 skip_prefix(var, "color.diff.", &name)) {
438 int slot = parse_diff_color_slot(name);
439 if (slot < 0)
440 return 0;
441 if (!value)
442 return config_error_nonbool(var);
443 return color_parse(value, diff_colors[slot]);
446 /* like GNU diff's --suppress-blank-empty option */
447 if (!strcmp(var, "diff.suppressblankempty") ||
448 /* for backwards compatibility */
449 !strcmp(var, "diff.suppress-blank-empty")) {
450 diff_suppress_blank_empty = git_config_bool(var, value);
451 return 0;
454 if (!strcmp(var, "diff.dirstat")) {
455 struct strbuf errmsg = STRBUF_INIT;
456 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
457 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
458 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
459 errmsg.buf);
460 strbuf_release(&errmsg);
461 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
462 return 0;
465 if (git_diff_heuristic_config(var, value, cb) < 0)
466 return -1;
468 return git_default_config(var, value, cb);
471 static char *quote_two(const char *one, const char *two)
473 int need_one = quote_c_style(one, NULL, NULL, 1);
474 int need_two = quote_c_style(two, NULL, NULL, 1);
475 struct strbuf res = STRBUF_INIT;
477 if (need_one + need_two) {
478 strbuf_addch(&res, '"');
479 quote_c_style(one, &res, NULL, 1);
480 quote_c_style(two, &res, NULL, 1);
481 strbuf_addch(&res, '"');
482 } else {
483 strbuf_addstr(&res, one);
484 strbuf_addstr(&res, two);
486 return strbuf_detach(&res, NULL);
489 static const char *external_diff(void)
491 static const char *external_diff_cmd = NULL;
492 static int done_preparing = 0;
494 if (done_preparing)
495 return external_diff_cmd;
496 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
497 if (!external_diff_cmd)
498 external_diff_cmd = external_diff_cmd_cfg;
499 done_preparing = 1;
500 return external_diff_cmd;
504 * Keep track of files used for diffing. Sometimes such an entry
505 * refers to a temporary file, sometimes to an existing file, and
506 * sometimes to "/dev/null".
508 static struct diff_tempfile {
510 * filename external diff should read from, or NULL if this
511 * entry is currently not in use:
513 const char *name;
515 char hex[GIT_MAX_HEXSZ + 1];
516 char mode[10];
519 * If this diff_tempfile instance refers to a temporary file,
520 * this tempfile object is used to manage its lifetime.
522 struct tempfile *tempfile;
523 } diff_temp[2];
525 struct emit_callback {
526 int color_diff;
527 unsigned ws_rule;
528 int blank_at_eof_in_preimage;
529 int blank_at_eof_in_postimage;
530 int lno_in_preimage;
531 int lno_in_postimage;
532 const char **label_path;
533 struct diff_words_data *diff_words;
534 struct diff_options *opt;
535 struct strbuf *header;
538 static int count_lines(const char *data, int size)
540 int count, ch, completely_empty = 1, nl_just_seen = 0;
541 count = 0;
542 while (0 < size--) {
543 ch = *data++;
544 if (ch == '\n') {
545 count++;
546 nl_just_seen = 1;
547 completely_empty = 0;
549 else {
550 nl_just_seen = 0;
551 completely_empty = 0;
554 if (completely_empty)
555 return 0;
556 if (!nl_just_seen)
557 count++; /* no trailing newline */
558 return count;
561 static int fill_mmfile(struct repository *r, mmfile_t *mf,
562 struct diff_filespec *one)
564 if (!DIFF_FILE_VALID(one)) {
565 mf->ptr = (char *)""; /* does not matter */
566 mf->size = 0;
567 return 0;
569 else if (diff_populate_filespec(r, one, 0))
570 return -1;
572 mf->ptr = one->data;
573 mf->size = one->size;
574 return 0;
577 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
578 static unsigned long diff_filespec_size(struct repository *r,
579 struct diff_filespec *one)
581 if (!DIFF_FILE_VALID(one))
582 return 0;
583 diff_populate_filespec(r, one, CHECK_SIZE_ONLY);
584 return one->size;
587 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
589 char *ptr = mf->ptr;
590 long size = mf->size;
591 int cnt = 0;
593 if (!size)
594 return cnt;
595 ptr += size - 1; /* pointing at the very end */
596 if (*ptr != '\n')
597 ; /* incomplete line */
598 else
599 ptr--; /* skip the last LF */
600 while (mf->ptr < ptr) {
601 char *prev_eol;
602 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
603 if (*prev_eol == '\n')
604 break;
605 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
606 break;
607 cnt++;
608 ptr = prev_eol - 1;
610 return cnt;
613 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
614 struct emit_callback *ecbdata)
616 int l1, l2, at;
617 unsigned ws_rule = ecbdata->ws_rule;
618 l1 = count_trailing_blank(mf1, ws_rule);
619 l2 = count_trailing_blank(mf2, ws_rule);
620 if (l2 <= l1) {
621 ecbdata->blank_at_eof_in_preimage = 0;
622 ecbdata->blank_at_eof_in_postimage = 0;
623 return;
625 at = count_lines(mf1->ptr, mf1->size);
626 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
628 at = count_lines(mf2->ptr, mf2->size);
629 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
632 static void emit_line_0(struct diff_options *o,
633 const char *set_sign, const char *set, unsigned reverse, const char *reset,
634 int first, const char *line, int len)
636 int has_trailing_newline, has_trailing_carriage_return;
637 int needs_reset = 0; /* at the end of the line */
638 FILE *file = o->file;
640 fputs(diff_line_prefix(o), file);
642 has_trailing_newline = (len > 0 && line[len-1] == '\n');
643 if (has_trailing_newline)
644 len--;
646 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
647 if (has_trailing_carriage_return)
648 len--;
650 if (!len && !first)
651 goto end_of_line;
653 if (reverse && want_color(o->use_color)) {
654 fputs(GIT_COLOR_REVERSE, file);
655 needs_reset = 1;
658 if (set_sign) {
659 fputs(set_sign, file);
660 needs_reset = 1;
663 if (first)
664 fputc(first, file);
666 if (!len)
667 goto end_of_line;
669 if (set) {
670 if (set_sign && set != set_sign)
671 fputs(reset, file);
672 fputs(set, file);
673 needs_reset = 1;
675 fwrite(line, len, 1, file);
676 needs_reset = 1; /* 'line' may contain color codes. */
678 end_of_line:
679 if (needs_reset)
680 fputs(reset, file);
681 if (has_trailing_carriage_return)
682 fputc('\r', file);
683 if (has_trailing_newline)
684 fputc('\n', file);
687 static void emit_line(struct diff_options *o, const char *set, const char *reset,
688 const char *line, int len)
690 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
693 enum diff_symbol {
694 DIFF_SYMBOL_BINARY_DIFF_HEADER,
695 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
696 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
697 DIFF_SYMBOL_BINARY_DIFF_BODY,
698 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
699 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
700 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
701 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
702 DIFF_SYMBOL_STATS_LINE,
703 DIFF_SYMBOL_WORD_DIFF,
704 DIFF_SYMBOL_STAT_SEP,
705 DIFF_SYMBOL_SUMMARY,
706 DIFF_SYMBOL_SUBMODULE_ADD,
707 DIFF_SYMBOL_SUBMODULE_DEL,
708 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
709 DIFF_SYMBOL_SUBMODULE_MODIFIED,
710 DIFF_SYMBOL_SUBMODULE_HEADER,
711 DIFF_SYMBOL_SUBMODULE_ERROR,
712 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
713 DIFF_SYMBOL_REWRITE_DIFF,
714 DIFF_SYMBOL_BINARY_FILES,
715 DIFF_SYMBOL_HEADER,
716 DIFF_SYMBOL_FILEPAIR_PLUS,
717 DIFF_SYMBOL_FILEPAIR_MINUS,
718 DIFF_SYMBOL_WORDS_PORCELAIN,
719 DIFF_SYMBOL_WORDS,
720 DIFF_SYMBOL_CONTEXT,
721 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
722 DIFF_SYMBOL_PLUS,
723 DIFF_SYMBOL_MINUS,
724 DIFF_SYMBOL_NO_LF_EOF,
725 DIFF_SYMBOL_CONTEXT_FRAGINFO,
726 DIFF_SYMBOL_CONTEXT_MARKER,
727 DIFF_SYMBOL_SEPARATOR
730 * Flags for content lines:
731 * 0..12 are whitespace rules
732 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
733 * 16 is marking if the line is blank at EOF
735 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
736 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
737 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
738 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
739 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
742 * This struct is used when we need to buffer the output of the diff output.
744 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
745 * into the pre/post image file. This pointer could be a union with the
746 * line pointer. By storing an offset into the file instead of the literal line,
747 * we can decrease the memory footprint for the buffered output. At first we
748 * may want to only have indirection for the content lines, but we could also
749 * enhance the state for emitting prefabricated lines, e.g. the similarity
750 * score line or hunk/file headers would only need to store a number or path
751 * and then the output can be constructed later on depending on state.
753 struct emitted_diff_symbol {
754 const char *line;
755 int len;
756 int flags;
757 enum diff_symbol s;
759 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
761 struct emitted_diff_symbols {
762 struct emitted_diff_symbol *buf;
763 int nr, alloc;
765 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
767 static void append_emitted_diff_symbol(struct diff_options *o,
768 struct emitted_diff_symbol *e)
770 struct emitted_diff_symbol *f;
772 ALLOC_GROW(o->emitted_symbols->buf,
773 o->emitted_symbols->nr + 1,
774 o->emitted_symbols->alloc);
775 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
777 memcpy(f, e, sizeof(struct emitted_diff_symbol));
778 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
781 struct moved_entry {
782 struct hashmap_entry ent;
783 const struct emitted_diff_symbol *es;
784 struct moved_entry *next_line;
788 * The struct ws_delta holds white space differences between moved lines, i.e.
789 * between '+' and '-' lines that have been detected to be a move.
790 * The string contains the difference in leading white spaces, before the
791 * rest of the line is compared using the white space config for move
792 * coloring. The current_longer indicates if the first string in the
793 * comparision is longer than the second.
795 struct ws_delta {
796 char *string;
797 unsigned int current_longer : 1;
799 #define WS_DELTA_INIT { NULL, 0 }
801 struct moved_block {
802 struct moved_entry *match;
803 struct ws_delta wsd;
806 static void moved_block_clear(struct moved_block *b)
808 FREE_AND_NULL(b->wsd.string);
809 b->match = NULL;
812 static int compute_ws_delta(const struct emitted_diff_symbol *a,
813 const struct emitted_diff_symbol *b,
814 struct ws_delta *out)
816 const struct emitted_diff_symbol *longer = a->len > b->len ? a : b;
817 const struct emitted_diff_symbol *shorter = a->len > b->len ? b : a;
818 int d = longer->len - shorter->len;
820 if (strncmp(longer->line + d, shorter->line, shorter->len))
821 return 0;
823 out->string = xmemdupz(longer->line, d);
824 out->current_longer = (a == longer);
826 return 1;
829 static int cmp_in_block_with_wsd(const struct diff_options *o,
830 const struct moved_entry *cur,
831 const struct moved_entry *match,
832 struct moved_block *pmb,
833 int n)
835 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
836 int al = cur->es->len, cl = l->len;
837 const char *a = cur->es->line,
838 *b = match->es->line,
839 *c = l->line;
841 int wslen;
844 * We need to check if 'cur' is equal to 'match'.
845 * As those are from the same (+/-) side, we do not need to adjust for
846 * indent changes. However these were found using fuzzy matching
847 * so we do have to check if they are equal.
849 if (strcmp(a, b))
850 return 1;
852 if (!pmb->wsd.string)
854 * The white space delta is not active? This can happen
855 * when we exit early in this function.
857 return 1;
860 * The indent changes of the block are known and stored in
861 * pmb->wsd; however we need to check if the indent changes of the
862 * current line are still the same as before.
864 * To do so we need to compare 'l' to 'cur', adjusting the
865 * one of them for the white spaces, depending which was longer.
868 wslen = strlen(pmb->wsd.string);
869 if (pmb->wsd.current_longer) {
870 c += wslen;
871 cl -= wslen;
872 } else {
873 a += wslen;
874 al -= wslen;
877 if (al != cl || memcmp(a, c, al))
878 return 1;
880 return 0;
883 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
884 const void *entry,
885 const void *entry_or_key,
886 const void *keydata)
888 const struct diff_options *diffopt = hashmap_cmp_fn_data;
889 const struct moved_entry *a = entry;
890 const struct moved_entry *b = entry_or_key;
891 unsigned flags = diffopt->color_moved_ws_handling
892 & XDF_WHITESPACE_FLAGS;
894 if (diffopt->color_moved_ws_handling &
895 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
897 * As there is not specific white space config given,
898 * we'd need to check for a new block, so ignore all
899 * white space. The setup of the white space
900 * configuration for the next block is done else where
902 flags |= XDF_IGNORE_WHITESPACE;
904 return !xdiff_compare_lines(a->es->line, a->es->len,
905 b->es->line, b->es->len,
906 flags);
909 static struct moved_entry *prepare_entry(struct diff_options *o,
910 int line_no)
912 struct moved_entry *ret = xmalloc(sizeof(*ret));
913 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
914 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
916 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
917 ret->es = l;
918 ret->next_line = NULL;
920 return ret;
923 static void add_lines_to_move_detection(struct diff_options *o,
924 struct hashmap *add_lines,
925 struct hashmap *del_lines)
927 struct moved_entry *prev_line = NULL;
929 int n;
930 for (n = 0; n < o->emitted_symbols->nr; n++) {
931 struct hashmap *hm;
932 struct moved_entry *key;
934 switch (o->emitted_symbols->buf[n].s) {
935 case DIFF_SYMBOL_PLUS:
936 hm = add_lines;
937 break;
938 case DIFF_SYMBOL_MINUS:
939 hm = del_lines;
940 break;
941 default:
942 prev_line = NULL;
943 continue;
946 key = prepare_entry(o, n);
947 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
948 prev_line->next_line = key;
950 hashmap_add(hm, key);
951 prev_line = key;
955 static void pmb_advance_or_null(struct diff_options *o,
956 struct moved_entry *match,
957 struct hashmap *hm,
958 struct moved_block *pmb,
959 int pmb_nr)
961 int i;
962 for (i = 0; i < pmb_nr; i++) {
963 struct moved_entry *prev = pmb[i].match;
964 struct moved_entry *cur = (prev && prev->next_line) ?
965 prev->next_line : NULL;
966 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
967 pmb[i].match = cur;
968 } else {
969 pmb[i].match = NULL;
974 static void pmb_advance_or_null_multi_match(struct diff_options *o,
975 struct moved_entry *match,
976 struct hashmap *hm,
977 struct moved_block *pmb,
978 int pmb_nr, int n)
980 int i;
981 char *got_match = xcalloc(1, pmb_nr);
983 for (; match; match = hashmap_get_next(hm, match)) {
984 for (i = 0; i < pmb_nr; i++) {
985 struct moved_entry *prev = pmb[i].match;
986 struct moved_entry *cur = (prev && prev->next_line) ?
987 prev->next_line : NULL;
988 if (!cur)
989 continue;
990 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
991 got_match[i] |= 1;
995 for (i = 0; i < pmb_nr; i++) {
996 if (got_match[i]) {
997 /* Advance to the next line */
998 pmb[i].match = pmb[i].match->next_line;
999 } else {
1000 moved_block_clear(&pmb[i]);
1004 free(got_match);
1007 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1008 int pmb_nr)
1010 int lp, rp;
1012 /* Shrink the set of potential block to the remaining running */
1013 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1014 while (lp < pmb_nr && pmb[lp].match)
1015 lp++;
1016 /* lp points at the first NULL now */
1018 while (rp > -1 && !pmb[rp].match)
1019 rp--;
1020 /* rp points at the last non-NULL */
1022 if (lp < pmb_nr && rp > -1 && lp < rp) {
1023 pmb[lp] = pmb[rp];
1024 pmb[rp].match = NULL;
1025 pmb[rp].wsd.string = NULL;
1026 rp--;
1027 lp++;
1031 /* Remember the number of running sets */
1032 return rp + 1;
1036 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1038 * Otherwise, if the last block has fewer alphanumeric characters than
1039 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1040 * that block.
1042 * The last block consists of the (n - block_length)'th line up to but not
1043 * including the nth line.
1045 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1046 * Think of a way to unify them.
1048 static void adjust_last_block(struct diff_options *o, int n, int block_length)
1050 int i, alnum_count = 0;
1051 if (o->color_moved == COLOR_MOVED_PLAIN)
1052 return;
1053 for (i = 1; i < block_length + 1; i++) {
1054 const char *c = o->emitted_symbols->buf[n - i].line;
1055 for (; *c; c++) {
1056 if (!isalnum(*c))
1057 continue;
1058 alnum_count++;
1059 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1060 return;
1063 for (i = 1; i < block_length + 1; i++)
1064 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1067 /* Find blocks of moved code, delegate actual coloring decision to helper */
1068 static void mark_color_as_moved(struct diff_options *o,
1069 struct hashmap *add_lines,
1070 struct hashmap *del_lines)
1072 struct moved_block *pmb = NULL; /* potentially moved blocks */
1073 int pmb_nr = 0, pmb_alloc = 0;
1074 int n, flipped_block = 1, block_length = 0;
1077 for (n = 0; n < o->emitted_symbols->nr; n++) {
1078 struct hashmap *hm = NULL;
1079 struct moved_entry *key;
1080 struct moved_entry *match = NULL;
1081 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1083 switch (l->s) {
1084 case DIFF_SYMBOL_PLUS:
1085 hm = del_lines;
1086 key = prepare_entry(o, n);
1087 match = hashmap_get(hm, key, NULL);
1088 free(key);
1089 break;
1090 case DIFF_SYMBOL_MINUS:
1091 hm = add_lines;
1092 key = prepare_entry(o, n);
1093 match = hashmap_get(hm, key, NULL);
1094 free(key);
1095 break;
1096 default:
1097 flipped_block = 1;
1100 if (!match) {
1101 int i;
1103 adjust_last_block(o, n, block_length);
1104 for(i = 0; i < pmb_nr; i++)
1105 moved_block_clear(&pmb[i]);
1106 pmb_nr = 0;
1107 block_length = 0;
1108 continue;
1111 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1113 if (o->color_moved == COLOR_MOVED_PLAIN)
1114 continue;
1116 if (o->color_moved_ws_handling &
1117 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1118 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1119 else
1120 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1122 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1124 if (pmb_nr == 0) {
1126 * The current line is the start of a new block.
1127 * Setup the set of potential blocks.
1129 for (; match; match = hashmap_get_next(hm, match)) {
1130 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1131 if (o->color_moved_ws_handling &
1132 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1133 if (compute_ws_delta(l, match->es,
1134 &pmb[pmb_nr].wsd))
1135 pmb[pmb_nr++].match = match;
1136 } else {
1137 pmb[pmb_nr].wsd.string = NULL;
1138 pmb[pmb_nr++].match = match;
1142 flipped_block = (flipped_block + 1) % 2;
1144 adjust_last_block(o, n, block_length);
1145 block_length = 0;
1148 block_length++;
1150 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1151 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1153 adjust_last_block(o, n, block_length);
1155 for(n = 0; n < pmb_nr; n++)
1156 moved_block_clear(&pmb[n]);
1157 free(pmb);
1160 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1161 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1162 static void dim_moved_lines(struct diff_options *o)
1164 int n;
1165 for (n = 0; n < o->emitted_symbols->nr; n++) {
1166 struct emitted_diff_symbol *prev = (n != 0) ?
1167 &o->emitted_symbols->buf[n - 1] : NULL;
1168 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1169 struct emitted_diff_symbol *next =
1170 (n < o->emitted_symbols->nr - 1) ?
1171 &o->emitted_symbols->buf[n + 1] : NULL;
1173 /* Not a plus or minus line? */
1174 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1175 continue;
1177 /* Not a moved line? */
1178 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1179 continue;
1182 * If prev or next are not a plus or minus line,
1183 * pretend they don't exist
1185 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1186 prev->s != DIFF_SYMBOL_MINUS)
1187 prev = NULL;
1188 if (next && next->s != DIFF_SYMBOL_PLUS &&
1189 next->s != DIFF_SYMBOL_MINUS)
1190 next = NULL;
1192 /* Inside a block? */
1193 if ((prev &&
1194 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1195 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1196 (next &&
1197 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1198 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1199 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1200 continue;
1203 /* Check if we are at an interesting bound: */
1204 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1205 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1206 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1207 continue;
1208 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1209 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1210 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1211 continue;
1214 * The boundary to prev and next are not interesting,
1215 * so this line is not interesting as a whole
1217 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1221 static void emit_line_ws_markup(struct diff_options *o,
1222 const char *set_sign, const char *set,
1223 const char *reset,
1224 int sign_index, const char *line, int len,
1225 unsigned ws_rule, int blank_at_eof)
1227 const char *ws = NULL;
1228 int sign = o->output_indicators[sign_index];
1230 if (o->ws_error_highlight & ws_rule) {
1231 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1232 if (!*ws)
1233 ws = NULL;
1236 if (!ws && !set_sign)
1237 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1238 else if (!ws) {
1239 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1240 } else if (blank_at_eof)
1241 /* Blank line at EOF - paint '+' as well */
1242 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1243 else {
1244 /* Emit just the prefix, then the rest. */
1245 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1246 sign, "", 0);
1247 ws_check_emit(line, len, ws_rule,
1248 o->file, set, reset, ws);
1252 static void emit_diff_symbol_from_struct(struct diff_options *o,
1253 struct emitted_diff_symbol *eds)
1255 static const char *nneof = " No newline at end of file\n";
1256 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1257 struct strbuf sb = STRBUF_INIT;
1259 enum diff_symbol s = eds->s;
1260 const char *line = eds->line;
1261 int len = eds->len;
1262 unsigned flags = eds->flags;
1264 switch (s) {
1265 case DIFF_SYMBOL_NO_LF_EOF:
1266 context = diff_get_color_opt(o, DIFF_CONTEXT);
1267 reset = diff_get_color_opt(o, DIFF_RESET);
1268 putc('\n', o->file);
1269 emit_line_0(o, context, NULL, 0, reset, '\\',
1270 nneof, strlen(nneof));
1271 break;
1272 case DIFF_SYMBOL_SUBMODULE_HEADER:
1273 case DIFF_SYMBOL_SUBMODULE_ERROR:
1274 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1275 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1276 case DIFF_SYMBOL_SUMMARY:
1277 case DIFF_SYMBOL_STATS_LINE:
1278 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1279 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1280 emit_line(o, "", "", line, len);
1281 break;
1282 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1283 case DIFF_SYMBOL_CONTEXT_MARKER:
1284 context = diff_get_color_opt(o, DIFF_CONTEXT);
1285 reset = diff_get_color_opt(o, DIFF_RESET);
1286 emit_line(o, context, reset, line, len);
1287 break;
1288 case DIFF_SYMBOL_SEPARATOR:
1289 fprintf(o->file, "%s%c",
1290 diff_line_prefix(o),
1291 o->line_termination);
1292 break;
1293 case DIFF_SYMBOL_CONTEXT:
1294 set = diff_get_color_opt(o, DIFF_CONTEXT);
1295 reset = diff_get_color_opt(o, DIFF_RESET);
1296 set_sign = NULL;
1297 if (o->flags.dual_color_diffed_diffs) {
1298 char c = !len ? 0 : line[0];
1300 if (c == '+')
1301 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1302 else if (c == '@')
1303 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1304 else if (c == '-')
1305 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1307 emit_line_ws_markup(o, set_sign, set, reset,
1308 OUTPUT_INDICATOR_CONTEXT, line, len,
1309 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1310 break;
1311 case DIFF_SYMBOL_PLUS:
1312 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1313 DIFF_SYMBOL_MOVED_LINE_ALT |
1314 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1315 case DIFF_SYMBOL_MOVED_LINE |
1316 DIFF_SYMBOL_MOVED_LINE_ALT |
1317 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1318 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1319 break;
1320 case DIFF_SYMBOL_MOVED_LINE |
1321 DIFF_SYMBOL_MOVED_LINE_ALT:
1322 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1323 break;
1324 case DIFF_SYMBOL_MOVED_LINE |
1325 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1326 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1327 break;
1328 case DIFF_SYMBOL_MOVED_LINE:
1329 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1330 break;
1331 default:
1332 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1334 reset = diff_get_color_opt(o, DIFF_RESET);
1335 if (!o->flags.dual_color_diffed_diffs)
1336 set_sign = NULL;
1337 else {
1338 char c = !len ? 0 : line[0];
1340 set_sign = set;
1341 if (c == '-')
1342 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1343 else if (c == '@')
1344 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1345 else if (c == '+')
1346 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1347 else
1348 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1349 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1351 emit_line_ws_markup(o, set_sign, set, reset,
1352 OUTPUT_INDICATOR_NEW, line, len,
1353 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1354 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1355 break;
1356 case DIFF_SYMBOL_MINUS:
1357 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1358 DIFF_SYMBOL_MOVED_LINE_ALT |
1359 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1360 case DIFF_SYMBOL_MOVED_LINE |
1361 DIFF_SYMBOL_MOVED_LINE_ALT |
1362 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1363 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1364 break;
1365 case DIFF_SYMBOL_MOVED_LINE |
1366 DIFF_SYMBOL_MOVED_LINE_ALT:
1367 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1368 break;
1369 case DIFF_SYMBOL_MOVED_LINE |
1370 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1371 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1372 break;
1373 case DIFF_SYMBOL_MOVED_LINE:
1374 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1375 break;
1376 default:
1377 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1379 reset = diff_get_color_opt(o, DIFF_RESET);
1380 if (!o->flags.dual_color_diffed_diffs)
1381 set_sign = NULL;
1382 else {
1383 char c = !len ? 0 : line[0];
1385 set_sign = set;
1386 if (c == '+')
1387 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1388 else if (c == '@')
1389 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1390 else if (c == '-')
1391 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1392 else
1393 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1395 emit_line_ws_markup(o, set_sign, set, reset,
1396 OUTPUT_INDICATOR_OLD, line, len,
1397 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1398 break;
1399 case DIFF_SYMBOL_WORDS_PORCELAIN:
1400 context = diff_get_color_opt(o, DIFF_CONTEXT);
1401 reset = diff_get_color_opt(o, DIFF_RESET);
1402 emit_line(o, context, reset, line, len);
1403 fputs("~\n", o->file);
1404 break;
1405 case DIFF_SYMBOL_WORDS:
1406 context = diff_get_color_opt(o, DIFF_CONTEXT);
1407 reset = diff_get_color_opt(o, DIFF_RESET);
1409 * Skip the prefix character, if any. With
1410 * diff_suppress_blank_empty, there may be
1411 * none.
1413 if (line[0] != '\n') {
1414 line++;
1415 len--;
1417 emit_line(o, context, reset, line, len);
1418 break;
1419 case DIFF_SYMBOL_FILEPAIR_PLUS:
1420 meta = diff_get_color_opt(o, DIFF_METAINFO);
1421 reset = diff_get_color_opt(o, DIFF_RESET);
1422 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1423 line, reset,
1424 strchr(line, ' ') ? "\t" : "");
1425 break;
1426 case DIFF_SYMBOL_FILEPAIR_MINUS:
1427 meta = diff_get_color_opt(o, DIFF_METAINFO);
1428 reset = diff_get_color_opt(o, DIFF_RESET);
1429 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1430 line, reset,
1431 strchr(line, ' ') ? "\t" : "");
1432 break;
1433 case DIFF_SYMBOL_BINARY_FILES:
1434 case DIFF_SYMBOL_HEADER:
1435 fprintf(o->file, "%s", line);
1436 break;
1437 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1438 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1439 break;
1440 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1441 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1442 break;
1443 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1444 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1445 break;
1446 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1447 fputs(diff_line_prefix(o), o->file);
1448 fputc('\n', o->file);
1449 break;
1450 case DIFF_SYMBOL_REWRITE_DIFF:
1451 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1452 reset = diff_get_color_opt(o, DIFF_RESET);
1453 emit_line(o, fraginfo, reset, line, len);
1454 break;
1455 case DIFF_SYMBOL_SUBMODULE_ADD:
1456 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1457 reset = diff_get_color_opt(o, DIFF_RESET);
1458 emit_line(o, set, reset, line, len);
1459 break;
1460 case DIFF_SYMBOL_SUBMODULE_DEL:
1461 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1462 reset = diff_get_color_opt(o, DIFF_RESET);
1463 emit_line(o, set, reset, line, len);
1464 break;
1465 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1466 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1467 diff_line_prefix(o), line);
1468 break;
1469 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1470 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1471 diff_line_prefix(o), line);
1472 break;
1473 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1474 emit_line(o, "", "", " 0 files changed\n",
1475 strlen(" 0 files changed\n"));
1476 break;
1477 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1478 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1479 break;
1480 case DIFF_SYMBOL_WORD_DIFF:
1481 fprintf(o->file, "%.*s", len, line);
1482 break;
1483 case DIFF_SYMBOL_STAT_SEP:
1484 fputs(o->stat_sep, o->file);
1485 break;
1486 default:
1487 BUG("unknown diff symbol");
1489 strbuf_release(&sb);
1492 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1493 const char *line, int len, unsigned flags)
1495 struct emitted_diff_symbol e = {line, len, flags, s};
1497 if (o->emitted_symbols)
1498 append_emitted_diff_symbol(o, &e);
1499 else
1500 emit_diff_symbol_from_struct(o, &e);
1503 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1505 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1508 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1510 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1513 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1515 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1516 path, strlen(path), 0);
1519 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1521 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1522 path, strlen(path), 0);
1525 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1527 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1528 header, strlen(header), 0);
1531 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1533 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1536 void diff_emit_submodule_pipethrough(struct diff_options *o,
1537 const char *line, int len)
1539 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1542 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1544 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1545 ecbdata->blank_at_eof_in_preimage &&
1546 ecbdata->blank_at_eof_in_postimage &&
1547 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1548 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1549 return 0;
1550 return ws_blank_line(line, len, ecbdata->ws_rule);
1553 static void emit_add_line(const char *reset,
1554 struct emit_callback *ecbdata,
1555 const char *line, int len)
1557 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1558 if (new_blank_line_at_eof(ecbdata, line, len))
1559 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1561 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1564 static void emit_del_line(const char *reset,
1565 struct emit_callback *ecbdata,
1566 const char *line, int len)
1568 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1569 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1572 static void emit_context_line(const char *reset,
1573 struct emit_callback *ecbdata,
1574 const char *line, int len)
1576 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1577 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1580 static void emit_hunk_header(struct emit_callback *ecbdata,
1581 const char *line, int len)
1583 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1584 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1585 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1586 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1587 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1588 static const char atat[2] = { '@', '@' };
1589 const char *cp, *ep;
1590 struct strbuf msgbuf = STRBUF_INIT;
1591 int org_len = len;
1592 int i = 1;
1595 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1596 * it always is at least 10 bytes long.
1598 if (len < 10 ||
1599 memcmp(line, atat, 2) ||
1600 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1601 emit_diff_symbol(ecbdata->opt,
1602 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1603 return;
1605 ep += 2; /* skip over @@ */
1607 /* The hunk header in fraginfo color */
1608 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1609 strbuf_addstr(&msgbuf, reverse);
1610 strbuf_addstr(&msgbuf, frag);
1611 strbuf_add(&msgbuf, line, ep - line);
1612 strbuf_addstr(&msgbuf, reset);
1615 * trailing "\r\n"
1617 for ( ; i < 3; i++)
1618 if (line[len - i] == '\r' || line[len - i] == '\n')
1619 len--;
1621 /* blank before the func header */
1622 for (cp = ep; ep - line < len; ep++)
1623 if (*ep != ' ' && *ep != '\t')
1624 break;
1625 if (ep != cp) {
1626 strbuf_addstr(&msgbuf, context);
1627 strbuf_add(&msgbuf, cp, ep - cp);
1628 strbuf_addstr(&msgbuf, reset);
1631 if (ep < line + len) {
1632 strbuf_addstr(&msgbuf, func);
1633 strbuf_add(&msgbuf, ep, line + len - ep);
1634 strbuf_addstr(&msgbuf, reset);
1637 strbuf_add(&msgbuf, line + len, org_len - len);
1638 strbuf_complete_line(&msgbuf);
1639 emit_diff_symbol(ecbdata->opt,
1640 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1641 strbuf_release(&msgbuf);
1644 static struct diff_tempfile *claim_diff_tempfile(void) {
1645 int i;
1646 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1647 if (!diff_temp[i].name)
1648 return diff_temp + i;
1649 BUG("diff is failing to clean up its tempfiles");
1652 static void remove_tempfile(void)
1654 int i;
1655 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1656 if (is_tempfile_active(diff_temp[i].tempfile))
1657 delete_tempfile(&diff_temp[i].tempfile);
1658 diff_temp[i].name = NULL;
1662 static void add_line_count(struct strbuf *out, int count)
1664 switch (count) {
1665 case 0:
1666 strbuf_addstr(out, "0,0");
1667 break;
1668 case 1:
1669 strbuf_addstr(out, "1");
1670 break;
1671 default:
1672 strbuf_addf(out, "1,%d", count);
1673 break;
1677 static void emit_rewrite_lines(struct emit_callback *ecb,
1678 int prefix, const char *data, int size)
1680 const char *endp = NULL;
1681 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1683 while (0 < size) {
1684 int len;
1686 endp = memchr(data, '\n', size);
1687 len = endp ? (endp - data + 1) : size;
1688 if (prefix != '+') {
1689 ecb->lno_in_preimage++;
1690 emit_del_line(reset, ecb, data, len);
1691 } else {
1692 ecb->lno_in_postimage++;
1693 emit_add_line(reset, ecb, data, len);
1695 size -= len;
1696 data += len;
1698 if (!endp)
1699 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1702 static void emit_rewrite_diff(const char *name_a,
1703 const char *name_b,
1704 struct diff_filespec *one,
1705 struct diff_filespec *two,
1706 struct userdiff_driver *textconv_one,
1707 struct userdiff_driver *textconv_two,
1708 struct diff_options *o)
1710 int lc_a, lc_b;
1711 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1712 const char *a_prefix, *b_prefix;
1713 char *data_one, *data_two;
1714 size_t size_one, size_two;
1715 struct emit_callback ecbdata;
1716 struct strbuf out = STRBUF_INIT;
1718 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1719 a_prefix = o->b_prefix;
1720 b_prefix = o->a_prefix;
1721 } else {
1722 a_prefix = o->a_prefix;
1723 b_prefix = o->b_prefix;
1726 name_a += (*name_a == '/');
1727 name_b += (*name_b == '/');
1729 strbuf_reset(&a_name);
1730 strbuf_reset(&b_name);
1731 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1732 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1734 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1735 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1737 memset(&ecbdata, 0, sizeof(ecbdata));
1738 ecbdata.color_diff = want_color(o->use_color);
1739 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1740 ecbdata.opt = o;
1741 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1742 mmfile_t mf1, mf2;
1743 mf1.ptr = (char *)data_one;
1744 mf2.ptr = (char *)data_two;
1745 mf1.size = size_one;
1746 mf2.size = size_two;
1747 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1749 ecbdata.lno_in_preimage = 1;
1750 ecbdata.lno_in_postimage = 1;
1752 lc_a = count_lines(data_one, size_one);
1753 lc_b = count_lines(data_two, size_two);
1755 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1756 a_name.buf, a_name.len, 0);
1757 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1758 b_name.buf, b_name.len, 0);
1760 strbuf_addstr(&out, "@@ -");
1761 if (!o->irreversible_delete)
1762 add_line_count(&out, lc_a);
1763 else
1764 strbuf_addstr(&out, "?,?");
1765 strbuf_addstr(&out, " +");
1766 add_line_count(&out, lc_b);
1767 strbuf_addstr(&out, " @@\n");
1768 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1769 strbuf_release(&out);
1771 if (lc_a && !o->irreversible_delete)
1772 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1773 if (lc_b)
1774 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1775 if (textconv_one)
1776 free((char *)data_one);
1777 if (textconv_two)
1778 free((char *)data_two);
1781 struct diff_words_buffer {
1782 mmfile_t text;
1783 unsigned long alloc;
1784 struct diff_words_orig {
1785 const char *begin, *end;
1786 } *orig;
1787 int orig_nr, orig_alloc;
1790 static void diff_words_append(char *line, unsigned long len,
1791 struct diff_words_buffer *buffer)
1793 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1794 line++;
1795 len--;
1796 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1797 buffer->text.size += len;
1798 buffer->text.ptr[buffer->text.size] = '\0';
1801 struct diff_words_style_elem {
1802 const char *prefix;
1803 const char *suffix;
1804 const char *color; /* NULL; filled in by the setup code if
1805 * color is enabled */
1808 struct diff_words_style {
1809 enum diff_words_type type;
1810 struct diff_words_style_elem new_word, old_word, ctx;
1811 const char *newline;
1814 static struct diff_words_style diff_words_styles[] = {
1815 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1816 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1817 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1820 struct diff_words_data {
1821 struct diff_words_buffer minus, plus;
1822 const char *current_plus;
1823 int last_minus;
1824 struct diff_options *opt;
1825 regex_t *word_regex;
1826 enum diff_words_type type;
1827 struct diff_words_style *style;
1830 static int fn_out_diff_words_write_helper(struct diff_options *o,
1831 struct diff_words_style_elem *st_el,
1832 const char *newline,
1833 size_t count, const char *buf)
1835 int print = 0;
1836 struct strbuf sb = STRBUF_INIT;
1838 while (count) {
1839 char *p = memchr(buf, '\n', count);
1840 if (print)
1841 strbuf_addstr(&sb, diff_line_prefix(o));
1843 if (p != buf) {
1844 const char *reset = st_el->color && *st_el->color ?
1845 GIT_COLOR_RESET : NULL;
1846 if (st_el->color && *st_el->color)
1847 strbuf_addstr(&sb, st_el->color);
1848 strbuf_addstr(&sb, st_el->prefix);
1849 strbuf_add(&sb, buf, p ? p - buf : count);
1850 strbuf_addstr(&sb, st_el->suffix);
1851 if (reset)
1852 strbuf_addstr(&sb, reset);
1854 if (!p)
1855 goto out;
1857 strbuf_addstr(&sb, newline);
1858 count -= p + 1 - buf;
1859 buf = p + 1;
1860 print = 1;
1861 if (count) {
1862 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1863 sb.buf, sb.len, 0);
1864 strbuf_reset(&sb);
1868 out:
1869 if (sb.len)
1870 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1871 sb.buf, sb.len, 0);
1872 strbuf_release(&sb);
1873 return 0;
1877 * '--color-words' algorithm can be described as:
1879 * 1. collect the minus/plus lines of a diff hunk, divided into
1880 * minus-lines and plus-lines;
1882 * 2. break both minus-lines and plus-lines into words and
1883 * place them into two mmfile_t with one word for each line;
1885 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1887 * And for the common parts of the both file, we output the plus side text.
1888 * diff_words->current_plus is used to trace the current position of the plus file
1889 * which printed. diff_words->last_minus is used to trace the last minus word
1890 * printed.
1892 * For '--graph' to work with '--color-words', we need to output the graph prefix
1893 * on each line of color words output. Generally, there are two conditions on
1894 * which we should output the prefix.
1896 * 1. diff_words->last_minus == 0 &&
1897 * diff_words->current_plus == diff_words->plus.text.ptr
1899 * that is: the plus text must start as a new line, and if there is no minus
1900 * word printed, a graph prefix must be printed.
1902 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1903 * *(diff_words->current_plus - 1) == '\n'
1905 * that is: a graph prefix must be printed following a '\n'
1907 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1909 if ((diff_words->last_minus == 0 &&
1910 diff_words->current_plus == diff_words->plus.text.ptr) ||
1911 (diff_words->current_plus > diff_words->plus.text.ptr &&
1912 *(diff_words->current_plus - 1) == '\n')) {
1913 return 1;
1914 } else {
1915 return 0;
1919 static void fn_out_diff_words_aux(void *priv,
1920 long minus_first, long minus_len,
1921 long plus_first, long plus_len,
1922 const char *func, long funclen)
1924 struct diff_words_data *diff_words = priv;
1925 struct diff_words_style *style = diff_words->style;
1926 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1927 struct diff_options *opt = diff_words->opt;
1928 const char *line_prefix;
1930 assert(opt);
1931 line_prefix = diff_line_prefix(opt);
1933 /* POSIX requires that first be decremented by one if len == 0... */
1934 if (minus_len) {
1935 minus_begin = diff_words->minus.orig[minus_first].begin;
1936 minus_end =
1937 diff_words->minus.orig[minus_first + minus_len - 1].end;
1938 } else
1939 minus_begin = minus_end =
1940 diff_words->minus.orig[minus_first].end;
1942 if (plus_len) {
1943 plus_begin = diff_words->plus.orig[plus_first].begin;
1944 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1945 } else
1946 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1948 if (color_words_output_graph_prefix(diff_words)) {
1949 fputs(line_prefix, diff_words->opt->file);
1951 if (diff_words->current_plus != plus_begin) {
1952 fn_out_diff_words_write_helper(diff_words->opt,
1953 &style->ctx, style->newline,
1954 plus_begin - diff_words->current_plus,
1955 diff_words->current_plus);
1957 if (minus_begin != minus_end) {
1958 fn_out_diff_words_write_helper(diff_words->opt,
1959 &style->old_word, style->newline,
1960 minus_end - minus_begin, minus_begin);
1962 if (plus_begin != plus_end) {
1963 fn_out_diff_words_write_helper(diff_words->opt,
1964 &style->new_word, style->newline,
1965 plus_end - plus_begin, plus_begin);
1968 diff_words->current_plus = plus_end;
1969 diff_words->last_minus = minus_first;
1972 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1973 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1974 int *begin, int *end)
1976 if (word_regex && *begin < buffer->size) {
1977 regmatch_t match[1];
1978 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1979 buffer->size - *begin, 1, match, 0)) {
1980 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1981 '\n', match[0].rm_eo - match[0].rm_so);
1982 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1983 *begin += match[0].rm_so;
1984 return *begin >= *end;
1986 return -1;
1989 /* find the next word */
1990 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1991 (*begin)++;
1992 if (*begin >= buffer->size)
1993 return -1;
1995 /* find the end of the word */
1996 *end = *begin + 1;
1997 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1998 (*end)++;
2000 return 0;
2004 * This function splits the words in buffer->text, stores the list with
2005 * newline separator into out, and saves the offsets of the original words
2006 * in buffer->orig.
2008 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2009 regex_t *word_regex)
2011 int i, j;
2012 long alloc = 0;
2014 out->size = 0;
2015 out->ptr = NULL;
2017 /* fake an empty "0th" word */
2018 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2019 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2020 buffer->orig_nr = 1;
2022 for (i = 0; i < buffer->text.size; i++) {
2023 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2024 return;
2026 /* store original boundaries */
2027 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2028 buffer->orig_alloc);
2029 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2030 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2031 buffer->orig_nr++;
2033 /* store one word */
2034 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2035 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2036 out->ptr[out->size + j - i] = '\n';
2037 out->size += j - i + 1;
2039 i = j - 1;
2043 /* this executes the word diff on the accumulated buffers */
2044 static void diff_words_show(struct diff_words_data *diff_words)
2046 xpparam_t xpp;
2047 xdemitconf_t xecfg;
2048 mmfile_t minus, plus;
2049 struct diff_words_style *style = diff_words->style;
2051 struct diff_options *opt = diff_words->opt;
2052 const char *line_prefix;
2054 assert(opt);
2055 line_prefix = diff_line_prefix(opt);
2057 /* special case: only removal */
2058 if (!diff_words->plus.text.size) {
2059 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2060 line_prefix, strlen(line_prefix), 0);
2061 fn_out_diff_words_write_helper(diff_words->opt,
2062 &style->old_word, style->newline,
2063 diff_words->minus.text.size,
2064 diff_words->minus.text.ptr);
2065 diff_words->minus.text.size = 0;
2066 return;
2069 diff_words->current_plus = diff_words->plus.text.ptr;
2070 diff_words->last_minus = 0;
2072 memset(&xpp, 0, sizeof(xpp));
2073 memset(&xecfg, 0, sizeof(xecfg));
2074 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2075 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2076 xpp.flags = 0;
2077 /* as only the hunk header will be parsed, we need a 0-context */
2078 xecfg.ctxlen = 0;
2079 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2080 diff_words, &xpp, &xecfg))
2081 die("unable to generate word diff");
2082 free(minus.ptr);
2083 free(plus.ptr);
2084 if (diff_words->current_plus != diff_words->plus.text.ptr +
2085 diff_words->plus.text.size) {
2086 if (color_words_output_graph_prefix(diff_words))
2087 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2088 line_prefix, strlen(line_prefix), 0);
2089 fn_out_diff_words_write_helper(diff_words->opt,
2090 &style->ctx, style->newline,
2091 diff_words->plus.text.ptr + diff_words->plus.text.size
2092 - diff_words->current_plus, diff_words->current_plus);
2094 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2097 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2098 static void diff_words_flush(struct emit_callback *ecbdata)
2100 struct diff_options *wo = ecbdata->diff_words->opt;
2102 if (ecbdata->diff_words->minus.text.size ||
2103 ecbdata->diff_words->plus.text.size)
2104 diff_words_show(ecbdata->diff_words);
2106 if (wo->emitted_symbols) {
2107 struct diff_options *o = ecbdata->opt;
2108 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2109 int i;
2112 * NEEDSWORK:
2113 * Instead of appending each, concat all words to a line?
2115 for (i = 0; i < wol->nr; i++)
2116 append_emitted_diff_symbol(o, &wol->buf[i]);
2118 for (i = 0; i < wol->nr; i++)
2119 free((void *)wol->buf[i].line);
2121 wol->nr = 0;
2125 static void diff_filespec_load_driver(struct diff_filespec *one,
2126 struct index_state *istate)
2128 /* Use already-loaded driver */
2129 if (one->driver)
2130 return;
2132 if (S_ISREG(one->mode))
2133 one->driver = userdiff_find_by_path(istate, one->path);
2135 /* Fallback to default settings */
2136 if (!one->driver)
2137 one->driver = userdiff_find_by_name("default");
2140 static const char *userdiff_word_regex(struct diff_filespec *one,
2141 struct index_state *istate)
2143 diff_filespec_load_driver(one, istate);
2144 return one->driver->word_regex;
2147 static void init_diff_words_data(struct emit_callback *ecbdata,
2148 struct diff_options *orig_opts,
2149 struct diff_filespec *one,
2150 struct diff_filespec *two)
2152 int i;
2153 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2154 memcpy(o, orig_opts, sizeof(struct diff_options));
2156 ecbdata->diff_words =
2157 xcalloc(1, sizeof(struct diff_words_data));
2158 ecbdata->diff_words->type = o->word_diff;
2159 ecbdata->diff_words->opt = o;
2161 if (orig_opts->emitted_symbols)
2162 o->emitted_symbols =
2163 xcalloc(1, sizeof(struct emitted_diff_symbols));
2165 if (!o->word_regex)
2166 o->word_regex = userdiff_word_regex(one, o->repo->index);
2167 if (!o->word_regex)
2168 o->word_regex = userdiff_word_regex(two, o->repo->index);
2169 if (!o->word_regex)
2170 o->word_regex = diff_word_regex_cfg;
2171 if (o->word_regex) {
2172 ecbdata->diff_words->word_regex = (regex_t *)
2173 xmalloc(sizeof(regex_t));
2174 if (regcomp(ecbdata->diff_words->word_regex,
2175 o->word_regex,
2176 REG_EXTENDED | REG_NEWLINE))
2177 die("invalid regular expression: %s",
2178 o->word_regex);
2180 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2181 if (o->word_diff == diff_words_styles[i].type) {
2182 ecbdata->diff_words->style =
2183 &diff_words_styles[i];
2184 break;
2187 if (want_color(o->use_color)) {
2188 struct diff_words_style *st = ecbdata->diff_words->style;
2189 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2190 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2191 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2195 static void free_diff_words_data(struct emit_callback *ecbdata)
2197 if (ecbdata->diff_words) {
2198 diff_words_flush(ecbdata);
2199 free (ecbdata->diff_words->opt->emitted_symbols);
2200 free (ecbdata->diff_words->opt);
2201 free (ecbdata->diff_words->minus.text.ptr);
2202 free (ecbdata->diff_words->minus.orig);
2203 free (ecbdata->diff_words->plus.text.ptr);
2204 free (ecbdata->diff_words->plus.orig);
2205 if (ecbdata->diff_words->word_regex) {
2206 regfree(ecbdata->diff_words->word_regex);
2207 free(ecbdata->diff_words->word_regex);
2209 FREE_AND_NULL(ecbdata->diff_words);
2213 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2215 if (want_color(diff_use_color))
2216 return diff_colors[ix];
2217 return "";
2220 const char *diff_line_prefix(struct diff_options *opt)
2222 struct strbuf *msgbuf;
2223 if (!opt->output_prefix)
2224 return "";
2226 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2227 return msgbuf->buf;
2230 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
2232 const char *cp;
2233 unsigned long allot;
2234 size_t l = len;
2236 cp = line;
2237 allot = l;
2238 while (0 < l) {
2239 (void) utf8_width(&cp, &l);
2240 if (!cp)
2241 break; /* truncated in the middle? */
2243 return allot - l;
2246 static void find_lno(const char *line, struct emit_callback *ecbdata)
2248 const char *p;
2249 ecbdata->lno_in_preimage = 0;
2250 ecbdata->lno_in_postimage = 0;
2251 p = strchr(line, '-');
2252 if (!p)
2253 return; /* cannot happen */
2254 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2255 p = strchr(p, '+');
2256 if (!p)
2257 return; /* cannot happen */
2258 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2261 static void fn_out_consume(void *priv, char *line, unsigned long len)
2263 struct emit_callback *ecbdata = priv;
2264 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
2265 struct diff_options *o = ecbdata->opt;
2267 o->found_changes = 1;
2269 if (ecbdata->header) {
2270 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2271 ecbdata->header->buf, ecbdata->header->len, 0);
2272 strbuf_reset(ecbdata->header);
2273 ecbdata->header = NULL;
2276 if (ecbdata->label_path[0]) {
2277 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2278 ecbdata->label_path[0],
2279 strlen(ecbdata->label_path[0]), 0);
2280 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2281 ecbdata->label_path[1],
2282 strlen(ecbdata->label_path[1]), 0);
2283 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2286 if (diff_suppress_blank_empty
2287 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2288 line[0] = '\n';
2289 len = 1;
2292 if (line[0] == '@') {
2293 if (ecbdata->diff_words)
2294 diff_words_flush(ecbdata);
2295 len = sane_truncate_line(ecbdata, line, len);
2296 find_lno(line, ecbdata);
2297 emit_hunk_header(ecbdata, line, len);
2298 return;
2301 if (ecbdata->diff_words) {
2302 enum diff_symbol s =
2303 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2304 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2305 if (line[0] == '-') {
2306 diff_words_append(line, len,
2307 &ecbdata->diff_words->minus);
2308 return;
2309 } else if (line[0] == '+') {
2310 diff_words_append(line, len,
2311 &ecbdata->diff_words->plus);
2312 return;
2313 } else if (starts_with(line, "\\ ")) {
2315 * Eat the "no newline at eof" marker as if we
2316 * saw a "+" or "-" line with nothing on it,
2317 * and return without diff_words_flush() to
2318 * defer processing. If this is the end of
2319 * preimage, more "+" lines may come after it.
2321 return;
2323 diff_words_flush(ecbdata);
2324 emit_diff_symbol(o, s, line, len, 0);
2325 return;
2328 switch (line[0]) {
2329 case '+':
2330 ecbdata->lno_in_postimage++;
2331 emit_add_line(reset, ecbdata, line + 1, len - 1);
2332 break;
2333 case '-':
2334 ecbdata->lno_in_preimage++;
2335 emit_del_line(reset, ecbdata, line + 1, len - 1);
2336 break;
2337 case ' ':
2338 ecbdata->lno_in_postimage++;
2339 ecbdata->lno_in_preimage++;
2340 emit_context_line(reset, ecbdata, line + 1, len - 1);
2341 break;
2342 default:
2343 /* incomplete line at the end */
2344 ecbdata->lno_in_preimage++;
2345 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2346 line, len, 0);
2347 break;
2351 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2353 const char *old_name = a;
2354 const char *new_name = b;
2355 int pfx_length, sfx_length;
2356 int pfx_adjust_for_slash;
2357 int len_a = strlen(a);
2358 int len_b = strlen(b);
2359 int a_midlen, b_midlen;
2360 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2361 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2363 if (qlen_a || qlen_b) {
2364 quote_c_style(a, name, NULL, 0);
2365 strbuf_addstr(name, " => ");
2366 quote_c_style(b, name, NULL, 0);
2367 return;
2370 /* Find common prefix */
2371 pfx_length = 0;
2372 while (*old_name && *new_name && *old_name == *new_name) {
2373 if (*old_name == '/')
2374 pfx_length = old_name - a + 1;
2375 old_name++;
2376 new_name++;
2379 /* Find common suffix */
2380 old_name = a + len_a;
2381 new_name = b + len_b;
2382 sfx_length = 0;
2384 * If there is a common prefix, it must end in a slash. In
2385 * that case we let this loop run 1 into the prefix to see the
2386 * same slash.
2388 * If there is no common prefix, we cannot do this as it would
2389 * underrun the input strings.
2391 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2392 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2393 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2394 *old_name == *new_name) {
2395 if (*old_name == '/')
2396 sfx_length = len_a - (old_name - a);
2397 old_name--;
2398 new_name--;
2402 * pfx{mid-a => mid-b}sfx
2403 * {pfx-a => pfx-b}sfx
2404 * pfx{sfx-a => sfx-b}
2405 * name-a => name-b
2407 a_midlen = len_a - pfx_length - sfx_length;
2408 b_midlen = len_b - pfx_length - sfx_length;
2409 if (a_midlen < 0)
2410 a_midlen = 0;
2411 if (b_midlen < 0)
2412 b_midlen = 0;
2414 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2415 if (pfx_length + sfx_length) {
2416 strbuf_add(name, a, pfx_length);
2417 strbuf_addch(name, '{');
2419 strbuf_add(name, a + pfx_length, a_midlen);
2420 strbuf_addstr(name, " => ");
2421 strbuf_add(name, b + pfx_length, b_midlen);
2422 if (pfx_length + sfx_length) {
2423 strbuf_addch(name, '}');
2424 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2428 struct diffstat_t {
2429 int nr;
2430 int alloc;
2431 struct diffstat_file {
2432 char *from_name;
2433 char *name;
2434 char *print_name;
2435 const char *comments;
2436 unsigned is_unmerged:1;
2437 unsigned is_binary:1;
2438 unsigned is_renamed:1;
2439 unsigned is_interesting:1;
2440 uintmax_t added, deleted;
2441 } **files;
2444 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2445 const char *name_a,
2446 const char *name_b)
2448 struct diffstat_file *x;
2449 x = xcalloc(1, sizeof(*x));
2450 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2451 diffstat->files[diffstat->nr++] = x;
2452 if (name_b) {
2453 x->from_name = xstrdup(name_a);
2454 x->name = xstrdup(name_b);
2455 x->is_renamed = 1;
2457 else {
2458 x->from_name = NULL;
2459 x->name = xstrdup(name_a);
2461 return x;
2464 static void diffstat_consume(void *priv, char *line, unsigned long len)
2466 struct diffstat_t *diffstat = priv;
2467 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2469 if (line[0] == '+')
2470 x->added++;
2471 else if (line[0] == '-')
2472 x->deleted++;
2475 const char mime_boundary_leader[] = "------------";
2477 static int scale_linear(int it, int width, int max_change)
2479 if (!it)
2480 return 0;
2482 * make sure that at least one '-' or '+' is printed if
2483 * there is any change to this path. The easiest way is to
2484 * scale linearly as if the alloted width is one column shorter
2485 * than it is, and then add 1 to the result.
2487 return 1 + (it * (width - 1) / max_change);
2490 static void show_graph(struct strbuf *out, char ch, int cnt,
2491 const char *set, const char *reset)
2493 if (cnt <= 0)
2494 return;
2495 strbuf_addstr(out, set);
2496 strbuf_addchars(out, ch, cnt);
2497 strbuf_addstr(out, reset);
2500 static void fill_print_name(struct diffstat_file *file)
2502 struct strbuf pname = STRBUF_INIT;
2504 if (file->print_name)
2505 return;
2507 if (file->is_renamed)
2508 pprint_rename(&pname, file->from_name, file->name);
2509 else
2510 quote_c_style(file->name, &pname, NULL, 0);
2512 if (file->comments)
2513 strbuf_addf(&pname, " (%s)", file->comments);
2515 file->print_name = strbuf_detach(&pname, NULL);
2518 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2519 int files, int insertions, int deletions)
2521 struct strbuf sb = STRBUF_INIT;
2523 if (!files) {
2524 assert(insertions == 0 && deletions == 0);
2525 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2526 NULL, 0, 0);
2527 return;
2530 strbuf_addf(&sb,
2531 (files == 1) ? " %d file changed" : " %d files changed",
2532 files);
2535 * For binary diff, the caller may want to print "x files
2536 * changed" with insertions == 0 && deletions == 0.
2538 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2539 * is probably less confusing (i.e skip over "2 files changed
2540 * but nothing about added/removed lines? Is this a bug in Git?").
2542 if (insertions || deletions == 0) {
2543 strbuf_addf(&sb,
2544 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2545 insertions);
2548 if (deletions || insertions == 0) {
2549 strbuf_addf(&sb,
2550 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2551 deletions);
2553 strbuf_addch(&sb, '\n');
2554 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2555 sb.buf, sb.len, 0);
2556 strbuf_release(&sb);
2559 void print_stat_summary(FILE *fp, int files,
2560 int insertions, int deletions)
2562 struct diff_options o;
2563 memset(&o, 0, sizeof(o));
2564 o.file = fp;
2566 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2569 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2571 int i, len, add, del, adds = 0, dels = 0;
2572 uintmax_t max_change = 0, max_len = 0;
2573 int total_files = data->nr, count;
2574 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2575 const char *reset, *add_c, *del_c;
2576 int extra_shown = 0;
2577 const char *line_prefix = diff_line_prefix(options);
2578 struct strbuf out = STRBUF_INIT;
2580 if (data->nr == 0)
2581 return;
2583 count = options->stat_count ? options->stat_count : data->nr;
2585 reset = diff_get_color_opt(options, DIFF_RESET);
2586 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2587 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2590 * Find the longest filename and max number of changes
2592 for (i = 0; (i < count) && (i < data->nr); i++) {
2593 struct diffstat_file *file = data->files[i];
2594 uintmax_t change = file->added + file->deleted;
2596 if (!file->is_interesting && (change == 0)) {
2597 count++; /* not shown == room for one more */
2598 continue;
2600 fill_print_name(file);
2601 len = strlen(file->print_name);
2602 if (max_len < len)
2603 max_len = len;
2605 if (file->is_unmerged) {
2606 /* "Unmerged" is 8 characters */
2607 bin_width = bin_width < 8 ? 8 : bin_width;
2608 continue;
2610 if (file->is_binary) {
2611 /* "Bin XXX -> YYY bytes" */
2612 int w = 14 + decimal_width(file->added)
2613 + decimal_width(file->deleted);
2614 bin_width = bin_width < w ? w : bin_width;
2615 /* Display change counts aligned with "Bin" */
2616 number_width = 3;
2617 continue;
2620 if (max_change < change)
2621 max_change = change;
2623 count = i; /* where we can stop scanning in data->files[] */
2626 * We have width = stat_width or term_columns() columns total.
2627 * We want a maximum of min(max_len, stat_name_width) for the name part.
2628 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2629 * We also need 1 for " " and 4 + decimal_width(max_change)
2630 * for " | NNNN " and one the empty column at the end, altogether
2631 * 6 + decimal_width(max_change).
2633 * If there's not enough space, we will use the smaller of
2634 * stat_name_width (if set) and 5/8*width for the filename,
2635 * and the rest for constant elements + graph part, but no more
2636 * than stat_graph_width for the graph part.
2637 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2638 * for the standard terminal size).
2640 * In other words: stat_width limits the maximum width, and
2641 * stat_name_width fixes the maximum width of the filename,
2642 * and is also used to divide available columns if there
2643 * aren't enough.
2645 * Binary files are displayed with "Bin XXX -> YYY bytes"
2646 * instead of the change count and graph. This part is treated
2647 * similarly to the graph part, except that it is not
2648 * "scaled". If total width is too small to accommodate the
2649 * guaranteed minimum width of the filename part and the
2650 * separators and this message, this message will "overflow"
2651 * making the line longer than the maximum width.
2654 if (options->stat_width == -1)
2655 width = term_columns() - strlen(line_prefix);
2656 else
2657 width = options->stat_width ? options->stat_width : 80;
2658 number_width = decimal_width(max_change) > number_width ?
2659 decimal_width(max_change) : number_width;
2661 if (options->stat_graph_width == -1)
2662 options->stat_graph_width = diff_stat_graph_width;
2665 * Guarantee 3/8*16==6 for the graph part
2666 * and 5/8*16==10 for the filename part
2668 if (width < 16 + 6 + number_width)
2669 width = 16 + 6 + number_width;
2672 * First assign sizes that are wanted, ignoring available width.
2673 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2674 * starting from "XXX" should fit in graph_width.
2676 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2677 if (options->stat_graph_width &&
2678 options->stat_graph_width < graph_width)
2679 graph_width = options->stat_graph_width;
2681 name_width = (options->stat_name_width > 0 &&
2682 options->stat_name_width < max_len) ?
2683 options->stat_name_width : max_len;
2686 * Adjust adjustable widths not to exceed maximum width
2688 if (name_width + number_width + 6 + graph_width > width) {
2689 if (graph_width > width * 3/8 - number_width - 6) {
2690 graph_width = width * 3/8 - number_width - 6;
2691 if (graph_width < 6)
2692 graph_width = 6;
2695 if (options->stat_graph_width &&
2696 graph_width > options->stat_graph_width)
2697 graph_width = options->stat_graph_width;
2698 if (name_width > width - number_width - 6 - graph_width)
2699 name_width = width - number_width - 6 - graph_width;
2700 else
2701 graph_width = width - number_width - 6 - name_width;
2705 * From here name_width is the width of the name area,
2706 * and graph_width is the width of the graph area.
2707 * max_change is used to scale graph properly.
2709 for (i = 0; i < count; i++) {
2710 const char *prefix = "";
2711 struct diffstat_file *file = data->files[i];
2712 char *name = file->print_name;
2713 uintmax_t added = file->added;
2714 uintmax_t deleted = file->deleted;
2715 int name_len;
2717 if (!file->is_interesting && (added + deleted == 0))
2718 continue;
2721 * "scale" the filename
2723 len = name_width;
2724 name_len = strlen(name);
2725 if (name_width < name_len) {
2726 char *slash;
2727 prefix = "...";
2728 len -= 3;
2729 name += name_len - len;
2730 slash = strchr(name, '/');
2731 if (slash)
2732 name = slash;
2735 if (file->is_binary) {
2736 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2737 strbuf_addf(&out, " %*s", number_width, "Bin");
2738 if (!added && !deleted) {
2739 strbuf_addch(&out, '\n');
2740 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2741 out.buf, out.len, 0);
2742 strbuf_reset(&out);
2743 continue;
2745 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2746 del_c, deleted, reset);
2747 strbuf_addstr(&out, " -> ");
2748 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2749 add_c, added, reset);
2750 strbuf_addstr(&out, " bytes\n");
2751 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2752 out.buf, out.len, 0);
2753 strbuf_reset(&out);
2754 continue;
2756 else if (file->is_unmerged) {
2757 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2758 strbuf_addstr(&out, " Unmerged\n");
2759 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2760 out.buf, out.len, 0);
2761 strbuf_reset(&out);
2762 continue;
2766 * scale the add/delete
2768 add = added;
2769 del = deleted;
2771 if (graph_width <= max_change) {
2772 int total = scale_linear(add + del, graph_width, max_change);
2773 if (total < 2 && add && del)
2774 /* width >= 2 due to the sanity check */
2775 total = 2;
2776 if (add < del) {
2777 add = scale_linear(add, graph_width, max_change);
2778 del = total - add;
2779 } else {
2780 del = scale_linear(del, graph_width, max_change);
2781 add = total - del;
2784 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2785 strbuf_addf(&out, " %*"PRIuMAX"%s",
2786 number_width, added + deleted,
2787 added + deleted ? " " : "");
2788 show_graph(&out, '+', add, add_c, reset);
2789 show_graph(&out, '-', del, del_c, reset);
2790 strbuf_addch(&out, '\n');
2791 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2792 out.buf, out.len, 0);
2793 strbuf_reset(&out);
2796 for (i = 0; i < data->nr; i++) {
2797 struct diffstat_file *file = data->files[i];
2798 uintmax_t added = file->added;
2799 uintmax_t deleted = file->deleted;
2801 if (file->is_unmerged ||
2802 (!file->is_interesting && (added + deleted == 0))) {
2803 total_files--;
2804 continue;
2807 if (!file->is_binary) {
2808 adds += added;
2809 dels += deleted;
2811 if (i < count)
2812 continue;
2813 if (!extra_shown)
2814 emit_diff_symbol(options,
2815 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2816 NULL, 0, 0);
2817 extra_shown = 1;
2820 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2821 strbuf_release(&out);
2824 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2826 int i, adds = 0, dels = 0, total_files = data->nr;
2828 if (data->nr == 0)
2829 return;
2831 for (i = 0; i < data->nr; i++) {
2832 int added = data->files[i]->added;
2833 int deleted = data->files[i]->deleted;
2835 if (data->files[i]->is_unmerged ||
2836 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2837 total_files--;
2838 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2839 adds += added;
2840 dels += deleted;
2843 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2846 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2848 int i;
2850 if (data->nr == 0)
2851 return;
2853 for (i = 0; i < data->nr; i++) {
2854 struct diffstat_file *file = data->files[i];
2856 fprintf(options->file, "%s", diff_line_prefix(options));
2858 if (file->is_binary)
2859 fprintf(options->file, "-\t-\t");
2860 else
2861 fprintf(options->file,
2862 "%"PRIuMAX"\t%"PRIuMAX"\t",
2863 file->added, file->deleted);
2864 if (options->line_termination) {
2865 fill_print_name(file);
2866 if (!file->is_renamed)
2867 write_name_quoted(file->name, options->file,
2868 options->line_termination);
2869 else {
2870 fputs(file->print_name, options->file);
2871 putc(options->line_termination, options->file);
2873 } else {
2874 if (file->is_renamed) {
2875 putc('\0', options->file);
2876 write_name_quoted(file->from_name, options->file, '\0');
2878 write_name_quoted(file->name, options->file, '\0');
2883 struct dirstat_file {
2884 const char *name;
2885 unsigned long changed;
2888 struct dirstat_dir {
2889 struct dirstat_file *files;
2890 int alloc, nr, permille, cumulative;
2893 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2894 unsigned long changed, const char *base, int baselen)
2896 unsigned long sum_changes = 0;
2897 unsigned int sources = 0;
2898 const char *line_prefix = diff_line_prefix(opt);
2900 while (dir->nr) {
2901 struct dirstat_file *f = dir->files;
2902 int namelen = strlen(f->name);
2903 unsigned long changes;
2904 char *slash;
2906 if (namelen < baselen)
2907 break;
2908 if (memcmp(f->name, base, baselen))
2909 break;
2910 slash = strchr(f->name + baselen, '/');
2911 if (slash) {
2912 int newbaselen = slash + 1 - f->name;
2913 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2914 sources++;
2915 } else {
2916 changes = f->changed;
2917 dir->files++;
2918 dir->nr--;
2919 sources += 2;
2921 sum_changes += changes;
2925 * We don't report dirstat's for
2926 * - the top level
2927 * - or cases where everything came from a single directory
2928 * under this directory (sources == 1).
2930 if (baselen && sources != 1) {
2931 if (sum_changes) {
2932 int permille = sum_changes * 1000 / changed;
2933 if (permille >= dir->permille) {
2934 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2935 permille / 10, permille % 10, baselen, base);
2936 if (!dir->cumulative)
2937 return 0;
2941 return sum_changes;
2944 static int dirstat_compare(const void *_a, const void *_b)
2946 const struct dirstat_file *a = _a;
2947 const struct dirstat_file *b = _b;
2948 return strcmp(a->name, b->name);
2951 static void show_dirstat(struct diff_options *options)
2953 int i;
2954 unsigned long changed;
2955 struct dirstat_dir dir;
2956 struct diff_queue_struct *q = &diff_queued_diff;
2958 dir.files = NULL;
2959 dir.alloc = 0;
2960 dir.nr = 0;
2961 dir.permille = options->dirstat_permille;
2962 dir.cumulative = options->flags.dirstat_cumulative;
2964 changed = 0;
2965 for (i = 0; i < q->nr; i++) {
2966 struct diff_filepair *p = q->queue[i];
2967 const char *name;
2968 unsigned long copied, added, damage;
2970 name = p->two->path ? p->two->path : p->one->path;
2972 if (p->one->oid_valid && p->two->oid_valid &&
2973 oideq(&p->one->oid, &p->two->oid)) {
2975 * The SHA1 has not changed, so pre-/post-content is
2976 * identical. We can therefore skip looking at the
2977 * file contents altogether.
2979 damage = 0;
2980 goto found_damage;
2983 if (options->flags.dirstat_by_file) {
2985 * In --dirstat-by-file mode, we don't really need to
2986 * look at the actual file contents at all.
2987 * The fact that the SHA1 changed is enough for us to
2988 * add this file to the list of results
2989 * (with each file contributing equal damage).
2991 damage = 1;
2992 goto found_damage;
2995 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2996 diff_populate_filespec(options->repo, p->one, 0);
2997 diff_populate_filespec(options->repo, p->two, 0);
2998 diffcore_count_changes(options->repo,
2999 p->one, p->two, NULL, NULL,
3000 &copied, &added);
3001 diff_free_filespec_data(p->one);
3002 diff_free_filespec_data(p->two);
3003 } else if (DIFF_FILE_VALID(p->one)) {
3004 diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
3005 copied = added = 0;
3006 diff_free_filespec_data(p->one);
3007 } else if (DIFF_FILE_VALID(p->two)) {
3008 diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
3009 copied = 0;
3010 added = p->two->size;
3011 diff_free_filespec_data(p->two);
3012 } else
3013 continue;
3016 * Original minus copied is the removed material,
3017 * added is the new material. They are both damages
3018 * made to the preimage.
3019 * If the resulting damage is zero, we know that
3020 * diffcore_count_changes() considers the two entries to
3021 * be identical, but since the oid changed, we
3022 * know that there must have been _some_ kind of change,
3023 * so we force all entries to have damage > 0.
3025 damage = (p->one->size - copied) + added;
3026 if (!damage)
3027 damage = 1;
3029 found_damage:
3030 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3031 dir.files[dir.nr].name = name;
3032 dir.files[dir.nr].changed = damage;
3033 changed += damage;
3034 dir.nr++;
3037 /* This can happen even with many files, if everything was renames */
3038 if (!changed)
3039 return;
3041 /* Show all directories with more than x% of the changes */
3042 QSORT(dir.files, dir.nr, dirstat_compare);
3043 gather_dirstat(options, &dir, changed, "", 0);
3046 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3048 int i;
3049 unsigned long changed;
3050 struct dirstat_dir dir;
3052 if (data->nr == 0)
3053 return;
3055 dir.files = NULL;
3056 dir.alloc = 0;
3057 dir.nr = 0;
3058 dir.permille = options->dirstat_permille;
3059 dir.cumulative = options->flags.dirstat_cumulative;
3061 changed = 0;
3062 for (i = 0; i < data->nr; i++) {
3063 struct diffstat_file *file = data->files[i];
3064 unsigned long damage = file->added + file->deleted;
3065 if (file->is_binary)
3067 * binary files counts bytes, not lines. Must find some
3068 * way to normalize binary bytes vs. textual lines.
3069 * The following heuristic assumes that there are 64
3070 * bytes per "line".
3071 * This is stupid and ugly, but very cheap...
3073 damage = DIV_ROUND_UP(damage, 64);
3074 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3075 dir.files[dir.nr].name = file->name;
3076 dir.files[dir.nr].changed = damage;
3077 changed += damage;
3078 dir.nr++;
3081 /* This can happen even with many files, if everything was renames */
3082 if (!changed)
3083 return;
3085 /* Show all directories with more than x% of the changes */
3086 QSORT(dir.files, dir.nr, dirstat_compare);
3087 gather_dirstat(options, &dir, changed, "", 0);
3090 static void free_diffstat_info(struct diffstat_t *diffstat)
3092 int i;
3093 for (i = 0; i < diffstat->nr; i++) {
3094 struct diffstat_file *f = diffstat->files[i];
3095 free(f->print_name);
3096 free(f->name);
3097 free(f->from_name);
3098 free(f);
3100 free(diffstat->files);
3103 struct checkdiff_t {
3104 const char *filename;
3105 int lineno;
3106 int conflict_marker_size;
3107 struct diff_options *o;
3108 unsigned ws_rule;
3109 unsigned status;
3112 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3114 char firstchar;
3115 int cnt;
3117 if (len < marker_size + 1)
3118 return 0;
3119 firstchar = line[0];
3120 switch (firstchar) {
3121 case '=': case '>': case '<': case '|':
3122 break;
3123 default:
3124 return 0;
3126 for (cnt = 1; cnt < marker_size; cnt++)
3127 if (line[cnt] != firstchar)
3128 return 0;
3129 /* line[1] thru line[marker_size-1] are same as firstchar */
3130 if (len < marker_size + 1 || !isspace(line[marker_size]))
3131 return 0;
3132 return 1;
3135 static void checkdiff_consume_hunk(void *priv,
3136 long ob, long on, long nb, long nn,
3137 const char *func, long funclen)
3140 struct checkdiff_t *data = priv;
3141 data->lineno = nb - 1;
3144 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3146 struct checkdiff_t *data = priv;
3147 int marker_size = data->conflict_marker_size;
3148 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3149 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3150 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3151 char *err;
3152 const char *line_prefix;
3154 assert(data->o);
3155 line_prefix = diff_line_prefix(data->o);
3157 if (line[0] == '+') {
3158 unsigned bad;
3159 data->lineno++;
3160 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3161 data->status |= 1;
3162 fprintf(data->o->file,
3163 "%s%s:%d: leftover conflict marker\n",
3164 line_prefix, data->filename, data->lineno);
3166 bad = ws_check(line + 1, len - 1, data->ws_rule);
3167 if (!bad)
3168 return;
3169 data->status |= bad;
3170 err = whitespace_error_string(bad);
3171 fprintf(data->o->file, "%s%s:%d: %s.\n",
3172 line_prefix, data->filename, data->lineno, err);
3173 free(err);
3174 emit_line(data->o, set, reset, line, 1);
3175 ws_check_emit(line + 1, len - 1, data->ws_rule,
3176 data->o->file, set, reset, ws);
3177 } else if (line[0] == ' ') {
3178 data->lineno++;
3182 static unsigned char *deflate_it(char *data,
3183 unsigned long size,
3184 unsigned long *result_size)
3186 int bound;
3187 unsigned char *deflated;
3188 git_zstream stream;
3190 git_deflate_init(&stream, zlib_compression_level);
3191 bound = git_deflate_bound(&stream, size);
3192 deflated = xmalloc(bound);
3193 stream.next_out = deflated;
3194 stream.avail_out = bound;
3196 stream.next_in = (unsigned char *)data;
3197 stream.avail_in = size;
3198 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3199 ; /* nothing */
3200 git_deflate_end(&stream);
3201 *result_size = stream.total_out;
3202 return deflated;
3205 static void emit_binary_diff_body(struct diff_options *o,
3206 mmfile_t *one, mmfile_t *two)
3208 void *cp;
3209 void *delta;
3210 void *deflated;
3211 void *data;
3212 unsigned long orig_size;
3213 unsigned long delta_size;
3214 unsigned long deflate_size;
3215 unsigned long data_size;
3217 /* We could do deflated delta, or we could do just deflated two,
3218 * whichever is smaller.
3220 delta = NULL;
3221 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3222 if (one->size && two->size) {
3223 delta = diff_delta(one->ptr, one->size,
3224 two->ptr, two->size,
3225 &delta_size, deflate_size);
3226 if (delta) {
3227 void *to_free = delta;
3228 orig_size = delta_size;
3229 delta = deflate_it(delta, delta_size, &delta_size);
3230 free(to_free);
3234 if (delta && delta_size < deflate_size) {
3235 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3236 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3237 s, strlen(s), 0);
3238 free(s);
3239 free(deflated);
3240 data = delta;
3241 data_size = delta_size;
3242 } else {
3243 char *s = xstrfmt("%lu", two->size);
3244 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3245 s, strlen(s), 0);
3246 free(s);
3247 free(delta);
3248 data = deflated;
3249 data_size = deflate_size;
3252 /* emit data encoded in base85 */
3253 cp = data;
3254 while (data_size) {
3255 int len;
3256 int bytes = (52 < data_size) ? 52 : data_size;
3257 char line[71];
3258 data_size -= bytes;
3259 if (bytes <= 26)
3260 line[0] = bytes + 'A' - 1;
3261 else
3262 line[0] = bytes - 26 + 'a' - 1;
3263 encode_85(line + 1, cp, bytes);
3264 cp = (char *) cp + bytes;
3266 len = strlen(line);
3267 line[len++] = '\n';
3268 line[len] = '\0';
3270 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3271 line, len, 0);
3273 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3274 free(data);
3277 static void emit_binary_diff(struct diff_options *o,
3278 mmfile_t *one, mmfile_t *two)
3280 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3281 emit_binary_diff_body(o, one, two);
3282 emit_binary_diff_body(o, two, one);
3285 int diff_filespec_is_binary(struct repository *r,
3286 struct diff_filespec *one)
3288 if (one->is_binary == -1) {
3289 diff_filespec_load_driver(one, r->index);
3290 if (one->driver->binary != -1)
3291 one->is_binary = one->driver->binary;
3292 else {
3293 if (!one->data && DIFF_FILE_VALID(one))
3294 diff_populate_filespec(r, one, CHECK_BINARY);
3295 if (one->is_binary == -1 && one->data)
3296 one->is_binary = buffer_is_binary(one->data,
3297 one->size);
3298 if (one->is_binary == -1)
3299 one->is_binary = 0;
3302 return one->is_binary;
3305 static const struct userdiff_funcname *
3306 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3308 diff_filespec_load_driver(one, o->repo->index);
3309 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3312 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3314 if (!options->a_prefix)
3315 options->a_prefix = a;
3316 if (!options->b_prefix)
3317 options->b_prefix = b;
3320 struct userdiff_driver *get_textconv(struct repository *r,
3321 struct diff_filespec *one)
3323 if (!DIFF_FILE_VALID(one))
3324 return NULL;
3326 diff_filespec_load_driver(one, r->index);
3327 return userdiff_get_textconv(r, one->driver);
3330 static void builtin_diff(const char *name_a,
3331 const char *name_b,
3332 struct diff_filespec *one,
3333 struct diff_filespec *two,
3334 const char *xfrm_msg,
3335 int must_show_header,
3336 struct diff_options *o,
3337 int complete_rewrite)
3339 mmfile_t mf1, mf2;
3340 const char *lbl[2];
3341 char *a_one, *b_two;
3342 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3343 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3344 const char *a_prefix, *b_prefix;
3345 struct userdiff_driver *textconv_one = NULL;
3346 struct userdiff_driver *textconv_two = NULL;
3347 struct strbuf header = STRBUF_INIT;
3348 const char *line_prefix = diff_line_prefix(o);
3350 diff_set_mnemonic_prefix(o, "a/", "b/");
3351 if (o->flags.reverse_diff) {
3352 a_prefix = o->b_prefix;
3353 b_prefix = o->a_prefix;
3354 } else {
3355 a_prefix = o->a_prefix;
3356 b_prefix = o->b_prefix;
3359 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3360 (!one->mode || S_ISGITLINK(one->mode)) &&
3361 (!two->mode || S_ISGITLINK(two->mode))) {
3362 show_submodule_summary(o, one->path ? one->path : two->path,
3363 &one->oid, &two->oid,
3364 two->dirty_submodule);
3365 return;
3366 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3367 (!one->mode || S_ISGITLINK(one->mode)) &&
3368 (!two->mode || S_ISGITLINK(two->mode))) {
3369 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3370 &one->oid, &two->oid,
3371 two->dirty_submodule);
3372 return;
3375 if (o->flags.allow_textconv) {
3376 textconv_one = get_textconv(o->repo, one);
3377 textconv_two = get_textconv(o->repo, two);
3380 /* Never use a non-valid filename anywhere if at all possible */
3381 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3382 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3384 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3385 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3386 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3387 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3388 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3389 if (lbl[0][0] == '/') {
3390 /* /dev/null */
3391 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3392 if (xfrm_msg)
3393 strbuf_addstr(&header, xfrm_msg);
3394 must_show_header = 1;
3396 else if (lbl[1][0] == '/') {
3397 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3398 if (xfrm_msg)
3399 strbuf_addstr(&header, xfrm_msg);
3400 must_show_header = 1;
3402 else {
3403 if (one->mode != two->mode) {
3404 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3405 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3406 must_show_header = 1;
3408 if (xfrm_msg)
3409 strbuf_addstr(&header, xfrm_msg);
3412 * we do not run diff between different kind
3413 * of objects.
3415 if ((one->mode ^ two->mode) & S_IFMT)
3416 goto free_ab_and_return;
3417 if (complete_rewrite &&
3418 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3419 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3420 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3421 header.buf, header.len, 0);
3422 strbuf_reset(&header);
3423 emit_rewrite_diff(name_a, name_b, one, two,
3424 textconv_one, textconv_two, o);
3425 o->found_changes = 1;
3426 goto free_ab_and_return;
3430 if (o->irreversible_delete && lbl[1][0] == '/') {
3431 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3432 header.len, 0);
3433 strbuf_reset(&header);
3434 goto free_ab_and_return;
3435 } else if (!o->flags.text &&
3436 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3437 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3438 struct strbuf sb = STRBUF_INIT;
3439 if (!one->data && !two->data &&
3440 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3441 !o->flags.binary) {
3442 if (oideq(&one->oid, &two->oid)) {
3443 if (must_show_header)
3444 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3445 header.buf, header.len,
3447 goto free_ab_and_return;
3449 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3450 header.buf, header.len, 0);
3451 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3452 diff_line_prefix(o), lbl[0], lbl[1]);
3453 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3454 sb.buf, sb.len, 0);
3455 strbuf_release(&sb);
3456 goto free_ab_and_return;
3458 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3459 fill_mmfile(o->repo, &mf2, two) < 0)
3460 die("unable to read files to diff");
3461 /* Quite common confusing case */
3462 if (mf1.size == mf2.size &&
3463 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3464 if (must_show_header)
3465 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3466 header.buf, header.len, 0);
3467 goto free_ab_and_return;
3469 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3470 strbuf_reset(&header);
3471 if (o->flags.binary)
3472 emit_binary_diff(o, &mf1, &mf2);
3473 else {
3474 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3475 diff_line_prefix(o), lbl[0], lbl[1]);
3476 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3477 sb.buf, sb.len, 0);
3478 strbuf_release(&sb);
3480 o->found_changes = 1;
3481 } else {
3482 /* Crazy xdl interfaces.. */
3483 const char *diffopts = getenv("GIT_DIFF_OPTS");
3484 const char *v;
3485 xpparam_t xpp;
3486 xdemitconf_t xecfg;
3487 struct emit_callback ecbdata;
3488 const struct userdiff_funcname *pe;
3490 if (must_show_header) {
3491 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3492 header.buf, header.len, 0);
3493 strbuf_reset(&header);
3496 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3497 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3499 pe = diff_funcname_pattern(o, one);
3500 if (!pe)
3501 pe = diff_funcname_pattern(o, two);
3503 memset(&xpp, 0, sizeof(xpp));
3504 memset(&xecfg, 0, sizeof(xecfg));
3505 memset(&ecbdata, 0, sizeof(ecbdata));
3506 if (o->flags.suppress_diff_headers)
3507 lbl[0] = NULL;
3508 ecbdata.label_path = lbl;
3509 ecbdata.color_diff = want_color(o->use_color);
3510 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3511 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3512 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3513 ecbdata.opt = o;
3514 if (header.len && !o->flags.suppress_diff_headers)
3515 ecbdata.header = &header;
3516 xpp.flags = o->xdl_opts;
3517 xpp.anchors = o->anchors;
3518 xpp.anchors_nr = o->anchors_nr;
3519 xecfg.ctxlen = o->context;
3520 xecfg.interhunkctxlen = o->interhunkcontext;
3521 xecfg.flags = XDL_EMIT_FUNCNAMES;
3522 if (o->flags.funccontext)
3523 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3524 if (pe)
3525 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3526 if (!diffopts)
3528 else if (skip_prefix(diffopts, "--unified=", &v))
3529 xecfg.ctxlen = strtoul(v, NULL, 10);
3530 else if (skip_prefix(diffopts, "-u", &v))
3531 xecfg.ctxlen = strtoul(v, NULL, 10);
3532 if (o->word_diff)
3533 init_diff_words_data(&ecbdata, o, one, two);
3534 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3535 &ecbdata, &xpp, &xecfg))
3536 die("unable to generate diff for %s", one->path);
3537 if (o->word_diff)
3538 free_diff_words_data(&ecbdata);
3539 if (textconv_one)
3540 free(mf1.ptr);
3541 if (textconv_two)
3542 free(mf2.ptr);
3543 xdiff_clear_find_func(&xecfg);
3546 free_ab_and_return:
3547 strbuf_release(&header);
3548 diff_free_filespec_data(one);
3549 diff_free_filespec_data(two);
3550 free(a_one);
3551 free(b_two);
3552 return;
3555 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3557 if (!is_renamed) {
3558 if (p->status == DIFF_STATUS_ADDED) {
3559 if (S_ISLNK(p->two->mode))
3560 return "new +l";
3561 else if ((p->two->mode & 0777) == 0755)
3562 return "new +x";
3563 else
3564 return "new";
3565 } else if (p->status == DIFF_STATUS_DELETED)
3566 return "gone";
3568 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3569 return "mode -l";
3570 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3571 return "mode +l";
3572 else if ((p->one->mode & 0777) == 0644 &&
3573 (p->two->mode & 0777) == 0755)
3574 return "mode +x";
3575 else if ((p->one->mode & 0777) == 0755 &&
3576 (p->two->mode & 0777) == 0644)
3577 return "mode -x";
3578 return NULL;
3581 static void builtin_diffstat(const char *name_a, const char *name_b,
3582 struct diff_filespec *one,
3583 struct diff_filespec *two,
3584 struct diffstat_t *diffstat,
3585 struct diff_options *o,
3586 struct diff_filepair *p)
3588 mmfile_t mf1, mf2;
3589 struct diffstat_file *data;
3590 int same_contents;
3591 int complete_rewrite = 0;
3593 if (!DIFF_PAIR_UNMERGED(p)) {
3594 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3595 complete_rewrite = 1;
3598 data = diffstat_add(diffstat, name_a, name_b);
3599 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3600 if (o->flags.stat_with_summary)
3601 data->comments = get_compact_summary(p, data->is_renamed);
3603 if (!one || !two) {
3604 data->is_unmerged = 1;
3605 return;
3608 same_contents = oideq(&one->oid, &two->oid);
3610 if (diff_filespec_is_binary(o->repo, one) ||
3611 diff_filespec_is_binary(o->repo, two)) {
3612 data->is_binary = 1;
3613 if (same_contents) {
3614 data->added = 0;
3615 data->deleted = 0;
3616 } else {
3617 data->added = diff_filespec_size(o->repo, two);
3618 data->deleted = diff_filespec_size(o->repo, one);
3622 else if (complete_rewrite) {
3623 diff_populate_filespec(o->repo, one, 0);
3624 diff_populate_filespec(o->repo, two, 0);
3625 data->deleted = count_lines(one->data, one->size);
3626 data->added = count_lines(two->data, two->size);
3629 else if (!same_contents) {
3630 /* Crazy xdl interfaces.. */
3631 xpparam_t xpp;
3632 xdemitconf_t xecfg;
3634 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3635 fill_mmfile(o->repo, &mf2, two) < 0)
3636 die("unable to read files to diff");
3638 memset(&xpp, 0, sizeof(xpp));
3639 memset(&xecfg, 0, sizeof(xecfg));
3640 xpp.flags = o->xdl_opts;
3641 xpp.anchors = o->anchors;
3642 xpp.anchors_nr = o->anchors_nr;
3643 xecfg.ctxlen = o->context;
3644 xecfg.interhunkctxlen = o->interhunkcontext;
3645 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3646 diffstat_consume, diffstat, &xpp, &xecfg))
3647 die("unable to generate diffstat for %s", one->path);
3650 diff_free_filespec_data(one);
3651 diff_free_filespec_data(two);
3654 static void builtin_checkdiff(const char *name_a, const char *name_b,
3655 const char *attr_path,
3656 struct diff_filespec *one,
3657 struct diff_filespec *two,
3658 struct diff_options *o)
3660 mmfile_t mf1, mf2;
3661 struct checkdiff_t data;
3663 if (!two)
3664 return;
3666 memset(&data, 0, sizeof(data));
3667 data.filename = name_b ? name_b : name_a;
3668 data.lineno = 0;
3669 data.o = o;
3670 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3671 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3673 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3674 fill_mmfile(o->repo, &mf2, two) < 0)
3675 die("unable to read files to diff");
3678 * All the other codepaths check both sides, but not checking
3679 * the "old" side here is deliberate. We are checking the newly
3680 * introduced changes, and as long as the "new" side is text, we
3681 * can and should check what it introduces.
3683 if (diff_filespec_is_binary(o->repo, two))
3684 goto free_and_return;
3685 else {
3686 /* Crazy xdl interfaces.. */
3687 xpparam_t xpp;
3688 xdemitconf_t xecfg;
3690 memset(&xpp, 0, sizeof(xpp));
3691 memset(&xecfg, 0, sizeof(xecfg));
3692 xecfg.ctxlen = 1; /* at least one context line */
3693 xpp.flags = 0;
3694 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3695 checkdiff_consume, &data,
3696 &xpp, &xecfg))
3697 die("unable to generate checkdiff for %s", one->path);
3699 if (data.ws_rule & WS_BLANK_AT_EOF) {
3700 struct emit_callback ecbdata;
3701 int blank_at_eof;
3703 ecbdata.ws_rule = data.ws_rule;
3704 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3705 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3707 if (blank_at_eof) {
3708 static char *err;
3709 if (!err)
3710 err = whitespace_error_string(WS_BLANK_AT_EOF);
3711 fprintf(o->file, "%s:%d: %s.\n",
3712 data.filename, blank_at_eof, err);
3713 data.status = 1; /* report errors */
3717 free_and_return:
3718 diff_free_filespec_data(one);
3719 diff_free_filespec_data(two);
3720 if (data.status)
3721 o->flags.check_failed = 1;
3724 struct diff_filespec *alloc_filespec(const char *path)
3726 struct diff_filespec *spec;
3728 FLEXPTR_ALLOC_STR(spec, path, path);
3729 spec->count = 1;
3730 spec->is_binary = -1;
3731 return spec;
3734 void free_filespec(struct diff_filespec *spec)
3736 if (!--spec->count) {
3737 diff_free_filespec_data(spec);
3738 free(spec);
3742 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3743 int oid_valid, unsigned short mode)
3745 if (mode) {
3746 spec->mode = canon_mode(mode);
3747 oidcpy(&spec->oid, oid);
3748 spec->oid_valid = oid_valid;
3753 * Given a name and sha1 pair, if the index tells us the file in
3754 * the work tree has that object contents, return true, so that
3755 * prepare_temp_file() does not have to inflate and extract.
3757 static int reuse_worktree_file(struct index_state *istate,
3758 const char *name,
3759 const struct object_id *oid,
3760 int want_file)
3762 const struct cache_entry *ce;
3763 struct stat st;
3764 int pos, len;
3767 * We do not read the cache ourselves here, because the
3768 * benchmark with my previous version that always reads cache
3769 * shows that it makes things worse for diff-tree comparing
3770 * two linux-2.6 kernel trees in an already checked out work
3771 * tree. This is because most diff-tree comparisons deal with
3772 * only a small number of files, while reading the cache is
3773 * expensive for a large project, and its cost outweighs the
3774 * savings we get by not inflating the object to a temporary
3775 * file. Practically, this code only helps when we are used
3776 * by diff-cache --cached, which does read the cache before
3777 * calling us.
3779 if (!istate->cache)
3780 return 0;
3782 /* We want to avoid the working directory if our caller
3783 * doesn't need the data in a normal file, this system
3784 * is rather slow with its stat/open/mmap/close syscalls,
3785 * and the object is contained in a pack file. The pack
3786 * is probably already open and will be faster to obtain
3787 * the data through than the working directory. Loose
3788 * objects however would tend to be slower as they need
3789 * to be individually opened and inflated.
3791 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3792 return 0;
3795 * Similarly, if we'd have to convert the file contents anyway, that
3796 * makes the optimization not worthwhile.
3798 if (!want_file && would_convert_to_git(istate, name))
3799 return 0;
3801 len = strlen(name);
3802 pos = index_name_pos(istate, name, len);
3803 if (pos < 0)
3804 return 0;
3805 ce = istate->cache[pos];
3808 * This is not the sha1 we are looking for, or
3809 * unreusable because it is not a regular file.
3811 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3812 return 0;
3815 * If ce is marked as "assume unchanged", there is no
3816 * guarantee that work tree matches what we are looking for.
3818 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3819 return 0;
3822 * If ce matches the file in the work tree, we can reuse it.
3824 if (ce_uptodate(ce) ||
3825 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3826 return 1;
3828 return 0;
3831 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3833 struct strbuf buf = STRBUF_INIT;
3834 char *dirty = "";
3836 /* Are we looking at the work tree? */
3837 if (s->dirty_submodule)
3838 dirty = "-dirty";
3840 strbuf_addf(&buf, "Subproject commit %s%s\n",
3841 oid_to_hex(&s->oid), dirty);
3842 s->size = buf.len;
3843 if (size_only) {
3844 s->data = NULL;
3845 strbuf_release(&buf);
3846 } else {
3847 s->data = strbuf_detach(&buf, NULL);
3848 s->should_free = 1;
3850 return 0;
3854 * While doing rename detection and pickaxe operation, we may need to
3855 * grab the data for the blob (or file) for our own in-core comparison.
3856 * diff_filespec has data and size fields for this purpose.
3858 int diff_populate_filespec(struct repository *r,
3859 struct diff_filespec *s,
3860 unsigned int flags)
3862 int size_only = flags & CHECK_SIZE_ONLY;
3863 int err = 0;
3864 int conv_flags = global_conv_flags_eol;
3866 * demote FAIL to WARN to allow inspecting the situation
3867 * instead of refusing.
3869 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3870 conv_flags = CONV_EOL_RNDTRP_WARN;
3872 if (!DIFF_FILE_VALID(s))
3873 die("internal error: asking to populate invalid file.");
3874 if (S_ISDIR(s->mode))
3875 return -1;
3877 if (s->data)
3878 return 0;
3880 if (size_only && 0 < s->size)
3881 return 0;
3883 if (S_ISGITLINK(s->mode))
3884 return diff_populate_gitlink(s, size_only);
3886 if (!s->oid_valid ||
3887 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3888 struct strbuf buf = STRBUF_INIT;
3889 struct stat st;
3890 int fd;
3892 if (lstat(s->path, &st) < 0) {
3893 err_empty:
3894 err = -1;
3895 empty:
3896 s->data = (char *)"";
3897 s->size = 0;
3898 return err;
3900 s->size = xsize_t(st.st_size);
3901 if (!s->size)
3902 goto empty;
3903 if (S_ISLNK(st.st_mode)) {
3904 struct strbuf sb = STRBUF_INIT;
3906 if (strbuf_readlink(&sb, s->path, s->size))
3907 goto err_empty;
3908 s->size = sb.len;
3909 s->data = strbuf_detach(&sb, NULL);
3910 s->should_free = 1;
3911 return 0;
3915 * Even if the caller would be happy with getting
3916 * only the size, we cannot return early at this
3917 * point if the path requires us to run the content
3918 * conversion.
3920 if (size_only && !would_convert_to_git(r->index, s->path))
3921 return 0;
3924 * Note: this check uses xsize_t(st.st_size) that may
3925 * not be the true size of the blob after it goes
3926 * through convert_to_git(). This may not strictly be
3927 * correct, but the whole point of big_file_threshold
3928 * and is_binary check being that we want to avoid
3929 * opening the file and inspecting the contents, this
3930 * is probably fine.
3932 if ((flags & CHECK_BINARY) &&
3933 s->size > big_file_threshold && s->is_binary == -1) {
3934 s->is_binary = 1;
3935 return 0;
3937 fd = open(s->path, O_RDONLY);
3938 if (fd < 0)
3939 goto err_empty;
3940 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3941 close(fd);
3942 s->should_munmap = 1;
3945 * Convert from working tree format to canonical git format
3947 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
3948 size_t size = 0;
3949 munmap(s->data, s->size);
3950 s->should_munmap = 0;
3951 s->data = strbuf_detach(&buf, &size);
3952 s->size = size;
3953 s->should_free = 1;
3956 else {
3957 enum object_type type;
3958 if (size_only || (flags & CHECK_BINARY)) {
3959 type = oid_object_info(r, &s->oid, &s->size);
3960 if (type < 0)
3961 die("unable to read %s",
3962 oid_to_hex(&s->oid));
3963 if (size_only)
3964 return 0;
3965 if (s->size > big_file_threshold && s->is_binary == -1) {
3966 s->is_binary = 1;
3967 return 0;
3970 s->data = read_object_file(&s->oid, &type, &s->size);
3971 if (!s->data)
3972 die("unable to read %s", oid_to_hex(&s->oid));
3973 s->should_free = 1;
3975 return 0;
3978 void diff_free_filespec_blob(struct diff_filespec *s)
3980 if (s->should_free)
3981 free(s->data);
3982 else if (s->should_munmap)
3983 munmap(s->data, s->size);
3985 if (s->should_free || s->should_munmap) {
3986 s->should_free = s->should_munmap = 0;
3987 s->data = NULL;
3991 void diff_free_filespec_data(struct diff_filespec *s)
3993 diff_free_filespec_blob(s);
3994 FREE_AND_NULL(s->cnt_data);
3997 static void prep_temp_blob(struct index_state *istate,
3998 const char *path, struct diff_tempfile *temp,
3999 void *blob,
4000 unsigned long size,
4001 const struct object_id *oid,
4002 int mode)
4004 struct strbuf buf = STRBUF_INIT;
4005 struct strbuf tempfile = STRBUF_INIT;
4006 char *path_dup = xstrdup(path);
4007 const char *base = basename(path_dup);
4009 /* Generate "XXXXXX_basename.ext" */
4010 strbuf_addstr(&tempfile, "XXXXXX_");
4011 strbuf_addstr(&tempfile, base);
4013 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4014 if (!temp->tempfile)
4015 die_errno("unable to create temp-file");
4016 if (convert_to_working_tree(istate, path,
4017 (const char *)blob, (size_t)size, &buf)) {
4018 blob = buf.buf;
4019 size = buf.len;
4021 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4022 close_tempfile_gently(temp->tempfile))
4023 die_errno("unable to write temp-file");
4024 temp->name = get_tempfile_path(temp->tempfile);
4025 oid_to_hex_r(temp->hex, oid);
4026 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4027 strbuf_release(&buf);
4028 strbuf_release(&tempfile);
4029 free(path_dup);
4032 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4033 const char *name,
4034 struct diff_filespec *one)
4036 struct diff_tempfile *temp = claim_diff_tempfile();
4038 if (!DIFF_FILE_VALID(one)) {
4039 not_a_valid_file:
4040 /* A '-' entry produces this for file-2, and
4041 * a '+' entry produces this for file-1.
4043 temp->name = "/dev/null";
4044 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4045 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4046 return temp;
4049 if (!S_ISGITLINK(one->mode) &&
4050 (!one->oid_valid ||
4051 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4052 struct stat st;
4053 if (lstat(name, &st) < 0) {
4054 if (errno == ENOENT)
4055 goto not_a_valid_file;
4056 die_errno("stat(%s)", name);
4058 if (S_ISLNK(st.st_mode)) {
4059 struct strbuf sb = STRBUF_INIT;
4060 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4061 die_errno("readlink(%s)", name);
4062 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4063 (one->oid_valid ?
4064 &one->oid : &null_oid),
4065 (one->oid_valid ?
4066 one->mode : S_IFLNK));
4067 strbuf_release(&sb);
4069 else {
4070 /* we can borrow from the file in the work tree */
4071 temp->name = name;
4072 if (!one->oid_valid)
4073 oid_to_hex_r(temp->hex, &null_oid);
4074 else
4075 oid_to_hex_r(temp->hex, &one->oid);
4076 /* Even though we may sometimes borrow the
4077 * contents from the work tree, we always want
4078 * one->mode. mode is trustworthy even when
4079 * !(one->oid_valid), as long as
4080 * DIFF_FILE_VALID(one).
4082 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4084 return temp;
4086 else {
4087 if (diff_populate_filespec(r, one, 0))
4088 die("cannot read data blob for %s", one->path);
4089 prep_temp_blob(r->index, name, temp,
4090 one->data, one->size,
4091 &one->oid, one->mode);
4093 return temp;
4096 static void add_external_diff_name(struct repository *r,
4097 struct argv_array *argv,
4098 const char *name,
4099 struct diff_filespec *df)
4101 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4102 argv_array_push(argv, temp->name);
4103 argv_array_push(argv, temp->hex);
4104 argv_array_push(argv, temp->mode);
4107 /* An external diff command takes:
4109 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4110 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4113 static void run_external_diff(const char *pgm,
4114 const char *name,
4115 const char *other,
4116 struct diff_filespec *one,
4117 struct diff_filespec *two,
4118 const char *xfrm_msg,
4119 int complete_rewrite,
4120 struct diff_options *o)
4122 struct argv_array argv = ARGV_ARRAY_INIT;
4123 struct argv_array env = ARGV_ARRAY_INIT;
4124 struct diff_queue_struct *q = &diff_queued_diff;
4126 argv_array_push(&argv, pgm);
4127 argv_array_push(&argv, name);
4129 if (one && two) {
4130 add_external_diff_name(o->repo, &argv, name, one);
4131 if (!other)
4132 add_external_diff_name(o->repo, &argv, name, two);
4133 else {
4134 add_external_diff_name(o->repo, &argv, other, two);
4135 argv_array_push(&argv, other);
4136 argv_array_push(&argv, xfrm_msg);
4140 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4141 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4143 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4144 die(_("external diff died, stopping at %s"), name);
4146 remove_tempfile();
4147 argv_array_clear(&argv);
4148 argv_array_clear(&env);
4151 static int similarity_index(struct diff_filepair *p)
4153 return p->score * 100 / MAX_SCORE;
4156 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4158 if (startup_info->have_repository)
4159 return find_unique_abbrev(oid, abbrev);
4160 else {
4161 char *hex = oid_to_hex(oid);
4162 if (abbrev < 0)
4163 abbrev = FALLBACK_DEFAULT_ABBREV;
4164 if (abbrev > the_hash_algo->hexsz)
4165 BUG("oid abbreviation out of range: %d", abbrev);
4166 if (abbrev)
4167 hex[abbrev] = '\0';
4168 return hex;
4172 static void fill_metainfo(struct strbuf *msg,
4173 const char *name,
4174 const char *other,
4175 struct diff_filespec *one,
4176 struct diff_filespec *two,
4177 struct diff_options *o,
4178 struct diff_filepair *p,
4179 int *must_show_header,
4180 int use_color)
4182 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4183 const char *reset = diff_get_color(use_color, DIFF_RESET);
4184 const char *line_prefix = diff_line_prefix(o);
4186 *must_show_header = 1;
4187 strbuf_init(msg, PATH_MAX * 2 + 300);
4188 switch (p->status) {
4189 case DIFF_STATUS_COPIED:
4190 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4191 line_prefix, set, similarity_index(p));
4192 strbuf_addf(msg, "%s\n%s%scopy from ",
4193 reset, line_prefix, set);
4194 quote_c_style(name, msg, NULL, 0);
4195 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4196 quote_c_style(other, msg, NULL, 0);
4197 strbuf_addf(msg, "%s\n", reset);
4198 break;
4199 case DIFF_STATUS_RENAMED:
4200 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4201 line_prefix, set, similarity_index(p));
4202 strbuf_addf(msg, "%s\n%s%srename from ",
4203 reset, line_prefix, set);
4204 quote_c_style(name, msg, NULL, 0);
4205 strbuf_addf(msg, "%s\n%s%srename to ",
4206 reset, line_prefix, set);
4207 quote_c_style(other, msg, NULL, 0);
4208 strbuf_addf(msg, "%s\n", reset);
4209 break;
4210 case DIFF_STATUS_MODIFIED:
4211 if (p->score) {
4212 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4213 line_prefix,
4214 set, similarity_index(p), reset);
4215 break;
4217 /* fallthru */
4218 default:
4219 *must_show_header = 0;
4221 if (one && two && !oideq(&one->oid, &two->oid)) {
4222 const unsigned hexsz = the_hash_algo->hexsz;
4223 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
4225 if (o->flags.binary) {
4226 mmfile_t mf;
4227 if ((!fill_mmfile(o->repo, &mf, one) &&
4228 diff_filespec_is_binary(o->repo, one)) ||
4229 (!fill_mmfile(o->repo, &mf, two) &&
4230 diff_filespec_is_binary(o->repo, two)))
4231 abbrev = hexsz;
4233 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4234 diff_abbrev_oid(&one->oid, abbrev),
4235 diff_abbrev_oid(&two->oid, abbrev));
4236 if (one->mode == two->mode)
4237 strbuf_addf(msg, " %06o", one->mode);
4238 strbuf_addf(msg, "%s\n", reset);
4242 static void run_diff_cmd(const char *pgm,
4243 const char *name,
4244 const char *other,
4245 const char *attr_path,
4246 struct diff_filespec *one,
4247 struct diff_filespec *two,
4248 struct strbuf *msg,
4249 struct diff_options *o,
4250 struct diff_filepair *p)
4252 const char *xfrm_msg = NULL;
4253 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4254 int must_show_header = 0;
4257 if (o->flags.allow_external) {
4258 struct userdiff_driver *drv;
4260 drv = userdiff_find_by_path(o->repo->index, attr_path);
4261 if (drv && drv->external)
4262 pgm = drv->external;
4265 if (msg) {
4267 * don't use colors when the header is intended for an
4268 * external diff driver
4270 fill_metainfo(msg, name, other, one, two, o, p,
4271 &must_show_header,
4272 want_color(o->use_color) && !pgm);
4273 xfrm_msg = msg->len ? msg->buf : NULL;
4276 if (pgm) {
4277 run_external_diff(pgm, name, other, one, two, xfrm_msg,
4278 complete_rewrite, o);
4279 return;
4281 if (one && two)
4282 builtin_diff(name, other ? other : name,
4283 one, two, xfrm_msg, must_show_header,
4284 o, complete_rewrite);
4285 else
4286 fprintf(o->file, "* Unmerged path %s\n", name);
4289 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4291 if (DIFF_FILE_VALID(one)) {
4292 if (!one->oid_valid) {
4293 struct stat st;
4294 if (one->is_stdin) {
4295 oidclr(&one->oid);
4296 return;
4298 if (lstat(one->path, &st) < 0)
4299 die_errno("stat '%s'", one->path);
4300 if (index_path(istate, &one->oid, one->path, &st, 0))
4301 die("cannot hash %s", one->path);
4304 else
4305 oidclr(&one->oid);
4308 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4310 /* Strip the prefix but do not molest /dev/null and absolute paths */
4311 if (*namep && !is_absolute_path(*namep)) {
4312 *namep += prefix_length;
4313 if (**namep == '/')
4314 ++*namep;
4316 if (*otherp && !is_absolute_path(*otherp)) {
4317 *otherp += prefix_length;
4318 if (**otherp == '/')
4319 ++*otherp;
4323 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4325 const char *pgm = external_diff();
4326 struct strbuf msg;
4327 struct diff_filespec *one = p->one;
4328 struct diff_filespec *two = p->two;
4329 const char *name;
4330 const char *other;
4331 const char *attr_path;
4333 name = one->path;
4334 other = (strcmp(name, two->path) ? two->path : NULL);
4335 attr_path = name;
4336 if (o->prefix_length)
4337 strip_prefix(o->prefix_length, &name, &other);
4339 if (!o->flags.allow_external)
4340 pgm = NULL;
4342 if (DIFF_PAIR_UNMERGED(p)) {
4343 run_diff_cmd(pgm, name, NULL, attr_path,
4344 NULL, NULL, NULL, o, p);
4345 return;
4348 diff_fill_oid_info(one, o->repo->index);
4349 diff_fill_oid_info(two, o->repo->index);
4351 if (!pgm &&
4352 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4353 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4355 * a filepair that changes between file and symlink
4356 * needs to be split into deletion and creation.
4358 struct diff_filespec *null = alloc_filespec(two->path);
4359 run_diff_cmd(NULL, name, other, attr_path,
4360 one, null, &msg,
4361 o, p);
4362 free(null);
4363 strbuf_release(&msg);
4365 null = alloc_filespec(one->path);
4366 run_diff_cmd(NULL, name, other, attr_path,
4367 null, two, &msg, o, p);
4368 free(null);
4370 else
4371 run_diff_cmd(pgm, name, other, attr_path,
4372 one, two, &msg, o, p);
4374 strbuf_release(&msg);
4377 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4378 struct diffstat_t *diffstat)
4380 const char *name;
4381 const char *other;
4383 if (DIFF_PAIR_UNMERGED(p)) {
4384 /* unmerged */
4385 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4386 diffstat, o, p);
4387 return;
4390 name = p->one->path;
4391 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4393 if (o->prefix_length)
4394 strip_prefix(o->prefix_length, &name, &other);
4396 diff_fill_oid_info(p->one, o->repo->index);
4397 diff_fill_oid_info(p->two, o->repo->index);
4399 builtin_diffstat(name, other, p->one, p->two,
4400 diffstat, o, p);
4403 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4405 const char *name;
4406 const char *other;
4407 const char *attr_path;
4409 if (DIFF_PAIR_UNMERGED(p)) {
4410 /* unmerged */
4411 return;
4414 name = p->one->path;
4415 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4416 attr_path = other ? other : name;
4418 if (o->prefix_length)
4419 strip_prefix(o->prefix_length, &name, &other);
4421 diff_fill_oid_info(p->one, o->repo->index);
4422 diff_fill_oid_info(p->two, o->repo->index);
4424 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4427 void repo_diff_setup(struct repository *r, struct diff_options *options)
4429 memcpy(options, &default_diff_options, sizeof(*options));
4431 options->file = stdout;
4432 options->repo = r;
4434 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4435 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4436 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4437 options->abbrev = DEFAULT_ABBREV;
4438 options->line_termination = '\n';
4439 options->break_opt = -1;
4440 options->rename_limit = -1;
4441 options->dirstat_permille = diff_dirstat_permille_default;
4442 options->context = diff_context_default;
4443 options->interhunkcontext = diff_interhunk_context_default;
4444 options->ws_error_highlight = ws_error_highlight_default;
4445 options->flags.rename_empty = 1;
4446 options->objfind = NULL;
4448 /* pathchange left =NULL by default */
4449 options->change = diff_change;
4450 options->add_remove = diff_addremove;
4451 options->use_color = diff_use_color_default;
4452 options->detect_rename = diff_detect_rename_default;
4453 options->xdl_opts |= diff_algorithm;
4454 if (diff_indent_heuristic)
4455 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4457 options->orderfile = diff_order_file_cfg;
4459 if (diff_no_prefix) {
4460 options->a_prefix = options->b_prefix = "";
4461 } else if (!diff_mnemonic_prefix) {
4462 options->a_prefix = "a/";
4463 options->b_prefix = "b/";
4466 options->color_moved = diff_color_moved_default;
4467 options->color_moved_ws_handling = diff_color_moved_ws_default;
4470 void diff_setup_done(struct diff_options *options)
4472 unsigned check_mask = DIFF_FORMAT_NAME |
4473 DIFF_FORMAT_NAME_STATUS |
4474 DIFF_FORMAT_CHECKDIFF |
4475 DIFF_FORMAT_NO_OUTPUT;
4477 * This must be signed because we're comparing against a potentially
4478 * negative value.
4480 const int hexsz = the_hash_algo->hexsz;
4482 if (options->set_default)
4483 options->set_default(options);
4485 if (HAS_MULTI_BITS(options->output_format & check_mask))
4486 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4488 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4489 die(_("-G, -S and --find-object are mutually exclusive"));
4492 * Most of the time we can say "there are changes"
4493 * only by checking if there are changed paths, but
4494 * --ignore-whitespace* options force us to look
4495 * inside contents.
4498 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4499 options->flags.diff_from_contents = 1;
4500 else
4501 options->flags.diff_from_contents = 0;
4503 if (options->flags.find_copies_harder)
4504 options->detect_rename = DIFF_DETECT_COPY;
4506 if (!options->flags.relative_name)
4507 options->prefix = NULL;
4508 if (options->prefix)
4509 options->prefix_length = strlen(options->prefix);
4510 else
4511 options->prefix_length = 0;
4513 if (options->output_format & (DIFF_FORMAT_NAME |
4514 DIFF_FORMAT_NAME_STATUS |
4515 DIFF_FORMAT_CHECKDIFF |
4516 DIFF_FORMAT_NO_OUTPUT))
4517 options->output_format &= ~(DIFF_FORMAT_RAW |
4518 DIFF_FORMAT_NUMSTAT |
4519 DIFF_FORMAT_DIFFSTAT |
4520 DIFF_FORMAT_SHORTSTAT |
4521 DIFF_FORMAT_DIRSTAT |
4522 DIFF_FORMAT_SUMMARY |
4523 DIFF_FORMAT_PATCH);
4526 * These cases always need recursive; we do not drop caller-supplied
4527 * recursive bits for other formats here.
4529 if (options->output_format & (DIFF_FORMAT_PATCH |
4530 DIFF_FORMAT_NUMSTAT |
4531 DIFF_FORMAT_DIFFSTAT |
4532 DIFF_FORMAT_SHORTSTAT |
4533 DIFF_FORMAT_DIRSTAT |
4534 DIFF_FORMAT_SUMMARY |
4535 DIFF_FORMAT_CHECKDIFF))
4536 options->flags.recursive = 1;
4538 * Also pickaxe would not work very well if you do not say recursive
4540 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4541 options->flags.recursive = 1;
4543 * When patches are generated, submodules diffed against the work tree
4544 * must be checked for dirtiness too so it can be shown in the output
4546 if (options->output_format & DIFF_FORMAT_PATCH)
4547 options->flags.dirty_submodules = 1;
4549 if (options->detect_rename && options->rename_limit < 0)
4550 options->rename_limit = diff_rename_limit_default;
4551 if (hexsz < options->abbrev)
4552 options->abbrev = hexsz; /* full */
4555 * It does not make sense to show the first hit we happened
4556 * to have found. It does not make sense not to return with
4557 * exit code in such a case either.
4559 if (options->flags.quick) {
4560 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4561 options->flags.exit_with_status = 1;
4564 options->diff_path_counter = 0;
4566 if (options->flags.follow_renames && options->pathspec.nr != 1)
4567 die(_("--follow requires exactly one pathspec"));
4569 if (!options->use_color || external_diff())
4570 options->color_moved = 0;
4573 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4575 char c, *eq;
4576 int len;
4578 if (*arg != '-')
4579 return 0;
4580 c = *++arg;
4581 if (!c)
4582 return 0;
4583 if (c == arg_short) {
4584 c = *++arg;
4585 if (!c)
4586 return 1;
4587 if (val && isdigit(c)) {
4588 char *end;
4589 int n = strtoul(arg, &end, 10);
4590 if (*end)
4591 return 0;
4592 *val = n;
4593 return 1;
4595 return 0;
4597 if (c != '-')
4598 return 0;
4599 arg++;
4600 eq = strchrnul(arg, '=');
4601 len = eq - arg;
4602 if (!len || strncmp(arg, arg_long, len))
4603 return 0;
4604 if (*eq) {
4605 int n;
4606 char *end;
4607 if (!isdigit(*++eq))
4608 return 0;
4609 n = strtoul(eq, &end, 10);
4610 if (*end)
4611 return 0;
4612 *val = n;
4614 return 1;
4617 static int diff_scoreopt_parse(const char *opt);
4619 static inline int short_opt(char opt, const char **argv,
4620 const char **optarg)
4622 const char *arg = argv[0];
4623 if (arg[0] != '-' || arg[1] != opt)
4624 return 0;
4625 if (arg[2] != '\0') {
4626 *optarg = arg + 2;
4627 return 1;
4629 if (!argv[1])
4630 die("Option '%c' requires a value", opt);
4631 *optarg = argv[1];
4632 return 2;
4635 int parse_long_opt(const char *opt, const char **argv,
4636 const char **optarg)
4638 const char *arg = argv[0];
4639 if (!skip_prefix(arg, "--", &arg))
4640 return 0;
4641 if (!skip_prefix(arg, opt, &arg))
4642 return 0;
4643 if (*arg == '=') { /* stuck form: --option=value */
4644 *optarg = arg + 1;
4645 return 1;
4647 if (*arg != '\0')
4648 return 0;
4649 /* separate form: --option value */
4650 if (!argv[1])
4651 die("Option '--%s' requires a value", opt);
4652 *optarg = argv[1];
4653 return 2;
4656 static int stat_opt(struct diff_options *options, const char **av)
4658 const char *arg = av[0];
4659 char *end;
4660 int width = options->stat_width;
4661 int name_width = options->stat_name_width;
4662 int graph_width = options->stat_graph_width;
4663 int count = options->stat_count;
4664 int argcount = 1;
4666 if (!skip_prefix(arg, "--stat", &arg))
4667 BUG("stat option does not begin with --stat: %s", arg);
4668 end = (char *)arg;
4670 switch (*arg) {
4671 case '-':
4672 if (skip_prefix(arg, "-width", &arg)) {
4673 if (*arg == '=')
4674 width = strtoul(arg + 1, &end, 10);
4675 else if (!*arg && !av[1])
4676 die_want_option("--stat-width");
4677 else if (!*arg) {
4678 width = strtoul(av[1], &end, 10);
4679 argcount = 2;
4681 } else if (skip_prefix(arg, "-name-width", &arg)) {
4682 if (*arg == '=')
4683 name_width = strtoul(arg + 1, &end, 10);
4684 else if (!*arg && !av[1])
4685 die_want_option("--stat-name-width");
4686 else if (!*arg) {
4687 name_width = strtoul(av[1], &end, 10);
4688 argcount = 2;
4690 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4691 if (*arg == '=')
4692 graph_width = strtoul(arg + 1, &end, 10);
4693 else if (!*arg && !av[1])
4694 die_want_option("--stat-graph-width");
4695 else if (!*arg) {
4696 graph_width = strtoul(av[1], &end, 10);
4697 argcount = 2;
4699 } else if (skip_prefix(arg, "-count", &arg)) {
4700 if (*arg == '=')
4701 count = strtoul(arg + 1, &end, 10);
4702 else if (!*arg && !av[1])
4703 die_want_option("--stat-count");
4704 else if (!*arg) {
4705 count = strtoul(av[1], &end, 10);
4706 argcount = 2;
4709 break;
4710 case '=':
4711 width = strtoul(arg+1, &end, 10);
4712 if (*end == ',')
4713 name_width = strtoul(end+1, &end, 10);
4714 if (*end == ',')
4715 count = strtoul(end+1, &end, 10);
4718 /* Important! This checks all the error cases! */
4719 if (*end)
4720 return 0;
4721 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4722 options->stat_name_width = name_width;
4723 options->stat_graph_width = graph_width;
4724 options->stat_width = width;
4725 options->stat_count = count;
4726 return argcount;
4729 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4731 struct strbuf errmsg = STRBUF_INIT;
4732 if (parse_dirstat_params(options, params, &errmsg))
4733 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4734 errmsg.buf);
4735 strbuf_release(&errmsg);
4737 * The caller knows a dirstat-related option is given from the command
4738 * line; allow it to say "return this_function();"
4740 options->output_format |= DIFF_FORMAT_DIRSTAT;
4741 return 1;
4744 static int parse_submodule_opt(struct diff_options *options, const char *value)
4746 if (parse_submodule_params(options, value))
4747 die(_("Failed to parse --submodule option parameter: '%s'"),
4748 value);
4749 return 1;
4752 static const char diff_status_letters[] = {
4753 DIFF_STATUS_ADDED,
4754 DIFF_STATUS_COPIED,
4755 DIFF_STATUS_DELETED,
4756 DIFF_STATUS_MODIFIED,
4757 DIFF_STATUS_RENAMED,
4758 DIFF_STATUS_TYPE_CHANGED,
4759 DIFF_STATUS_UNKNOWN,
4760 DIFF_STATUS_UNMERGED,
4761 DIFF_STATUS_FILTER_AON,
4762 DIFF_STATUS_FILTER_BROKEN,
4763 '\0',
4766 static unsigned int filter_bit['Z' + 1];
4768 static void prepare_filter_bits(void)
4770 int i;
4772 if (!filter_bit[DIFF_STATUS_ADDED]) {
4773 for (i = 0; diff_status_letters[i]; i++)
4774 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4778 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4780 return opt->filter & filter_bit[(int) status];
4783 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4785 int i, optch;
4787 prepare_filter_bits();
4790 * If there is a negation e.g. 'd' in the input, and we haven't
4791 * initialized the filter field with another --diff-filter, start
4792 * from full set of bits, except for AON.
4794 if (!opt->filter) {
4795 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4796 if (optch < 'a' || 'z' < optch)
4797 continue;
4798 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4799 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4800 break;
4804 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4805 unsigned int bit;
4806 int negate;
4808 if ('a' <= optch && optch <= 'z') {
4809 negate = 1;
4810 optch = toupper(optch);
4811 } else {
4812 negate = 0;
4815 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4816 if (!bit)
4817 return optarg[i];
4818 if (negate)
4819 opt->filter &= ~bit;
4820 else
4821 opt->filter |= bit;
4823 return 0;
4826 static void enable_patch_output(int *fmt) {
4827 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4828 *fmt |= DIFF_FORMAT_PATCH;
4831 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4833 int val = parse_ws_error_highlight(arg);
4835 if (val < 0) {
4836 error("unknown value after ws-error-highlight=%.*s",
4837 -1 - val, arg);
4838 return 0;
4840 opt->ws_error_highlight = val;
4841 return 1;
4844 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4846 struct object_id oid;
4848 if (get_oid(arg, &oid))
4849 return error("unable to resolve '%s'", arg);
4851 if (!opt->objfind)
4852 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4854 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4855 opt->flags.recursive = 1;
4856 opt->flags.tree_in_recursive = 1;
4857 oidset_insert(opt->objfind, &oid);
4858 return 1;
4861 int diff_opt_parse(struct diff_options *options,
4862 const char **av, int ac, const char *prefix)
4864 const char *arg = av[0];
4865 const char *optarg;
4866 int argcount;
4868 if (!prefix)
4869 prefix = "";
4871 /* Output format options */
4872 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4873 || opt_arg(arg, 'U', "unified", &options->context))
4874 enable_patch_output(&options->output_format);
4875 else if (!strcmp(arg, "--raw"))
4876 options->output_format |= DIFF_FORMAT_RAW;
4877 else if (!strcmp(arg, "--patch-with-raw")) {
4878 enable_patch_output(&options->output_format);
4879 options->output_format |= DIFF_FORMAT_RAW;
4880 } else if (!strcmp(arg, "--numstat"))
4881 options->output_format |= DIFF_FORMAT_NUMSTAT;
4882 else if (!strcmp(arg, "--shortstat"))
4883 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4884 else if (skip_prefix(arg, "-X", &arg) ||
4885 skip_to_optional_arg(arg, "--dirstat", &arg))
4886 return parse_dirstat_opt(options, arg);
4887 else if (!strcmp(arg, "--cumulative"))
4888 return parse_dirstat_opt(options, "cumulative");
4889 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
4890 parse_dirstat_opt(options, "files");
4891 return parse_dirstat_opt(options, arg);
4893 else if (!strcmp(arg, "--check"))
4894 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4895 else if (!strcmp(arg, "--summary"))
4896 options->output_format |= DIFF_FORMAT_SUMMARY;
4897 else if (!strcmp(arg, "--patch-with-stat")) {
4898 enable_patch_output(&options->output_format);
4899 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4900 } else if (!strcmp(arg, "--name-only"))
4901 options->output_format |= DIFF_FORMAT_NAME;
4902 else if (!strcmp(arg, "--name-status"))
4903 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4904 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4905 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4906 else if (starts_with(arg, "--stat"))
4907 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4908 return stat_opt(options, av);
4909 else if (!strcmp(arg, "--compact-summary")) {
4910 options->flags.stat_with_summary = 1;
4911 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4912 } else if (!strcmp(arg, "--no-compact-summary"))
4913 options->flags.stat_with_summary = 0;
4914 else if (skip_prefix(arg, "--output-indicator-new=", &arg))
4915 options->output_indicators[OUTPUT_INDICATOR_NEW] = arg[0];
4916 else if (skip_prefix(arg, "--output-indicator-old=", &arg))
4917 options->output_indicators[OUTPUT_INDICATOR_OLD] = arg[0];
4918 else if (skip_prefix(arg, "--output-indicator-context=", &arg))
4919 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = arg[0];
4921 /* renames options */
4922 else if (starts_with(arg, "-B") ||
4923 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
4924 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4925 return error("invalid argument to -B: %s", arg+2);
4927 else if (starts_with(arg, "-M") ||
4928 skip_to_optional_arg(arg, "--find-renames", NULL)) {
4929 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4930 return error("invalid argument to -M: %s", arg+2);
4931 options->detect_rename = DIFF_DETECT_RENAME;
4933 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4934 options->irreversible_delete = 1;
4936 else if (starts_with(arg, "-C") ||
4937 skip_to_optional_arg(arg, "--find-copies", NULL)) {
4938 if (options->detect_rename == DIFF_DETECT_COPY)
4939 options->flags.find_copies_harder = 1;
4940 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4941 return error("invalid argument to -C: %s", arg+2);
4942 options->detect_rename = DIFF_DETECT_COPY;
4944 else if (!strcmp(arg, "--no-renames"))
4945 options->detect_rename = 0;
4946 else if (!strcmp(arg, "--rename-empty"))
4947 options->flags.rename_empty = 1;
4948 else if (!strcmp(arg, "--no-rename-empty"))
4949 options->flags.rename_empty = 0;
4950 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
4951 options->flags.relative_name = 1;
4952 if (arg)
4953 options->prefix = arg;
4956 /* xdiff options */
4957 else if (!strcmp(arg, "--minimal"))
4958 DIFF_XDL_SET(options, NEED_MINIMAL);
4959 else if (!strcmp(arg, "--no-minimal"))
4960 DIFF_XDL_CLR(options, NEED_MINIMAL);
4961 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4962 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4963 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4964 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4965 else if (!strcmp(arg, "--ignore-space-at-eol"))
4966 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4967 else if (!strcmp(arg, "--ignore-cr-at-eol"))
4968 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
4969 else if (!strcmp(arg, "--ignore-blank-lines"))
4970 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4971 else if (!strcmp(arg, "--indent-heuristic"))
4972 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4973 else if (!strcmp(arg, "--no-indent-heuristic"))
4974 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4975 else if (!strcmp(arg, "--patience")) {
4976 int i;
4977 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4979 * Both --patience and --anchored use PATIENCE_DIFF
4980 * internally, so remove any anchors previously
4981 * specified.
4983 for (i = 0; i < options->anchors_nr; i++)
4984 free(options->anchors[i]);
4985 options->anchors_nr = 0;
4986 } else if (!strcmp(arg, "--histogram"))
4987 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4988 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4989 long value = parse_algorithm_value(optarg);
4990 if (value < 0)
4991 return error("option diff-algorithm accepts \"myers\", "
4992 "\"minimal\", \"patience\" and \"histogram\"");
4993 /* clear out previous settings */
4994 DIFF_XDL_CLR(options, NEED_MINIMAL);
4995 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4996 options->xdl_opts |= value;
4997 return argcount;
4998 } else if (skip_prefix(arg, "--anchored=", &arg)) {
4999 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5000 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5001 options->anchors_alloc);
5002 options->anchors[options->anchors_nr++] = xstrdup(arg);
5005 /* flags options */
5006 else if (!strcmp(arg, "--binary")) {
5007 enable_patch_output(&options->output_format);
5008 options->flags.binary = 1;
5010 else if (!strcmp(arg, "--full-index"))
5011 options->flags.full_index = 1;
5012 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
5013 options->flags.text = 1;
5014 else if (!strcmp(arg, "-R"))
5015 options->flags.reverse_diff = 1;
5016 else if (!strcmp(arg, "--find-copies-harder"))
5017 options->flags.find_copies_harder = 1;
5018 else if (!strcmp(arg, "--follow"))
5019 options->flags.follow_renames = 1;
5020 else if (!strcmp(arg, "--no-follow")) {
5021 options->flags.follow_renames = 0;
5022 options->flags.default_follow_renames = 0;
5023 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
5024 int value = git_config_colorbool(NULL, arg);
5025 if (value < 0)
5026 return error("option `color' expects \"always\", \"auto\", or \"never\"");
5027 options->use_color = value;
5029 else if (!strcmp(arg, "--no-color"))
5030 options->use_color = 0;
5031 else if (!strcmp(arg, "--color-moved")) {
5032 if (diff_color_moved_default)
5033 options->color_moved = diff_color_moved_default;
5034 if (options->color_moved == COLOR_MOVED_NO)
5035 options->color_moved = COLOR_MOVED_DEFAULT;
5036 } else if (!strcmp(arg, "--no-color-moved"))
5037 options->color_moved = COLOR_MOVED_NO;
5038 else if (skip_prefix(arg, "--color-moved=", &arg)) {
5039 int cm = parse_color_moved(arg);
5040 if (cm < 0)
5041 return error("bad --color-moved argument: %s", arg);
5042 options->color_moved = cm;
5043 } else if (skip_prefix(arg, "--color-moved-ws=", &arg)) {
5044 unsigned cm = parse_color_moved_ws(arg);
5045 if (cm & COLOR_MOVED_WS_ERROR)
5046 return -1;
5047 options->color_moved_ws_handling = cm;
5048 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
5049 options->use_color = 1;
5050 options->word_diff = DIFF_WORDS_COLOR;
5052 else if (!strcmp(arg, "--word-diff")) {
5053 if (options->word_diff == DIFF_WORDS_NONE)
5054 options->word_diff = DIFF_WORDS_PLAIN;
5056 else if (skip_prefix(arg, "--word-diff=", &arg)) {
5057 if (!strcmp(arg, "plain"))
5058 options->word_diff = DIFF_WORDS_PLAIN;
5059 else if (!strcmp(arg, "color")) {
5060 options->use_color = 1;
5061 options->word_diff = DIFF_WORDS_COLOR;
5063 else if (!strcmp(arg, "porcelain"))
5064 options->word_diff = DIFF_WORDS_PORCELAIN;
5065 else if (!strcmp(arg, "none"))
5066 options->word_diff = DIFF_WORDS_NONE;
5067 else
5068 die("bad --word-diff argument: %s", arg);
5070 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
5071 if (options->word_diff == DIFF_WORDS_NONE)
5072 options->word_diff = DIFF_WORDS_PLAIN;
5073 options->word_regex = optarg;
5074 return argcount;
5076 else if (!strcmp(arg, "--exit-code"))
5077 options->flags.exit_with_status = 1;
5078 else if (!strcmp(arg, "--quiet"))
5079 options->flags.quick = 1;
5080 else if (!strcmp(arg, "--ext-diff"))
5081 options->flags.allow_external = 1;
5082 else if (!strcmp(arg, "--no-ext-diff"))
5083 options->flags.allow_external = 0;
5084 else if (!strcmp(arg, "--textconv")) {
5085 options->flags.allow_textconv = 1;
5086 options->flags.textconv_set_via_cmdline = 1;
5087 } else if (!strcmp(arg, "--no-textconv"))
5088 options->flags.allow_textconv = 0;
5089 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
5090 options->flags.override_submodule_config = 1;
5091 handle_ignore_submodules_arg(options, arg);
5092 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
5093 return parse_submodule_opt(options, arg);
5094 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
5095 return parse_ws_error_highlight_opt(options, arg);
5096 else if (!strcmp(arg, "--ita-invisible-in-index"))
5097 options->ita_invisible_in_index = 1;
5098 else if (!strcmp(arg, "--ita-visible-in-index"))
5099 options->ita_invisible_in_index = 0;
5101 /* misc options */
5102 else if (!strcmp(arg, "-z"))
5103 options->line_termination = 0;
5104 else if ((argcount = short_opt('l', av, &optarg))) {
5105 options->rename_limit = strtoul(optarg, NULL, 10);
5106 return argcount;
5108 else if ((argcount = short_opt('S', av, &optarg))) {
5109 options->pickaxe = optarg;
5110 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5111 return argcount;
5112 } else if ((argcount = short_opt('G', av, &optarg))) {
5113 options->pickaxe = optarg;
5114 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5115 return argcount;
5117 else if (!strcmp(arg, "--pickaxe-all"))
5118 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
5119 else if (!strcmp(arg, "--pickaxe-regex"))
5120 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
5121 else if ((argcount = short_opt('O', av, &optarg))) {
5122 options->orderfile = prefix_filename(prefix, optarg);
5123 return argcount;
5124 } else if (skip_prefix(arg, "--find-object=", &arg))
5125 return parse_objfind_opt(options, arg);
5126 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
5127 int offending = parse_diff_filter_opt(optarg, options);
5128 if (offending)
5129 die("unknown change class '%c' in --diff-filter=%s",
5130 offending, optarg);
5131 return argcount;
5133 else if (!strcmp(arg, "--no-abbrev"))
5134 options->abbrev = 0;
5135 else if (!strcmp(arg, "--abbrev"))
5136 options->abbrev = DEFAULT_ABBREV;
5137 else if (skip_prefix(arg, "--abbrev=", &arg)) {
5138 options->abbrev = strtoul(arg, NULL, 10);
5139 if (options->abbrev < MINIMUM_ABBREV)
5140 options->abbrev = MINIMUM_ABBREV;
5141 else if (the_hash_algo->hexsz < options->abbrev)
5142 options->abbrev = the_hash_algo->hexsz;
5144 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
5145 options->a_prefix = optarg;
5146 return argcount;
5148 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
5149 options->line_prefix = optarg;
5150 options->line_prefix_length = strlen(options->line_prefix);
5151 graph_setup_line_prefix(options);
5152 return argcount;
5154 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
5155 options->b_prefix = optarg;
5156 return argcount;
5158 else if (!strcmp(arg, "--no-prefix"))
5159 options->a_prefix = options->b_prefix = "";
5160 else if (opt_arg(arg, '\0', "inter-hunk-context",
5161 &options->interhunkcontext))
5163 else if (!strcmp(arg, "-W"))
5164 options->flags.funccontext = 1;
5165 else if (!strcmp(arg, "--function-context"))
5166 options->flags.funccontext = 1;
5167 else if (!strcmp(arg, "--no-function-context"))
5168 options->flags.funccontext = 0;
5169 else if ((argcount = parse_long_opt("output", av, &optarg))) {
5170 char *path = prefix_filename(prefix, optarg);
5171 options->file = xfopen(path, "w");
5172 options->close_file = 1;
5173 if (options->use_color != GIT_COLOR_ALWAYS)
5174 options->use_color = GIT_COLOR_NEVER;
5175 free(path);
5176 return argcount;
5177 } else
5178 return 0;
5179 return 1;
5182 int parse_rename_score(const char **cp_p)
5184 unsigned long num, scale;
5185 int ch, dot;
5186 const char *cp = *cp_p;
5188 num = 0;
5189 scale = 1;
5190 dot = 0;
5191 for (;;) {
5192 ch = *cp;
5193 if ( !dot && ch == '.' ) {
5194 scale = 1;
5195 dot = 1;
5196 } else if ( ch == '%' ) {
5197 scale = dot ? scale*100 : 100;
5198 cp++; /* % is always at the end */
5199 break;
5200 } else if ( ch >= '0' && ch <= '9' ) {
5201 if ( scale < 100000 ) {
5202 scale *= 10;
5203 num = (num*10) + (ch-'0');
5205 } else {
5206 break;
5208 cp++;
5210 *cp_p = cp;
5212 /* user says num divided by scale and we say internally that
5213 * is MAX_SCORE * num / scale.
5215 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5218 static int diff_scoreopt_parse(const char *opt)
5220 int opt1, opt2, cmd;
5222 if (*opt++ != '-')
5223 return -1;
5224 cmd = *opt++;
5225 if (cmd == '-') {
5226 /* convert the long-form arguments into short-form versions */
5227 if (skip_prefix(opt, "break-rewrites", &opt)) {
5228 if (*opt == 0 || *opt++ == '=')
5229 cmd = 'B';
5230 } else if (skip_prefix(opt, "find-copies", &opt)) {
5231 if (*opt == 0 || *opt++ == '=')
5232 cmd = 'C';
5233 } else if (skip_prefix(opt, "find-renames", &opt)) {
5234 if (*opt == 0 || *opt++ == '=')
5235 cmd = 'M';
5238 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
5239 return -1; /* that is not a -M, -C, or -B option */
5241 opt1 = parse_rename_score(&opt);
5242 if (cmd != 'B')
5243 opt2 = 0;
5244 else {
5245 if (*opt == 0)
5246 opt2 = 0;
5247 else if (*opt != '/')
5248 return -1; /* we expect -B80/99 or -B80 */
5249 else {
5250 opt++;
5251 opt2 = parse_rename_score(&opt);
5254 if (*opt != 0)
5255 return -1;
5256 return opt1 | (opt2 << 16);
5259 struct diff_queue_struct diff_queued_diff;
5261 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5263 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5264 queue->queue[queue->nr++] = dp;
5267 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5268 struct diff_filespec *one,
5269 struct diff_filespec *two)
5271 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5272 dp->one = one;
5273 dp->two = two;
5274 if (queue)
5275 diff_q(queue, dp);
5276 return dp;
5279 void diff_free_filepair(struct diff_filepair *p)
5281 free_filespec(p->one);
5282 free_filespec(p->two);
5283 free(p);
5286 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5288 int abblen;
5289 const char *abbrev;
5291 /* Do we want all 40 hex characters? */
5292 if (len == the_hash_algo->hexsz)
5293 return oid_to_hex(oid);
5295 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5296 abbrev = diff_abbrev_oid(oid, len);
5298 if (!print_sha1_ellipsis())
5299 return abbrev;
5301 abblen = strlen(abbrev);
5304 * In well-behaved cases, where the abbreviated result is the
5305 * same as the requested length, append three dots after the
5306 * abbreviation (hence the whole logic is limited to the case
5307 * where abblen < 37); when the actual abbreviated result is a
5308 * bit longer than the requested length, we reduce the number
5309 * of dots so that they match the well-behaved ones. However,
5310 * if the actual abbreviation is longer than the requested
5311 * length by more than three, we give up on aligning, and add
5312 * three dots anyway, to indicate that the output is not the
5313 * full object name. Yes, this may be suboptimal, but this
5314 * appears only in "diff --raw --abbrev" output and it is not
5315 * worth the effort to change it now. Note that this would
5316 * likely to work fine when the automatic sizing of default
5317 * abbreviation length is used--we would be fed -1 in "len" in
5318 * that case, and will end up always appending three-dots, but
5319 * the automatic sizing is supposed to give abblen that ensures
5320 * uniqueness across all objects (statistically speaking).
5322 if (abblen < the_hash_algo->hexsz - 3) {
5323 static char hex[GIT_MAX_HEXSZ + 1];
5324 if (len < abblen && abblen <= len + 2)
5325 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5326 else
5327 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5328 return hex;
5331 return oid_to_hex(oid);
5334 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5336 int line_termination = opt->line_termination;
5337 int inter_name_termination = line_termination ? '\t' : '\0';
5339 fprintf(opt->file, "%s", diff_line_prefix(opt));
5340 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5341 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5342 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5343 fprintf(opt->file, "%s ",
5344 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5346 if (p->score) {
5347 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5348 inter_name_termination);
5349 } else {
5350 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5353 if (p->status == DIFF_STATUS_COPIED ||
5354 p->status == DIFF_STATUS_RENAMED) {
5355 const char *name_a, *name_b;
5356 name_a = p->one->path;
5357 name_b = p->two->path;
5358 strip_prefix(opt->prefix_length, &name_a, &name_b);
5359 write_name_quoted(name_a, opt->file, inter_name_termination);
5360 write_name_quoted(name_b, opt->file, line_termination);
5361 } else {
5362 const char *name_a, *name_b;
5363 name_a = p->one->mode ? p->one->path : p->two->path;
5364 name_b = NULL;
5365 strip_prefix(opt->prefix_length, &name_a, &name_b);
5366 write_name_quoted(name_a, opt->file, line_termination);
5370 int diff_unmodified_pair(struct diff_filepair *p)
5372 /* This function is written stricter than necessary to support
5373 * the currently implemented transformers, but the idea is to
5374 * let transformers to produce diff_filepairs any way they want,
5375 * and filter and clean them up here before producing the output.
5377 struct diff_filespec *one = p->one, *two = p->two;
5379 if (DIFF_PAIR_UNMERGED(p))
5380 return 0; /* unmerged is interesting */
5382 /* deletion, addition, mode or type change
5383 * and rename are all interesting.
5385 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5386 DIFF_PAIR_MODE_CHANGED(p) ||
5387 strcmp(one->path, two->path))
5388 return 0;
5390 /* both are valid and point at the same path. that is, we are
5391 * dealing with a change.
5393 if (one->oid_valid && two->oid_valid &&
5394 oideq(&one->oid, &two->oid) &&
5395 !one->dirty_submodule && !two->dirty_submodule)
5396 return 1; /* no change */
5397 if (!one->oid_valid && !two->oid_valid)
5398 return 1; /* both look at the same file on the filesystem. */
5399 return 0;
5402 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5404 if (diff_unmodified_pair(p))
5405 return;
5407 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5408 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5409 return; /* no tree diffs in patch format */
5411 run_diff(p, o);
5414 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5415 struct diffstat_t *diffstat)
5417 if (diff_unmodified_pair(p))
5418 return;
5420 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5421 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5422 return; /* no useful stat for tree diffs */
5424 run_diffstat(p, o, diffstat);
5427 static void diff_flush_checkdiff(struct diff_filepair *p,
5428 struct diff_options *o)
5430 if (diff_unmodified_pair(p))
5431 return;
5433 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5434 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5435 return; /* nothing to check in tree diffs */
5437 run_checkdiff(p, o);
5440 int diff_queue_is_empty(void)
5442 struct diff_queue_struct *q = &diff_queued_diff;
5443 int i;
5444 for (i = 0; i < q->nr; i++)
5445 if (!diff_unmodified_pair(q->queue[i]))
5446 return 0;
5447 return 1;
5450 #if DIFF_DEBUG
5451 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5453 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5454 x, one ? one : "",
5455 s->path,
5456 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5457 s->mode,
5458 s->oid_valid ? oid_to_hex(&s->oid) : "");
5459 fprintf(stderr, "queue[%d] %s size %lu\n",
5460 x, one ? one : "",
5461 s->size);
5464 void diff_debug_filepair(const struct diff_filepair *p, int i)
5466 diff_debug_filespec(p->one, i, "one");
5467 diff_debug_filespec(p->two, i, "two");
5468 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5469 p->score, p->status ? p->status : '?',
5470 p->one->rename_used, p->broken_pair);
5473 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5475 int i;
5476 if (msg)
5477 fprintf(stderr, "%s\n", msg);
5478 fprintf(stderr, "q->nr = %d\n", q->nr);
5479 for (i = 0; i < q->nr; i++) {
5480 struct diff_filepair *p = q->queue[i];
5481 diff_debug_filepair(p, i);
5484 #endif
5486 static void diff_resolve_rename_copy(void)
5488 int i;
5489 struct diff_filepair *p;
5490 struct diff_queue_struct *q = &diff_queued_diff;
5492 diff_debug_queue("resolve-rename-copy", q);
5494 for (i = 0; i < q->nr; i++) {
5495 p = q->queue[i];
5496 p->status = 0; /* undecided */
5497 if (DIFF_PAIR_UNMERGED(p))
5498 p->status = DIFF_STATUS_UNMERGED;
5499 else if (!DIFF_FILE_VALID(p->one))
5500 p->status = DIFF_STATUS_ADDED;
5501 else if (!DIFF_FILE_VALID(p->two))
5502 p->status = DIFF_STATUS_DELETED;
5503 else if (DIFF_PAIR_TYPE_CHANGED(p))
5504 p->status = DIFF_STATUS_TYPE_CHANGED;
5506 /* from this point on, we are dealing with a pair
5507 * whose both sides are valid and of the same type, i.e.
5508 * either in-place edit or rename/copy edit.
5510 else if (DIFF_PAIR_RENAME(p)) {
5512 * A rename might have re-connected a broken
5513 * pair up, causing the pathnames to be the
5514 * same again. If so, that's not a rename at
5515 * all, just a modification..
5517 * Otherwise, see if this source was used for
5518 * multiple renames, in which case we decrement
5519 * the count, and call it a copy.
5521 if (!strcmp(p->one->path, p->two->path))
5522 p->status = DIFF_STATUS_MODIFIED;
5523 else if (--p->one->rename_used > 0)
5524 p->status = DIFF_STATUS_COPIED;
5525 else
5526 p->status = DIFF_STATUS_RENAMED;
5528 else if (!oideq(&p->one->oid, &p->two->oid) ||
5529 p->one->mode != p->two->mode ||
5530 p->one->dirty_submodule ||
5531 p->two->dirty_submodule ||
5532 is_null_oid(&p->one->oid))
5533 p->status = DIFF_STATUS_MODIFIED;
5534 else {
5535 /* This is a "no-change" entry and should not
5536 * happen anymore, but prepare for broken callers.
5538 error("feeding unmodified %s to diffcore",
5539 p->one->path);
5540 p->status = DIFF_STATUS_UNKNOWN;
5543 diff_debug_queue("resolve-rename-copy done", q);
5546 static int check_pair_status(struct diff_filepair *p)
5548 switch (p->status) {
5549 case DIFF_STATUS_UNKNOWN:
5550 return 0;
5551 case 0:
5552 die("internal error in diff-resolve-rename-copy");
5553 default:
5554 return 1;
5558 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5560 int fmt = opt->output_format;
5562 if (fmt & DIFF_FORMAT_CHECKDIFF)
5563 diff_flush_checkdiff(p, opt);
5564 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5565 diff_flush_raw(p, opt);
5566 else if (fmt & DIFF_FORMAT_NAME) {
5567 const char *name_a, *name_b;
5568 name_a = p->two->path;
5569 name_b = NULL;
5570 strip_prefix(opt->prefix_length, &name_a, &name_b);
5571 fprintf(opt->file, "%s", diff_line_prefix(opt));
5572 write_name_quoted(name_a, opt->file, opt->line_termination);
5576 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5578 struct strbuf sb = STRBUF_INIT;
5579 if (fs->mode)
5580 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5581 else
5582 strbuf_addf(&sb, " %s ", newdelete);
5584 quote_c_style(fs->path, &sb, NULL, 0);
5585 strbuf_addch(&sb, '\n');
5586 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5587 sb.buf, sb.len, 0);
5588 strbuf_release(&sb);
5591 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5592 int show_name)
5594 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5595 struct strbuf sb = STRBUF_INIT;
5596 strbuf_addf(&sb, " mode change %06o => %06o",
5597 p->one->mode, p->two->mode);
5598 if (show_name) {
5599 strbuf_addch(&sb, ' ');
5600 quote_c_style(p->two->path, &sb, NULL, 0);
5602 strbuf_addch(&sb, '\n');
5603 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5604 sb.buf, sb.len, 0);
5605 strbuf_release(&sb);
5609 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5610 struct diff_filepair *p)
5612 struct strbuf sb = STRBUF_INIT;
5613 struct strbuf names = STRBUF_INIT;
5615 pprint_rename(&names, p->one->path, p->two->path);
5616 strbuf_addf(&sb, " %s %s (%d%%)\n",
5617 renamecopy, names.buf, similarity_index(p));
5618 strbuf_release(&names);
5619 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5620 sb.buf, sb.len, 0);
5621 show_mode_change(opt, p, 0);
5622 strbuf_release(&sb);
5625 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5627 switch(p->status) {
5628 case DIFF_STATUS_DELETED:
5629 show_file_mode_name(opt, "delete", p->one);
5630 break;
5631 case DIFF_STATUS_ADDED:
5632 show_file_mode_name(opt, "create", p->two);
5633 break;
5634 case DIFF_STATUS_COPIED:
5635 show_rename_copy(opt, "copy", p);
5636 break;
5637 case DIFF_STATUS_RENAMED:
5638 show_rename_copy(opt, "rename", p);
5639 break;
5640 default:
5641 if (p->score) {
5642 struct strbuf sb = STRBUF_INIT;
5643 strbuf_addstr(&sb, " rewrite ");
5644 quote_c_style(p->two->path, &sb, NULL, 0);
5645 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5646 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5647 sb.buf, sb.len, 0);
5648 strbuf_release(&sb);
5650 show_mode_change(opt, p, !p->score);
5651 break;
5655 struct patch_id_t {
5656 git_SHA_CTX *ctx;
5657 int patchlen;
5660 static int remove_space(char *line, int len)
5662 int i;
5663 char *dst = line;
5664 unsigned char c;
5666 for (i = 0; i < len; i++)
5667 if (!isspace((c = line[i])))
5668 *dst++ = c;
5670 return dst - line;
5673 static void patch_id_consume(void *priv, char *line, unsigned long len)
5675 struct patch_id_t *data = priv;
5676 int new_len;
5678 new_len = remove_space(line, len);
5680 git_SHA1_Update(data->ctx, line, new_len);
5681 data->patchlen += new_len;
5684 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5686 git_SHA1_Update(ctx, str, strlen(str));
5689 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5691 /* large enough for 2^32 in octal */
5692 char buf[12];
5693 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5694 git_SHA1_Update(ctx, buf, len);
5697 /* returns 0 upon success, and writes result into sha1 */
5698 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5700 struct diff_queue_struct *q = &diff_queued_diff;
5701 int i;
5702 git_SHA_CTX ctx;
5703 struct patch_id_t data;
5705 git_SHA1_Init(&ctx);
5706 memset(&data, 0, sizeof(struct patch_id_t));
5707 data.ctx = &ctx;
5709 for (i = 0; i < q->nr; i++) {
5710 xpparam_t xpp;
5711 xdemitconf_t xecfg;
5712 mmfile_t mf1, mf2;
5713 struct diff_filepair *p = q->queue[i];
5714 int len1, len2;
5716 memset(&xpp, 0, sizeof(xpp));
5717 memset(&xecfg, 0, sizeof(xecfg));
5718 if (p->status == 0)
5719 return error("internal diff status error");
5720 if (p->status == DIFF_STATUS_UNKNOWN)
5721 continue;
5722 if (diff_unmodified_pair(p))
5723 continue;
5724 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5725 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5726 continue;
5727 if (DIFF_PAIR_UNMERGED(p))
5728 continue;
5730 diff_fill_oid_info(p->one, options->repo->index);
5731 diff_fill_oid_info(p->two, options->repo->index);
5733 len1 = remove_space(p->one->path, strlen(p->one->path));
5734 len2 = remove_space(p->two->path, strlen(p->two->path));
5735 patch_id_add_string(&ctx, "diff--git");
5736 patch_id_add_string(&ctx, "a/");
5737 git_SHA1_Update(&ctx, p->one->path, len1);
5738 patch_id_add_string(&ctx, "b/");
5739 git_SHA1_Update(&ctx, p->two->path, len2);
5741 if (p->one->mode == 0) {
5742 patch_id_add_string(&ctx, "newfilemode");
5743 patch_id_add_mode(&ctx, p->two->mode);
5744 patch_id_add_string(&ctx, "---/dev/null");
5745 patch_id_add_string(&ctx, "+++b/");
5746 git_SHA1_Update(&ctx, p->two->path, len2);
5747 } else if (p->two->mode == 0) {
5748 patch_id_add_string(&ctx, "deletedfilemode");
5749 patch_id_add_mode(&ctx, p->one->mode);
5750 patch_id_add_string(&ctx, "---a/");
5751 git_SHA1_Update(&ctx, p->one->path, len1);
5752 patch_id_add_string(&ctx, "+++/dev/null");
5753 } else {
5754 patch_id_add_string(&ctx, "---a/");
5755 git_SHA1_Update(&ctx, p->one->path, len1);
5756 patch_id_add_string(&ctx, "+++b/");
5757 git_SHA1_Update(&ctx, p->two->path, len2);
5760 if (diff_header_only)
5761 continue;
5763 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
5764 fill_mmfile(options->repo, &mf2, p->two) < 0)
5765 return error("unable to read files to diff");
5767 if (diff_filespec_is_binary(options->repo, p->one) ||
5768 diff_filespec_is_binary(options->repo, p->two)) {
5769 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5770 GIT_SHA1_HEXSZ);
5771 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5772 GIT_SHA1_HEXSZ);
5773 continue;
5776 xpp.flags = 0;
5777 xecfg.ctxlen = 3;
5778 xecfg.flags = 0;
5779 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
5780 patch_id_consume, &data, &xpp, &xecfg))
5781 return error("unable to generate patch-id diff for %s",
5782 p->one->path);
5785 git_SHA1_Final(oid->hash, &ctx);
5786 return 0;
5789 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5791 struct diff_queue_struct *q = &diff_queued_diff;
5792 int i;
5793 int result = diff_get_patch_id(options, oid, diff_header_only);
5795 for (i = 0; i < q->nr; i++)
5796 diff_free_filepair(q->queue[i]);
5798 free(q->queue);
5799 DIFF_QUEUE_CLEAR(q);
5801 return result;
5804 static int is_summary_empty(const struct diff_queue_struct *q)
5806 int i;
5808 for (i = 0; i < q->nr; i++) {
5809 const struct diff_filepair *p = q->queue[i];
5811 switch (p->status) {
5812 case DIFF_STATUS_DELETED:
5813 case DIFF_STATUS_ADDED:
5814 case DIFF_STATUS_COPIED:
5815 case DIFF_STATUS_RENAMED:
5816 return 0;
5817 default:
5818 if (p->score)
5819 return 0;
5820 if (p->one->mode && p->two->mode &&
5821 p->one->mode != p->two->mode)
5822 return 0;
5823 break;
5826 return 1;
5829 static const char rename_limit_warning[] =
5830 N_("inexact rename detection was skipped due to too many files.");
5832 static const char degrade_cc_to_c_warning[] =
5833 N_("only found copies from modified paths due to too many files.");
5835 static const char rename_limit_advice[] =
5836 N_("you may want to set your %s variable to at least "
5837 "%d and retry the command.");
5839 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5841 fflush(stdout);
5842 if (degraded_cc)
5843 warning(_(degrade_cc_to_c_warning));
5844 else if (needed)
5845 warning(_(rename_limit_warning));
5846 else
5847 return;
5848 if (0 < needed)
5849 warning(_(rename_limit_advice), varname, needed);
5852 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5854 int i;
5855 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5856 struct diff_queue_struct *q = &diff_queued_diff;
5858 if (WSEH_NEW & WS_RULE_MASK)
5859 BUG("WS rules bit mask overlaps with diff symbol flags");
5861 if (o->color_moved)
5862 o->emitted_symbols = &esm;
5864 for (i = 0; i < q->nr; i++) {
5865 struct diff_filepair *p = q->queue[i];
5866 if (check_pair_status(p))
5867 diff_flush_patch(p, o);
5870 if (o->emitted_symbols) {
5871 if (o->color_moved) {
5872 struct hashmap add_lines, del_lines;
5874 if (o->color_moved_ws_handling &
5875 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
5876 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
5878 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
5879 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
5881 add_lines_to_move_detection(o, &add_lines, &del_lines);
5882 mark_color_as_moved(o, &add_lines, &del_lines);
5883 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5884 dim_moved_lines(o);
5886 hashmap_free(&add_lines, 1);
5887 hashmap_free(&del_lines, 1);
5890 for (i = 0; i < esm.nr; i++)
5891 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5893 for (i = 0; i < esm.nr; i++)
5894 free((void *)esm.buf[i].line);
5896 esm.nr = 0;
5899 void diff_flush(struct diff_options *options)
5901 struct diff_queue_struct *q = &diff_queued_diff;
5902 int i, output_format = options->output_format;
5903 int separator = 0;
5904 int dirstat_by_line = 0;
5907 * Order: raw, stat, summary, patch
5908 * or: name/name-status/checkdiff (other bits clear)
5910 if (!q->nr)
5911 goto free_queue;
5913 if (output_format & (DIFF_FORMAT_RAW |
5914 DIFF_FORMAT_NAME |
5915 DIFF_FORMAT_NAME_STATUS |
5916 DIFF_FORMAT_CHECKDIFF)) {
5917 for (i = 0; i < q->nr; i++) {
5918 struct diff_filepair *p = q->queue[i];
5919 if (check_pair_status(p))
5920 flush_one_pair(p, options);
5922 separator++;
5925 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
5926 dirstat_by_line = 1;
5928 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5929 dirstat_by_line) {
5930 struct diffstat_t diffstat;
5932 memset(&diffstat, 0, sizeof(struct diffstat_t));
5933 for (i = 0; i < q->nr; i++) {
5934 struct diff_filepair *p = q->queue[i];
5935 if (check_pair_status(p))
5936 diff_flush_stat(p, options, &diffstat);
5938 if (output_format & DIFF_FORMAT_NUMSTAT)
5939 show_numstat(&diffstat, options);
5940 if (output_format & DIFF_FORMAT_DIFFSTAT)
5941 show_stats(&diffstat, options);
5942 if (output_format & DIFF_FORMAT_SHORTSTAT)
5943 show_shortstats(&diffstat, options);
5944 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5945 show_dirstat_by_line(&diffstat, options);
5946 free_diffstat_info(&diffstat);
5947 separator++;
5949 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5950 show_dirstat(options);
5952 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5953 for (i = 0; i < q->nr; i++) {
5954 diff_summary(options, q->queue[i]);
5956 separator++;
5959 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5960 options->flags.exit_with_status &&
5961 options->flags.diff_from_contents) {
5963 * run diff_flush_patch for the exit status. setting
5964 * options->file to /dev/null should be safe, because we
5965 * aren't supposed to produce any output anyway.
5967 if (options->close_file)
5968 fclose(options->file);
5969 options->file = xfopen("/dev/null", "w");
5970 options->close_file = 1;
5971 options->color_moved = 0;
5972 for (i = 0; i < q->nr; i++) {
5973 struct diff_filepair *p = q->queue[i];
5974 if (check_pair_status(p))
5975 diff_flush_patch(p, options);
5976 if (options->found_changes)
5977 break;
5981 if (output_format & DIFF_FORMAT_PATCH) {
5982 if (separator) {
5983 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5984 if (options->stat_sep)
5985 /* attach patch instead of inline */
5986 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5987 NULL, 0, 0);
5990 diff_flush_patch_all_file_pairs(options);
5993 if (output_format & DIFF_FORMAT_CALLBACK)
5994 options->format_callback(q, options, options->format_callback_data);
5996 for (i = 0; i < q->nr; i++)
5997 diff_free_filepair(q->queue[i]);
5998 free_queue:
5999 free(q->queue);
6000 DIFF_QUEUE_CLEAR(q);
6001 if (options->close_file)
6002 fclose(options->file);
6005 * Report the content-level differences with HAS_CHANGES;
6006 * diff_addremove/diff_change does not set the bit when
6007 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6009 if (options->flags.diff_from_contents) {
6010 if (options->found_changes)
6011 options->flags.has_changes = 1;
6012 else
6013 options->flags.has_changes = 0;
6017 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6019 return (((p->status == DIFF_STATUS_MODIFIED) &&
6020 ((p->score &&
6021 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6022 (!p->score &&
6023 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6024 ((p->status != DIFF_STATUS_MODIFIED) &&
6025 filter_bit_tst(p->status, options)));
6028 static void diffcore_apply_filter(struct diff_options *options)
6030 int i;
6031 struct diff_queue_struct *q = &diff_queued_diff;
6032 struct diff_queue_struct outq;
6034 DIFF_QUEUE_CLEAR(&outq);
6036 if (!options->filter)
6037 return;
6039 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6040 int found;
6041 for (i = found = 0; !found && i < q->nr; i++) {
6042 if (match_filter(options, q->queue[i]))
6043 found++;
6045 if (found)
6046 return;
6048 /* otherwise we will clear the whole queue
6049 * by copying the empty outq at the end of this
6050 * function, but first clear the current entries
6051 * in the queue.
6053 for (i = 0; i < q->nr; i++)
6054 diff_free_filepair(q->queue[i]);
6056 else {
6057 /* Only the matching ones */
6058 for (i = 0; i < q->nr; i++) {
6059 struct diff_filepair *p = q->queue[i];
6060 if (match_filter(options, p))
6061 diff_q(&outq, p);
6062 else
6063 diff_free_filepair(p);
6066 free(q->queue);
6067 *q = outq;
6070 /* Check whether two filespecs with the same mode and size are identical */
6071 static int diff_filespec_is_identical(struct repository *r,
6072 struct diff_filespec *one,
6073 struct diff_filespec *two)
6075 if (S_ISGITLINK(one->mode))
6076 return 0;
6077 if (diff_populate_filespec(r, one, 0))
6078 return 0;
6079 if (diff_populate_filespec(r, two, 0))
6080 return 0;
6081 return !memcmp(one->data, two->data, one->size);
6084 static int diff_filespec_check_stat_unmatch(struct repository *r,
6085 struct diff_filepair *p)
6087 if (p->done_skip_stat_unmatch)
6088 return p->skip_stat_unmatch_result;
6090 p->done_skip_stat_unmatch = 1;
6091 p->skip_stat_unmatch_result = 0;
6093 * 1. Entries that come from stat info dirtiness
6094 * always have both sides (iow, not create/delete),
6095 * one side of the object name is unknown, with
6096 * the same mode and size. Keep the ones that
6097 * do not match these criteria. They have real
6098 * differences.
6100 * 2. At this point, the file is known to be modified,
6101 * with the same mode and size, and the object
6102 * name of one side is unknown. Need to inspect
6103 * the identical contents.
6105 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6106 !DIFF_FILE_VALID(p->two) ||
6107 (p->one->oid_valid && p->two->oid_valid) ||
6108 (p->one->mode != p->two->mode) ||
6109 diff_populate_filespec(r, p->one, CHECK_SIZE_ONLY) ||
6110 diff_populate_filespec(r, p->two, CHECK_SIZE_ONLY) ||
6111 (p->one->size != p->two->size) ||
6112 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6113 p->skip_stat_unmatch_result = 1;
6114 return p->skip_stat_unmatch_result;
6117 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6119 int i;
6120 struct diff_queue_struct *q = &diff_queued_diff;
6121 struct diff_queue_struct outq;
6122 DIFF_QUEUE_CLEAR(&outq);
6124 for (i = 0; i < q->nr; i++) {
6125 struct diff_filepair *p = q->queue[i];
6127 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6128 diff_q(&outq, p);
6129 else {
6131 * The caller can subtract 1 from skip_stat_unmatch
6132 * to determine how many paths were dirty only
6133 * due to stat info mismatch.
6135 if (!diffopt->flags.no_index)
6136 diffopt->skip_stat_unmatch++;
6137 diff_free_filepair(p);
6140 free(q->queue);
6141 *q = outq;
6144 static int diffnamecmp(const void *a_, const void *b_)
6146 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6147 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6148 const char *name_a, *name_b;
6150 name_a = a->one ? a->one->path : a->two->path;
6151 name_b = b->one ? b->one->path : b->two->path;
6152 return strcmp(name_a, name_b);
6155 void diffcore_fix_diff_index(struct diff_options *options)
6157 struct diff_queue_struct *q = &diff_queued_diff;
6158 QSORT(q->queue, q->nr, diffnamecmp);
6161 void diffcore_std(struct diff_options *options)
6163 /* NOTE please keep the following in sync with diff_tree_combined() */
6164 if (options->skip_stat_unmatch)
6165 diffcore_skip_stat_unmatch(options);
6166 if (!options->found_follow) {
6167 /* See try_to_follow_renames() in tree-diff.c */
6168 if (options->break_opt != -1)
6169 diffcore_break(options->repo,
6170 options->break_opt);
6171 if (options->detect_rename)
6172 diffcore_rename(options);
6173 if (options->break_opt != -1)
6174 diffcore_merge_broken();
6176 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6177 diffcore_pickaxe(options);
6178 if (options->orderfile)
6179 diffcore_order(options->orderfile);
6180 if (!options->found_follow)
6181 /* See try_to_follow_renames() in tree-diff.c */
6182 diff_resolve_rename_copy();
6183 diffcore_apply_filter(options);
6185 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6186 options->flags.has_changes = 1;
6187 else
6188 options->flags.has_changes = 0;
6190 options->found_follow = 0;
6193 int diff_result_code(struct diff_options *opt, int status)
6195 int result = 0;
6197 diff_warn_rename_limit("diff.renameLimit",
6198 opt->needed_rename_limit,
6199 opt->degraded_cc_to_c);
6200 if (!opt->flags.exit_with_status &&
6201 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6202 return status;
6203 if (opt->flags.exit_with_status &&
6204 opt->flags.has_changes)
6205 result |= 01;
6206 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6207 opt->flags.check_failed)
6208 result |= 02;
6209 return result;
6212 int diff_can_quit_early(struct diff_options *opt)
6214 return (opt->flags.quick &&
6215 !opt->filter &&
6216 opt->flags.has_changes);
6220 * Shall changes to this submodule be ignored?
6222 * Submodule changes can be configured to be ignored separately for each path,
6223 * but that configuration can be overridden from the command line.
6225 static int is_submodule_ignored(const char *path, struct diff_options *options)
6227 int ignored = 0;
6228 struct diff_flags orig_flags = options->flags;
6229 if (!options->flags.override_submodule_config)
6230 set_diffopt_flags_from_submodule_config(options, path);
6231 if (options->flags.ignore_submodules)
6232 ignored = 1;
6233 options->flags = orig_flags;
6234 return ignored;
6237 void diff_addremove(struct diff_options *options,
6238 int addremove, unsigned mode,
6239 const struct object_id *oid,
6240 int oid_valid,
6241 const char *concatpath, unsigned dirty_submodule)
6243 struct diff_filespec *one, *two;
6245 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6246 return;
6248 /* This may look odd, but it is a preparation for
6249 * feeding "there are unchanged files which should
6250 * not produce diffs, but when you are doing copy
6251 * detection you would need them, so here they are"
6252 * entries to the diff-core. They will be prefixed
6253 * with something like '=' or '*' (I haven't decided
6254 * which but should not make any difference).
6255 * Feeding the same new and old to diff_change()
6256 * also has the same effect.
6257 * Before the final output happens, they are pruned after
6258 * merged into rename/copy pairs as appropriate.
6260 if (options->flags.reverse_diff)
6261 addremove = (addremove == '+' ? '-' :
6262 addremove == '-' ? '+' : addremove);
6264 if (options->prefix &&
6265 strncmp(concatpath, options->prefix, options->prefix_length))
6266 return;
6268 one = alloc_filespec(concatpath);
6269 two = alloc_filespec(concatpath);
6271 if (addremove != '+')
6272 fill_filespec(one, oid, oid_valid, mode);
6273 if (addremove != '-') {
6274 fill_filespec(two, oid, oid_valid, mode);
6275 two->dirty_submodule = dirty_submodule;
6278 diff_queue(&diff_queued_diff, one, two);
6279 if (!options->flags.diff_from_contents)
6280 options->flags.has_changes = 1;
6283 void diff_change(struct diff_options *options,
6284 unsigned old_mode, unsigned new_mode,
6285 const struct object_id *old_oid,
6286 const struct object_id *new_oid,
6287 int old_oid_valid, int new_oid_valid,
6288 const char *concatpath,
6289 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6291 struct diff_filespec *one, *two;
6292 struct diff_filepair *p;
6294 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6295 is_submodule_ignored(concatpath, options))
6296 return;
6298 if (options->flags.reverse_diff) {
6299 SWAP(old_mode, new_mode);
6300 SWAP(old_oid, new_oid);
6301 SWAP(old_oid_valid, new_oid_valid);
6302 SWAP(old_dirty_submodule, new_dirty_submodule);
6305 if (options->prefix &&
6306 strncmp(concatpath, options->prefix, options->prefix_length))
6307 return;
6309 one = alloc_filespec(concatpath);
6310 two = alloc_filespec(concatpath);
6311 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6312 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6313 one->dirty_submodule = old_dirty_submodule;
6314 two->dirty_submodule = new_dirty_submodule;
6315 p = diff_queue(&diff_queued_diff, one, two);
6317 if (options->flags.diff_from_contents)
6318 return;
6320 if (options->flags.quick && options->skip_stat_unmatch &&
6321 !diff_filespec_check_stat_unmatch(options->repo, p))
6322 return;
6324 options->flags.has_changes = 1;
6327 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6329 struct diff_filepair *pair;
6330 struct diff_filespec *one, *two;
6332 if (options->prefix &&
6333 strncmp(path, options->prefix, options->prefix_length))
6334 return NULL;
6336 one = alloc_filespec(path);
6337 two = alloc_filespec(path);
6338 pair = diff_queue(&diff_queued_diff, one, two);
6339 pair->is_unmerged = 1;
6340 return pair;
6343 static char *run_textconv(struct repository *r,
6344 const char *pgm,
6345 struct diff_filespec *spec,
6346 size_t *outsize)
6348 struct diff_tempfile *temp;
6349 const char *argv[3];
6350 const char **arg = argv;
6351 struct child_process child = CHILD_PROCESS_INIT;
6352 struct strbuf buf = STRBUF_INIT;
6353 int err = 0;
6355 temp = prepare_temp_file(r, spec->path, spec);
6356 *arg++ = pgm;
6357 *arg++ = temp->name;
6358 *arg = NULL;
6360 child.use_shell = 1;
6361 child.argv = argv;
6362 child.out = -1;
6363 if (start_command(&child)) {
6364 remove_tempfile();
6365 return NULL;
6368 if (strbuf_read(&buf, child.out, 0) < 0)
6369 err = error("error reading from textconv command '%s'", pgm);
6370 close(child.out);
6372 if (finish_command(&child) || err) {
6373 strbuf_release(&buf);
6374 remove_tempfile();
6375 return NULL;
6377 remove_tempfile();
6379 return strbuf_detach(&buf, outsize);
6382 size_t fill_textconv(struct repository *r,
6383 struct userdiff_driver *driver,
6384 struct diff_filespec *df,
6385 char **outbuf)
6387 size_t size;
6389 if (!driver) {
6390 if (!DIFF_FILE_VALID(df)) {
6391 *outbuf = "";
6392 return 0;
6394 if (diff_populate_filespec(r, df, 0))
6395 die("unable to read files to diff");
6396 *outbuf = df->data;
6397 return df->size;
6400 if (!driver->textconv)
6401 BUG("fill_textconv called with non-textconv driver");
6403 if (driver->textconv_cache && df->oid_valid) {
6404 *outbuf = notes_cache_get(driver->textconv_cache,
6405 &df->oid,
6406 &size);
6407 if (*outbuf)
6408 return size;
6411 *outbuf = run_textconv(r, driver->textconv, df, &size);
6412 if (!*outbuf)
6413 die("unable to read files to diff");
6415 if (driver->textconv_cache && df->oid_valid) {
6416 /* ignore errors, as we might be in a readonly repository */
6417 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6418 size);
6420 * we could save up changes and flush them all at the end,
6421 * but we would need an extra call after all diffing is done.
6422 * Since generating a cache entry is the slow path anyway,
6423 * this extra overhead probably isn't a big deal.
6425 notes_cache_write(driver->textconv_cache);
6428 return size;
6431 int textconv_object(struct repository *r,
6432 const char *path,
6433 unsigned mode,
6434 const struct object_id *oid,
6435 int oid_valid,
6436 char **buf,
6437 unsigned long *buf_size)
6439 struct diff_filespec *df;
6440 struct userdiff_driver *textconv;
6442 df = alloc_filespec(path);
6443 fill_filespec(df, oid, oid_valid, mode);
6444 textconv = get_textconv(r, df);
6445 if (!textconv) {
6446 free_filespec(df);
6447 return 0;
6450 *buf_size = fill_textconv(r, textconv, df, buf);
6451 free_filespec(df);
6452 return 1;
6455 void setup_diff_pager(struct diff_options *opt)
6458 * If the user asked for our exit code, then either they want --quiet
6459 * or --exit-code. We should definitely not bother with a pager in the
6460 * former case, as we will generate no output. Since we still properly
6461 * report our exit code even when a pager is run, we _could_ run a
6462 * pager with --exit-code. But since we have not done so historically,
6463 * and because it is easy to find people oneline advising "git diff
6464 * --exit-code" in hooks and other scripts, we do not do so.
6466 if (!opt->flags.exit_with_status &&
6467 check_pager_config("diff") != 0)
6468 setup_pager();