Merge branch 'es/doc-worktree-guessremote-config'
[git.git] / diff.c
blob1b5f27636061feb0ecf273f257c5e080c5ff7481
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)
1646 int i;
1647 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1648 if (!diff_temp[i].name)
1649 return diff_temp + i;
1650 BUG("diff is failing to clean up its tempfiles");
1653 static void remove_tempfile(void)
1655 int i;
1656 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1657 if (is_tempfile_active(diff_temp[i].tempfile))
1658 delete_tempfile(&diff_temp[i].tempfile);
1659 diff_temp[i].name = NULL;
1663 static void add_line_count(struct strbuf *out, int count)
1665 switch (count) {
1666 case 0:
1667 strbuf_addstr(out, "0,0");
1668 break;
1669 case 1:
1670 strbuf_addstr(out, "1");
1671 break;
1672 default:
1673 strbuf_addf(out, "1,%d", count);
1674 break;
1678 static void emit_rewrite_lines(struct emit_callback *ecb,
1679 int prefix, const char *data, int size)
1681 const char *endp = NULL;
1682 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1684 while (0 < size) {
1685 int len;
1687 endp = memchr(data, '\n', size);
1688 len = endp ? (endp - data + 1) : size;
1689 if (prefix != '+') {
1690 ecb->lno_in_preimage++;
1691 emit_del_line(reset, ecb, data, len);
1692 } else {
1693 ecb->lno_in_postimage++;
1694 emit_add_line(reset, ecb, data, len);
1696 size -= len;
1697 data += len;
1699 if (!endp)
1700 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1703 static void emit_rewrite_diff(const char *name_a,
1704 const char *name_b,
1705 struct diff_filespec *one,
1706 struct diff_filespec *two,
1707 struct userdiff_driver *textconv_one,
1708 struct userdiff_driver *textconv_two,
1709 struct diff_options *o)
1711 int lc_a, lc_b;
1712 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1713 const char *a_prefix, *b_prefix;
1714 char *data_one, *data_two;
1715 size_t size_one, size_two;
1716 struct emit_callback ecbdata;
1717 struct strbuf out = STRBUF_INIT;
1719 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1720 a_prefix = o->b_prefix;
1721 b_prefix = o->a_prefix;
1722 } else {
1723 a_prefix = o->a_prefix;
1724 b_prefix = o->b_prefix;
1727 name_a += (*name_a == '/');
1728 name_b += (*name_b == '/');
1730 strbuf_reset(&a_name);
1731 strbuf_reset(&b_name);
1732 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1733 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1735 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1736 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1738 memset(&ecbdata, 0, sizeof(ecbdata));
1739 ecbdata.color_diff = want_color(o->use_color);
1740 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1741 ecbdata.opt = o;
1742 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1743 mmfile_t mf1, mf2;
1744 mf1.ptr = (char *)data_one;
1745 mf2.ptr = (char *)data_two;
1746 mf1.size = size_one;
1747 mf2.size = size_two;
1748 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1750 ecbdata.lno_in_preimage = 1;
1751 ecbdata.lno_in_postimage = 1;
1753 lc_a = count_lines(data_one, size_one);
1754 lc_b = count_lines(data_two, size_two);
1756 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1757 a_name.buf, a_name.len, 0);
1758 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1759 b_name.buf, b_name.len, 0);
1761 strbuf_addstr(&out, "@@ -");
1762 if (!o->irreversible_delete)
1763 add_line_count(&out, lc_a);
1764 else
1765 strbuf_addstr(&out, "?,?");
1766 strbuf_addstr(&out, " +");
1767 add_line_count(&out, lc_b);
1768 strbuf_addstr(&out, " @@\n");
1769 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1770 strbuf_release(&out);
1772 if (lc_a && !o->irreversible_delete)
1773 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1774 if (lc_b)
1775 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1776 if (textconv_one)
1777 free((char *)data_one);
1778 if (textconv_two)
1779 free((char *)data_two);
1782 struct diff_words_buffer {
1783 mmfile_t text;
1784 unsigned long alloc;
1785 struct diff_words_orig {
1786 const char *begin, *end;
1787 } *orig;
1788 int orig_nr, orig_alloc;
1791 static void diff_words_append(char *line, unsigned long len,
1792 struct diff_words_buffer *buffer)
1794 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1795 line++;
1796 len--;
1797 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1798 buffer->text.size += len;
1799 buffer->text.ptr[buffer->text.size] = '\0';
1802 struct diff_words_style_elem {
1803 const char *prefix;
1804 const char *suffix;
1805 const char *color; /* NULL; filled in by the setup code if
1806 * color is enabled */
1809 struct diff_words_style {
1810 enum diff_words_type type;
1811 struct diff_words_style_elem new_word, old_word, ctx;
1812 const char *newline;
1815 static struct diff_words_style diff_words_styles[] = {
1816 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1817 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1818 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1821 struct diff_words_data {
1822 struct diff_words_buffer minus, plus;
1823 const char *current_plus;
1824 int last_minus;
1825 struct diff_options *opt;
1826 regex_t *word_regex;
1827 enum diff_words_type type;
1828 struct diff_words_style *style;
1831 static int fn_out_diff_words_write_helper(struct diff_options *o,
1832 struct diff_words_style_elem *st_el,
1833 const char *newline,
1834 size_t count, const char *buf)
1836 int print = 0;
1837 struct strbuf sb = STRBUF_INIT;
1839 while (count) {
1840 char *p = memchr(buf, '\n', count);
1841 if (print)
1842 strbuf_addstr(&sb, diff_line_prefix(o));
1844 if (p != buf) {
1845 const char *reset = st_el->color && *st_el->color ?
1846 GIT_COLOR_RESET : NULL;
1847 if (st_el->color && *st_el->color)
1848 strbuf_addstr(&sb, st_el->color);
1849 strbuf_addstr(&sb, st_el->prefix);
1850 strbuf_add(&sb, buf, p ? p - buf : count);
1851 strbuf_addstr(&sb, st_el->suffix);
1852 if (reset)
1853 strbuf_addstr(&sb, reset);
1855 if (!p)
1856 goto out;
1858 strbuf_addstr(&sb, newline);
1859 count -= p + 1 - buf;
1860 buf = p + 1;
1861 print = 1;
1862 if (count) {
1863 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1864 sb.buf, sb.len, 0);
1865 strbuf_reset(&sb);
1869 out:
1870 if (sb.len)
1871 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1872 sb.buf, sb.len, 0);
1873 strbuf_release(&sb);
1874 return 0;
1878 * '--color-words' algorithm can be described as:
1880 * 1. collect the minus/plus lines of a diff hunk, divided into
1881 * minus-lines and plus-lines;
1883 * 2. break both minus-lines and plus-lines into words and
1884 * place them into two mmfile_t with one word for each line;
1886 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1888 * And for the common parts of the both file, we output the plus side text.
1889 * diff_words->current_plus is used to trace the current position of the plus file
1890 * which printed. diff_words->last_minus is used to trace the last minus word
1891 * printed.
1893 * For '--graph' to work with '--color-words', we need to output the graph prefix
1894 * on each line of color words output. Generally, there are two conditions on
1895 * which we should output the prefix.
1897 * 1. diff_words->last_minus == 0 &&
1898 * diff_words->current_plus == diff_words->plus.text.ptr
1900 * that is: the plus text must start as a new line, and if there is no minus
1901 * word printed, a graph prefix must be printed.
1903 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1904 * *(diff_words->current_plus - 1) == '\n'
1906 * that is: a graph prefix must be printed following a '\n'
1908 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1910 if ((diff_words->last_minus == 0 &&
1911 diff_words->current_plus == diff_words->plus.text.ptr) ||
1912 (diff_words->current_plus > diff_words->plus.text.ptr &&
1913 *(diff_words->current_plus - 1) == '\n')) {
1914 return 1;
1915 } else {
1916 return 0;
1920 static void fn_out_diff_words_aux(void *priv,
1921 long minus_first, long minus_len,
1922 long plus_first, long plus_len,
1923 const char *func, long funclen)
1925 struct diff_words_data *diff_words = priv;
1926 struct diff_words_style *style = diff_words->style;
1927 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1928 struct diff_options *opt = diff_words->opt;
1929 const char *line_prefix;
1931 assert(opt);
1932 line_prefix = diff_line_prefix(opt);
1934 /* POSIX requires that first be decremented by one if len == 0... */
1935 if (minus_len) {
1936 minus_begin = diff_words->minus.orig[minus_first].begin;
1937 minus_end =
1938 diff_words->minus.orig[minus_first + minus_len - 1].end;
1939 } else
1940 minus_begin = minus_end =
1941 diff_words->minus.orig[minus_first].end;
1943 if (plus_len) {
1944 plus_begin = diff_words->plus.orig[plus_first].begin;
1945 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1946 } else
1947 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1949 if (color_words_output_graph_prefix(diff_words)) {
1950 fputs(line_prefix, diff_words->opt->file);
1952 if (diff_words->current_plus != plus_begin) {
1953 fn_out_diff_words_write_helper(diff_words->opt,
1954 &style->ctx, style->newline,
1955 plus_begin - diff_words->current_plus,
1956 diff_words->current_plus);
1958 if (minus_begin != minus_end) {
1959 fn_out_diff_words_write_helper(diff_words->opt,
1960 &style->old_word, style->newline,
1961 minus_end - minus_begin, minus_begin);
1963 if (plus_begin != plus_end) {
1964 fn_out_diff_words_write_helper(diff_words->opt,
1965 &style->new_word, style->newline,
1966 plus_end - plus_begin, plus_begin);
1969 diff_words->current_plus = plus_end;
1970 diff_words->last_minus = minus_first;
1973 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1974 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1975 int *begin, int *end)
1977 if (word_regex && *begin < buffer->size) {
1978 regmatch_t match[1];
1979 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1980 buffer->size - *begin, 1, match, 0)) {
1981 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1982 '\n', match[0].rm_eo - match[0].rm_so);
1983 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1984 *begin += match[0].rm_so;
1985 return *begin >= *end;
1987 return -1;
1990 /* find the next word */
1991 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1992 (*begin)++;
1993 if (*begin >= buffer->size)
1994 return -1;
1996 /* find the end of the word */
1997 *end = *begin + 1;
1998 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1999 (*end)++;
2001 return 0;
2005 * This function splits the words in buffer->text, stores the list with
2006 * newline separator into out, and saves the offsets of the original words
2007 * in buffer->orig.
2009 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2010 regex_t *word_regex)
2012 int i, j;
2013 long alloc = 0;
2015 out->size = 0;
2016 out->ptr = NULL;
2018 /* fake an empty "0th" word */
2019 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2020 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2021 buffer->orig_nr = 1;
2023 for (i = 0; i < buffer->text.size; i++) {
2024 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2025 return;
2027 /* store original boundaries */
2028 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2029 buffer->orig_alloc);
2030 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2031 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2032 buffer->orig_nr++;
2034 /* store one word */
2035 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2036 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2037 out->ptr[out->size + j - i] = '\n';
2038 out->size += j - i + 1;
2040 i = j - 1;
2044 /* this executes the word diff on the accumulated buffers */
2045 static void diff_words_show(struct diff_words_data *diff_words)
2047 xpparam_t xpp;
2048 xdemitconf_t xecfg;
2049 mmfile_t minus, plus;
2050 struct diff_words_style *style = diff_words->style;
2052 struct diff_options *opt = diff_words->opt;
2053 const char *line_prefix;
2055 assert(opt);
2056 line_prefix = diff_line_prefix(opt);
2058 /* special case: only removal */
2059 if (!diff_words->plus.text.size) {
2060 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2061 line_prefix, strlen(line_prefix), 0);
2062 fn_out_diff_words_write_helper(diff_words->opt,
2063 &style->old_word, style->newline,
2064 diff_words->minus.text.size,
2065 diff_words->minus.text.ptr);
2066 diff_words->minus.text.size = 0;
2067 return;
2070 diff_words->current_plus = diff_words->plus.text.ptr;
2071 diff_words->last_minus = 0;
2073 memset(&xpp, 0, sizeof(xpp));
2074 memset(&xecfg, 0, sizeof(xecfg));
2075 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2076 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2077 xpp.flags = 0;
2078 /* as only the hunk header will be parsed, we need a 0-context */
2079 xecfg.ctxlen = 0;
2080 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2081 diff_words, &xpp, &xecfg))
2082 die("unable to generate word diff");
2083 free(minus.ptr);
2084 free(plus.ptr);
2085 if (diff_words->current_plus != diff_words->plus.text.ptr +
2086 diff_words->plus.text.size) {
2087 if (color_words_output_graph_prefix(diff_words))
2088 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2089 line_prefix, strlen(line_prefix), 0);
2090 fn_out_diff_words_write_helper(diff_words->opt,
2091 &style->ctx, style->newline,
2092 diff_words->plus.text.ptr + diff_words->plus.text.size
2093 - diff_words->current_plus, diff_words->current_plus);
2095 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2098 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2099 static void diff_words_flush(struct emit_callback *ecbdata)
2101 struct diff_options *wo = ecbdata->diff_words->opt;
2103 if (ecbdata->diff_words->minus.text.size ||
2104 ecbdata->diff_words->plus.text.size)
2105 diff_words_show(ecbdata->diff_words);
2107 if (wo->emitted_symbols) {
2108 struct diff_options *o = ecbdata->opt;
2109 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2110 int i;
2113 * NEEDSWORK:
2114 * Instead of appending each, concat all words to a line?
2116 for (i = 0; i < wol->nr; i++)
2117 append_emitted_diff_symbol(o, &wol->buf[i]);
2119 for (i = 0; i < wol->nr; i++)
2120 free((void *)wol->buf[i].line);
2122 wol->nr = 0;
2126 static void diff_filespec_load_driver(struct diff_filespec *one,
2127 struct index_state *istate)
2129 /* Use already-loaded driver */
2130 if (one->driver)
2131 return;
2133 if (S_ISREG(one->mode))
2134 one->driver = userdiff_find_by_path(istate, one->path);
2136 /* Fallback to default settings */
2137 if (!one->driver)
2138 one->driver = userdiff_find_by_name("default");
2141 static const char *userdiff_word_regex(struct diff_filespec *one,
2142 struct index_state *istate)
2144 diff_filespec_load_driver(one, istate);
2145 return one->driver->word_regex;
2148 static void init_diff_words_data(struct emit_callback *ecbdata,
2149 struct diff_options *orig_opts,
2150 struct diff_filespec *one,
2151 struct diff_filespec *two)
2153 int i;
2154 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2155 memcpy(o, orig_opts, sizeof(struct diff_options));
2157 ecbdata->diff_words =
2158 xcalloc(1, sizeof(struct diff_words_data));
2159 ecbdata->diff_words->type = o->word_diff;
2160 ecbdata->diff_words->opt = o;
2162 if (orig_opts->emitted_symbols)
2163 o->emitted_symbols =
2164 xcalloc(1, sizeof(struct emitted_diff_symbols));
2166 if (!o->word_regex)
2167 o->word_regex = userdiff_word_regex(one, o->repo->index);
2168 if (!o->word_regex)
2169 o->word_regex = userdiff_word_regex(two, o->repo->index);
2170 if (!o->word_regex)
2171 o->word_regex = diff_word_regex_cfg;
2172 if (o->word_regex) {
2173 ecbdata->diff_words->word_regex = (regex_t *)
2174 xmalloc(sizeof(regex_t));
2175 if (regcomp(ecbdata->diff_words->word_regex,
2176 o->word_regex,
2177 REG_EXTENDED | REG_NEWLINE))
2178 die("invalid regular expression: %s",
2179 o->word_regex);
2181 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2182 if (o->word_diff == diff_words_styles[i].type) {
2183 ecbdata->diff_words->style =
2184 &diff_words_styles[i];
2185 break;
2188 if (want_color(o->use_color)) {
2189 struct diff_words_style *st = ecbdata->diff_words->style;
2190 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2191 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2192 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2196 static void free_diff_words_data(struct emit_callback *ecbdata)
2198 if (ecbdata->diff_words) {
2199 diff_words_flush(ecbdata);
2200 free (ecbdata->diff_words->opt->emitted_symbols);
2201 free (ecbdata->diff_words->opt);
2202 free (ecbdata->diff_words->minus.text.ptr);
2203 free (ecbdata->diff_words->minus.orig);
2204 free (ecbdata->diff_words->plus.text.ptr);
2205 free (ecbdata->diff_words->plus.orig);
2206 if (ecbdata->diff_words->word_regex) {
2207 regfree(ecbdata->diff_words->word_regex);
2208 free(ecbdata->diff_words->word_regex);
2210 FREE_AND_NULL(ecbdata->diff_words);
2214 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2216 if (want_color(diff_use_color))
2217 return diff_colors[ix];
2218 return "";
2221 const char *diff_line_prefix(struct diff_options *opt)
2223 struct strbuf *msgbuf;
2224 if (!opt->output_prefix)
2225 return "";
2227 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2228 return msgbuf->buf;
2231 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
2233 const char *cp;
2234 unsigned long allot;
2235 size_t l = len;
2237 cp = line;
2238 allot = l;
2239 while (0 < l) {
2240 (void) utf8_width(&cp, &l);
2241 if (!cp)
2242 break; /* truncated in the middle? */
2244 return allot - l;
2247 static void find_lno(const char *line, struct emit_callback *ecbdata)
2249 const char *p;
2250 ecbdata->lno_in_preimage = 0;
2251 ecbdata->lno_in_postimage = 0;
2252 p = strchr(line, '-');
2253 if (!p)
2254 return; /* cannot happen */
2255 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2256 p = strchr(p, '+');
2257 if (!p)
2258 return; /* cannot happen */
2259 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2262 static void fn_out_consume(void *priv, char *line, unsigned long len)
2264 struct emit_callback *ecbdata = priv;
2265 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
2266 struct diff_options *o = ecbdata->opt;
2268 o->found_changes = 1;
2270 if (ecbdata->header) {
2271 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2272 ecbdata->header->buf, ecbdata->header->len, 0);
2273 strbuf_reset(ecbdata->header);
2274 ecbdata->header = NULL;
2277 if (ecbdata->label_path[0]) {
2278 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2279 ecbdata->label_path[0],
2280 strlen(ecbdata->label_path[0]), 0);
2281 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2282 ecbdata->label_path[1],
2283 strlen(ecbdata->label_path[1]), 0);
2284 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2287 if (diff_suppress_blank_empty
2288 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2289 line[0] = '\n';
2290 len = 1;
2293 if (line[0] == '@') {
2294 if (ecbdata->diff_words)
2295 diff_words_flush(ecbdata);
2296 len = sane_truncate_line(ecbdata, line, len);
2297 find_lno(line, ecbdata);
2298 emit_hunk_header(ecbdata, line, len);
2299 return;
2302 if (ecbdata->diff_words) {
2303 enum diff_symbol s =
2304 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2305 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2306 if (line[0] == '-') {
2307 diff_words_append(line, len,
2308 &ecbdata->diff_words->minus);
2309 return;
2310 } else if (line[0] == '+') {
2311 diff_words_append(line, len,
2312 &ecbdata->diff_words->plus);
2313 return;
2314 } else if (starts_with(line, "\\ ")) {
2316 * Eat the "no newline at eof" marker as if we
2317 * saw a "+" or "-" line with nothing on it,
2318 * and return without diff_words_flush() to
2319 * defer processing. If this is the end of
2320 * preimage, more "+" lines may come after it.
2322 return;
2324 diff_words_flush(ecbdata);
2325 emit_diff_symbol(o, s, line, len, 0);
2326 return;
2329 switch (line[0]) {
2330 case '+':
2331 ecbdata->lno_in_postimage++;
2332 emit_add_line(reset, ecbdata, line + 1, len - 1);
2333 break;
2334 case '-':
2335 ecbdata->lno_in_preimage++;
2336 emit_del_line(reset, ecbdata, line + 1, len - 1);
2337 break;
2338 case ' ':
2339 ecbdata->lno_in_postimage++;
2340 ecbdata->lno_in_preimage++;
2341 emit_context_line(reset, ecbdata, line + 1, len - 1);
2342 break;
2343 default:
2344 /* incomplete line at the end */
2345 ecbdata->lno_in_preimage++;
2346 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2347 line, len, 0);
2348 break;
2352 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2354 const char *old_name = a;
2355 const char *new_name = b;
2356 int pfx_length, sfx_length;
2357 int pfx_adjust_for_slash;
2358 int len_a = strlen(a);
2359 int len_b = strlen(b);
2360 int a_midlen, b_midlen;
2361 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2362 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2364 if (qlen_a || qlen_b) {
2365 quote_c_style(a, name, NULL, 0);
2366 strbuf_addstr(name, " => ");
2367 quote_c_style(b, name, NULL, 0);
2368 return;
2371 /* Find common prefix */
2372 pfx_length = 0;
2373 while (*old_name && *new_name && *old_name == *new_name) {
2374 if (*old_name == '/')
2375 pfx_length = old_name - a + 1;
2376 old_name++;
2377 new_name++;
2380 /* Find common suffix */
2381 old_name = a + len_a;
2382 new_name = b + len_b;
2383 sfx_length = 0;
2385 * If there is a common prefix, it must end in a slash. In
2386 * that case we let this loop run 1 into the prefix to see the
2387 * same slash.
2389 * If there is no common prefix, we cannot do this as it would
2390 * underrun the input strings.
2392 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2393 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2394 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2395 *old_name == *new_name) {
2396 if (*old_name == '/')
2397 sfx_length = len_a - (old_name - a);
2398 old_name--;
2399 new_name--;
2403 * pfx{mid-a => mid-b}sfx
2404 * {pfx-a => pfx-b}sfx
2405 * pfx{sfx-a => sfx-b}
2406 * name-a => name-b
2408 a_midlen = len_a - pfx_length - sfx_length;
2409 b_midlen = len_b - pfx_length - sfx_length;
2410 if (a_midlen < 0)
2411 a_midlen = 0;
2412 if (b_midlen < 0)
2413 b_midlen = 0;
2415 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2416 if (pfx_length + sfx_length) {
2417 strbuf_add(name, a, pfx_length);
2418 strbuf_addch(name, '{');
2420 strbuf_add(name, a + pfx_length, a_midlen);
2421 strbuf_addstr(name, " => ");
2422 strbuf_add(name, b + pfx_length, b_midlen);
2423 if (pfx_length + sfx_length) {
2424 strbuf_addch(name, '}');
2425 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2429 struct diffstat_t {
2430 int nr;
2431 int alloc;
2432 struct diffstat_file {
2433 char *from_name;
2434 char *name;
2435 char *print_name;
2436 const char *comments;
2437 unsigned is_unmerged:1;
2438 unsigned is_binary:1;
2439 unsigned is_renamed:1;
2440 unsigned is_interesting:1;
2441 uintmax_t added, deleted;
2442 } **files;
2445 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2446 const char *name_a,
2447 const char *name_b)
2449 struct diffstat_file *x;
2450 x = xcalloc(1, sizeof(*x));
2451 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2452 diffstat->files[diffstat->nr++] = x;
2453 if (name_b) {
2454 x->from_name = xstrdup(name_a);
2455 x->name = xstrdup(name_b);
2456 x->is_renamed = 1;
2458 else {
2459 x->from_name = NULL;
2460 x->name = xstrdup(name_a);
2462 return x;
2465 static void diffstat_consume(void *priv, char *line, unsigned long len)
2467 struct diffstat_t *diffstat = priv;
2468 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2470 if (line[0] == '+')
2471 x->added++;
2472 else if (line[0] == '-')
2473 x->deleted++;
2476 const char mime_boundary_leader[] = "------------";
2478 static int scale_linear(int it, int width, int max_change)
2480 if (!it)
2481 return 0;
2483 * make sure that at least one '-' or '+' is printed if
2484 * there is any change to this path. The easiest way is to
2485 * scale linearly as if the alloted width is one column shorter
2486 * than it is, and then add 1 to the result.
2488 return 1 + (it * (width - 1) / max_change);
2491 static void show_graph(struct strbuf *out, char ch, int cnt,
2492 const char *set, const char *reset)
2494 if (cnt <= 0)
2495 return;
2496 strbuf_addstr(out, set);
2497 strbuf_addchars(out, ch, cnt);
2498 strbuf_addstr(out, reset);
2501 static void fill_print_name(struct diffstat_file *file)
2503 struct strbuf pname = STRBUF_INIT;
2505 if (file->print_name)
2506 return;
2508 if (file->is_renamed)
2509 pprint_rename(&pname, file->from_name, file->name);
2510 else
2511 quote_c_style(file->name, &pname, NULL, 0);
2513 if (file->comments)
2514 strbuf_addf(&pname, " (%s)", file->comments);
2516 file->print_name = strbuf_detach(&pname, NULL);
2519 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2520 int files, int insertions, int deletions)
2522 struct strbuf sb = STRBUF_INIT;
2524 if (!files) {
2525 assert(insertions == 0 && deletions == 0);
2526 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2527 NULL, 0, 0);
2528 return;
2531 strbuf_addf(&sb,
2532 (files == 1) ? " %d file changed" : " %d files changed",
2533 files);
2536 * For binary diff, the caller may want to print "x files
2537 * changed" with insertions == 0 && deletions == 0.
2539 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2540 * is probably less confusing (i.e skip over "2 files changed
2541 * but nothing about added/removed lines? Is this a bug in Git?").
2543 if (insertions || deletions == 0) {
2544 strbuf_addf(&sb,
2545 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2546 insertions);
2549 if (deletions || insertions == 0) {
2550 strbuf_addf(&sb,
2551 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2552 deletions);
2554 strbuf_addch(&sb, '\n');
2555 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2556 sb.buf, sb.len, 0);
2557 strbuf_release(&sb);
2560 void print_stat_summary(FILE *fp, int files,
2561 int insertions, int deletions)
2563 struct diff_options o;
2564 memset(&o, 0, sizeof(o));
2565 o.file = fp;
2567 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2570 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2572 int i, len, add, del, adds = 0, dels = 0;
2573 uintmax_t max_change = 0, max_len = 0;
2574 int total_files = data->nr, count;
2575 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2576 const char *reset, *add_c, *del_c;
2577 int extra_shown = 0;
2578 const char *line_prefix = diff_line_prefix(options);
2579 struct strbuf out = STRBUF_INIT;
2581 if (data->nr == 0)
2582 return;
2584 count = options->stat_count ? options->stat_count : data->nr;
2586 reset = diff_get_color_opt(options, DIFF_RESET);
2587 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2588 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2591 * Find the longest filename and max number of changes
2593 for (i = 0; (i < count) && (i < data->nr); i++) {
2594 struct diffstat_file *file = data->files[i];
2595 uintmax_t change = file->added + file->deleted;
2597 if (!file->is_interesting && (change == 0)) {
2598 count++; /* not shown == room for one more */
2599 continue;
2601 fill_print_name(file);
2602 len = strlen(file->print_name);
2603 if (max_len < len)
2604 max_len = len;
2606 if (file->is_unmerged) {
2607 /* "Unmerged" is 8 characters */
2608 bin_width = bin_width < 8 ? 8 : bin_width;
2609 continue;
2611 if (file->is_binary) {
2612 /* "Bin XXX -> YYY bytes" */
2613 int w = 14 + decimal_width(file->added)
2614 + decimal_width(file->deleted);
2615 bin_width = bin_width < w ? w : bin_width;
2616 /* Display change counts aligned with "Bin" */
2617 number_width = 3;
2618 continue;
2621 if (max_change < change)
2622 max_change = change;
2624 count = i; /* where we can stop scanning in data->files[] */
2627 * We have width = stat_width or term_columns() columns total.
2628 * We want a maximum of min(max_len, stat_name_width) for the name part.
2629 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2630 * We also need 1 for " " and 4 + decimal_width(max_change)
2631 * for " | NNNN " and one the empty column at the end, altogether
2632 * 6 + decimal_width(max_change).
2634 * If there's not enough space, we will use the smaller of
2635 * stat_name_width (if set) and 5/8*width for the filename,
2636 * and the rest for constant elements + graph part, but no more
2637 * than stat_graph_width for the graph part.
2638 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2639 * for the standard terminal size).
2641 * In other words: stat_width limits the maximum width, and
2642 * stat_name_width fixes the maximum width of the filename,
2643 * and is also used to divide available columns if there
2644 * aren't enough.
2646 * Binary files are displayed with "Bin XXX -> YYY bytes"
2647 * instead of the change count and graph. This part is treated
2648 * similarly to the graph part, except that it is not
2649 * "scaled". If total width is too small to accommodate the
2650 * guaranteed minimum width of the filename part and the
2651 * separators and this message, this message will "overflow"
2652 * making the line longer than the maximum width.
2655 if (options->stat_width == -1)
2656 width = term_columns() - strlen(line_prefix);
2657 else
2658 width = options->stat_width ? options->stat_width : 80;
2659 number_width = decimal_width(max_change) > number_width ?
2660 decimal_width(max_change) : number_width;
2662 if (options->stat_graph_width == -1)
2663 options->stat_graph_width = diff_stat_graph_width;
2666 * Guarantee 3/8*16==6 for the graph part
2667 * and 5/8*16==10 for the filename part
2669 if (width < 16 + 6 + number_width)
2670 width = 16 + 6 + number_width;
2673 * First assign sizes that are wanted, ignoring available width.
2674 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2675 * starting from "XXX" should fit in graph_width.
2677 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2678 if (options->stat_graph_width &&
2679 options->stat_graph_width < graph_width)
2680 graph_width = options->stat_graph_width;
2682 name_width = (options->stat_name_width > 0 &&
2683 options->stat_name_width < max_len) ?
2684 options->stat_name_width : max_len;
2687 * Adjust adjustable widths not to exceed maximum width
2689 if (name_width + number_width + 6 + graph_width > width) {
2690 if (graph_width > width * 3/8 - number_width - 6) {
2691 graph_width = width * 3/8 - number_width - 6;
2692 if (graph_width < 6)
2693 graph_width = 6;
2696 if (options->stat_graph_width &&
2697 graph_width > options->stat_graph_width)
2698 graph_width = options->stat_graph_width;
2699 if (name_width > width - number_width - 6 - graph_width)
2700 name_width = width - number_width - 6 - graph_width;
2701 else
2702 graph_width = width - number_width - 6 - name_width;
2706 * From here name_width is the width of the name area,
2707 * and graph_width is the width of the graph area.
2708 * max_change is used to scale graph properly.
2710 for (i = 0; i < count; i++) {
2711 const char *prefix = "";
2712 struct diffstat_file *file = data->files[i];
2713 char *name = file->print_name;
2714 uintmax_t added = file->added;
2715 uintmax_t deleted = file->deleted;
2716 int name_len;
2718 if (!file->is_interesting && (added + deleted == 0))
2719 continue;
2722 * "scale" the filename
2724 len = name_width;
2725 name_len = strlen(name);
2726 if (name_width < name_len) {
2727 char *slash;
2728 prefix = "...";
2729 len -= 3;
2730 name += name_len - len;
2731 slash = strchr(name, '/');
2732 if (slash)
2733 name = slash;
2736 if (file->is_binary) {
2737 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2738 strbuf_addf(&out, " %*s", number_width, "Bin");
2739 if (!added && !deleted) {
2740 strbuf_addch(&out, '\n');
2741 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2742 out.buf, out.len, 0);
2743 strbuf_reset(&out);
2744 continue;
2746 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2747 del_c, deleted, reset);
2748 strbuf_addstr(&out, " -> ");
2749 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2750 add_c, added, reset);
2751 strbuf_addstr(&out, " bytes\n");
2752 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2753 out.buf, out.len, 0);
2754 strbuf_reset(&out);
2755 continue;
2757 else if (file->is_unmerged) {
2758 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2759 strbuf_addstr(&out, " Unmerged\n");
2760 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2761 out.buf, out.len, 0);
2762 strbuf_reset(&out);
2763 continue;
2767 * scale the add/delete
2769 add = added;
2770 del = deleted;
2772 if (graph_width <= max_change) {
2773 int total = scale_linear(add + del, graph_width, max_change);
2774 if (total < 2 && add && del)
2775 /* width >= 2 due to the sanity check */
2776 total = 2;
2777 if (add < del) {
2778 add = scale_linear(add, graph_width, max_change);
2779 del = total - add;
2780 } else {
2781 del = scale_linear(del, graph_width, max_change);
2782 add = total - del;
2785 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2786 strbuf_addf(&out, " %*"PRIuMAX"%s",
2787 number_width, added + deleted,
2788 added + deleted ? " " : "");
2789 show_graph(&out, '+', add, add_c, reset);
2790 show_graph(&out, '-', del, del_c, reset);
2791 strbuf_addch(&out, '\n');
2792 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2793 out.buf, out.len, 0);
2794 strbuf_reset(&out);
2797 for (i = 0; i < data->nr; i++) {
2798 struct diffstat_file *file = data->files[i];
2799 uintmax_t added = file->added;
2800 uintmax_t deleted = file->deleted;
2802 if (file->is_unmerged ||
2803 (!file->is_interesting && (added + deleted == 0))) {
2804 total_files--;
2805 continue;
2808 if (!file->is_binary) {
2809 adds += added;
2810 dels += deleted;
2812 if (i < count)
2813 continue;
2814 if (!extra_shown)
2815 emit_diff_symbol(options,
2816 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2817 NULL, 0, 0);
2818 extra_shown = 1;
2821 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2822 strbuf_release(&out);
2825 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2827 int i, adds = 0, dels = 0, total_files = data->nr;
2829 if (data->nr == 0)
2830 return;
2832 for (i = 0; i < data->nr; i++) {
2833 int added = data->files[i]->added;
2834 int deleted = data->files[i]->deleted;
2836 if (data->files[i]->is_unmerged ||
2837 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2838 total_files--;
2839 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2840 adds += added;
2841 dels += deleted;
2844 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2847 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2849 int i;
2851 if (data->nr == 0)
2852 return;
2854 for (i = 0; i < data->nr; i++) {
2855 struct diffstat_file *file = data->files[i];
2857 fprintf(options->file, "%s", diff_line_prefix(options));
2859 if (file->is_binary)
2860 fprintf(options->file, "-\t-\t");
2861 else
2862 fprintf(options->file,
2863 "%"PRIuMAX"\t%"PRIuMAX"\t",
2864 file->added, file->deleted);
2865 if (options->line_termination) {
2866 fill_print_name(file);
2867 if (!file->is_renamed)
2868 write_name_quoted(file->name, options->file,
2869 options->line_termination);
2870 else {
2871 fputs(file->print_name, options->file);
2872 putc(options->line_termination, options->file);
2874 } else {
2875 if (file->is_renamed) {
2876 putc('\0', options->file);
2877 write_name_quoted(file->from_name, options->file, '\0');
2879 write_name_quoted(file->name, options->file, '\0');
2884 struct dirstat_file {
2885 const char *name;
2886 unsigned long changed;
2889 struct dirstat_dir {
2890 struct dirstat_file *files;
2891 int alloc, nr, permille, cumulative;
2894 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2895 unsigned long changed, const char *base, int baselen)
2897 unsigned long sum_changes = 0;
2898 unsigned int sources = 0;
2899 const char *line_prefix = diff_line_prefix(opt);
2901 while (dir->nr) {
2902 struct dirstat_file *f = dir->files;
2903 int namelen = strlen(f->name);
2904 unsigned long changes;
2905 char *slash;
2907 if (namelen < baselen)
2908 break;
2909 if (memcmp(f->name, base, baselen))
2910 break;
2911 slash = strchr(f->name + baselen, '/');
2912 if (slash) {
2913 int newbaselen = slash + 1 - f->name;
2914 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2915 sources++;
2916 } else {
2917 changes = f->changed;
2918 dir->files++;
2919 dir->nr--;
2920 sources += 2;
2922 sum_changes += changes;
2926 * We don't report dirstat's for
2927 * - the top level
2928 * - or cases where everything came from a single directory
2929 * under this directory (sources == 1).
2931 if (baselen && sources != 1) {
2932 if (sum_changes) {
2933 int permille = sum_changes * 1000 / changed;
2934 if (permille >= dir->permille) {
2935 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2936 permille / 10, permille % 10, baselen, base);
2937 if (!dir->cumulative)
2938 return 0;
2942 return sum_changes;
2945 static int dirstat_compare(const void *_a, const void *_b)
2947 const struct dirstat_file *a = _a;
2948 const struct dirstat_file *b = _b;
2949 return strcmp(a->name, b->name);
2952 static void show_dirstat(struct diff_options *options)
2954 int i;
2955 unsigned long changed;
2956 struct dirstat_dir dir;
2957 struct diff_queue_struct *q = &diff_queued_diff;
2959 dir.files = NULL;
2960 dir.alloc = 0;
2961 dir.nr = 0;
2962 dir.permille = options->dirstat_permille;
2963 dir.cumulative = options->flags.dirstat_cumulative;
2965 changed = 0;
2966 for (i = 0; i < q->nr; i++) {
2967 struct diff_filepair *p = q->queue[i];
2968 const char *name;
2969 unsigned long copied, added, damage;
2971 name = p->two->path ? p->two->path : p->one->path;
2973 if (p->one->oid_valid && p->two->oid_valid &&
2974 oideq(&p->one->oid, &p->two->oid)) {
2976 * The SHA1 has not changed, so pre-/post-content is
2977 * identical. We can therefore skip looking at the
2978 * file contents altogether.
2980 damage = 0;
2981 goto found_damage;
2984 if (options->flags.dirstat_by_file) {
2986 * In --dirstat-by-file mode, we don't really need to
2987 * look at the actual file contents at all.
2988 * The fact that the SHA1 changed is enough for us to
2989 * add this file to the list of results
2990 * (with each file contributing equal damage).
2992 damage = 1;
2993 goto found_damage;
2996 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2997 diff_populate_filespec(options->repo, p->one, 0);
2998 diff_populate_filespec(options->repo, p->two, 0);
2999 diffcore_count_changes(options->repo,
3000 p->one, p->two, NULL, NULL,
3001 &copied, &added);
3002 diff_free_filespec_data(p->one);
3003 diff_free_filespec_data(p->two);
3004 } else if (DIFF_FILE_VALID(p->one)) {
3005 diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
3006 copied = added = 0;
3007 diff_free_filespec_data(p->one);
3008 } else if (DIFF_FILE_VALID(p->two)) {
3009 diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
3010 copied = 0;
3011 added = p->two->size;
3012 diff_free_filespec_data(p->two);
3013 } else
3014 continue;
3017 * Original minus copied is the removed material,
3018 * added is the new material. They are both damages
3019 * made to the preimage.
3020 * If the resulting damage is zero, we know that
3021 * diffcore_count_changes() considers the two entries to
3022 * be identical, but since the oid changed, we
3023 * know that there must have been _some_ kind of change,
3024 * so we force all entries to have damage > 0.
3026 damage = (p->one->size - copied) + added;
3027 if (!damage)
3028 damage = 1;
3030 found_damage:
3031 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3032 dir.files[dir.nr].name = name;
3033 dir.files[dir.nr].changed = damage;
3034 changed += damage;
3035 dir.nr++;
3038 /* This can happen even with many files, if everything was renames */
3039 if (!changed)
3040 return;
3042 /* Show all directories with more than x% of the changes */
3043 QSORT(dir.files, dir.nr, dirstat_compare);
3044 gather_dirstat(options, &dir, changed, "", 0);
3047 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3049 int i;
3050 unsigned long changed;
3051 struct dirstat_dir dir;
3053 if (data->nr == 0)
3054 return;
3056 dir.files = NULL;
3057 dir.alloc = 0;
3058 dir.nr = 0;
3059 dir.permille = options->dirstat_permille;
3060 dir.cumulative = options->flags.dirstat_cumulative;
3062 changed = 0;
3063 for (i = 0; i < data->nr; i++) {
3064 struct diffstat_file *file = data->files[i];
3065 unsigned long damage = file->added + file->deleted;
3066 if (file->is_binary)
3068 * binary files counts bytes, not lines. Must find some
3069 * way to normalize binary bytes vs. textual lines.
3070 * The following heuristic assumes that there are 64
3071 * bytes per "line".
3072 * This is stupid and ugly, but very cheap...
3074 damage = DIV_ROUND_UP(damage, 64);
3075 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3076 dir.files[dir.nr].name = file->name;
3077 dir.files[dir.nr].changed = damage;
3078 changed += damage;
3079 dir.nr++;
3082 /* This can happen even with many files, if everything was renames */
3083 if (!changed)
3084 return;
3086 /* Show all directories with more than x% of the changes */
3087 QSORT(dir.files, dir.nr, dirstat_compare);
3088 gather_dirstat(options, &dir, changed, "", 0);
3091 static void free_diffstat_info(struct diffstat_t *diffstat)
3093 int i;
3094 for (i = 0; i < diffstat->nr; i++) {
3095 struct diffstat_file *f = diffstat->files[i];
3096 free(f->print_name);
3097 free(f->name);
3098 free(f->from_name);
3099 free(f);
3101 free(diffstat->files);
3104 struct checkdiff_t {
3105 const char *filename;
3106 int lineno;
3107 int conflict_marker_size;
3108 struct diff_options *o;
3109 unsigned ws_rule;
3110 unsigned status;
3113 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3115 char firstchar;
3116 int cnt;
3118 if (len < marker_size + 1)
3119 return 0;
3120 firstchar = line[0];
3121 switch (firstchar) {
3122 case '=': case '>': case '<': case '|':
3123 break;
3124 default:
3125 return 0;
3127 for (cnt = 1; cnt < marker_size; cnt++)
3128 if (line[cnt] != firstchar)
3129 return 0;
3130 /* line[1] thru line[marker_size-1] are same as firstchar */
3131 if (len < marker_size + 1 || !isspace(line[marker_size]))
3132 return 0;
3133 return 1;
3136 static void checkdiff_consume_hunk(void *priv,
3137 long ob, long on, long nb, long nn,
3138 const char *func, long funclen)
3141 struct checkdiff_t *data = priv;
3142 data->lineno = nb - 1;
3145 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3147 struct checkdiff_t *data = priv;
3148 int marker_size = data->conflict_marker_size;
3149 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3150 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3151 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3152 char *err;
3153 const char *line_prefix;
3155 assert(data->o);
3156 line_prefix = diff_line_prefix(data->o);
3158 if (line[0] == '+') {
3159 unsigned bad;
3160 data->lineno++;
3161 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3162 data->status |= 1;
3163 fprintf(data->o->file,
3164 "%s%s:%d: leftover conflict marker\n",
3165 line_prefix, data->filename, data->lineno);
3167 bad = ws_check(line + 1, len - 1, data->ws_rule);
3168 if (!bad)
3169 return;
3170 data->status |= bad;
3171 err = whitespace_error_string(bad);
3172 fprintf(data->o->file, "%s%s:%d: %s.\n",
3173 line_prefix, data->filename, data->lineno, err);
3174 free(err);
3175 emit_line(data->o, set, reset, line, 1);
3176 ws_check_emit(line + 1, len - 1, data->ws_rule,
3177 data->o->file, set, reset, ws);
3178 } else if (line[0] == ' ') {
3179 data->lineno++;
3183 static unsigned char *deflate_it(char *data,
3184 unsigned long size,
3185 unsigned long *result_size)
3187 int bound;
3188 unsigned char *deflated;
3189 git_zstream stream;
3191 git_deflate_init(&stream, zlib_compression_level);
3192 bound = git_deflate_bound(&stream, size);
3193 deflated = xmalloc(bound);
3194 stream.next_out = deflated;
3195 stream.avail_out = bound;
3197 stream.next_in = (unsigned char *)data;
3198 stream.avail_in = size;
3199 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3200 ; /* nothing */
3201 git_deflate_end(&stream);
3202 *result_size = stream.total_out;
3203 return deflated;
3206 static void emit_binary_diff_body(struct diff_options *o,
3207 mmfile_t *one, mmfile_t *two)
3209 void *cp;
3210 void *delta;
3211 void *deflated;
3212 void *data;
3213 unsigned long orig_size;
3214 unsigned long delta_size;
3215 unsigned long deflate_size;
3216 unsigned long data_size;
3218 /* We could do deflated delta, or we could do just deflated two,
3219 * whichever is smaller.
3221 delta = NULL;
3222 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3223 if (one->size && two->size) {
3224 delta = diff_delta(one->ptr, one->size,
3225 two->ptr, two->size,
3226 &delta_size, deflate_size);
3227 if (delta) {
3228 void *to_free = delta;
3229 orig_size = delta_size;
3230 delta = deflate_it(delta, delta_size, &delta_size);
3231 free(to_free);
3235 if (delta && delta_size < deflate_size) {
3236 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3237 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3238 s, strlen(s), 0);
3239 free(s);
3240 free(deflated);
3241 data = delta;
3242 data_size = delta_size;
3243 } else {
3244 char *s = xstrfmt("%lu", two->size);
3245 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3246 s, strlen(s), 0);
3247 free(s);
3248 free(delta);
3249 data = deflated;
3250 data_size = deflate_size;
3253 /* emit data encoded in base85 */
3254 cp = data;
3255 while (data_size) {
3256 int len;
3257 int bytes = (52 < data_size) ? 52 : data_size;
3258 char line[71];
3259 data_size -= bytes;
3260 if (bytes <= 26)
3261 line[0] = bytes + 'A' - 1;
3262 else
3263 line[0] = bytes - 26 + 'a' - 1;
3264 encode_85(line + 1, cp, bytes);
3265 cp = (char *) cp + bytes;
3267 len = strlen(line);
3268 line[len++] = '\n';
3269 line[len] = '\0';
3271 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3272 line, len, 0);
3274 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3275 free(data);
3278 static void emit_binary_diff(struct diff_options *o,
3279 mmfile_t *one, mmfile_t *two)
3281 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3282 emit_binary_diff_body(o, one, two);
3283 emit_binary_diff_body(o, two, one);
3286 int diff_filespec_is_binary(struct repository *r,
3287 struct diff_filespec *one)
3289 if (one->is_binary == -1) {
3290 diff_filespec_load_driver(one, r->index);
3291 if (one->driver->binary != -1)
3292 one->is_binary = one->driver->binary;
3293 else {
3294 if (!one->data && DIFF_FILE_VALID(one))
3295 diff_populate_filespec(r, one, CHECK_BINARY);
3296 if (one->is_binary == -1 && one->data)
3297 one->is_binary = buffer_is_binary(one->data,
3298 one->size);
3299 if (one->is_binary == -1)
3300 one->is_binary = 0;
3303 return one->is_binary;
3306 static const struct userdiff_funcname *
3307 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3309 diff_filespec_load_driver(one, o->repo->index);
3310 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3313 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3315 if (!options->a_prefix)
3316 options->a_prefix = a;
3317 if (!options->b_prefix)
3318 options->b_prefix = b;
3321 struct userdiff_driver *get_textconv(struct repository *r,
3322 struct diff_filespec *one)
3324 if (!DIFF_FILE_VALID(one))
3325 return NULL;
3327 diff_filespec_load_driver(one, r->index);
3328 return userdiff_get_textconv(r, one->driver);
3331 static void builtin_diff(const char *name_a,
3332 const char *name_b,
3333 struct diff_filespec *one,
3334 struct diff_filespec *two,
3335 const char *xfrm_msg,
3336 int must_show_header,
3337 struct diff_options *o,
3338 int complete_rewrite)
3340 mmfile_t mf1, mf2;
3341 const char *lbl[2];
3342 char *a_one, *b_two;
3343 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3344 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3345 const char *a_prefix, *b_prefix;
3346 struct userdiff_driver *textconv_one = NULL;
3347 struct userdiff_driver *textconv_two = NULL;
3348 struct strbuf header = STRBUF_INIT;
3349 const char *line_prefix = diff_line_prefix(o);
3351 diff_set_mnemonic_prefix(o, "a/", "b/");
3352 if (o->flags.reverse_diff) {
3353 a_prefix = o->b_prefix;
3354 b_prefix = o->a_prefix;
3355 } else {
3356 a_prefix = o->a_prefix;
3357 b_prefix = o->b_prefix;
3360 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3361 (!one->mode || S_ISGITLINK(one->mode)) &&
3362 (!two->mode || S_ISGITLINK(two->mode))) {
3363 show_submodule_summary(o, one->path ? one->path : two->path,
3364 &one->oid, &two->oid,
3365 two->dirty_submodule);
3366 return;
3367 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3368 (!one->mode || S_ISGITLINK(one->mode)) &&
3369 (!two->mode || S_ISGITLINK(two->mode))) {
3370 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3371 &one->oid, &two->oid,
3372 two->dirty_submodule);
3373 return;
3376 if (o->flags.allow_textconv) {
3377 textconv_one = get_textconv(o->repo, one);
3378 textconv_two = get_textconv(o->repo, two);
3381 /* Never use a non-valid filename anywhere if at all possible */
3382 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3383 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3385 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3386 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3387 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3388 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3389 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3390 if (lbl[0][0] == '/') {
3391 /* /dev/null */
3392 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3393 if (xfrm_msg)
3394 strbuf_addstr(&header, xfrm_msg);
3395 must_show_header = 1;
3397 else if (lbl[1][0] == '/') {
3398 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3399 if (xfrm_msg)
3400 strbuf_addstr(&header, xfrm_msg);
3401 must_show_header = 1;
3403 else {
3404 if (one->mode != two->mode) {
3405 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3406 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3407 must_show_header = 1;
3409 if (xfrm_msg)
3410 strbuf_addstr(&header, xfrm_msg);
3413 * we do not run diff between different kind
3414 * of objects.
3416 if ((one->mode ^ two->mode) & S_IFMT)
3417 goto free_ab_and_return;
3418 if (complete_rewrite &&
3419 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3420 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3421 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3422 header.buf, header.len, 0);
3423 strbuf_reset(&header);
3424 emit_rewrite_diff(name_a, name_b, one, two,
3425 textconv_one, textconv_two, o);
3426 o->found_changes = 1;
3427 goto free_ab_and_return;
3431 if (o->irreversible_delete && lbl[1][0] == '/') {
3432 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3433 header.len, 0);
3434 strbuf_reset(&header);
3435 goto free_ab_and_return;
3436 } else if (!o->flags.text &&
3437 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3438 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3439 struct strbuf sb = STRBUF_INIT;
3440 if (!one->data && !two->data &&
3441 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3442 !o->flags.binary) {
3443 if (oideq(&one->oid, &two->oid)) {
3444 if (must_show_header)
3445 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3446 header.buf, header.len,
3448 goto free_ab_and_return;
3450 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3451 header.buf, header.len, 0);
3452 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3453 diff_line_prefix(o), lbl[0], lbl[1]);
3454 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3455 sb.buf, sb.len, 0);
3456 strbuf_release(&sb);
3457 goto free_ab_and_return;
3459 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3460 fill_mmfile(o->repo, &mf2, two) < 0)
3461 die("unable to read files to diff");
3462 /* Quite common confusing case */
3463 if (mf1.size == mf2.size &&
3464 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3465 if (must_show_header)
3466 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3467 header.buf, header.len, 0);
3468 goto free_ab_and_return;
3470 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3471 strbuf_reset(&header);
3472 if (o->flags.binary)
3473 emit_binary_diff(o, &mf1, &mf2);
3474 else {
3475 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3476 diff_line_prefix(o), lbl[0], lbl[1]);
3477 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3478 sb.buf, sb.len, 0);
3479 strbuf_release(&sb);
3481 o->found_changes = 1;
3482 } else {
3483 /* Crazy xdl interfaces.. */
3484 const char *diffopts = getenv("GIT_DIFF_OPTS");
3485 const char *v;
3486 xpparam_t xpp;
3487 xdemitconf_t xecfg;
3488 struct emit_callback ecbdata;
3489 const struct userdiff_funcname *pe;
3491 if (must_show_header) {
3492 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3493 header.buf, header.len, 0);
3494 strbuf_reset(&header);
3497 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3498 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3500 pe = diff_funcname_pattern(o, one);
3501 if (!pe)
3502 pe = diff_funcname_pattern(o, two);
3504 memset(&xpp, 0, sizeof(xpp));
3505 memset(&xecfg, 0, sizeof(xecfg));
3506 memset(&ecbdata, 0, sizeof(ecbdata));
3507 if (o->flags.suppress_diff_headers)
3508 lbl[0] = NULL;
3509 ecbdata.label_path = lbl;
3510 ecbdata.color_diff = want_color(o->use_color);
3511 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3512 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3513 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3514 ecbdata.opt = o;
3515 if (header.len && !o->flags.suppress_diff_headers)
3516 ecbdata.header = &header;
3517 xpp.flags = o->xdl_opts;
3518 xpp.anchors = o->anchors;
3519 xpp.anchors_nr = o->anchors_nr;
3520 xecfg.ctxlen = o->context;
3521 xecfg.interhunkctxlen = o->interhunkcontext;
3522 xecfg.flags = XDL_EMIT_FUNCNAMES;
3523 if (o->flags.funccontext)
3524 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3525 if (pe)
3526 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3527 if (!diffopts)
3529 else if (skip_prefix(diffopts, "--unified=", &v))
3530 xecfg.ctxlen = strtoul(v, NULL, 10);
3531 else if (skip_prefix(diffopts, "-u", &v))
3532 xecfg.ctxlen = strtoul(v, NULL, 10);
3533 if (o->word_diff)
3534 init_diff_words_data(&ecbdata, o, one, two);
3535 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3536 &ecbdata, &xpp, &xecfg))
3537 die("unable to generate diff for %s", one->path);
3538 if (o->word_diff)
3539 free_diff_words_data(&ecbdata);
3540 if (textconv_one)
3541 free(mf1.ptr);
3542 if (textconv_two)
3543 free(mf2.ptr);
3544 xdiff_clear_find_func(&xecfg);
3547 free_ab_and_return:
3548 strbuf_release(&header);
3549 diff_free_filespec_data(one);
3550 diff_free_filespec_data(two);
3551 free(a_one);
3552 free(b_two);
3553 return;
3556 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3558 if (!is_renamed) {
3559 if (p->status == DIFF_STATUS_ADDED) {
3560 if (S_ISLNK(p->two->mode))
3561 return "new +l";
3562 else if ((p->two->mode & 0777) == 0755)
3563 return "new +x";
3564 else
3565 return "new";
3566 } else if (p->status == DIFF_STATUS_DELETED)
3567 return "gone";
3569 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3570 return "mode -l";
3571 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3572 return "mode +l";
3573 else if ((p->one->mode & 0777) == 0644 &&
3574 (p->two->mode & 0777) == 0755)
3575 return "mode +x";
3576 else if ((p->one->mode & 0777) == 0755 &&
3577 (p->two->mode & 0777) == 0644)
3578 return "mode -x";
3579 return NULL;
3582 static void builtin_diffstat(const char *name_a, const char *name_b,
3583 struct diff_filespec *one,
3584 struct diff_filespec *two,
3585 struct diffstat_t *diffstat,
3586 struct diff_options *o,
3587 struct diff_filepair *p)
3589 mmfile_t mf1, mf2;
3590 struct diffstat_file *data;
3591 int same_contents;
3592 int complete_rewrite = 0;
3594 if (!DIFF_PAIR_UNMERGED(p)) {
3595 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3596 complete_rewrite = 1;
3599 data = diffstat_add(diffstat, name_a, name_b);
3600 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3601 if (o->flags.stat_with_summary)
3602 data->comments = get_compact_summary(p, data->is_renamed);
3604 if (!one || !two) {
3605 data->is_unmerged = 1;
3606 return;
3609 same_contents = oideq(&one->oid, &two->oid);
3611 if (diff_filespec_is_binary(o->repo, one) ||
3612 diff_filespec_is_binary(o->repo, two)) {
3613 data->is_binary = 1;
3614 if (same_contents) {
3615 data->added = 0;
3616 data->deleted = 0;
3617 } else {
3618 data->added = diff_filespec_size(o->repo, two);
3619 data->deleted = diff_filespec_size(o->repo, one);
3623 else if (complete_rewrite) {
3624 diff_populate_filespec(o->repo, one, 0);
3625 diff_populate_filespec(o->repo, two, 0);
3626 data->deleted = count_lines(one->data, one->size);
3627 data->added = count_lines(two->data, two->size);
3630 else if (!same_contents) {
3631 /* Crazy xdl interfaces.. */
3632 xpparam_t xpp;
3633 xdemitconf_t xecfg;
3635 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3636 fill_mmfile(o->repo, &mf2, two) < 0)
3637 die("unable to read files to diff");
3639 memset(&xpp, 0, sizeof(xpp));
3640 memset(&xecfg, 0, sizeof(xecfg));
3641 xpp.flags = o->xdl_opts;
3642 xpp.anchors = o->anchors;
3643 xpp.anchors_nr = o->anchors_nr;
3644 xecfg.ctxlen = o->context;
3645 xecfg.interhunkctxlen = o->interhunkcontext;
3646 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3647 diffstat_consume, diffstat, &xpp, &xecfg))
3648 die("unable to generate diffstat for %s", one->path);
3651 diff_free_filespec_data(one);
3652 diff_free_filespec_data(two);
3655 static void builtin_checkdiff(const char *name_a, const char *name_b,
3656 const char *attr_path,
3657 struct diff_filespec *one,
3658 struct diff_filespec *two,
3659 struct diff_options *o)
3661 mmfile_t mf1, mf2;
3662 struct checkdiff_t data;
3664 if (!two)
3665 return;
3667 memset(&data, 0, sizeof(data));
3668 data.filename = name_b ? name_b : name_a;
3669 data.lineno = 0;
3670 data.o = o;
3671 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3672 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3674 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3675 fill_mmfile(o->repo, &mf2, two) < 0)
3676 die("unable to read files to diff");
3679 * All the other codepaths check both sides, but not checking
3680 * the "old" side here is deliberate. We are checking the newly
3681 * introduced changes, and as long as the "new" side is text, we
3682 * can and should check what it introduces.
3684 if (diff_filespec_is_binary(o->repo, two))
3685 goto free_and_return;
3686 else {
3687 /* Crazy xdl interfaces.. */
3688 xpparam_t xpp;
3689 xdemitconf_t xecfg;
3691 memset(&xpp, 0, sizeof(xpp));
3692 memset(&xecfg, 0, sizeof(xecfg));
3693 xecfg.ctxlen = 1; /* at least one context line */
3694 xpp.flags = 0;
3695 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3696 checkdiff_consume, &data,
3697 &xpp, &xecfg))
3698 die("unable to generate checkdiff for %s", one->path);
3700 if (data.ws_rule & WS_BLANK_AT_EOF) {
3701 struct emit_callback ecbdata;
3702 int blank_at_eof;
3704 ecbdata.ws_rule = data.ws_rule;
3705 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3706 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3708 if (blank_at_eof) {
3709 static char *err;
3710 if (!err)
3711 err = whitespace_error_string(WS_BLANK_AT_EOF);
3712 fprintf(o->file, "%s:%d: %s.\n",
3713 data.filename, blank_at_eof, err);
3714 data.status = 1; /* report errors */
3718 free_and_return:
3719 diff_free_filespec_data(one);
3720 diff_free_filespec_data(two);
3721 if (data.status)
3722 o->flags.check_failed = 1;
3725 struct diff_filespec *alloc_filespec(const char *path)
3727 struct diff_filespec *spec;
3729 FLEXPTR_ALLOC_STR(spec, path, path);
3730 spec->count = 1;
3731 spec->is_binary = -1;
3732 return spec;
3735 void free_filespec(struct diff_filespec *spec)
3737 if (!--spec->count) {
3738 diff_free_filespec_data(spec);
3739 free(spec);
3743 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3744 int oid_valid, unsigned short mode)
3746 if (mode) {
3747 spec->mode = canon_mode(mode);
3748 oidcpy(&spec->oid, oid);
3749 spec->oid_valid = oid_valid;
3754 * Given a name and sha1 pair, if the index tells us the file in
3755 * the work tree has that object contents, return true, so that
3756 * prepare_temp_file() does not have to inflate and extract.
3758 static int reuse_worktree_file(struct index_state *istate,
3759 const char *name,
3760 const struct object_id *oid,
3761 int want_file)
3763 const struct cache_entry *ce;
3764 struct stat st;
3765 int pos, len;
3768 * We do not read the cache ourselves here, because the
3769 * benchmark with my previous version that always reads cache
3770 * shows that it makes things worse for diff-tree comparing
3771 * two linux-2.6 kernel trees in an already checked out work
3772 * tree. This is because most diff-tree comparisons deal with
3773 * only a small number of files, while reading the cache is
3774 * expensive for a large project, and its cost outweighs the
3775 * savings we get by not inflating the object to a temporary
3776 * file. Practically, this code only helps when we are used
3777 * by diff-cache --cached, which does read the cache before
3778 * calling us.
3780 if (!istate->cache)
3781 return 0;
3783 /* We want to avoid the working directory if our caller
3784 * doesn't need the data in a normal file, this system
3785 * is rather slow with its stat/open/mmap/close syscalls,
3786 * and the object is contained in a pack file. The pack
3787 * is probably already open and will be faster to obtain
3788 * the data through than the working directory. Loose
3789 * objects however would tend to be slower as they need
3790 * to be individually opened and inflated.
3792 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3793 return 0;
3796 * Similarly, if we'd have to convert the file contents anyway, that
3797 * makes the optimization not worthwhile.
3799 if (!want_file && would_convert_to_git(istate, name))
3800 return 0;
3802 len = strlen(name);
3803 pos = index_name_pos(istate, name, len);
3804 if (pos < 0)
3805 return 0;
3806 ce = istate->cache[pos];
3809 * This is not the sha1 we are looking for, or
3810 * unreusable because it is not a regular file.
3812 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3813 return 0;
3816 * If ce is marked as "assume unchanged", there is no
3817 * guarantee that work tree matches what we are looking for.
3819 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3820 return 0;
3823 * If ce matches the file in the work tree, we can reuse it.
3825 if (ce_uptodate(ce) ||
3826 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3827 return 1;
3829 return 0;
3832 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3834 struct strbuf buf = STRBUF_INIT;
3835 char *dirty = "";
3837 /* Are we looking at the work tree? */
3838 if (s->dirty_submodule)
3839 dirty = "-dirty";
3841 strbuf_addf(&buf, "Subproject commit %s%s\n",
3842 oid_to_hex(&s->oid), dirty);
3843 s->size = buf.len;
3844 if (size_only) {
3845 s->data = NULL;
3846 strbuf_release(&buf);
3847 } else {
3848 s->data = strbuf_detach(&buf, NULL);
3849 s->should_free = 1;
3851 return 0;
3855 * While doing rename detection and pickaxe operation, we may need to
3856 * grab the data for the blob (or file) for our own in-core comparison.
3857 * diff_filespec has data and size fields for this purpose.
3859 int diff_populate_filespec(struct repository *r,
3860 struct diff_filespec *s,
3861 unsigned int flags)
3863 int size_only = flags & CHECK_SIZE_ONLY;
3864 int err = 0;
3865 int conv_flags = global_conv_flags_eol;
3867 * demote FAIL to WARN to allow inspecting the situation
3868 * instead of refusing.
3870 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3871 conv_flags = CONV_EOL_RNDTRP_WARN;
3873 if (!DIFF_FILE_VALID(s))
3874 die("internal error: asking to populate invalid file