treewide: remove cache.h inclusion due to object-file.h changes
[alt-git.git] / diff.c
blobf8e0d3b5c592ff66cb6573ab3a155a5635aebc1a
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "abspath.h"
6 #include "alloc.h"
7 #include "config.h"
8 #include "convert.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "tempfile.h"
12 #include "quote.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "delta.h"
16 #include "hex.h"
17 #include "xdiff-interface.h"
18 #include "color.h"
19 #include "attr.h"
20 #include "run-command.h"
21 #include "utf8.h"
22 #include "object-store.h"
23 #include "userdiff.h"
24 #include "submodule-config.h"
25 #include "submodule.h"
26 #include "hashmap.h"
27 #include "mem-pool.h"
28 #include "ll-merge.h"
29 #include "string-list.h"
30 #include "strvec.h"
31 #include "graph.h"
32 #include "oid-array.h"
33 #include "packfile.h"
34 #include "parse-options.h"
35 #include "help.h"
36 #include "promisor-remote.h"
37 #include "dir.h"
38 #include "object-file.h"
39 #include "object-name.h"
40 #include "setup.h"
41 #include "strmap.h"
42 #include "wrapper.h"
44 #ifdef NO_FAST_WORKING_DIRECTORY
45 #define FAST_WORKING_DIRECTORY 0
46 #else
47 #define FAST_WORKING_DIRECTORY 1
48 #endif
50 static int diff_detect_rename_default;
51 static int diff_indent_heuristic = 1;
52 static int diff_rename_limit_default = 1000;
53 static int diff_suppress_blank_empty;
54 static int diff_use_color_default = -1;
55 static int diff_color_moved_default;
56 static int diff_color_moved_ws_default;
57 static int diff_context_default = 3;
58 static int diff_interhunk_context_default;
59 static const char *diff_word_regex_cfg;
60 static const char *external_diff_cmd_cfg;
61 static const char *diff_order_file_cfg;
62 int diff_auto_refresh_index = 1;
63 static int diff_mnemonic_prefix;
64 static int diff_no_prefix;
65 static int diff_relative;
66 static int diff_stat_graph_width;
67 static int diff_dirstat_permille_default = 30;
68 static struct diff_options default_diff_options;
69 static long diff_algorithm;
70 static unsigned ws_error_highlight_default = WSEH_NEW;
72 static char diff_colors[][COLOR_MAXLEN] = {
73 GIT_COLOR_RESET,
74 GIT_COLOR_NORMAL, /* CONTEXT */
75 GIT_COLOR_BOLD, /* METAINFO */
76 GIT_COLOR_CYAN, /* FRAGINFO */
77 GIT_COLOR_RED, /* OLD */
78 GIT_COLOR_GREEN, /* NEW */
79 GIT_COLOR_YELLOW, /* COMMIT */
80 GIT_COLOR_BG_RED, /* WHITESPACE */
81 GIT_COLOR_NORMAL, /* FUNCINFO */
82 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
83 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
84 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
85 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
86 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
87 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
88 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
89 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
90 GIT_COLOR_FAINT, /* CONTEXT_DIM */
91 GIT_COLOR_FAINT_RED, /* OLD_DIM */
92 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
93 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
94 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
95 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
98 static const char *color_diff_slots[] = {
99 [DIFF_CONTEXT] = "context",
100 [DIFF_METAINFO] = "meta",
101 [DIFF_FRAGINFO] = "frag",
102 [DIFF_FILE_OLD] = "old",
103 [DIFF_FILE_NEW] = "new",
104 [DIFF_COMMIT] = "commit",
105 [DIFF_WHITESPACE] = "whitespace",
106 [DIFF_FUNCINFO] = "func",
107 [DIFF_FILE_OLD_MOVED] = "oldMoved",
108 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
109 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
110 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
111 [DIFF_FILE_NEW_MOVED] = "newMoved",
112 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
113 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
114 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
115 [DIFF_CONTEXT_DIM] = "contextDimmed",
116 [DIFF_FILE_OLD_DIM] = "oldDimmed",
117 [DIFF_FILE_NEW_DIM] = "newDimmed",
118 [DIFF_CONTEXT_BOLD] = "contextBold",
119 [DIFF_FILE_OLD_BOLD] = "oldBold",
120 [DIFF_FILE_NEW_BOLD] = "newBold",
123 define_list_config_array_extra(color_diff_slots, {"plain"});
125 static int parse_diff_color_slot(const char *var)
127 if (!strcasecmp(var, "plain"))
128 return DIFF_CONTEXT;
129 return LOOKUP_CONFIG(color_diff_slots, var);
132 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
133 struct strbuf *errmsg)
135 char *params_copy = xstrdup(params_string);
136 struct string_list params = STRING_LIST_INIT_NODUP;
137 int ret = 0;
138 int i;
140 if (*params_copy)
141 string_list_split_in_place(&params, params_copy, ',', -1);
142 for (i = 0; i < params.nr; i++) {
143 const char *p = params.items[i].string;
144 if (!strcmp(p, "changes")) {
145 options->flags.dirstat_by_line = 0;
146 options->flags.dirstat_by_file = 0;
147 } else if (!strcmp(p, "lines")) {
148 options->flags.dirstat_by_line = 1;
149 options->flags.dirstat_by_file = 0;
150 } else if (!strcmp(p, "files")) {
151 options->flags.dirstat_by_line = 0;
152 options->flags.dirstat_by_file = 1;
153 } else if (!strcmp(p, "noncumulative")) {
154 options->flags.dirstat_cumulative = 0;
155 } else if (!strcmp(p, "cumulative")) {
156 options->flags.dirstat_cumulative = 1;
157 } else if (isdigit(*p)) {
158 char *end;
159 int permille = strtoul(p, &end, 10) * 10;
160 if (*end == '.' && isdigit(*++end)) {
161 /* only use first digit */
162 permille += *end - '0';
163 /* .. and ignore any further digits */
164 while (isdigit(*++end))
165 ; /* nothing */
167 if (!*end)
168 options->dirstat_permille = permille;
169 else {
170 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
172 ret++;
174 } else {
175 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
176 ret++;
180 string_list_clear(&params, 0);
181 free(params_copy);
182 return ret;
185 static int parse_submodule_params(struct diff_options *options, const char *value)
187 if (!strcmp(value, "log"))
188 options->submodule_format = DIFF_SUBMODULE_LOG;
189 else if (!strcmp(value, "short"))
190 options->submodule_format = DIFF_SUBMODULE_SHORT;
191 else if (!strcmp(value, "diff"))
192 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
194 * Please update $__git_diff_submodule_formats in
195 * git-completion.bash when you add new formats.
197 else
198 return -1;
199 return 0;
202 int git_config_rename(const char *var, const char *value)
204 if (!value)
205 return DIFF_DETECT_RENAME;
206 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
207 return DIFF_DETECT_COPY;
208 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
211 long parse_algorithm_value(const char *value)
213 if (!value)
214 return -1;
215 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
216 return 0;
217 else if (!strcasecmp(value, "minimal"))
218 return XDF_NEED_MINIMAL;
219 else if (!strcasecmp(value, "patience"))
220 return XDF_PATIENCE_DIFF;
221 else if (!strcasecmp(value, "histogram"))
222 return XDF_HISTOGRAM_DIFF;
224 * Please update $__git_diff_algorithms in git-completion.bash
225 * when you add new algorithms.
227 return -1;
230 static int parse_one_token(const char **arg, const char *token)
232 const char *rest;
233 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
234 *arg = rest;
235 return 1;
237 return 0;
240 static int parse_ws_error_highlight(const char *arg)
242 const char *orig_arg = arg;
243 unsigned val = 0;
245 while (*arg) {
246 if (parse_one_token(&arg, "none"))
247 val = 0;
248 else if (parse_one_token(&arg, "default"))
249 val = WSEH_NEW;
250 else if (parse_one_token(&arg, "all"))
251 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
252 else if (parse_one_token(&arg, "new"))
253 val |= WSEH_NEW;
254 else if (parse_one_token(&arg, "old"))
255 val |= WSEH_OLD;
256 else if (parse_one_token(&arg, "context"))
257 val |= WSEH_CONTEXT;
258 else {
259 return -1 - (int)(arg - orig_arg);
261 if (*arg)
262 arg++;
264 return val;
268 * These are to give UI layer defaults.
269 * The core-level commands such as git-diff-files should
270 * never be affected by the setting of diff.renames
271 * the user happens to have in the configuration file.
273 void init_diff_ui_defaults(void)
275 diff_detect_rename_default = DIFF_DETECT_RENAME;
278 int git_diff_heuristic_config(const char *var, const char *value,
279 void *cb UNUSED)
281 if (!strcmp(var, "diff.indentheuristic"))
282 diff_indent_heuristic = git_config_bool(var, value);
283 return 0;
286 static int parse_color_moved(const char *arg)
288 switch (git_parse_maybe_bool(arg)) {
289 case 0:
290 return COLOR_MOVED_NO;
291 case 1:
292 return COLOR_MOVED_DEFAULT;
293 default:
294 break;
297 if (!strcmp(arg, "no"))
298 return COLOR_MOVED_NO;
299 else if (!strcmp(arg, "plain"))
300 return COLOR_MOVED_PLAIN;
301 else if (!strcmp(arg, "blocks"))
302 return COLOR_MOVED_BLOCKS;
303 else if (!strcmp(arg, "zebra"))
304 return COLOR_MOVED_ZEBRA;
305 else if (!strcmp(arg, "default"))
306 return COLOR_MOVED_DEFAULT;
307 else if (!strcmp(arg, "dimmed-zebra"))
308 return COLOR_MOVED_ZEBRA_DIM;
309 else if (!strcmp(arg, "dimmed_zebra"))
310 return COLOR_MOVED_ZEBRA_DIM;
311 else
312 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
315 static unsigned parse_color_moved_ws(const char *arg)
317 int ret = 0;
318 struct string_list l = STRING_LIST_INIT_DUP;
319 struct string_list_item *i;
321 string_list_split(&l, arg, ',', -1);
323 for_each_string_list_item(i, &l) {
324 struct strbuf sb = STRBUF_INIT;
325 strbuf_addstr(&sb, i->string);
326 strbuf_trim(&sb);
328 if (!strcmp(sb.buf, "no"))
329 ret = 0;
330 else if (!strcmp(sb.buf, "ignore-space-change"))
331 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
332 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
333 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
334 else if (!strcmp(sb.buf, "ignore-all-space"))
335 ret |= XDF_IGNORE_WHITESPACE;
336 else if (!strcmp(sb.buf, "allow-indentation-change"))
337 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
338 else {
339 ret |= COLOR_MOVED_WS_ERROR;
340 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);
343 strbuf_release(&sb);
346 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
347 (ret & XDF_WHITESPACE_FLAGS)) {
348 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
349 ret |= COLOR_MOVED_WS_ERROR;
352 string_list_clear(&l, 0);
354 return ret;
357 int git_diff_ui_config(const char *var, const char *value, void *cb)
359 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
360 diff_use_color_default = git_config_colorbool(var, value);
361 return 0;
363 if (!strcmp(var, "diff.colormoved")) {
364 int cm = parse_color_moved(value);
365 if (cm < 0)
366 return -1;
367 diff_color_moved_default = cm;
368 return 0;
370 if (!strcmp(var, "diff.colormovedws")) {
371 unsigned cm = parse_color_moved_ws(value);
372 if (cm & COLOR_MOVED_WS_ERROR)
373 return -1;
374 diff_color_moved_ws_default = cm;
375 return 0;
377 if (!strcmp(var, "diff.context")) {
378 diff_context_default = git_config_int(var, value);
379 if (diff_context_default < 0)
380 return -1;
381 return 0;
383 if (!strcmp(var, "diff.interhunkcontext")) {
384 diff_interhunk_context_default = git_config_int(var, value);
385 if (diff_interhunk_context_default < 0)
386 return -1;
387 return 0;
389 if (!strcmp(var, "diff.renames")) {
390 diff_detect_rename_default = git_config_rename(var, value);
391 return 0;
393 if (!strcmp(var, "diff.autorefreshindex")) {
394 diff_auto_refresh_index = git_config_bool(var, value);
395 return 0;
397 if (!strcmp(var, "diff.mnemonicprefix")) {
398 diff_mnemonic_prefix = git_config_bool(var, value);
399 return 0;
401 if (!strcmp(var, "diff.noprefix")) {
402 diff_no_prefix = git_config_bool(var, value);
403 return 0;
405 if (!strcmp(var, "diff.relative")) {
406 diff_relative = git_config_bool(var, value);
407 return 0;
409 if (!strcmp(var, "diff.statgraphwidth")) {
410 diff_stat_graph_width = git_config_int(var, value);
411 return 0;
413 if (!strcmp(var, "diff.external"))
414 return git_config_string(&external_diff_cmd_cfg, var, value);
415 if (!strcmp(var, "diff.wordregex"))
416 return git_config_string(&diff_word_regex_cfg, var, value);
417 if (!strcmp(var, "diff.orderfile"))
418 return git_config_pathname(&diff_order_file_cfg, var, value);
420 if (!strcmp(var, "diff.ignoresubmodules"))
421 handle_ignore_submodules_arg(&default_diff_options, value);
423 if (!strcmp(var, "diff.submodule")) {
424 if (parse_submodule_params(&default_diff_options, value))
425 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
426 value);
427 return 0;
430 if (!strcmp(var, "diff.algorithm")) {
431 diff_algorithm = parse_algorithm_value(value);
432 if (diff_algorithm < 0)
433 return -1;
434 return 0;
437 if (git_color_config(var, value, cb) < 0)
438 return -1;
440 return git_diff_basic_config(var, value, cb);
443 int git_diff_basic_config(const char *var, const char *value, void *cb)
445 const char *name;
447 if (!strcmp(var, "diff.renamelimit")) {
448 diff_rename_limit_default = git_config_int(var, value);
449 return 0;
452 if (userdiff_config(var, value) < 0)
453 return -1;
455 if (skip_prefix(var, "diff.color.", &name) ||
456 skip_prefix(var, "color.diff.", &name)) {
457 int slot = parse_diff_color_slot(name);
458 if (slot < 0)
459 return 0;
460 if (!value)
461 return config_error_nonbool(var);
462 return color_parse(value, diff_colors[slot]);
465 if (!strcmp(var, "diff.wserrorhighlight")) {
466 int val = parse_ws_error_highlight(value);
467 if (val < 0)
468 return -1;
469 ws_error_highlight_default = val;
470 return 0;
473 /* like GNU diff's --suppress-blank-empty option */
474 if (!strcmp(var, "diff.suppressblankempty") ||
475 /* for backwards compatibility */
476 !strcmp(var, "diff.suppress-blank-empty")) {
477 diff_suppress_blank_empty = git_config_bool(var, value);
478 return 0;
481 if (!strcmp(var, "diff.dirstat")) {
482 struct strbuf errmsg = STRBUF_INIT;
483 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
484 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
485 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
486 errmsg.buf);
487 strbuf_release(&errmsg);
488 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
489 return 0;
492 if (git_diff_heuristic_config(var, value, cb) < 0)
493 return -1;
495 return git_default_config(var, value, cb);
498 static char *quote_two(const char *one, const char *two)
500 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
501 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
502 struct strbuf res = STRBUF_INIT;
504 if (need_one + need_two) {
505 strbuf_addch(&res, '"');
506 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
507 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
508 strbuf_addch(&res, '"');
509 } else {
510 strbuf_addstr(&res, one);
511 strbuf_addstr(&res, two);
513 return strbuf_detach(&res, NULL);
516 static const char *external_diff(void)
518 static const char *external_diff_cmd = NULL;
519 static int done_preparing = 0;
521 if (done_preparing)
522 return external_diff_cmd;
523 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
524 if (!external_diff_cmd)
525 external_diff_cmd = external_diff_cmd_cfg;
526 done_preparing = 1;
527 return external_diff_cmd;
531 * Keep track of files used for diffing. Sometimes such an entry
532 * refers to a temporary file, sometimes to an existing file, and
533 * sometimes to "/dev/null".
535 static struct diff_tempfile {
537 * filename external diff should read from, or NULL if this
538 * entry is currently not in use:
540 const char *name;
542 char hex[GIT_MAX_HEXSZ + 1];
543 char mode[10];
546 * If this diff_tempfile instance refers to a temporary file,
547 * this tempfile object is used to manage its lifetime.
549 struct tempfile *tempfile;
550 } diff_temp[2];
552 struct emit_callback {
553 int color_diff;
554 unsigned ws_rule;
555 int blank_at_eof_in_preimage;
556 int blank_at_eof_in_postimage;
557 int lno_in_preimage;
558 int lno_in_postimage;
559 const char **label_path;
560 struct diff_words_data *diff_words;
561 struct diff_options *opt;
562 struct strbuf *header;
565 static int count_lines(const char *data, int size)
567 int count, ch, completely_empty = 1, nl_just_seen = 0;
568 count = 0;
569 while (0 < size--) {
570 ch = *data++;
571 if (ch == '\n') {
572 count++;
573 nl_just_seen = 1;
574 completely_empty = 0;
576 else {
577 nl_just_seen = 0;
578 completely_empty = 0;
581 if (completely_empty)
582 return 0;
583 if (!nl_just_seen)
584 count++; /* no trailing newline */
585 return count;
588 static int fill_mmfile(struct repository *r, mmfile_t *mf,
589 struct diff_filespec *one)
591 if (!DIFF_FILE_VALID(one)) {
592 mf->ptr = (char *)""; /* does not matter */
593 mf->size = 0;
594 return 0;
596 else if (diff_populate_filespec(r, one, NULL))
597 return -1;
599 mf->ptr = one->data;
600 mf->size = one->size;
601 return 0;
604 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
605 static unsigned long diff_filespec_size(struct repository *r,
606 struct diff_filespec *one)
608 struct diff_populate_filespec_options dpf_options = {
609 .check_size_only = 1,
612 if (!DIFF_FILE_VALID(one))
613 return 0;
614 diff_populate_filespec(r, one, &dpf_options);
615 return one->size;
618 static int count_trailing_blank(mmfile_t *mf)
620 char *ptr = mf->ptr;
621 long size = mf->size;
622 int cnt = 0;
624 if (!size)
625 return cnt;
626 ptr += size - 1; /* pointing at the very end */
627 if (*ptr != '\n')
628 ; /* incomplete line */
629 else
630 ptr--; /* skip the last LF */
631 while (mf->ptr < ptr) {
632 char *prev_eol;
633 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
634 if (*prev_eol == '\n')
635 break;
636 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
637 break;
638 cnt++;
639 ptr = prev_eol - 1;
641 return cnt;
644 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
645 struct emit_callback *ecbdata)
647 int l1, l2, at;
648 l1 = count_trailing_blank(mf1);
649 l2 = count_trailing_blank(mf2);
650 if (l2 <= l1) {
651 ecbdata->blank_at_eof_in_preimage = 0;
652 ecbdata->blank_at_eof_in_postimage = 0;
653 return;
655 at = count_lines(mf1->ptr, mf1->size);
656 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
658 at = count_lines(mf2->ptr, mf2->size);
659 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
662 static void emit_line_0(struct diff_options *o,
663 const char *set_sign, const char *set, unsigned reverse, const char *reset,
664 int first, const char *line, int len)
666 int has_trailing_newline, has_trailing_carriage_return;
667 int needs_reset = 0; /* at the end of the line */
668 FILE *file = o->file;
670 fputs(diff_line_prefix(o), file);
672 has_trailing_newline = (len > 0 && line[len-1] == '\n');
673 if (has_trailing_newline)
674 len--;
676 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
677 if (has_trailing_carriage_return)
678 len--;
680 if (!len && !first)
681 goto end_of_line;
683 if (reverse && want_color(o->use_color)) {
684 fputs(GIT_COLOR_REVERSE, file);
685 needs_reset = 1;
688 if (set_sign) {
689 fputs(set_sign, file);
690 needs_reset = 1;
693 if (first)
694 fputc(first, file);
696 if (!len)
697 goto end_of_line;
699 if (set) {
700 if (set_sign && set != set_sign)
701 fputs(reset, file);
702 fputs(set, file);
703 needs_reset = 1;
705 fwrite(line, len, 1, file);
706 needs_reset = 1; /* 'line' may contain color codes. */
708 end_of_line:
709 if (needs_reset)
710 fputs(reset, file);
711 if (has_trailing_carriage_return)
712 fputc('\r', file);
713 if (has_trailing_newline)
714 fputc('\n', file);
717 static void emit_line(struct diff_options *o, const char *set, const char *reset,
718 const char *line, int len)
720 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
723 enum diff_symbol {
724 DIFF_SYMBOL_BINARY_DIFF_HEADER,
725 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
726 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
727 DIFF_SYMBOL_BINARY_DIFF_BODY,
728 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
729 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
730 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
731 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
732 DIFF_SYMBOL_STATS_LINE,
733 DIFF_SYMBOL_WORD_DIFF,
734 DIFF_SYMBOL_STAT_SEP,
735 DIFF_SYMBOL_SUMMARY,
736 DIFF_SYMBOL_SUBMODULE_ADD,
737 DIFF_SYMBOL_SUBMODULE_DEL,
738 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
739 DIFF_SYMBOL_SUBMODULE_MODIFIED,
740 DIFF_SYMBOL_SUBMODULE_HEADER,
741 DIFF_SYMBOL_SUBMODULE_ERROR,
742 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
743 DIFF_SYMBOL_REWRITE_DIFF,
744 DIFF_SYMBOL_BINARY_FILES,
745 DIFF_SYMBOL_HEADER,
746 DIFF_SYMBOL_FILEPAIR_PLUS,
747 DIFF_SYMBOL_FILEPAIR_MINUS,
748 DIFF_SYMBOL_WORDS_PORCELAIN,
749 DIFF_SYMBOL_WORDS,
750 DIFF_SYMBOL_CONTEXT,
751 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
752 DIFF_SYMBOL_PLUS,
753 DIFF_SYMBOL_MINUS,
754 DIFF_SYMBOL_NO_LF_EOF,
755 DIFF_SYMBOL_CONTEXT_FRAGINFO,
756 DIFF_SYMBOL_CONTEXT_MARKER,
757 DIFF_SYMBOL_SEPARATOR
760 * Flags for content lines:
761 * 0..12 are whitespace rules
762 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
763 * 16 is marking if the line is blank at EOF
765 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
766 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
767 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
768 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
769 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
772 * This struct is used when we need to buffer the output of the diff output.
774 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
775 * into the pre/post image file. This pointer could be a union with the
776 * line pointer. By storing an offset into the file instead of the literal line,
777 * we can decrease the memory footprint for the buffered output. At first we
778 * may want to only have indirection for the content lines, but we could also
779 * enhance the state for emitting prefabricated lines, e.g. the similarity
780 * score line or hunk/file headers would only need to store a number or path
781 * and then the output can be constructed later on depending on state.
783 struct emitted_diff_symbol {
784 const char *line;
785 int len;
786 int flags;
787 int indent_off; /* Offset to first non-whitespace character */
788 int indent_width; /* The visual width of the indentation */
789 unsigned id;
790 enum diff_symbol s;
792 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
794 struct emitted_diff_symbols {
795 struct emitted_diff_symbol *buf;
796 int nr, alloc;
798 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
800 static void append_emitted_diff_symbol(struct diff_options *o,
801 struct emitted_diff_symbol *e)
803 struct emitted_diff_symbol *f;
805 ALLOC_GROW(o->emitted_symbols->buf,
806 o->emitted_symbols->nr + 1,
807 o->emitted_symbols->alloc);
808 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
810 memcpy(f, e, sizeof(struct emitted_diff_symbol));
811 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
814 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
816 if (!e)
817 return;
818 free(e->buf);
819 free(e);
822 struct moved_entry {
823 const struct emitted_diff_symbol *es;
824 struct moved_entry *next_line;
825 struct moved_entry *next_match;
828 struct moved_block {
829 struct moved_entry *match;
830 int wsd; /* The whitespace delta of this block */
833 #define INDENT_BLANKLINE INT_MIN
835 static void fill_es_indent_data(struct emitted_diff_symbol *es)
837 unsigned int off = 0, i;
838 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
839 const char *s = es->line;
840 const int len = es->len;
842 /* skip any \v \f \r at start of indentation */
843 while (s[off] == '\f' || s[off] == '\v' ||
844 (s[off] == '\r' && off < len - 1))
845 off++;
847 /* calculate the visual width of indentation */
848 while(1) {
849 if (s[off] == ' ') {
850 width++;
851 off++;
852 } else if (s[off] == '\t') {
853 width += tab_width - (width % tab_width);
854 while (s[++off] == '\t')
855 width += tab_width;
856 } else {
857 break;
861 /* check if this line is blank */
862 for (i = off; i < len; i++)
863 if (!isspace(s[i]))
864 break;
866 if (i == len) {
867 es->indent_width = INDENT_BLANKLINE;
868 es->indent_off = len;
869 } else {
870 es->indent_off = off;
871 es->indent_width = width;
875 static int compute_ws_delta(const struct emitted_diff_symbol *a,
876 const struct emitted_diff_symbol *b)
878 int a_width = a->indent_width,
879 b_width = b->indent_width;
881 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
882 return INDENT_BLANKLINE;
884 return a_width - b_width;
887 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
888 const struct emitted_diff_symbol *l,
889 struct moved_block *pmb)
891 int a_width = cur->es->indent_width, b_width = l->indent_width;
892 int delta;
894 /* The text of each line must match */
895 if (cur->es->id != l->id)
896 return 1;
899 * If 'l' and 'cur' are both blank then we don't need to check the
900 * indent. We only need to check cur as we know the strings match.
901 * */
902 if (a_width == INDENT_BLANKLINE)
903 return 0;
906 * The indent changes of the block are known and stored in pmb->wsd;
907 * however we need to check if the indent changes of the current line
908 * match those of the current block.
910 delta = b_width - a_width;
913 * If the previous lines of this block were all blank then set its
914 * whitespace delta.
916 if (pmb->wsd == INDENT_BLANKLINE)
917 pmb->wsd = delta;
919 return delta != pmb->wsd;
922 struct interned_diff_symbol {
923 struct hashmap_entry ent;
924 struct emitted_diff_symbol *es;
927 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
928 const struct hashmap_entry *eptr,
929 const struct hashmap_entry *entry_or_key,
930 const void *keydata UNUSED)
932 const struct diff_options *diffopt = hashmap_cmp_fn_data;
933 const struct emitted_diff_symbol *a, *b;
934 unsigned flags = diffopt->color_moved_ws_handling
935 & XDF_WHITESPACE_FLAGS;
937 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
938 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
940 return !xdiff_compare_lines(a->line + a->indent_off,
941 a->len - a->indent_off,
942 b->line + b->indent_off,
943 b->len - b->indent_off, flags);
946 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
947 struct interned_diff_symbol *s)
949 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
950 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
951 l->len - l->indent_off, flags);
953 hashmap_entry_init(&s->ent, hash);
954 s->es = l;
957 struct moved_entry_list {
958 struct moved_entry *add, *del;
961 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
962 struct mem_pool *entry_mem_pool)
964 struct moved_entry *prev_line = NULL;
965 struct mem_pool interned_pool;
966 struct hashmap interned_map;
967 struct moved_entry_list *entry_list = NULL;
968 size_t entry_list_alloc = 0;
969 unsigned id = 0;
970 int n;
972 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
973 mem_pool_init(&interned_pool, 1024 * 1024);
975 for (n = 0; n < o->emitted_symbols->nr; n++) {
976 struct interned_diff_symbol key;
977 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
978 struct interned_diff_symbol *s;
979 struct moved_entry *entry;
981 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
982 prev_line = NULL;
983 continue;
986 if (o->color_moved_ws_handling &
987 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
988 fill_es_indent_data(l);
990 prepare_entry(o, l, &key);
991 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
992 if (s) {
993 l->id = s->es->id;
994 } else {
995 l->id = id;
996 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
997 hashmap_add(&interned_map,
998 memcpy(mem_pool_alloc(&interned_pool,
999 sizeof(key)),
1000 &key, sizeof(key)));
1002 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1003 entry->es = l;
1004 entry->next_line = NULL;
1005 if (prev_line && prev_line->es->s == l->s)
1006 prev_line->next_line = entry;
1007 prev_line = entry;
1008 if (l->s == DIFF_SYMBOL_PLUS) {
1009 entry->next_match = entry_list[l->id].add;
1010 entry_list[l->id].add = entry;
1011 } else {
1012 entry->next_match = entry_list[l->id].del;
1013 entry_list[l->id].del = entry;
1017 hashmap_clear(&interned_map);
1018 mem_pool_discard(&interned_pool, 0);
1020 return entry_list;
1023 static void pmb_advance_or_null(struct diff_options *o,
1024 struct emitted_diff_symbol *l,
1025 struct moved_block *pmb,
1026 int *pmb_nr)
1028 int i, j;
1030 for (i = 0, j = 0; i < *pmb_nr; i++) {
1031 int match;
1032 struct moved_entry *prev = pmb[i].match;
1033 struct moved_entry *cur = (prev && prev->next_line) ?
1034 prev->next_line : NULL;
1036 if (o->color_moved_ws_handling &
1037 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1038 match = cur &&
1039 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1040 else
1041 match = cur && cur->es->id == l->id;
1043 if (match) {
1044 pmb[j] = pmb[i];
1045 pmb[j++].match = cur;
1048 *pmb_nr = j;
1051 static void fill_potential_moved_blocks(struct diff_options *o,
1052 struct moved_entry *match,
1053 struct emitted_diff_symbol *l,
1054 struct moved_block **pmb_p,
1055 int *pmb_alloc_p, int *pmb_nr_p)
1058 struct moved_block *pmb = *pmb_p;
1059 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1062 * The current line is the start of a new block.
1063 * Setup the set of potential blocks.
1065 for (; match; match = match->next_match) {
1066 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1067 if (o->color_moved_ws_handling &
1068 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1069 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1070 else
1071 pmb[pmb_nr].wsd = 0;
1072 pmb[pmb_nr++].match = match;
1075 *pmb_p = pmb;
1076 *pmb_alloc_p = pmb_alloc;
1077 *pmb_nr_p = pmb_nr;
1081 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1083 * Otherwise, if the last block has fewer alphanumeric characters than
1084 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1085 * that block.
1087 * The last block consists of the (n - block_length)'th line up to but not
1088 * including the nth line.
1090 * Returns 0 if the last block is empty or is unset by this function, non zero
1091 * otherwise.
1093 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1094 * Think of a way to unify them.
1096 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1097 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1098 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1100 int i, alnum_count = 0;
1101 if (o->color_moved == COLOR_MOVED_PLAIN)
1102 return block_length;
1103 for (i = 1; i < block_length + 1; i++) {
1104 const char *c = o->emitted_symbols->buf[n - i].line;
1105 for (; *c; c++) {
1106 if (!isalnum(*c))
1107 continue;
1108 alnum_count++;
1109 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1110 return 1;
1113 for (i = 1; i < block_length + 1; i++)
1114 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1115 return 0;
1118 /* Find blocks of moved code, delegate actual coloring decision to helper */
1119 static void mark_color_as_moved(struct diff_options *o,
1120 struct moved_entry_list *entry_list)
1122 struct moved_block *pmb = NULL; /* potentially moved blocks */
1123 int pmb_nr = 0, pmb_alloc = 0;
1124 int n, flipped_block = 0, block_length = 0;
1125 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1128 for (n = 0; n < o->emitted_symbols->nr; n++) {
1129 struct moved_entry *match = NULL;
1130 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1132 switch (l->s) {
1133 case DIFF_SYMBOL_PLUS:
1134 match = entry_list[l->id].del;
1135 break;
1136 case DIFF_SYMBOL_MINUS:
1137 match = entry_list[l->id].add;
1138 break;
1139 default:
1140 flipped_block = 0;
1143 if (pmb_nr && (!match || l->s != moved_symbol)) {
1144 if (!adjust_last_block(o, n, block_length) &&
1145 block_length > 1) {
1147 * Rewind in case there is another match
1148 * starting at the second line of the block
1150 match = NULL;
1151 n -= block_length;
1153 pmb_nr = 0;
1154 block_length = 0;
1155 flipped_block = 0;
1157 if (!match) {
1158 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1159 continue;
1162 if (o->color_moved == COLOR_MOVED_PLAIN) {
1163 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1164 continue;
1167 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1169 if (pmb_nr == 0) {
1170 int contiguous = adjust_last_block(o, n, block_length);
1172 if (!contiguous && block_length > 1)
1174 * Rewind in case there is another match
1175 * starting at the second line of the block
1177 n -= block_length;
1178 else
1179 fill_potential_moved_blocks(o, match, l,
1180 &pmb, &pmb_alloc,
1181 &pmb_nr);
1183 if (contiguous && pmb_nr && moved_symbol == l->s)
1184 flipped_block = (flipped_block + 1) % 2;
1185 else
1186 flipped_block = 0;
1188 if (pmb_nr)
1189 moved_symbol = l->s;
1190 else
1191 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1193 block_length = 0;
1196 if (pmb_nr) {
1197 block_length++;
1198 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1199 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1200 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1203 adjust_last_block(o, n, block_length);
1205 free(pmb);
1208 static void dim_moved_lines(struct diff_options *o)
1210 int n;
1211 for (n = 0; n < o->emitted_symbols->nr; n++) {
1212 struct emitted_diff_symbol *prev = (n != 0) ?
1213 &o->emitted_symbols->buf[n - 1] : NULL;
1214 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1215 struct emitted_diff_symbol *next =
1216 (n < o->emitted_symbols->nr - 1) ?
1217 &o->emitted_symbols->buf[n + 1] : NULL;
1219 /* Not a plus or minus line? */
1220 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1221 continue;
1223 /* Not a moved line? */
1224 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1225 continue;
1228 * If prev or next are not a plus or minus line,
1229 * pretend they don't exist
1231 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1232 prev->s != DIFF_SYMBOL_MINUS)
1233 prev = NULL;
1234 if (next && next->s != DIFF_SYMBOL_PLUS &&
1235 next->s != DIFF_SYMBOL_MINUS)
1236 next = NULL;
1238 /* Inside a block? */
1239 if ((prev &&
1240 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1241 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1242 (next &&
1243 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1244 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1245 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1246 continue;
1249 /* Check if we are at an interesting bound: */
1250 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1251 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1252 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1253 continue;
1254 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1255 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1256 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1257 continue;
1260 * The boundary to prev and next are not interesting,
1261 * so this line is not interesting as a whole
1263 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1267 static void emit_line_ws_markup(struct diff_options *o,
1268 const char *set_sign, const char *set,
1269 const char *reset,
1270 int sign_index, const char *line, int len,
1271 unsigned ws_rule, int blank_at_eof)
1273 const char *ws = NULL;
1274 int sign = o->output_indicators[sign_index];
1276 if (o->ws_error_highlight & ws_rule) {
1277 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1278 if (!*ws)
1279 ws = NULL;
1282 if (!ws && !set_sign)
1283 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1284 else if (!ws) {
1285 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1286 } else if (blank_at_eof)
1287 /* Blank line at EOF - paint '+' as well */
1288 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1289 else {
1290 /* Emit just the prefix, then the rest. */
1291 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1292 sign, "", 0);
1293 ws_check_emit(line, len, ws_rule,
1294 o->file, set, reset, ws);
1298 static void emit_diff_symbol_from_struct(struct diff_options *o,
1299 struct emitted_diff_symbol *eds)
1301 static const char *nneof = " No newline at end of file\n";
1302 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1304 enum diff_symbol s = eds->s;
1305 const char *line = eds->line;
1306 int len = eds->len;
1307 unsigned flags = eds->flags;
1309 switch (s) {
1310 case DIFF_SYMBOL_NO_LF_EOF:
1311 context = diff_get_color_opt(o, DIFF_CONTEXT);
1312 reset = diff_get_color_opt(o, DIFF_RESET);
1313 putc('\n', o->file);
1314 emit_line_0(o, context, NULL, 0, reset, '\\',
1315 nneof, strlen(nneof));
1316 break;
1317 case DIFF_SYMBOL_SUBMODULE_HEADER:
1318 case DIFF_SYMBOL_SUBMODULE_ERROR:
1319 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1320 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1321 case DIFF_SYMBOL_SUMMARY:
1322 case DIFF_SYMBOL_STATS_LINE:
1323 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1324 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1325 emit_line(o, "", "", line, len);
1326 break;
1327 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1328 case DIFF_SYMBOL_CONTEXT_MARKER:
1329 context = diff_get_color_opt(o, DIFF_CONTEXT);
1330 reset = diff_get_color_opt(o, DIFF_RESET);
1331 emit_line(o, context, reset, line, len);
1332 break;
1333 case DIFF_SYMBOL_SEPARATOR:
1334 fprintf(o->file, "%s%c",
1335 diff_line_prefix(o),
1336 o->line_termination);
1337 break;
1338 case DIFF_SYMBOL_CONTEXT:
1339 set = diff_get_color_opt(o, DIFF_CONTEXT);
1340 reset = diff_get_color_opt(o, DIFF_RESET);
1341 set_sign = NULL;
1342 if (o->flags.dual_color_diffed_diffs) {
1343 char c = !len ? 0 : line[0];
1345 if (c == '+')
1346 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1347 else if (c == '@')
1348 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1349 else if (c == '-')
1350 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1352 emit_line_ws_markup(o, set_sign, set, reset,
1353 OUTPUT_INDICATOR_CONTEXT, line, len,
1354 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1355 break;
1356 case DIFF_SYMBOL_PLUS:
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_NEW_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_NEW_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_NEW_MOVED_DIM);
1372 break;
1373 case DIFF_SYMBOL_MOVED_LINE:
1374 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1375 break;
1376 default:
1377 set = diff_get_color_opt(o, DIFF_FILE_NEW);
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_OLD_BOLD);
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_NEW_BOLD);
1392 else
1393 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1394 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1396 emit_line_ws_markup(o, set_sign, set, reset,
1397 OUTPUT_INDICATOR_NEW, line, len,
1398 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1399 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1400 break;
1401 case DIFF_SYMBOL_MINUS:
1402 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1403 DIFF_SYMBOL_MOVED_LINE_ALT |
1404 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1405 case DIFF_SYMBOL_MOVED_LINE |
1406 DIFF_SYMBOL_MOVED_LINE_ALT |
1407 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1408 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1409 break;
1410 case DIFF_SYMBOL_MOVED_LINE |
1411 DIFF_SYMBOL_MOVED_LINE_ALT:
1412 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1413 break;
1414 case DIFF_SYMBOL_MOVED_LINE |
1415 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1416 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1417 break;
1418 case DIFF_SYMBOL_MOVED_LINE:
1419 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1420 break;
1421 default:
1422 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1424 reset = diff_get_color_opt(o, DIFF_RESET);
1425 if (!o->flags.dual_color_diffed_diffs)
1426 set_sign = NULL;
1427 else {
1428 char c = !len ? 0 : line[0];
1430 set_sign = set;
1431 if (c == '+')
1432 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1433 else if (c == '@')
1434 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1435 else if (c == '-')
1436 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1437 else
1438 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1440 emit_line_ws_markup(o, set_sign, set, reset,
1441 OUTPUT_INDICATOR_OLD, line, len,
1442 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1443 break;
1444 case DIFF_SYMBOL_WORDS_PORCELAIN:
1445 context = diff_get_color_opt(o, DIFF_CONTEXT);
1446 reset = diff_get_color_opt(o, DIFF_RESET);
1447 emit_line(o, context, reset, line, len);
1448 fputs("~\n", o->file);
1449 break;
1450 case DIFF_SYMBOL_WORDS:
1451 context = diff_get_color_opt(o, DIFF_CONTEXT);
1452 reset = diff_get_color_opt(o, DIFF_RESET);
1454 * Skip the prefix character, if any. With
1455 * diff_suppress_blank_empty, there may be
1456 * none.
1458 if (line[0] != '\n') {
1459 line++;
1460 len--;
1462 emit_line(o, context, reset, line, len);
1463 break;
1464 case DIFF_SYMBOL_FILEPAIR_PLUS:
1465 meta = diff_get_color_opt(o, DIFF_METAINFO);
1466 reset = diff_get_color_opt(o, DIFF_RESET);
1467 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1468 line, reset,
1469 strchr(line, ' ') ? "\t" : "");
1470 break;
1471 case DIFF_SYMBOL_FILEPAIR_MINUS:
1472 meta = diff_get_color_opt(o, DIFF_METAINFO);
1473 reset = diff_get_color_opt(o, DIFF_RESET);
1474 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1475 line, reset,
1476 strchr(line, ' ') ? "\t" : "");
1477 break;
1478 case DIFF_SYMBOL_BINARY_FILES:
1479 case DIFF_SYMBOL_HEADER:
1480 fprintf(o->file, "%s", line);
1481 break;
1482 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1483 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1484 break;
1485 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1486 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1487 break;
1488 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1489 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1490 break;
1491 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1492 fputs(diff_line_prefix(o), o->file);
1493 fputc('\n', o->file);
1494 break;
1495 case DIFF_SYMBOL_REWRITE_DIFF:
1496 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1497 reset = diff_get_color_opt(o, DIFF_RESET);
1498 emit_line(o, fraginfo, reset, line, len);
1499 break;
1500 case DIFF_SYMBOL_SUBMODULE_ADD:
1501 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1502 reset = diff_get_color_opt(o, DIFF_RESET);
1503 emit_line(o, set, reset, line, len);
1504 break;
1505 case DIFF_SYMBOL_SUBMODULE_DEL:
1506 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1507 reset = diff_get_color_opt(o, DIFF_RESET);
1508 emit_line(o, set, reset, line, len);
1509 break;
1510 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1511 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1512 diff_line_prefix(o), line);
1513 break;
1514 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1515 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1516 diff_line_prefix(o), line);
1517 break;
1518 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1519 emit_line(o, "", "", " 0 files changed\n",
1520 strlen(" 0 files changed\n"));
1521 break;
1522 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1523 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1524 break;
1525 case DIFF_SYMBOL_WORD_DIFF:
1526 fprintf(o->file, "%.*s", len, line);
1527 break;
1528 case DIFF_SYMBOL_STAT_SEP:
1529 fputs(o->stat_sep, o->file);
1530 break;
1531 default:
1532 BUG("unknown diff symbol");
1536 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1537 const char *line, int len, unsigned flags)
1539 struct emitted_diff_symbol e = {
1540 .line = line, .len = len, .flags = flags, .s = s
1543 if (o->emitted_symbols)
1544 append_emitted_diff_symbol(o, &e);
1545 else
1546 emit_diff_symbol_from_struct(o, &e);
1549 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1551 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1554 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1556 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1559 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1561 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1562 path, strlen(path), 0);
1565 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1567 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1568 path, strlen(path), 0);
1571 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1573 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1574 header, strlen(header), 0);
1577 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1579 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1582 void diff_emit_submodule_pipethrough(struct diff_options *o,
1583 const char *line, int len)
1585 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1588 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1590 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1591 ecbdata->blank_at_eof_in_preimage &&
1592 ecbdata->blank_at_eof_in_postimage &&
1593 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1594 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1595 return 0;
1596 return ws_blank_line(line, len);
1599 static void emit_add_line(struct emit_callback *ecbdata,
1600 const char *line, int len)
1602 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1603 if (new_blank_line_at_eof(ecbdata, line, len))
1604 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1606 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1609 static void emit_del_line(struct emit_callback *ecbdata,
1610 const char *line, int len)
1612 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1613 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1616 static void emit_context_line(struct emit_callback *ecbdata,
1617 const char *line, int len)
1619 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1620 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1623 static void emit_hunk_header(struct emit_callback *ecbdata,
1624 const char *line, int len)
1626 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1627 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1628 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1629 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1630 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1631 static const char atat[2] = { '@', '@' };
1632 const char *cp, *ep;
1633 struct strbuf msgbuf = STRBUF_INIT;
1634 int org_len = len;
1635 int i = 1;
1638 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1639 * it always is at least 10 bytes long.
1641 if (len < 10 ||
1642 memcmp(line, atat, 2) ||
1643 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1644 emit_diff_symbol(ecbdata->opt,
1645 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1646 return;
1648 ep += 2; /* skip over @@ */
1650 /* The hunk header in fraginfo color */
1651 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1652 strbuf_addstr(&msgbuf, reverse);
1653 strbuf_addstr(&msgbuf, frag);
1654 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1655 strbuf_add(&msgbuf, atat, sizeof(atat));
1656 else
1657 strbuf_add(&msgbuf, line, ep - line);
1658 strbuf_addstr(&msgbuf, reset);
1661 * trailing "\r\n"
1663 for ( ; i < 3; i++)
1664 if (line[len - i] == '\r' || line[len - i] == '\n')
1665 len--;
1667 /* blank before the func header */
1668 for (cp = ep; ep - line < len; ep++)
1669 if (*ep != ' ' && *ep != '\t')
1670 break;
1671 if (ep != cp) {
1672 strbuf_addstr(&msgbuf, context);
1673 strbuf_add(&msgbuf, cp, ep - cp);
1674 strbuf_addstr(&msgbuf, reset);
1677 if (ep < line + len) {
1678 strbuf_addstr(&msgbuf, func);
1679 strbuf_add(&msgbuf, ep, line + len - ep);
1680 strbuf_addstr(&msgbuf, reset);
1683 strbuf_add(&msgbuf, line + len, org_len - len);
1684 strbuf_complete_line(&msgbuf);
1685 emit_diff_symbol(ecbdata->opt,
1686 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1687 strbuf_release(&msgbuf);
1690 static struct diff_tempfile *claim_diff_tempfile(void)
1692 int i;
1693 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1694 if (!diff_temp[i].name)
1695 return diff_temp + i;
1696 BUG("diff is failing to clean up its tempfiles");
1699 static void remove_tempfile(void)
1701 int i;
1702 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1703 if (is_tempfile_active(diff_temp[i].tempfile))
1704 delete_tempfile(&diff_temp[i].tempfile);
1705 diff_temp[i].name = NULL;
1709 static void add_line_count(struct strbuf *out, int count)
1711 switch (count) {
1712 case 0:
1713 strbuf_addstr(out, "0,0");
1714 break;
1715 case 1:
1716 strbuf_addstr(out, "1");
1717 break;
1718 default:
1719 strbuf_addf(out, "1,%d", count);
1720 break;
1724 static void emit_rewrite_lines(struct emit_callback *ecb,
1725 int prefix, const char *data, int size)
1727 const char *endp = NULL;
1729 while (0 < size) {
1730 int len;
1732 endp = memchr(data, '\n', size);
1733 len = endp ? (endp - data + 1) : size;
1734 if (prefix != '+') {
1735 ecb->lno_in_preimage++;
1736 emit_del_line(ecb, data, len);
1737 } else {
1738 ecb->lno_in_postimage++;
1739 emit_add_line(ecb, data, len);
1741 size -= len;
1742 data += len;
1744 if (!endp)
1745 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1748 static void emit_rewrite_diff(const char *name_a,
1749 const char *name_b,
1750 struct diff_filespec *one,
1751 struct diff_filespec *two,
1752 struct userdiff_driver *textconv_one,
1753 struct userdiff_driver *textconv_two,
1754 struct diff_options *o)
1756 int lc_a, lc_b;
1757 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1758 const char *a_prefix, *b_prefix;
1759 char *data_one, *data_two;
1760 size_t size_one, size_two;
1761 struct emit_callback ecbdata;
1762 struct strbuf out = STRBUF_INIT;
1764 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1765 a_prefix = o->b_prefix;
1766 b_prefix = o->a_prefix;
1767 } else {
1768 a_prefix = o->a_prefix;
1769 b_prefix = o->b_prefix;
1772 name_a += (*name_a == '/');
1773 name_b += (*name_b == '/');
1775 strbuf_reset(&a_name);
1776 strbuf_reset(&b_name);
1777 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1778 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1780 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1781 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1783 memset(&ecbdata, 0, sizeof(ecbdata));
1784 ecbdata.color_diff = want_color(o->use_color);
1785 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1786 ecbdata.opt = o;
1787 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1788 mmfile_t mf1, mf2;
1789 mf1.ptr = (char *)data_one;
1790 mf2.ptr = (char *)data_two;
1791 mf1.size = size_one;
1792 mf2.size = size_two;
1793 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1795 ecbdata.lno_in_preimage = 1;
1796 ecbdata.lno_in_postimage = 1;
1798 lc_a = count_lines(data_one, size_one);
1799 lc_b = count_lines(data_two, size_two);
1801 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1802 a_name.buf, a_name.len, 0);
1803 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1804 b_name.buf, b_name.len, 0);
1806 strbuf_addstr(&out, "@@ -");
1807 if (!o->irreversible_delete)
1808 add_line_count(&out, lc_a);
1809 else
1810 strbuf_addstr(&out, "?,?");
1811 strbuf_addstr(&out, " +");
1812 add_line_count(&out, lc_b);
1813 strbuf_addstr(&out, " @@\n");
1814 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1815 strbuf_release(&out);
1817 if (lc_a && !o->irreversible_delete)
1818 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1819 if (lc_b)
1820 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1821 if (textconv_one)
1822 free((char *)data_one);
1823 if (textconv_two)
1824 free((char *)data_two);
1827 struct diff_words_buffer {
1828 mmfile_t text;
1829 unsigned long alloc;
1830 struct diff_words_orig {
1831 const char *begin, *end;
1832 } *orig;
1833 int orig_nr, orig_alloc;
1836 static void diff_words_append(char *line, unsigned long len,
1837 struct diff_words_buffer *buffer)
1839 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1840 line++;
1841 len--;
1842 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1843 buffer->text.size += len;
1844 buffer->text.ptr[buffer->text.size] = '\0';
1847 struct diff_words_style_elem {
1848 const char *prefix;
1849 const char *suffix;
1850 const char *color; /* NULL; filled in by the setup code if
1851 * color is enabled */
1854 struct diff_words_style {
1855 enum diff_words_type type;
1856 struct diff_words_style_elem new_word, old_word, ctx;
1857 const char *newline;
1860 static struct diff_words_style diff_words_styles[] = {
1861 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1862 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1863 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1866 struct diff_words_data {
1867 struct diff_words_buffer minus, plus;
1868 const char *current_plus;
1869 int last_minus;
1870 struct diff_options *opt;
1871 regex_t *word_regex;
1872 enum diff_words_type type;
1873 struct diff_words_style *style;
1876 static int fn_out_diff_words_write_helper(struct diff_options *o,
1877 struct diff_words_style_elem *st_el,
1878 const char *newline,
1879 size_t count, const char *buf)
1881 int print = 0;
1882 struct strbuf sb = STRBUF_INIT;
1884 while (count) {
1885 char *p = memchr(buf, '\n', count);
1886 if (print)
1887 strbuf_addstr(&sb, diff_line_prefix(o));
1889 if (p != buf) {
1890 const char *reset = st_el->color && *st_el->color ?
1891 GIT_COLOR_RESET : NULL;
1892 if (st_el->color && *st_el->color)
1893 strbuf_addstr(&sb, st_el->color);
1894 strbuf_addstr(&sb, st_el->prefix);
1895 strbuf_add(&sb, buf, p ? p - buf : count);
1896 strbuf_addstr(&sb, st_el->suffix);
1897 if (reset)
1898 strbuf_addstr(&sb, reset);
1900 if (!p)
1901 goto out;
1903 strbuf_addstr(&sb, newline);
1904 count -= p + 1 - buf;
1905 buf = p + 1;
1906 print = 1;
1907 if (count) {
1908 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1909 sb.buf, sb.len, 0);
1910 strbuf_reset(&sb);
1914 out:
1915 if (sb.len)
1916 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1917 sb.buf, sb.len, 0);
1918 strbuf_release(&sb);
1919 return 0;
1923 * '--color-words' algorithm can be described as:
1925 * 1. collect the minus/plus lines of a diff hunk, divided into
1926 * minus-lines and plus-lines;
1928 * 2. break both minus-lines and plus-lines into words and
1929 * place them into two mmfile_t with one word for each line;
1931 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1933 * And for the common parts of the both file, we output the plus side text.
1934 * diff_words->current_plus is used to trace the current position of the plus file
1935 * which printed. diff_words->last_minus is used to trace the last minus word
1936 * printed.
1938 * For '--graph' to work with '--color-words', we need to output the graph prefix
1939 * on each line of color words output. Generally, there are two conditions on
1940 * which we should output the prefix.
1942 * 1. diff_words->last_minus == 0 &&
1943 * diff_words->current_plus == diff_words->plus.text.ptr
1945 * that is: the plus text must start as a new line, and if there is no minus
1946 * word printed, a graph prefix must be printed.
1948 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1949 * *(diff_words->current_plus - 1) == '\n'
1951 * that is: a graph prefix must be printed following a '\n'
1953 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1955 if ((diff_words->last_minus == 0 &&
1956 diff_words->current_plus == diff_words->plus.text.ptr) ||
1957 (diff_words->current_plus > diff_words->plus.text.ptr &&
1958 *(diff_words->current_plus - 1) == '\n')) {
1959 return 1;
1960 } else {
1961 return 0;
1965 static void fn_out_diff_words_aux(void *priv,
1966 long minus_first, long minus_len,
1967 long plus_first, long plus_len,
1968 const char *func UNUSED, long funclen UNUSED)
1970 struct diff_words_data *diff_words = priv;
1971 struct diff_words_style *style = diff_words->style;
1972 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1973 struct diff_options *opt = diff_words->opt;
1974 const char *line_prefix;
1976 assert(opt);
1977 line_prefix = diff_line_prefix(opt);
1979 /* POSIX requires that first be decremented by one if len == 0... */
1980 if (minus_len) {
1981 minus_begin = diff_words->minus.orig[minus_first].begin;
1982 minus_end =
1983 diff_words->minus.orig[minus_first + minus_len - 1].end;
1984 } else
1985 minus_begin = minus_end =
1986 diff_words->minus.orig[minus_first].end;
1988 if (plus_len) {
1989 plus_begin = diff_words->plus.orig[plus_first].begin;
1990 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1991 } else
1992 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1994 if (color_words_output_graph_prefix(diff_words)) {
1995 fputs(line_prefix, diff_words->opt->file);
1997 if (diff_words->current_plus != plus_begin) {
1998 fn_out_diff_words_write_helper(diff_words->opt,
1999 &style->ctx, style->newline,
2000 plus_begin - diff_words->current_plus,
2001 diff_words->current_plus);
2003 if (minus_begin != minus_end) {
2004 fn_out_diff_words_write_helper(diff_words->opt,
2005 &style->old_word, style->newline,
2006 minus_end - minus_begin, minus_begin);
2008 if (plus_begin != plus_end) {
2009 fn_out_diff_words_write_helper(diff_words->opt,
2010 &style->new_word, style->newline,
2011 plus_end - plus_begin, plus_begin);
2014 diff_words->current_plus = plus_end;
2015 diff_words->last_minus = minus_first;
2018 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2019 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2020 int *begin, int *end)
2022 while (word_regex && *begin < buffer->size) {
2023 regmatch_t match[1];
2024 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2025 buffer->size - *begin, 1, match, 0)) {
2026 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2027 '\n', match[0].rm_eo - match[0].rm_so);
2028 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2029 *begin += match[0].rm_so;
2030 if (*begin == *end)
2031 (*begin)++;
2032 else
2033 return *begin > *end;
2034 } else {
2035 return -1;
2039 /* find the next word */
2040 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2041 (*begin)++;
2042 if (*begin >= buffer->size)
2043 return -1;
2045 /* find the end of the word */
2046 *end = *begin + 1;
2047 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2048 (*end)++;
2050 return 0;
2054 * This function splits the words in buffer->text, stores the list with
2055 * newline separator into out, and saves the offsets of the original words
2056 * in buffer->orig.
2058 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2059 regex_t *word_regex)
2061 int i, j;
2062 long alloc = 0;
2064 out->size = 0;
2065 out->ptr = NULL;
2067 /* fake an empty "0th" word */
2068 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2069 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2070 buffer->orig_nr = 1;
2072 for (i = 0; i < buffer->text.size; i++) {
2073 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2074 return;
2076 /* store original boundaries */
2077 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2078 buffer->orig_alloc);
2079 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2080 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2081 buffer->orig_nr++;
2083 /* store one word */
2084 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2085 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2086 out->ptr[out->size + j - i] = '\n';
2087 out->size += j - i + 1;
2089 i = j - 1;
2093 /* this executes the word diff on the accumulated buffers */
2094 static void diff_words_show(struct diff_words_data *diff_words)
2096 xpparam_t xpp;
2097 xdemitconf_t xecfg;
2098 mmfile_t minus, plus;
2099 struct diff_words_style *style = diff_words->style;
2101 struct diff_options *opt = diff_words->opt;
2102 const char *line_prefix;
2104 assert(opt);
2105 line_prefix = diff_line_prefix(opt);
2107 /* special case: only removal */
2108 if (!diff_words->plus.text.size) {
2109 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2110 line_prefix, strlen(line_prefix), 0);
2111 fn_out_diff_words_write_helper(diff_words->opt,
2112 &style->old_word, style->newline,
2113 diff_words->minus.text.size,
2114 diff_words->minus.text.ptr);
2115 diff_words->minus.text.size = 0;
2116 return;
2119 diff_words->current_plus = diff_words->plus.text.ptr;
2120 diff_words->last_minus = 0;
2122 memset(&xpp, 0, sizeof(xpp));
2123 memset(&xecfg, 0, sizeof(xecfg));
2124 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2125 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2126 xpp.flags = 0;
2127 /* as only the hunk header will be parsed, we need a 0-context */
2128 xecfg.ctxlen = 0;
2129 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2130 diff_words, &xpp, &xecfg))
2131 die("unable to generate word diff");
2132 free(minus.ptr);
2133 free(plus.ptr);
2134 if (diff_words->current_plus != diff_words->plus.text.ptr +
2135 diff_words->plus.text.size) {
2136 if (color_words_output_graph_prefix(diff_words))
2137 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2138 line_prefix, strlen(line_prefix), 0);
2139 fn_out_diff_words_write_helper(diff_words->opt,
2140 &style->ctx, style->newline,
2141 diff_words->plus.text.ptr + diff_words->plus.text.size
2142 - diff_words->current_plus, diff_words->current_plus);
2144 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2147 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2148 static void diff_words_flush(struct emit_callback *ecbdata)
2150 struct diff_options *wo = ecbdata->diff_words->opt;
2152 if (ecbdata->diff_words->minus.text.size ||
2153 ecbdata->diff_words->plus.text.size)
2154 diff_words_show(ecbdata->diff_words);
2156 if (wo->emitted_symbols) {
2157 struct diff_options *o = ecbdata->opt;
2158 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2159 int i;
2162 * NEEDSWORK:
2163 * Instead of appending each, concat all words to a line?
2165 for (i = 0; i < wol->nr; i++)
2166 append_emitted_diff_symbol(o, &wol->buf[i]);
2168 for (i = 0; i < wol->nr; i++)
2169 free((void *)wol->buf[i].line);
2171 wol->nr = 0;
2175 static void diff_filespec_load_driver(struct diff_filespec *one,
2176 struct index_state *istate)
2178 /* Use already-loaded driver */
2179 if (one->driver)
2180 return;
2182 if (S_ISREG(one->mode))
2183 one->driver = userdiff_find_by_path(istate, one->path);
2185 /* Fallback to default settings */
2186 if (!one->driver)
2187 one->driver = userdiff_find_by_name("default");
2190 static const char *userdiff_word_regex(struct diff_filespec *one,
2191 struct index_state *istate)
2193 diff_filespec_load_driver(one, istate);
2194 return one->driver->word_regex;
2197 static void init_diff_words_data(struct emit_callback *ecbdata,
2198 struct diff_options *orig_opts,
2199 struct diff_filespec *one,
2200 struct diff_filespec *two)
2202 int i;
2203 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2204 memcpy(o, orig_opts, sizeof(struct diff_options));
2206 CALLOC_ARRAY(ecbdata->diff_words, 1);
2207 ecbdata->diff_words->type = o->word_diff;
2208 ecbdata->diff_words->opt = o;
2210 if (orig_opts->emitted_symbols)
2211 CALLOC_ARRAY(o->emitted_symbols, 1);
2213 if (!o->word_regex)
2214 o->word_regex = userdiff_word_regex(one, o->repo->index);
2215 if (!o->word_regex)
2216 o->word_regex = userdiff_word_regex(two, o->repo->index);
2217 if (!o->word_regex)
2218 o->word_regex = diff_word_regex_cfg;
2219 if (o->word_regex) {
2220 ecbdata->diff_words->word_regex = (regex_t *)
2221 xmalloc(sizeof(regex_t));
2222 if (regcomp(ecbdata->diff_words->word_regex,
2223 o->word_regex,
2224 REG_EXTENDED | REG_NEWLINE))
2225 die("invalid regular expression: %s",
2226 o->word_regex);
2228 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2229 if (o->word_diff == diff_words_styles[i].type) {
2230 ecbdata->diff_words->style =
2231 &diff_words_styles[i];
2232 break;
2235 if (want_color(o->use_color)) {
2236 struct diff_words_style *st = ecbdata->diff_words->style;
2237 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2238 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2239 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2243 static void free_diff_words_data(struct emit_callback *ecbdata)
2245 if (ecbdata->diff_words) {
2246 diff_words_flush(ecbdata);
2247 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2248 free (ecbdata->diff_words->opt);
2249 free (ecbdata->diff_words->minus.text.ptr);
2250 free (ecbdata->diff_words->minus.orig);
2251 free (ecbdata->diff_words->plus.text.ptr);
2252 free (ecbdata->diff_words->plus.orig);
2253 if (ecbdata->diff_words->word_regex) {
2254 regfree(ecbdata->diff_words->word_regex);
2255 free(ecbdata->diff_words->word_regex);
2257 FREE_AND_NULL(ecbdata->diff_words);
2261 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2263 if (want_color(diff_use_color))
2264 return diff_colors[ix];
2265 return "";
2268 const char *diff_line_prefix(struct diff_options *opt)
2270 struct strbuf *msgbuf;
2271 if (!opt->output_prefix)
2272 return "";
2274 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2275 return msgbuf->buf;
2278 static unsigned long sane_truncate_line(char *line, unsigned long len)
2280 const char *cp;
2281 unsigned long allot;
2282 size_t l = len;
2284 cp = line;
2285 allot = l;
2286 while (0 < l) {
2287 (void) utf8_width(&cp, &l);
2288 if (!cp)
2289 break; /* truncated in the middle? */
2291 return allot - l;
2294 static void find_lno(const char *line, struct emit_callback *ecbdata)
2296 const char *p;
2297 ecbdata->lno_in_preimage = 0;
2298 ecbdata->lno_in_postimage = 0;
2299 p = strchr(line, '-');
2300 if (!p)
2301 return; /* cannot happen */
2302 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2303 p = strchr(p, '+');
2304 if (!p)
2305 return; /* cannot happen */
2306 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2309 static int fn_out_consume(void *priv, char *line, unsigned long len)
2311 struct emit_callback *ecbdata = priv;
2312 struct diff_options *o = ecbdata->opt;
2314 o->found_changes = 1;
2316 if (ecbdata->header) {
2317 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2318 ecbdata->header->buf, ecbdata->header->len, 0);
2319 strbuf_reset(ecbdata->header);
2320 ecbdata->header = NULL;
2323 if (ecbdata->label_path[0]) {
2324 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2325 ecbdata->label_path[0],
2326 strlen(ecbdata->label_path[0]), 0);
2327 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2328 ecbdata->label_path[1],
2329 strlen(ecbdata->label_path[1]), 0);
2330 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2333 if (diff_suppress_blank_empty
2334 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2335 line[0] = '\n';
2336 len = 1;
2339 if (line[0] == '@') {
2340 if (ecbdata->diff_words)
2341 diff_words_flush(ecbdata);
2342 len = sane_truncate_line(line, len);
2343 find_lno(line, ecbdata);
2344 emit_hunk_header(ecbdata, line, len);
2345 return 0;
2348 if (ecbdata->diff_words) {
2349 enum diff_symbol s =
2350 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2351 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2352 if (line[0] == '-') {
2353 diff_words_append(line, len,
2354 &ecbdata->diff_words->minus);
2355 return 0;
2356 } else if (line[0] == '+') {
2357 diff_words_append(line, len,
2358 &ecbdata->diff_words->plus);
2359 return 0;
2360 } else if (starts_with(line, "\\ ")) {
2362 * Eat the "no newline at eof" marker as if we
2363 * saw a "+" or "-" line with nothing on it,
2364 * and return without diff_words_flush() to
2365 * defer processing. If this is the end of
2366 * preimage, more "+" lines may come after it.
2368 return 0;
2370 diff_words_flush(ecbdata);
2371 emit_diff_symbol(o, s, line, len, 0);
2372 return 0;
2375 switch (line[0]) {
2376 case '+':
2377 ecbdata->lno_in_postimage++;
2378 emit_add_line(ecbdata, line + 1, len - 1);
2379 break;
2380 case '-':
2381 ecbdata->lno_in_preimage++;
2382 emit_del_line(ecbdata, line + 1, len - 1);
2383 break;
2384 case ' ':
2385 ecbdata->lno_in_postimage++;
2386 ecbdata->lno_in_preimage++;
2387 emit_context_line(ecbdata, line + 1, len - 1);
2388 break;
2389 default:
2390 /* incomplete line at the end */
2391 ecbdata->lno_in_preimage++;
2392 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2393 line, len, 0);
2394 break;
2396 return 0;
2399 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2401 const char *old_name = a;
2402 const char *new_name = b;
2403 int pfx_length, sfx_length;
2404 int pfx_adjust_for_slash;
2405 int len_a = strlen(a);
2406 int len_b = strlen(b);
2407 int a_midlen, b_midlen;
2408 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2409 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2411 if (qlen_a || qlen_b) {
2412 quote_c_style(a, name, NULL, 0);
2413 strbuf_addstr(name, " => ");
2414 quote_c_style(b, name, NULL, 0);
2415 return;
2418 /* Find common prefix */
2419 pfx_length = 0;
2420 while (*old_name && *new_name && *old_name == *new_name) {
2421 if (*old_name == '/')
2422 pfx_length = old_name - a + 1;
2423 old_name++;
2424 new_name++;
2427 /* Find common suffix */
2428 old_name = a + len_a;
2429 new_name = b + len_b;
2430 sfx_length = 0;
2432 * If there is a common prefix, it must end in a slash. In
2433 * that case we let this loop run 1 into the prefix to see the
2434 * same slash.
2436 * If there is no common prefix, we cannot do this as it would
2437 * underrun the input strings.
2439 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2440 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2441 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2442 *old_name == *new_name) {
2443 if (*old_name == '/')
2444 sfx_length = len_a - (old_name - a);
2445 old_name--;
2446 new_name--;
2450 * pfx{mid-a => mid-b}sfx
2451 * {pfx-a => pfx-b}sfx
2452 * pfx{sfx-a => sfx-b}
2453 * name-a => name-b
2455 a_midlen = len_a - pfx_length - sfx_length;
2456 b_midlen = len_b - pfx_length - sfx_length;
2457 if (a_midlen < 0)
2458 a_midlen = 0;
2459 if (b_midlen < 0)
2460 b_midlen = 0;
2462 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2463 if (pfx_length + sfx_length) {
2464 strbuf_add(name, a, pfx_length);
2465 strbuf_addch(name, '{');
2467 strbuf_add(name, a + pfx_length, a_midlen);
2468 strbuf_addstr(name, " => ");
2469 strbuf_add(name, b + pfx_length, b_midlen);
2470 if (pfx_length + sfx_length) {
2471 strbuf_addch(name, '}');
2472 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2476 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2477 const char *name_a,
2478 const char *name_b)
2480 struct diffstat_file *x;
2481 CALLOC_ARRAY(x, 1);
2482 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2483 diffstat->files[diffstat->nr++] = x;
2484 if (name_b) {
2485 x->from_name = xstrdup(name_a);
2486 x->name = xstrdup(name_b);
2487 x->is_renamed = 1;
2489 else {
2490 x->from_name = NULL;
2491 x->name = xstrdup(name_a);
2493 return x;
2496 static int diffstat_consume(void *priv, char *line, unsigned long len)
2498 struct diffstat_t *diffstat = priv;
2499 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2501 if (!len)
2502 BUG("xdiff fed us an empty line");
2504 if (line[0] == '+')
2505 x->added++;
2506 else if (line[0] == '-')
2507 x->deleted++;
2508 return 0;
2511 const char mime_boundary_leader[] = "------------";
2513 static int scale_linear(int it, int width, int max_change)
2515 if (!it)
2516 return 0;
2518 * make sure that at least one '-' or '+' is printed if
2519 * there is any change to this path. The easiest way is to
2520 * scale linearly as if the allotted width is one column shorter
2521 * than it is, and then add 1 to the result.
2523 return 1 + (it * (width - 1) / max_change);
2526 static void show_graph(struct strbuf *out, char ch, int cnt,
2527 const char *set, const char *reset)
2529 if (cnt <= 0)
2530 return;
2531 strbuf_addstr(out, set);
2532 strbuf_addchars(out, ch, cnt);
2533 strbuf_addstr(out, reset);
2536 static void fill_print_name(struct diffstat_file *file)
2538 struct strbuf pname = STRBUF_INIT;
2540 if (file->print_name)
2541 return;
2543 if (file->is_renamed)
2544 pprint_rename(&pname, file->from_name, file->name);
2545 else
2546 quote_c_style(file->name, &pname, NULL, 0);
2548 if (file->comments)
2549 strbuf_addf(&pname, " (%s)", file->comments);
2551 file->print_name = strbuf_detach(&pname, NULL);
2554 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2555 int files, int insertions, int deletions)
2557 struct strbuf sb = STRBUF_INIT;
2559 if (!files) {
2560 assert(insertions == 0 && deletions == 0);
2561 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2562 NULL, 0, 0);
2563 return;
2566 strbuf_addf(&sb,
2567 (files == 1) ? " %d file changed" : " %d files changed",
2568 files);
2571 * For binary diff, the caller may want to print "x files
2572 * changed" with insertions == 0 && deletions == 0.
2574 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2575 * is probably less confusing (i.e skip over "2 files changed
2576 * but nothing about added/removed lines? Is this a bug in Git?").
2578 if (insertions || deletions == 0) {
2579 strbuf_addf(&sb,
2580 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2581 insertions);
2584 if (deletions || insertions == 0) {
2585 strbuf_addf(&sb,
2586 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2587 deletions);
2589 strbuf_addch(&sb, '\n');
2590 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2591 sb.buf, sb.len, 0);
2592 strbuf_release(&sb);
2595 void print_stat_summary(FILE *fp, int files,
2596 int insertions, int deletions)
2598 struct diff_options o;
2599 memset(&o, 0, sizeof(o));
2600 o.file = fp;
2602 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2605 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2607 int i, len, add, del, adds = 0, dels = 0;
2608 uintmax_t max_change = 0, max_len = 0;
2609 int total_files = data->nr, count;
2610 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2611 const char *reset, *add_c, *del_c;
2612 int extra_shown = 0;
2613 const char *line_prefix = diff_line_prefix(options);
2614 struct strbuf out = STRBUF_INIT;
2616 if (data->nr == 0)
2617 return;
2619 count = options->stat_count ? options->stat_count : data->nr;
2621 reset = diff_get_color_opt(options, DIFF_RESET);
2622 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2623 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2626 * Find the longest filename and max number of changes
2628 for (i = 0; (i < count) && (i < data->nr); i++) {
2629 struct diffstat_file *file = data->files[i];
2630 uintmax_t change = file->added + file->deleted;
2632 if (!file->is_interesting && (change == 0)) {
2633 count++; /* not shown == room for one more */
2634 continue;
2636 fill_print_name(file);
2637 len = utf8_strwidth(file->print_name);
2638 if (max_len < len)
2639 max_len = len;
2641 if (file->is_unmerged) {
2642 /* "Unmerged" is 8 characters */
2643 bin_width = bin_width < 8 ? 8 : bin_width;
2644 continue;
2646 if (file->is_binary) {
2647 /* "Bin XXX -> YYY bytes" */
2648 int w = 14 + decimal_width(file->added)
2649 + decimal_width(file->deleted);
2650 bin_width = bin_width < w ? w : bin_width;
2651 /* Display change counts aligned with "Bin" */
2652 number_width = 3;
2653 continue;
2656 if (max_change < change)
2657 max_change = change;
2659 count = i; /* where we can stop scanning in data->files[] */
2662 * We have width = stat_width or term_columns() columns total.
2663 * We want a maximum of min(max_len, stat_name_width) for the name part.
2664 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2665 * We also need 1 for " " and 4 + decimal_width(max_change)
2666 * for " | NNNN " and one the empty column at the end, altogether
2667 * 6 + decimal_width(max_change).
2669 * If there's not enough space, we will use the smaller of
2670 * stat_name_width (if set) and 5/8*width for the filename,
2671 * and the rest for constant elements + graph part, but no more
2672 * than stat_graph_width for the graph part.
2673 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2674 * for the standard terminal size).
2676 * In other words: stat_width limits the maximum width, and
2677 * stat_name_width fixes the maximum width of the filename,
2678 * and is also used to divide available columns if there
2679 * aren't enough.
2681 * Binary files are displayed with "Bin XXX -> YYY bytes"
2682 * instead of the change count and graph. This part is treated
2683 * similarly to the graph part, except that it is not
2684 * "scaled". If total width is too small to accommodate the
2685 * guaranteed minimum width of the filename part and the
2686 * separators and this message, this message will "overflow"
2687 * making the line longer than the maximum width.
2691 * NEEDSWORK: line_prefix is often used for "log --graph" output
2692 * and contains ANSI-colored string. utf8_strnwidth() should be
2693 * used to correctly count the display width instead of strlen().
2695 if (options->stat_width == -1)
2696 width = term_columns() - strlen(line_prefix);
2697 else
2698 width = options->stat_width ? options->stat_width : 80;
2699 number_width = decimal_width(max_change) > number_width ?
2700 decimal_width(max_change) : number_width;
2702 if (options->stat_graph_width == -1)
2703 options->stat_graph_width = diff_stat_graph_width;
2706 * Guarantee 3/8*16==6 for the graph part
2707 * and 5/8*16==10 for the filename part
2709 if (width < 16 + 6 + number_width)
2710 width = 16 + 6 + number_width;
2713 * First assign sizes that are wanted, ignoring available width.
2714 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2715 * starting from "XXX" should fit in graph_width.
2717 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2718 if (options->stat_graph_width &&
2719 options->stat_graph_width < graph_width)
2720 graph_width = options->stat_graph_width;
2722 name_width = (options->stat_name_width > 0 &&
2723 options->stat_name_width < max_len) ?
2724 options->stat_name_width : max_len;
2727 * Adjust adjustable widths not to exceed maximum width
2729 if (name_width + number_width + 6 + graph_width > width) {
2730 if (graph_width > width * 3/8 - number_width - 6) {
2731 graph_width = width * 3/8 - number_width - 6;
2732 if (graph_width < 6)
2733 graph_width = 6;
2736 if (options->stat_graph_width &&
2737 graph_width > options->stat_graph_width)
2738 graph_width = options->stat_graph_width;
2739 if (name_width > width - number_width - 6 - graph_width)
2740 name_width = width - number_width - 6 - graph_width;
2741 else
2742 graph_width = width - number_width - 6 - name_width;
2746 * From here name_width is the width of the name area,
2747 * and graph_width is the width of the graph area.
2748 * max_change is used to scale graph properly.
2750 for (i = 0; i < count; i++) {
2751 const char *prefix = "";
2752 struct diffstat_file *file = data->files[i];
2753 char *name = file->print_name;
2754 uintmax_t added = file->added;
2755 uintmax_t deleted = file->deleted;
2756 int name_len, padding;
2758 if (!file->is_interesting && (added + deleted == 0))
2759 continue;
2762 * "scale" the filename
2764 len = name_width;
2765 name_len = utf8_strwidth(name);
2766 if (name_width < name_len) {
2767 char *slash;
2768 prefix = "...";
2769 len -= 3;
2771 * NEEDSWORK: (name_len - len) counts the display
2772 * width, which would be shorter than the byte
2773 * length of the corresponding substring.
2774 * Advancing "name" by that number of bytes does
2775 * *NOT* skip over that many columns, so it is
2776 * very likely that chomping the pathname at the
2777 * slash we will find starting from "name" will
2778 * leave the resulting string still too long.
2780 name += name_len - len;
2781 slash = strchr(name, '/');
2782 if (slash)
2783 name = slash;
2785 padding = len - utf8_strwidth(name);
2786 if (padding < 0)
2787 padding = 0;
2789 if (file->is_binary) {
2790 strbuf_addf(&out, " %s%s%*s | %*s",
2791 prefix, name, padding, "",
2792 number_width, "Bin");
2793 if (!added && !deleted) {
2794 strbuf_addch(&out, '\n');
2795 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2796 out.buf, out.len, 0);
2797 strbuf_reset(&out);
2798 continue;
2800 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2801 del_c, deleted, reset);
2802 strbuf_addstr(&out, " -> ");
2803 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2804 add_c, added, reset);
2805 strbuf_addstr(&out, " bytes\n");
2806 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2807 out.buf, out.len, 0);
2808 strbuf_reset(&out);
2809 continue;
2811 else if (file->is_unmerged) {
2812 strbuf_addf(&out, " %s%s%*s | %*s",
2813 prefix, name, padding, "",
2814 number_width, "Unmerged\n");
2815 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2816 out.buf, out.len, 0);
2817 strbuf_reset(&out);
2818 continue;
2822 * scale the add/delete
2824 add = added;
2825 del = deleted;
2827 if (graph_width <= max_change) {
2828 int total = scale_linear(add + del, graph_width, max_change);
2829 if (total < 2 && add && del)
2830 /* width >= 2 due to the sanity check */
2831 total = 2;
2832 if (add < del) {
2833 add = scale_linear(add, graph_width, max_change);
2834 del = total - add;
2835 } else {
2836 del = scale_linear(del, graph_width, max_change);
2837 add = total - del;
2840 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2841 prefix, name, padding, "",
2842 number_width, added + deleted,
2843 added + deleted ? " " : "");
2844 show_graph(&out, '+', add, add_c, reset);
2845 show_graph(&out, '-', del, del_c, reset);
2846 strbuf_addch(&out, '\n');
2847 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2848 out.buf, out.len, 0);
2849 strbuf_reset(&out);
2852 for (i = 0; i < data->nr; i++) {
2853 struct diffstat_file *file = data->files[i];
2854 uintmax_t added = file->added;
2855 uintmax_t deleted = file->deleted;
2857 if (file->is_unmerged ||
2858 (!file->is_interesting && (added + deleted == 0))) {
2859 total_files--;
2860 continue;
2863 if (!file->is_binary) {
2864 adds += added;
2865 dels += deleted;
2867 if (i < count)
2868 continue;
2869 if (!extra_shown)
2870 emit_diff_symbol(options,
2871 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2872 NULL, 0, 0);
2873 extra_shown = 1;
2876 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2877 strbuf_release(&out);
2880 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2882 int i, adds = 0, dels = 0, total_files = data->nr;
2884 if (data->nr == 0)
2885 return;
2887 for (i = 0; i < data->nr; i++) {
2888 int added = data->files[i]->added;
2889 int deleted = data->files[i]->deleted;
2891 if (data->files[i]->is_unmerged ||
2892 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2893 total_files--;
2894 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2895 adds += added;
2896 dels += deleted;
2899 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2902 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2904 int i;
2906 if (data->nr == 0)
2907 return;
2909 for (i = 0; i < data->nr; i++) {
2910 struct diffstat_file *file = data->files[i];
2912 fprintf(options->file, "%s", diff_line_prefix(options));
2914 if (file->is_binary)
2915 fprintf(options->file, "-\t-\t");
2916 else
2917 fprintf(options->file,
2918 "%"PRIuMAX"\t%"PRIuMAX"\t",
2919 file->added, file->deleted);
2920 if (options->line_termination) {
2921 fill_print_name(file);
2922 if (!file->is_renamed)
2923 write_name_quoted(file->name, options->file,
2924 options->line_termination);
2925 else {
2926 fputs(file->print_name, options->file);
2927 putc(options->line_termination, options->file);
2929 } else {
2930 if (file->is_renamed) {
2931 putc('\0', options->file);
2932 write_name_quoted(file->from_name, options->file, '\0');
2934 write_name_quoted(file->name, options->file, '\0');
2939 struct dirstat_file {
2940 const char *name;
2941 unsigned long changed;
2944 struct dirstat_dir {
2945 struct dirstat_file *files;
2946 int alloc, nr, permille, cumulative;
2949 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2950 unsigned long changed, const char *base, int baselen)
2952 unsigned long sum_changes = 0;
2953 unsigned int sources = 0;
2954 const char *line_prefix = diff_line_prefix(opt);
2956 while (dir->nr) {
2957 struct dirstat_file *f = dir->files;
2958 int namelen = strlen(f->name);
2959 unsigned long changes;
2960 char *slash;
2962 if (namelen < baselen)
2963 break;
2964 if (memcmp(f->name, base, baselen))
2965 break;
2966 slash = strchr(f->name + baselen, '/');
2967 if (slash) {
2968 int newbaselen = slash + 1 - f->name;
2969 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2970 sources++;
2971 } else {
2972 changes = f->changed;
2973 dir->files++;
2974 dir->nr--;
2975 sources += 2;
2977 sum_changes += changes;
2981 * We don't report dirstat's for
2982 * - the top level
2983 * - or cases where everything came from a single directory
2984 * under this directory (sources == 1).
2986 if (baselen && sources != 1) {
2987 if (sum_changes) {
2988 int permille = sum_changes * 1000 / changed;
2989 if (permille >= dir->permille) {
2990 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2991 permille / 10, permille % 10, baselen, base);
2992 if (!dir->cumulative)
2993 return 0;
2997 return sum_changes;
3000 static int dirstat_compare(const void *_a, const void *_b)
3002 const struct dirstat_file *a = _a;
3003 const struct dirstat_file *b = _b;
3004 return strcmp(a->name, b->name);
3007 static void show_dirstat(struct diff_options *options)
3009 int i;
3010 unsigned long changed;
3011 struct dirstat_dir dir;
3012 struct diff_queue_struct *q = &diff_queued_diff;
3014 dir.files = NULL;
3015 dir.alloc = 0;
3016 dir.nr = 0;
3017 dir.permille = options->dirstat_permille;
3018 dir.cumulative = options->flags.dirstat_cumulative;
3020 changed = 0;
3021 for (i = 0; i < q->nr; i++) {
3022 struct diff_filepair *p = q->queue[i];
3023 const char *name;
3024 unsigned long copied, added, damage;
3025 struct diff_populate_filespec_options dpf_options = {
3026 .check_size_only = 1,
3029 name = p->two->path ? p->two->path : p->one->path;
3031 if (p->one->oid_valid && p->two->oid_valid &&
3032 oideq(&p->one->oid, &p->two->oid)) {
3034 * The SHA1 has not changed, so pre-/post-content is
3035 * identical. We can therefore skip looking at the
3036 * file contents altogether.
3038 damage = 0;
3039 goto found_damage;
3042 if (options->flags.dirstat_by_file) {
3044 * In --dirstat-by-file mode, we don't really need to
3045 * look at the actual file contents at all.
3046 * The fact that the SHA1 changed is enough for us to
3047 * add this file to the list of results
3048 * (with each file contributing equal damage).
3050 damage = 1;
3051 goto found_damage;
3054 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3055 diff_populate_filespec(options->repo, p->one, NULL);
3056 diff_populate_filespec(options->repo, p->two, NULL);
3057 diffcore_count_changes(options->repo,
3058 p->one, p->two, NULL, NULL,
3059 &copied, &added);
3060 diff_free_filespec_data(p->one);
3061 diff_free_filespec_data(p->two);
3062 } else if (DIFF_FILE_VALID(p->one)) {
3063 diff_populate_filespec(options->repo, p->one, &dpf_options);
3064 copied = added = 0;
3065 diff_free_filespec_data(p->one);
3066 } else if (DIFF_FILE_VALID(p->two)) {
3067 diff_populate_filespec(options->repo, p->two, &dpf_options);
3068 copied = 0;
3069 added = p->two->size;
3070 diff_free_filespec_data(p->two);
3071 } else
3072 continue;
3075 * Original minus copied is the removed material,
3076 * added is the new material. They are both damages
3077 * made to the preimage.
3078 * If the resulting damage is zero, we know that
3079 * diffcore_count_changes() considers the two entries to
3080 * be identical, but since the oid changed, we
3081 * know that there must have been _some_ kind of change,
3082 * so we force all entries to have damage > 0.
3084 damage = (p->one->size - copied) + added;
3085 if (!damage)
3086 damage = 1;
3088 found_damage:
3089 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3090 dir.files[dir.nr].name = name;
3091 dir.files[dir.nr].changed = damage;
3092 changed += damage;
3093 dir.nr++;
3096 /* This can happen even with many files, if everything was renames */
3097 if (!changed)
3098 return;
3100 /* Show all directories with more than x% of the changes */
3101 QSORT(dir.files, dir.nr, dirstat_compare);
3102 gather_dirstat(options, &dir, changed, "", 0);
3105 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3107 int i;
3108 unsigned long changed;
3109 struct dirstat_dir dir;
3111 if (data->nr == 0)
3112 return;
3114 dir.files = NULL;
3115 dir.alloc = 0;
3116 dir.nr = 0;
3117 dir.permille = options->dirstat_permille;
3118 dir.cumulative = options->flags.dirstat_cumulative;
3120 changed = 0;
3121 for (i = 0; i < data->nr; i++) {
3122 struct diffstat_file *file = data->files[i];
3123 unsigned long damage = file->added + file->deleted;
3124 if (file->is_binary)
3126 * binary files counts bytes, not lines. Must find some
3127 * way to normalize binary bytes vs. textual lines.
3128 * The following heuristic assumes that there are 64
3129 * bytes per "line".
3130 * This is stupid and ugly, but very cheap...
3132 damage = DIV_ROUND_UP(damage, 64);
3133 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3134 dir.files[dir.nr].name = file->name;
3135 dir.files[dir.nr].changed = damage;
3136 changed += damage;
3137 dir.nr++;
3140 /* This can happen even with many files, if everything was renames */
3141 if (!changed)
3142 return;
3144 /* Show all directories with more than x% of the changes */
3145 QSORT(dir.files, dir.nr, dirstat_compare);
3146 gather_dirstat(options, &dir, changed, "", 0);
3149 static void free_diffstat_file(struct diffstat_file *f)
3151 free(f->print_name);
3152 free(f->name);
3153 free(f->from_name);
3154 free(f);
3157 void free_diffstat_info(struct diffstat_t *diffstat)
3159 int i;
3160 for (i = 0; i < diffstat->nr; i++)
3161 free_diffstat_file(diffstat->files[i]);
3162 free(diffstat->files);
3165 struct checkdiff_t {
3166 const char *filename;
3167 int lineno;
3168 int conflict_marker_size;
3169 struct diff_options *o;
3170 unsigned ws_rule;
3171 unsigned status;
3174 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3176 char firstchar;
3177 int cnt;
3179 if (len < marker_size + 1)
3180 return 0;
3181 firstchar = line[0];
3182 switch (firstchar) {
3183 case '=': case '>': case '<': case '|':
3184 break;
3185 default:
3186 return 0;
3188 for (cnt = 1; cnt < marker_size; cnt++)
3189 if (line[cnt] != firstchar)
3190 return 0;
3191 /* line[1] through line[marker_size-1] are same as firstchar */
3192 if (len < marker_size + 1 || !isspace(line[marker_size]))
3193 return 0;
3194 return 1;
3197 static void checkdiff_consume_hunk(void *priv,
3198 long ob UNUSED, long on UNUSED,
3199 long nb, long nn UNUSED,
3200 const char *func UNUSED, long funclen UNUSED)
3203 struct checkdiff_t *data = priv;
3204 data->lineno = nb - 1;
3207 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3209 struct checkdiff_t *data = priv;
3210 int marker_size = data->conflict_marker_size;
3211 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3212 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3213 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3214 char *err;
3215 const char *line_prefix;
3217 assert(data->o);
3218 line_prefix = diff_line_prefix(data->o);
3220 if (line[0] == '+') {
3221 unsigned bad;
3222 data->lineno++;
3223 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3224 data->status |= 1;
3225 fprintf(data->o->file,
3226 "%s%s:%d: leftover conflict marker\n",
3227 line_prefix, data->filename, data->lineno);
3229 bad = ws_check(line + 1, len - 1, data->ws_rule);
3230 if (!bad)
3231 return 0;
3232 data->status |= bad;
3233 err = whitespace_error_string(bad);
3234 fprintf(data->o->file, "%s%s:%d: %s.\n",
3235 line_prefix, data->filename, data->lineno, err);
3236 free(err);
3237 emit_line(data->o, set, reset, line, 1);
3238 ws_check_emit(line + 1, len - 1, data->ws_rule,
3239 data->o->file, set, reset, ws);
3240 } else if (line[0] == ' ') {
3241 data->lineno++;
3243 return 0;
3246 static unsigned char *deflate_it(char *data,
3247 unsigned long size,
3248 unsigned long *result_size)
3250 int bound;
3251 unsigned char *deflated;
3252 git_zstream stream;
3254 git_deflate_init(&stream, zlib_compression_level);
3255 bound = git_deflate_bound(&stream, size);
3256 deflated = xmalloc(bound);
3257 stream.next_out = deflated;
3258 stream.avail_out = bound;
3260 stream.next_in = (unsigned char *)data;
3261 stream.avail_in = size;
3262 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3263 ; /* nothing */
3264 git_deflate_end(&stream);
3265 *result_size = stream.total_out;
3266 return deflated;
3269 static void emit_binary_diff_body(struct diff_options *o,
3270 mmfile_t *one, mmfile_t *two)
3272 void *cp;
3273 void *delta;
3274 void *deflated;
3275 void *data;
3276 unsigned long orig_size;
3277 unsigned long delta_size;
3278 unsigned long deflate_size;
3279 unsigned long data_size;
3281 /* We could do deflated delta, or we could do just deflated two,
3282 * whichever is smaller.
3284 delta = NULL;
3285 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3286 if (one->size && two->size) {
3287 delta = diff_delta(one->ptr, one->size,
3288 two->ptr, two->size,
3289 &delta_size, deflate_size);
3290 if (delta) {
3291 void *to_free = delta;
3292 orig_size = delta_size;
3293 delta = deflate_it(delta, delta_size, &delta_size);
3294 free(to_free);
3298 if (delta && delta_size < deflate_size) {
3299 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3300 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3301 s, strlen(s), 0);
3302 free(s);
3303 free(deflated);
3304 data = delta;
3305 data_size = delta_size;
3306 } else {
3307 char *s = xstrfmt("%lu", two->size);
3308 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3309 s, strlen(s), 0);
3310 free(s);
3311 free(delta);
3312 data = deflated;
3313 data_size = deflate_size;
3316 /* emit data encoded in base85 */
3317 cp = data;
3318 while (data_size) {
3319 int len;
3320 int bytes = (52 < data_size) ? 52 : data_size;
3321 char line[71];
3322 data_size -= bytes;
3323 if (bytes <= 26)
3324 line[0] = bytes + 'A' - 1;
3325 else
3326 line[0] = bytes - 26 + 'a' - 1;
3327 encode_85(line + 1, cp, bytes);
3328 cp = (char *) cp + bytes;
3330 len = strlen(line);
3331 line[len++] = '\n';
3332 line[len] = '\0';
3334 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3335 line, len, 0);
3337 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3338 free(data);
3341 static void emit_binary_diff(struct diff_options *o,
3342 mmfile_t *one, mmfile_t *two)
3344 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3345 emit_binary_diff_body(o, one, two);
3346 emit_binary_diff_body(o, two, one);
3349 int diff_filespec_is_binary(struct repository *r,
3350 struct diff_filespec *one)
3352 struct diff_populate_filespec_options dpf_options = {
3353 .check_binary = 1,
3356 if (one->is_binary == -1) {
3357 diff_filespec_load_driver(one, r->index);
3358 if (one->driver->binary != -1)
3359 one->is_binary = one->driver->binary;
3360 else {
3361 if (!one->data && DIFF_FILE_VALID(one))
3362 diff_populate_filespec(r, one, &dpf_options);
3363 if (one->is_binary == -1 && one->data)
3364 one->is_binary = buffer_is_binary(one->data,
3365 one->size);
3366 if (one->is_binary == -1)
3367 one->is_binary = 0;
3370 return one->is_binary;
3373 static const struct userdiff_funcname *
3374 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3376 diff_filespec_load_driver(one, o->repo->index);
3377 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3380 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3382 if (!options->a_prefix)
3383 options->a_prefix = a;
3384 if (!options->b_prefix)
3385 options->b_prefix = b;
3388 struct userdiff_driver *get_textconv(struct repository *r,
3389 struct diff_filespec *one)
3391 if (!DIFF_FILE_VALID(one))
3392 return NULL;
3394 diff_filespec_load_driver(one, r->index);
3395 return userdiff_get_textconv(r, one->driver);
3398 static struct string_list *additional_headers(struct diff_options *o,
3399 const char *path)
3401 if (!o->additional_path_headers)
3402 return NULL;
3403 return strmap_get(o->additional_path_headers, path);
3406 static void add_formatted_header(struct strbuf *msg,
3407 const char *header,
3408 const char *line_prefix,
3409 const char *meta,
3410 const char *reset)
3412 const char *next, *newline;
3414 for (next = header; *next; next = newline) {
3415 newline = strchrnul(next, '\n');
3416 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3417 (int)(newline - next), next, reset);
3418 if (*newline)
3419 newline++;
3423 static void add_formatted_headers(struct strbuf *msg,
3424 struct string_list *more_headers,
3425 const char *line_prefix,
3426 const char *meta,
3427 const char *reset)
3429 int i;
3431 for (i = 0; i < more_headers->nr; i++)
3432 add_formatted_header(msg, more_headers->items[i].string,
3433 line_prefix, meta, reset);
3436 static int diff_filepair_is_phoney(struct diff_filespec *one,
3437 struct diff_filespec *two)
3440 * This function specifically looks for pairs injected by
3441 * create_filepairs_for_header_only_notifications(). Such
3442 * pairs are "phoney" in that they do not represent any
3443 * content or even mode difference, but were inserted because
3444 * diff_queued_diff previously had no pair associated with
3445 * that path but we needed some pair to avoid losing the
3446 * "remerge CONFLICT" header associated with the path.
3448 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3451 static int set_diff_algorithm(struct diff_options *opts,
3452 const char *alg)
3454 long value = parse_algorithm_value(alg);
3456 if (value < 0)
3457 return -1;
3459 /* clear out previous settings */
3460 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3461 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3462 opts->xdl_opts |= value;
3464 return 0;
3467 static void builtin_diff(const char *name_a,
3468 const char *name_b,
3469 struct diff_filespec *one,
3470 struct diff_filespec *two,
3471 const char *xfrm_msg,
3472 int must_show_header,
3473 struct diff_options *o,
3474 int complete_rewrite)
3476 mmfile_t mf1, mf2;
3477 const char *lbl[2];
3478 char *a_one, *b_two;
3479 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3480 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3481 const char *a_prefix, *b_prefix;
3482 struct userdiff_driver *textconv_one = NULL;
3483 struct userdiff_driver *textconv_two = NULL;
3484 struct strbuf header = STRBUF_INIT;
3485 const char *line_prefix = diff_line_prefix(o);
3487 diff_set_mnemonic_prefix(o, "a/", "b/");
3488 if (o->flags.reverse_diff) {
3489 a_prefix = o->b_prefix;
3490 b_prefix = o->a_prefix;
3491 } else {
3492 a_prefix = o->a_prefix;
3493 b_prefix = o->b_prefix;
3496 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3497 (!one->mode || S_ISGITLINK(one->mode)) &&
3498 (!two->mode || S_ISGITLINK(two->mode)) &&
3499 (!diff_filepair_is_phoney(one, two))) {
3500 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3501 &one->oid, &two->oid,
3502 two->dirty_submodule);
3503 return;
3504 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3505 (!one->mode || S_ISGITLINK(one->mode)) &&
3506 (!two->mode || S_ISGITLINK(two->mode)) &&
3507 (!diff_filepair_is_phoney(one, two))) {
3508 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3509 &one->oid, &two->oid,
3510 two->dirty_submodule);
3511 return;
3514 if (o->flags.allow_textconv) {
3515 textconv_one = get_textconv(o->repo, one);
3516 textconv_two = get_textconv(o->repo, two);
3519 /* Never use a non-valid filename anywhere if at all possible */
3520 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3521 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3523 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3524 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3525 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3526 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3527 if (diff_filepair_is_phoney(one, two)) {
3529 * We should only reach this point for pairs generated from
3530 * create_filepairs_for_header_only_notifications(). For
3531 * these, we want to avoid the "/dev/null" special casing
3532 * above, because we do not want such pairs shown as either
3533 * "new file" or "deleted file" below.
3535 lbl[0] = a_one;
3536 lbl[1] = b_two;
3538 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3539 if (lbl[0][0] == '/') {
3540 /* /dev/null */
3541 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3542 if (xfrm_msg)
3543 strbuf_addstr(&header, xfrm_msg);
3544 must_show_header = 1;
3546 else if (lbl[1][0] == '/') {
3547 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3548 if (xfrm_msg)
3549 strbuf_addstr(&header, xfrm_msg);
3550 must_show_header = 1;
3552 else {
3553 if (one->mode != two->mode) {
3554 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3555 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3556 must_show_header = 1;
3558 if (xfrm_msg)
3559 strbuf_addstr(&header, xfrm_msg);
3562 * we do not run diff between different kind
3563 * of objects.
3565 if ((one->mode ^ two->mode) & S_IFMT)
3566 goto free_ab_and_return;
3567 if (complete_rewrite &&
3568 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3569 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3570 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3571 header.buf, header.len, 0);
3572 strbuf_reset(&header);
3573 emit_rewrite_diff(name_a, name_b, one, two,
3574 textconv_one, textconv_two, o);
3575 o->found_changes = 1;
3576 goto free_ab_and_return;
3580 if (o->irreversible_delete && lbl[1][0] == '/') {
3581 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3582 header.len, 0);
3583 strbuf_reset(&header);
3584 goto free_ab_and_return;
3585 } else if (!o->flags.text &&
3586 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3587 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3588 struct strbuf sb = STRBUF_INIT;
3589 if (!one->data && !two->data &&
3590 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3591 !o->flags.binary) {
3592 if (oideq(&one->oid, &two->oid)) {
3593 if (must_show_header)
3594 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3595 header.buf, header.len,
3597 goto free_ab_and_return;
3599 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3600 header.buf, header.len, 0);
3601 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3602 diff_line_prefix(o), lbl[0], lbl[1]);
3603 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3604 sb.buf, sb.len, 0);
3605 strbuf_release(&sb);
3606 goto free_ab_and_return;
3608 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3609 fill_mmfile(o->repo, &mf2, two) < 0)
3610 die("unable to read files to diff");
3611 /* Quite common confusing case */
3612 if (mf1.size == mf2.size &&
3613 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3614 if (must_show_header)
3615 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3616 header.buf, header.len, 0);
3617 goto free_ab_and_return;
3619 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3620 strbuf_reset(&header);
3621 if (o->flags.binary)
3622 emit_binary_diff(o, &mf1, &mf2);
3623 else {
3624 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3625 diff_line_prefix(o), lbl[0], lbl[1]);
3626 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3627 sb.buf, sb.len, 0);
3628 strbuf_release(&sb);
3630 o->found_changes = 1;
3631 } else {
3632 /* Crazy xdl interfaces.. */
3633 const char *diffopts;
3634 const char *v;
3635 xpparam_t xpp;
3636 xdemitconf_t xecfg;
3637 struct emit_callback ecbdata;
3638 const struct userdiff_funcname *pe;
3640 if (must_show_header) {
3641 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3642 header.buf, header.len, 0);
3643 strbuf_reset(&header);
3646 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3647 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3649 pe = diff_funcname_pattern(o, one);
3650 if (!pe)
3651 pe = diff_funcname_pattern(o, two);
3653 memset(&xpp, 0, sizeof(xpp));
3654 memset(&xecfg, 0, sizeof(xecfg));
3655 memset(&ecbdata, 0, sizeof(ecbdata));
3656 if (o->flags.suppress_diff_headers)
3657 lbl[0] = NULL;
3658 ecbdata.label_path = lbl;
3659 ecbdata.color_diff = want_color(o->use_color);
3660 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3661 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3662 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3663 ecbdata.opt = o;
3664 if (header.len && !o->flags.suppress_diff_headers)
3665 ecbdata.header = &header;
3666 xpp.flags = o->xdl_opts;
3667 xpp.ignore_regex = o->ignore_regex;
3668 xpp.ignore_regex_nr = o->ignore_regex_nr;
3669 xpp.anchors = o->anchors;
3670 xpp.anchors_nr = o->anchors_nr;
3671 xecfg.ctxlen = o->context;
3672 xecfg.interhunkctxlen = o->interhunkcontext;
3673 xecfg.flags = XDL_EMIT_FUNCNAMES;
3674 if (o->flags.funccontext)
3675 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3676 if (pe)
3677 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3679 diffopts = getenv("GIT_DIFF_OPTS");
3680 if (!diffopts)
3682 else if (skip_prefix(diffopts, "--unified=", &v))
3683 xecfg.ctxlen = strtoul(v, NULL, 10);
3684 else if (skip_prefix(diffopts, "-u", &v))
3685 xecfg.ctxlen = strtoul(v, NULL, 10);
3687 if (o->word_diff)
3688 init_diff_words_data(&ecbdata, o, one, two);
3689 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3690 &ecbdata, &xpp, &xecfg))
3691 die("unable to generate diff for %s", one->path);
3692 if (o->word_diff)
3693 free_diff_words_data(&ecbdata);
3694 if (textconv_one)
3695 free(mf1.ptr);
3696 if (textconv_two)
3697 free(mf2.ptr);
3698 xdiff_clear_find_func(&xecfg);
3701 free_ab_and_return:
3702 strbuf_release(&header);
3703 diff_free_filespec_data(one);
3704 diff_free_filespec_data(two);
3705 free(a_one);
3706 free(b_two);
3707 return;
3710 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3712 if (!is_renamed) {
3713 if (p->status == DIFF_STATUS_ADDED) {
3714 if (S_ISLNK(p->two->mode))
3715 return "new +l";
3716 else if ((p->two->mode & 0777) == 0755)
3717 return "new +x";
3718 else
3719 return "new";
3720 } else if (p->status == DIFF_STATUS_DELETED)
3721 return "gone";
3723 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3724 return "mode -l";
3725 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3726 return "mode +l";
3727 else if ((p->one->mode & 0777) == 0644 &&
3728 (p->two->mode & 0777) == 0755)
3729 return "mode +x";
3730 else if ((p->one->mode & 0777) == 0755 &&
3731 (p->two->mode & 0777) == 0644)
3732 return "mode -x";
3733 return NULL;
3736 static void builtin_diffstat(const char *name_a, const char *name_b,
3737 struct diff_filespec *one,
3738 struct diff_filespec *two,
3739 struct diffstat_t *diffstat,
3740 struct diff_options *o,
3741 struct diff_filepair *p)
3743 mmfile_t mf1, mf2;
3744 struct diffstat_file *data;
3745 int may_differ;
3746 int complete_rewrite = 0;
3748 if (!DIFF_PAIR_UNMERGED(p)) {
3749 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3750 complete_rewrite = 1;
3753 data = diffstat_add(diffstat, name_a, name_b);
3754 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3755 if (o->flags.stat_with_summary)
3756 data->comments = get_compact_summary(p, data->is_renamed);
3758 if (!one || !two) {
3759 data->is_unmerged = 1;
3760 return;
3763 /* saves some reads if true, not a guarantee of diff outcome */
3764 may_differ = !(one->oid_valid && two->oid_valid &&
3765 oideq(&one->oid, &two->oid));
3767 if (diff_filespec_is_binary(o->repo, one) ||
3768 diff_filespec_is_binary(o->repo, two)) {
3769 data->is_binary = 1;
3770 if (!may_differ) {
3771 data->added = 0;
3772 data->deleted = 0;
3773 } else {
3774 data->added = diff_filespec_size(o->repo, two);
3775 data->deleted = diff_filespec_size(o->repo, one);
3779 else if (complete_rewrite) {
3780 diff_populate_filespec(o->repo, one, NULL);
3781 diff_populate_filespec(o->repo, two, NULL);
3782 data->deleted = count_lines(one->data, one->size);
3783 data->added = count_lines(two->data, two->size);
3786 else if (may_differ) {
3787 /* Crazy xdl interfaces.. */
3788 xpparam_t xpp;
3789 xdemitconf_t xecfg;
3791 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3792 fill_mmfile(o->repo, &mf2, two) < 0)
3793 die("unable to read files to diff");
3795 memset(&xpp, 0, sizeof(xpp));
3796 memset(&xecfg, 0, sizeof(xecfg));
3797 xpp.flags = o->xdl_opts;
3798 xpp.ignore_regex = o->ignore_regex;
3799 xpp.ignore_regex_nr = o->ignore_regex_nr;
3800 xpp.anchors = o->anchors;
3801 xpp.anchors_nr = o->anchors_nr;
3802 xecfg.ctxlen = o->context;
3803 xecfg.interhunkctxlen = o->interhunkcontext;
3804 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3805 if (xdi_diff_outf(&mf1, &mf2, NULL,
3806 diffstat_consume, diffstat, &xpp, &xecfg))
3807 die("unable to generate diffstat for %s", one->path);
3809 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3810 struct diffstat_file *file =
3811 diffstat->files[diffstat->nr - 1];
3813 * Omit diffstats of modified files where nothing changed.
3814 * Even if may_differ, this might be the case due to
3815 * ignoring whitespace changes, etc.
3817 * But note that we special-case additions, deletions,
3818 * renames, and mode changes as adding an empty file,
3819 * for example is still of interest.
3821 if ((p->status == DIFF_STATUS_MODIFIED)
3822 && !file->added
3823 && !file->deleted
3824 && one->mode == two->mode) {
3825 free_diffstat_file(file);
3826 diffstat->nr--;
3831 diff_free_filespec_data(one);
3832 diff_free_filespec_data(two);
3835 static void builtin_checkdiff(const char *name_a, const char *name_b,
3836 const char *attr_path,
3837 struct diff_filespec *one,
3838 struct diff_filespec *two,
3839 struct diff_options *o)
3841 mmfile_t mf1, mf2;
3842 struct checkdiff_t data;
3844 if (!two)
3845 return;
3847 memset(&data, 0, sizeof(data));
3848 data.filename = name_b ? name_b : name_a;
3849 data.lineno = 0;
3850 data.o = o;
3851 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3852 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3854 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3855 fill_mmfile(o->repo, &mf2, two) < 0)
3856 die("unable to read files to diff");
3859 * All the other codepaths check both sides, but not checking
3860 * the "old" side here is deliberate. We are checking the newly
3861 * introduced changes, and as long as the "new" side is text, we
3862 * can and should check what it introduces.
3864 if (diff_filespec_is_binary(o->repo, two))
3865 goto free_and_return;
3866 else {
3867 /* Crazy xdl interfaces.. */
3868 xpparam_t xpp;
3869 xdemitconf_t xecfg;
3871 memset(&xpp, 0, sizeof(xpp));
3872 memset(&xecfg, 0, sizeof(xecfg));
3873 xecfg.ctxlen = 1; /* at least one context line */
3874 xpp.flags = 0;
3875 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3876 checkdiff_consume, &data,
3877 &xpp, &xecfg))
3878 die("unable to generate checkdiff for %s", one->path);
3880 if (data.ws_rule & WS_BLANK_AT_EOF) {
3881 struct emit_callback ecbdata;
3882 int blank_at_eof;
3884 ecbdata.ws_rule = data.ws_rule;
3885 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3886 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3888 if (blank_at_eof) {
3889 static char *err;
3890 if (!err)
3891 err = whitespace_error_string(WS_BLANK_AT_EOF);
3892 fprintf(o->file, "%s:%d: %s.\n",
3893 data.filename, blank_at_eof, err);
3894 data.status = 1; /* report errors */
3898 free_and_return:
3899 diff_free_filespec_data(one);
3900 diff_free_filespec_data(two);
3901 if (data.status)
3902 o->flags.check_failed = 1;
3905 struct diff_filespec *alloc_filespec(const char *path)
3907 struct diff_filespec *spec;
3909 FLEXPTR_ALLOC_STR(spec, path, path);
3910 spec->count = 1;
3911 spec->is_binary = -1;
3912 return spec;
3915 void free_filespec(struct diff_filespec *spec)
3917 if (!--spec->count) {
3918 diff_free_filespec_data(spec);
3919 free(spec);
3923 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3924 int oid_valid, unsigned short mode)
3926 if (mode) {
3927 spec->mode = canon_mode(mode);
3928 oidcpy(&spec->oid, oid);
3929 spec->oid_valid = oid_valid;
3934 * Given a name and sha1 pair, if the index tells us the file in
3935 * the work tree has that object contents, return true, so that
3936 * prepare_temp_file() does not have to inflate and extract.
3938 static int reuse_worktree_file(struct index_state *istate,
3939 const char *name,
3940 const struct object_id *oid,
3941 int want_file)
3943 const struct cache_entry *ce;
3944 struct stat st;
3945 int pos, len;
3948 * We do not read the cache ourselves here, because the
3949 * benchmark with my previous version that always reads cache
3950 * shows that it makes things worse for diff-tree comparing
3951 * two linux-2.6 kernel trees in an already checked out work
3952 * tree. This is because most diff-tree comparisons deal with
3953 * only a small number of files, while reading the cache is
3954 * expensive for a large project, and its cost outweighs the
3955 * savings we get by not inflating the object to a temporary
3956 * file. Practically, this code only helps when we are used
3957 * by diff-cache --cached, which does read the cache before
3958 * calling us.
3960 if (!istate->cache)
3961 return 0;
3963 /* We want to avoid the working directory if our caller
3964 * doesn't need the data in a normal file, this system
3965 * is rather slow with its stat/open/mmap/close syscalls,
3966 * and the object is contained in a pack file. The pack
3967 * is probably already open and will be faster to obtain
3968 * the data through than the working directory. Loose
3969 * objects however would tend to be slower as they need
3970 * to be individually opened and inflated.
3972 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3973 return 0;
3976 * Similarly, if we'd have to convert the file contents anyway, that
3977 * makes the optimization not worthwhile.
3979 if (!want_file && would_convert_to_git(istate, name))
3980 return 0;
3983 * If this path does not match our sparse-checkout definition,
3984 * then the file will not be in the working directory.
3986 if (!path_in_sparse_checkout(name, istate))
3987 return 0;
3989 len = strlen(name);
3990 pos = index_name_pos(istate, name, len);
3991 if (pos < 0)
3992 return 0;
3993 ce = istate->cache[pos];
3996 * This is not the sha1 we are looking for, or
3997 * unreusable because it is not a regular file.
3999 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4000 return 0;
4003 * If ce is marked as "assume unchanged", there is no
4004 * guarantee that work tree matches what we are looking for.
4006 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4007 return 0;
4010 * If ce matches the file in the work tree, we can reuse it.
4012 if (ce_uptodate(ce) ||
4013 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4014 return 1;
4016 return 0;
4019 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4021 struct strbuf buf = STRBUF_INIT;
4022 char *dirty = "";
4024 /* Are we looking at the work tree? */
4025 if (s->dirty_submodule)
4026 dirty = "-dirty";
4028 strbuf_addf(&buf, "Subproject commit %s%s\n",
4029 oid_to_hex(&s->oid), dirty);
4030 s->size = buf.len;
4031 if (size_only) {
4032 s->data = NULL;
4033 strbuf_release(&buf);
4034 } else {
4035 s->data = strbuf_detach(&buf, NULL);
4036 s->should_free = 1;
4038 return 0;
4042 * While doing rename detection and pickaxe operation, we may need to
4043 * grab the data for the blob (or file) for our own in-core comparison.
4044 * diff_filespec has data and size fields for this purpose.
4046 int diff_populate_filespec(struct repository *r,
4047 struct diff_filespec *s,
4048 const struct diff_populate_filespec_options *options)
4050 int size_only = options ? options->check_size_only : 0;
4051 int check_binary = options ? options->check_binary : 0;
4052 int err = 0;
4053 int conv_flags = global_conv_flags_eol;
4055 * demote FAIL to WARN to allow inspecting the situation
4056 * instead of refusing.
4058 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4059 conv_flags = CONV_EOL_RNDTRP_WARN;
4061 if (!DIFF_FILE_VALID(s))
4062 die("internal error: asking to populate invalid file.");
4063 if (S_ISDIR(s->mode))
4064 return -1;
4066 if (s->data)
4067 return 0;
4069 if (size_only && 0 < s->size)
4070 return 0;
4072 if (S_ISGITLINK(s->mode))
4073 return diff_populate_gitlink(s, size_only);
4075 if (!s->oid_valid ||
4076 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4077 struct strbuf buf = STRBUF_INIT;
4078 struct stat st;
4079 int fd;
4081 if (lstat(s->path, &st) < 0) {
4082 err_empty:
4083 err = -1;
4084 empty:
4085 s->data = (char *)"";
4086 s->size = 0;
4087 return err;
4089 s->size = xsize_t(st.st_size);
4090 if (!s->size)
4091 goto empty;
4092 if (S_ISLNK(st.st_mode)) {
4093 struct strbuf sb = STRBUF_INIT;
4095 if (strbuf_readlink(&sb, s->path, s->size))
4096 goto err_empty;
4097 s->size = sb.len;
4098 s->data = strbuf_detach(&sb, NULL);
4099 s->should_free = 1;
4100 return 0;
4104 * Even if the caller would be happy with getting
4105 * only the size, we cannot return early at this
4106 * point if the path requires us to run the content
4107 * conversion.
4109 if (size_only && !would_convert_to_git(r->index, s->path))
4110 return 0;
4113 * Note: this check uses xsize_t(st.st_size) that may
4114 * not be the true size of the blob after it goes
4115 * through convert_to_git(). This may not strictly be
4116 * correct, but the whole point of big_file_threshold
4117 * and is_binary check being that we want to avoid
4118 * opening the file and inspecting the contents, this
4119 * is probably fine.
4121 if (check_binary &&
4122 s->size > big_file_threshold && s->is_binary == -1) {
4123 s->is_binary = 1;
4124 return 0;
4126 fd = open(s->path, O_RDONLY);
4127 if (fd < 0)
4128 goto err_empty;
4129 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4130 close(fd);
4131 s->should_munmap = 1;
4134 * Convert from working tree format to canonical git format
4136 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4137 size_t size = 0;
4138 munmap(s->data, s->size);
4139 s->should_munmap = 0;
4140 s->data = strbuf_detach(&buf, &size);
4141 s->size = size;
4142 s->should_free = 1;
4145 else {
4146 struct object_info info = {
4147 .sizep = &s->size
4150 if (!(size_only || check_binary))
4152 * Set contentp, since there is no chance that merely
4153 * the size is sufficient.
4155 info.contentp = &s->data;
4157 if (options && options->missing_object_cb) {
4158 if (!oid_object_info_extended(r, &s->oid, &info,
4159 OBJECT_INFO_LOOKUP_REPLACE |
4160 OBJECT_INFO_SKIP_FETCH_OBJECT))
4161 goto object_read;
4162 options->missing_object_cb(options->missing_object_data);
4164 if (oid_object_info_extended(r, &s->oid, &info,
4165 OBJECT_INFO_LOOKUP_REPLACE))
4166 die("unable to read %s", oid_to_hex(&s->oid));
4168 object_read:
4169 if (size_only || check_binary) {
4170 if (size_only)
4171 return 0;
4172 if (s->size > big_file_threshold && s->is_binary == -1) {
4173 s->is_binary = 1;
4174 return 0;
4177 if (!info.contentp) {
4178 info.contentp = &s->data;
4179 if (oid_object_info_extended(r, &s->oid, &info,
4180 OBJECT_INFO_LOOKUP_REPLACE))
4181 die("unable to read %s", oid_to_hex(&s->oid));
4183 s->should_free = 1;
4185 return 0;
4188 void diff_free_filespec_blob(struct diff_filespec *s)
4190 if (s->should_free)
4191 free(s->data);
4192 else if (s->should_munmap)
4193 munmap(s->data, s->size);
4195 if (s->should_free || s->should_munmap) {
4196 s->should_free = s->should_munmap = 0;
4197 s->data = NULL;
4201 void diff_free_filespec_data(struct diff_filespec *s)
4203 if (!s)
4204 return;
4206 diff_free_filespec_blob(s);
4207 FREE_AND_NULL(s->cnt_data);
4210 static void prep_temp_blob(struct index_state *istate,
4211 const char *path, struct diff_tempfile *temp,
4212 void *blob,
4213 unsigned long size,
4214 const struct object_id *oid,
4215 int mode)
4217 struct strbuf buf = STRBUF_INIT;
4218 char *path_dup = xstrdup(path);
4219 const char *base = basename(path_dup);
4220 struct checkout_metadata meta;
4222 init_checkout_metadata(&meta, NULL, NULL, oid);
4224 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4225 if (!temp->tempfile)
4226 die_errno("unable to create temp-file");
4227 if (convert_to_working_tree(istate, path,
4228 (const char *)blob, (size_t)size, &buf, &meta)) {
4229 blob = buf.buf;
4230 size = buf.len;
4232 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4233 close_tempfile_gently(temp->tempfile))
4234 die_errno("unable to write temp-file");
4235 temp->name = get_tempfile_path(temp->tempfile);
4236 oid_to_hex_r(temp->hex, oid);
4237 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4238 strbuf_release(&buf);
4239 free(path_dup);
4242 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4243 struct diff_filespec *one)
4245 struct diff_tempfile *temp = claim_diff_tempfile();
4247 if (!DIFF_FILE_VALID(one)) {
4248 not_a_valid_file:
4249 /* A '-' entry produces this for file-2, and
4250 * a '+' entry produces this for file-1.
4252 temp->name = "/dev/null";
4253 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4254 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4255 return temp;
4258 if (!S_ISGITLINK(one->mode) &&
4259 (!one->oid_valid ||
4260 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4261 struct stat st;
4262 if (lstat(one->path, &st) < 0) {
4263 if (errno == ENOENT)
4264 goto not_a_valid_file;
4265 die_errno("stat(%s)", one->path);
4267 if (S_ISLNK(st.st_mode)) {
4268 struct strbuf sb = STRBUF_INIT;
4269 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4270 die_errno("readlink(%s)", one->path);
4271 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4272 (one->oid_valid ?
4273 &one->oid : null_oid()),
4274 (one->oid_valid ?
4275 one->mode : S_IFLNK));
4276 strbuf_release(&sb);
4278 else {
4279 /* we can borrow from the file in the work tree */
4280 temp->name = one->path;
4281 if (!one->oid_valid)
4282 oid_to_hex_r(temp->hex, null_oid());
4283 else
4284 oid_to_hex_r(temp->hex, &one->oid);
4285 /* Even though we may sometimes borrow the
4286 * contents from the work tree, we always want
4287 * one->mode. mode is trustworthy even when
4288 * !(one->oid_valid), as long as
4289 * DIFF_FILE_VALID(one).
4291 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4293 return temp;
4295 else {
4296 if (diff_populate_filespec(r, one, NULL))
4297 die("cannot read data blob for %s", one->path);
4298 prep_temp_blob(r->index, one->path, temp,
4299 one->data, one->size,
4300 &one->oid, one->mode);
4302 return temp;
4305 static void add_external_diff_name(struct repository *r,
4306 struct strvec *argv,
4307 struct diff_filespec *df)
4309 struct diff_tempfile *temp = prepare_temp_file(r, df);
4310 strvec_push(argv, temp->name);
4311 strvec_push(argv, temp->hex);
4312 strvec_push(argv, temp->mode);
4315 /* An external diff command takes:
4317 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4318 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4321 static void run_external_diff(const char *pgm,
4322 const char *name,
4323 const char *other,
4324 struct diff_filespec *one,
4325 struct diff_filespec *two,
4326 const char *xfrm_msg,
4327 struct diff_options *o)
4329 struct child_process cmd = CHILD_PROCESS_INIT;
4330 struct diff_queue_struct *q = &diff_queued_diff;
4332 strvec_push(&cmd.args, pgm);
4333 strvec_push(&cmd.args, name);
4335 if (one && two) {
4336 add_external_diff_name(o->repo, &cmd.args, one);
4337 add_external_diff_name(o->repo, &cmd.args, two);
4338 if (other) {
4339 strvec_push(&cmd.args, other);
4340 strvec_push(&cmd.args, xfrm_msg);
4344 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4345 ++o->diff_path_counter);
4346 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4348 diff_free_filespec_data(one);
4349 diff_free_filespec_data(two);
4350 cmd.use_shell = 1;
4351 if (run_command(&cmd))
4352 die(_("external diff died, stopping at %s"), name);
4354 remove_tempfile();
4357 static int similarity_index(struct diff_filepair *p)
4359 return p->score * 100 / MAX_SCORE;
4362 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4364 if (startup_info->have_repository)
4365 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4366 else {
4367 char *hex = oid_to_hex(oid);
4368 if (abbrev < 0)
4369 abbrev = FALLBACK_DEFAULT_ABBREV;
4370 if (abbrev > the_hash_algo->hexsz)
4371 BUG("oid abbreviation out of range: %d", abbrev);
4372 if (abbrev)
4373 hex[abbrev] = '\0';
4374 return hex;
4378 static void fill_metainfo(struct strbuf *msg,
4379 const char *name,
4380 const char *other,
4381 struct diff_filespec *one,
4382 struct diff_filespec *two,
4383 struct diff_options *o,
4384 struct diff_filepair *p,
4385 int *must_show_header,
4386 int use_color)
4388 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4389 const char *reset = diff_get_color(use_color, DIFF_RESET);
4390 const char *line_prefix = diff_line_prefix(o);
4391 struct string_list *more_headers = NULL;
4393 *must_show_header = 1;
4394 strbuf_init(msg, PATH_MAX * 2 + 300);
4395 switch (p->status) {
4396 case DIFF_STATUS_COPIED:
4397 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4398 line_prefix, set, similarity_index(p));
4399 strbuf_addf(msg, "%s\n%s%scopy from ",
4400 reset, line_prefix, set);
4401 quote_c_style(name, msg, NULL, 0);
4402 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4403 quote_c_style(other, msg, NULL, 0);
4404 strbuf_addf(msg, "%s\n", reset);
4405 break;
4406 case DIFF_STATUS_RENAMED:
4407 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4408 line_prefix, set, similarity_index(p));
4409 strbuf_addf(msg, "%s\n%s%srename from ",
4410 reset, line_prefix, set);
4411 quote_c_style(name, msg, NULL, 0);
4412 strbuf_addf(msg, "%s\n%s%srename to ",
4413 reset, line_prefix, set);
4414 quote_c_style(other, msg, NULL, 0);
4415 strbuf_addf(msg, "%s\n", reset);
4416 break;
4417 case DIFF_STATUS_MODIFIED:
4418 if (p->score) {
4419 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4420 line_prefix,
4421 set, similarity_index(p), reset);
4422 break;
4424 /* fallthru */
4425 default:
4426 *must_show_header = 0;
4428 if ((more_headers = additional_headers(o, name))) {
4429 add_formatted_headers(msg, more_headers,
4430 line_prefix, set, reset);
4431 *must_show_header = 1;
4433 if (one && two && !oideq(&one->oid, &two->oid)) {
4434 const unsigned hexsz = the_hash_algo->hexsz;
4435 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4437 if (o->flags.full_index)
4438 abbrev = hexsz;
4440 if (o->flags.binary) {
4441 mmfile_t mf;
4442 if ((!fill_mmfile(o->repo, &mf, one) &&
4443 diff_filespec_is_binary(o->repo, one)) ||
4444 (!fill_mmfile(o->repo, &mf, two) &&
4445 diff_filespec_is_binary(o->repo, two)))
4446 abbrev = hexsz;
4448 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4449 diff_abbrev_oid(&one->oid, abbrev),
4450 diff_abbrev_oid(&two->oid, abbrev));
4451 if (one->mode == two->mode)
4452 strbuf_addf(msg, " %06o", one->mode);
4453 strbuf_addf(msg, "%s\n", reset);
4457 static void run_diff_cmd(const char *pgm,
4458 const char *name,
4459 const char *other,
4460 const char *attr_path,
4461 struct diff_filespec *one,
4462 struct diff_filespec *two,
4463 struct strbuf *msg,
4464 struct diff_options *o,
4465 struct diff_filepair *p)
4467 const char *xfrm_msg = NULL;
4468 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4469 int must_show_header = 0;
4470 struct userdiff_driver *drv = NULL;
4472 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4473 drv = userdiff_find_by_path(o->repo->index, attr_path);
4475 if (o->flags.allow_external && drv && drv->external)
4476 pgm = drv->external;
4478 if (msg) {
4480 * don't use colors when the header is intended for an
4481 * external diff driver
4483 fill_metainfo(msg, name, other, one, two, o, p,
4484 &must_show_header,
4485 want_color(o->use_color) && !pgm);
4486 xfrm_msg = msg->len ? msg->buf : NULL;
4489 if (pgm) {
4490 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4491 return;
4493 if (one && two) {
4494 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4495 set_diff_algorithm(o, drv->algorithm);
4497 builtin_diff(name, other ? other : name,
4498 one, two, xfrm_msg, must_show_header,
4499 o, complete_rewrite);
4500 } else {
4501 fprintf(o->file, "* Unmerged path %s\n", name);
4505 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4507 if (DIFF_FILE_VALID(one)) {
4508 if (!one->oid_valid) {
4509 struct stat st;
4510 if (one->is_stdin) {
4511 oidclr(&one->oid);
4512 return;
4514 if (lstat(one->path, &st) < 0)
4515 die_errno("stat '%s'", one->path);
4516 if (index_path(istate, &one->oid, one->path, &st, 0))
4517 die("cannot hash %s", one->path);
4520 else
4521 oidclr(&one->oid);
4524 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4526 /* Strip the prefix but do not molest /dev/null and absolute paths */
4527 if (*namep && !is_absolute_path(*namep)) {
4528 *namep += prefix_length;
4529 if (**namep == '/')
4530 ++*namep;
4532 if (*otherp && !is_absolute_path(*otherp)) {
4533 *otherp += prefix_length;
4534 if (**otherp == '/')
4535 ++*otherp;
4539 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4541 const char *pgm = external_diff();
4542 struct strbuf msg;
4543 struct diff_filespec *one = p->one;
4544 struct diff_filespec *two = p->two;
4545 const char *name;
4546 const char *other;
4547 const char *attr_path;
4549 name = one->path;
4550 other = (strcmp(name, two->path) ? two->path : NULL);
4551 attr_path = name;
4552 if (o->prefix_length)
4553 strip_prefix(o->prefix_length, &name, &other);
4555 if (!o->flags.allow_external)
4556 pgm = NULL;
4558 if (DIFF_PAIR_UNMERGED(p)) {
4559 run_diff_cmd(pgm, name, NULL, attr_path,
4560 NULL, NULL, NULL, o, p);
4561 return;
4564 diff_fill_oid_info(one, o->repo->index);
4565 diff_fill_oid_info(two, o->repo->index);
4567 if (!pgm &&
4568 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4569 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4571 * a filepair that changes between file and symlink
4572 * needs to be split into deletion and creation.
4574 struct diff_filespec *null = alloc_filespec(two->path);
4575 run_diff_cmd(NULL, name, other, attr_path,
4576 one, null, &msg,
4577 o, p);
4578 free(null);
4579 strbuf_release(&msg);
4581 null = alloc_filespec(one->path);
4582 run_diff_cmd(NULL, name, other, attr_path,
4583 null, two, &msg, o, p);
4584 free(null);
4586 else
4587 run_diff_cmd(pgm, name, other, attr_path,
4588 one, two, &msg, o, p);
4590 strbuf_release(&msg);
4593 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4594 struct diffstat_t *diffstat)
4596 const char *name;
4597 const char *other;
4599 if (!o->ignore_driver_algorithm) {
4600 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4601 p->one->path);
4603 if (drv && drv->algorithm)
4604 set_diff_algorithm(o, drv->algorithm);
4607 if (DIFF_PAIR_UNMERGED(p)) {
4608 /* unmerged */
4609 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4610 diffstat, o, p);
4611 return;
4614 name = p->one->path;
4615 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4617 if (o->prefix_length)
4618 strip_prefix(o->prefix_length, &name, &other);
4620 diff_fill_oid_info(p->one, o->repo->index);
4621 diff_fill_oid_info(p->two, o->repo->index);
4623 builtin_diffstat(name, other, p->one, p->two,
4624 diffstat, o, p);
4627 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4629 const char *name;
4630 const char *other;
4631 const char *attr_path;
4633 if (DIFF_PAIR_UNMERGED(p)) {
4634 /* unmerged */
4635 return;
4638 name = p->one->path;
4639 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4640 attr_path = other ? other : name;
4642 if (o->prefix_length)
4643 strip_prefix(o->prefix_length, &name, &other);
4645 diff_fill_oid_info(p->one, o->repo->index);
4646 diff_fill_oid_info(p->two, o->repo->index);
4648 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4651 void repo_diff_setup(struct repository *r, struct diff_options *options)
4653 memcpy(options, &default_diff_options, sizeof(*options));
4655 options->file = stdout;
4656 options->repo = r;
4658 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4659 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4660 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4661 options->abbrev = DEFAULT_ABBREV;
4662 options->line_termination = '\n';
4663 options->break_opt = -1;
4664 options->rename_limit = -1;
4665 options->dirstat_permille = diff_dirstat_permille_default;
4666 options->context = diff_context_default;
4667 options->interhunkcontext = diff_interhunk_context_default;
4668 options->ws_error_highlight = ws_error_highlight_default;
4669 options->flags.rename_empty = 1;
4670 options->flags.relative_name = diff_relative;
4671 options->objfind = NULL;
4673 /* pathchange left =NULL by default */
4674 options->change = diff_change;
4675 options->add_remove = diff_addremove;
4676 options->use_color = diff_use_color_default;
4677 options->detect_rename = diff_detect_rename_default;
4678 options->xdl_opts |= diff_algorithm;
4679 if (diff_indent_heuristic)
4680 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4682 options->orderfile = diff_order_file_cfg;
4684 if (!options->flags.ignore_submodule_set)
4685 options->flags.ignore_untracked_in_submodules = 1;
4687 if (diff_no_prefix) {
4688 options->a_prefix = options->b_prefix = "";
4689 } else if (!diff_mnemonic_prefix) {
4690 options->a_prefix = "a/";
4691 options->b_prefix = "b/";
4694 options->color_moved = diff_color_moved_default;
4695 options->color_moved_ws_handling = diff_color_moved_ws_default;
4698 static const char diff_status_letters[] = {
4699 DIFF_STATUS_ADDED,
4700 DIFF_STATUS_COPIED,
4701 DIFF_STATUS_DELETED,
4702 DIFF_STATUS_MODIFIED,
4703 DIFF_STATUS_RENAMED,
4704 DIFF_STATUS_TYPE_CHANGED,
4705 DIFF_STATUS_UNKNOWN,
4706 DIFF_STATUS_UNMERGED,
4707 DIFF_STATUS_FILTER_AON,
4708 DIFF_STATUS_FILTER_BROKEN,
4709 '\0',
4712 static unsigned int filter_bit['Z' + 1];
4714 static void prepare_filter_bits(void)
4716 int i;
4718 if (!filter_bit[DIFF_STATUS_ADDED]) {
4719 for (i = 0; diff_status_letters[i]; i++)
4720 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4724 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4726 return opt->filter & filter_bit[(int) status];
4729 unsigned diff_filter_bit(char status)
4731 prepare_filter_bits();
4732 return filter_bit[(int) status];
4735 void diff_setup_done(struct diff_options *options)
4737 unsigned check_mask = DIFF_FORMAT_NAME |
4738 DIFF_FORMAT_NAME_STATUS |
4739 DIFF_FORMAT_CHECKDIFF |
4740 DIFF_FORMAT_NO_OUTPUT;
4742 * This must be signed because we're comparing against a potentially
4743 * negative value.
4745 const int hexsz = the_hash_algo->hexsz;
4747 if (options->set_default)
4748 options->set_default(options);
4750 if (HAS_MULTI_BITS(options->output_format & check_mask))
4751 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4752 "--name-only", "--name-status", "--check", "-s");
4754 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4755 die(_("options '%s', '%s', and '%s' cannot be used together"),
4756 "-G", "-S", "--find-object");
4758 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4759 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4760 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4762 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4763 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4764 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4767 * Most of the time we can say "there are changes"
4768 * only by checking if there are changed paths, but
4769 * --ignore-whitespace* options force us to look
4770 * inside contents.
4773 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4774 options->ignore_regex_nr)
4775 options->flags.diff_from_contents = 1;
4776 else
4777 options->flags.diff_from_contents = 0;
4779 if (options->flags.find_copies_harder)
4780 options->detect_rename = DIFF_DETECT_COPY;
4782 if (!options->flags.relative_name)
4783 options->prefix = NULL;
4784 if (options->prefix)
4785 options->prefix_length = strlen(options->prefix);
4786 else
4787 options->prefix_length = 0;
4789 if (options->output_format & (DIFF_FORMAT_NAME |
4790 DIFF_FORMAT_NAME_STATUS |
4791 DIFF_FORMAT_CHECKDIFF |
4792 DIFF_FORMAT_NO_OUTPUT))
4793 options->output_format &= ~(DIFF_FORMAT_RAW |
4794 DIFF_FORMAT_NUMSTAT |
4795 DIFF_FORMAT_DIFFSTAT |
4796 DIFF_FORMAT_SHORTSTAT |
4797 DIFF_FORMAT_DIRSTAT |
4798 DIFF_FORMAT_SUMMARY |
4799 DIFF_FORMAT_PATCH);
4802 * These cases always need recursive; we do not drop caller-supplied
4803 * recursive bits for other formats here.
4805 if (options->output_format & (DIFF_FORMAT_PATCH |
4806 DIFF_FORMAT_NUMSTAT |
4807 DIFF_FORMAT_DIFFSTAT |
4808 DIFF_FORMAT_SHORTSTAT |
4809 DIFF_FORMAT_DIRSTAT |
4810 DIFF_FORMAT_SUMMARY |
4811 DIFF_FORMAT_CHECKDIFF))
4812 options->flags.recursive = 1;
4814 * Also pickaxe would not work very well if you do not say recursive
4816 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4817 options->flags.recursive = 1;
4819 * When patches are generated, submodules diffed against the work tree
4820 * must be checked for dirtiness too so it can be shown in the output
4822 if (options->output_format & DIFF_FORMAT_PATCH)
4823 options->flags.dirty_submodules = 1;
4825 if (options->detect_rename && options->rename_limit < 0)
4826 options->rename_limit = diff_rename_limit_default;
4827 if (hexsz < options->abbrev)
4828 options->abbrev = hexsz; /* full */
4831 * It does not make sense to show the first hit we happened
4832 * to have found. It does not make sense not to return with
4833 * exit code in such a case either.
4835 if (options->flags.quick) {
4836 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4837 options->flags.exit_with_status = 1;
4840 options->diff_path_counter = 0;
4842 if (options->flags.follow_renames && options->pathspec.nr != 1)
4843 die(_("--follow requires exactly one pathspec"));
4845 if (!options->use_color || external_diff())
4846 options->color_moved = 0;
4848 if (options->filter_not) {
4849 if (!options->filter)
4850 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4851 options->filter &= ~options->filter_not;
4855 int parse_long_opt(const char *opt, const char **argv,
4856 const char **optarg)
4858 const char *arg = argv[0];
4859 if (!skip_prefix(arg, "--", &arg))
4860 return 0;
4861 if (!skip_prefix(arg, opt, &arg))
4862 return 0;
4863 if (*arg == '=') { /* stuck form: --option=value */
4864 *optarg = arg + 1;
4865 return 1;
4867 if (*arg != '\0')
4868 return 0;
4869 /* separate form: --option value */
4870 if (!argv[1])
4871 die("Option '--%s' requires a value", opt);
4872 *optarg = argv[1];
4873 return 2;
4876 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4878 struct diff_options *options = opt->value;
4879 int width = options->stat_width;
4880 int name_width = options->stat_name_width;
4881 int graph_width = options->stat_graph_width;
4882 int count = options->stat_count;
4883 char *end;
4885 BUG_ON_OPT_NEG(unset);
4887 if (!strcmp(opt->long_name, "stat")) {
4888 if (value) {
4889 width = strtoul(value, &end, 10);
4890 if (*end == ',')
4891 name_width = strtoul(end+1, &end, 10);
4892 if (*end == ',')
4893 count = strtoul(end+1, &end, 10);
4894 if (*end)
4895 return error(_("invalid --stat value: %s"), value);
4897 } else if (!strcmp(opt->long_name, "stat-width")) {
4898 width = strtoul(value, &end, 10);
4899 if (*end)
4900 return error(_("%s expects a numerical value"),
4901 opt->long_name);
4902 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4903 name_width = strtoul(value, &end, 10);
4904 if (*end)
4905 return error(_("%s expects a numerical value"),
4906 opt->long_name);
4907 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4908 graph_width = strtoul(value, &end, 10);
4909 if (*end)
4910 return error(_("%s expects a numerical value"),
4911 opt->long_name);
4912 } else if (!strcmp(opt->long_name, "stat-count")) {
4913 count = strtoul(value, &end, 10);
4914 if (*end)
4915 return error(_("%s expects a numerical value"),
4916 opt->long_name);
4917 } else
4918 BUG("%s should not get here", opt->long_name);
4920 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4921 options->stat_name_width = name_width;
4922 options->stat_graph_width = graph_width;
4923 options->stat_width = width;
4924 options->stat_count = count;
4925 return 0;
4928 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4930 struct strbuf errmsg = STRBUF_INIT;
4931 if (parse_dirstat_params(options, params, &errmsg))
4932 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4933 errmsg.buf);
4934 strbuf_release(&errmsg);
4936 * The caller knows a dirstat-related option is given from the command
4937 * line; allow it to say "return this_function();"
4939 options->output_format |= DIFF_FORMAT_DIRSTAT;
4940 return 1;
4943 static int diff_opt_diff_filter(const struct option *option,
4944 const char *optarg, int unset)
4946 struct diff_options *opt = option->value;
4947 int i, optch;
4949 BUG_ON_OPT_NEG(unset);
4950 prepare_filter_bits();
4952 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4953 unsigned int bit;
4954 int negate;
4956 if ('a' <= optch && optch <= 'z') {
4957 negate = 1;
4958 optch = toupper(optch);
4959 } else {
4960 negate = 0;
4963 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4964 if (!bit)
4965 return error(_("unknown change class '%c' in --diff-filter=%s"),
4966 optarg[i], optarg);
4967 if (negate)
4968 opt->filter_not |= bit;
4969 else
4970 opt->filter |= bit;
4972 return 0;
4975 static void enable_patch_output(int *fmt)
4977 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4978 *fmt |= DIFF_FORMAT_PATCH;
4981 static int diff_opt_ws_error_highlight(const struct option *option,
4982 const char *arg, int unset)
4984 struct diff_options *opt = option->value;
4985 int val = parse_ws_error_highlight(arg);
4987 BUG_ON_OPT_NEG(unset);
4988 if (val < 0)
4989 return error(_("unknown value after ws-error-highlight=%.*s"),
4990 -1 - val, arg);
4991 opt->ws_error_highlight = val;
4992 return 0;
4995 static int diff_opt_find_object(const struct option *option,
4996 const char *arg, int unset)
4998 struct diff_options *opt = option->value;
4999 struct object_id oid;
5001 BUG_ON_OPT_NEG(unset);
5002 if (repo_get_oid(the_repository, arg, &oid))
5003 return error(_("unable to resolve '%s'"), arg);
5005 if (!opt->objfind)
5006 CALLOC_ARRAY(opt->objfind, 1);
5008 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5009 opt->flags.recursive = 1;
5010 opt->flags.tree_in_recursive = 1;
5011 oidset_insert(opt->objfind, &oid);
5012 return 0;
5015 static int diff_opt_anchored(const struct option *opt,
5016 const char *arg, int unset)
5018 struct diff_options *options = opt->value;
5020 BUG_ON_OPT_NEG(unset);
5021 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5022 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5023 options->anchors_alloc);
5024 options->anchors[options->anchors_nr++] = xstrdup(arg);
5025 return 0;
5028 static int diff_opt_binary(const struct option *opt,
5029 const char *arg, int unset)
5031 struct diff_options *options = opt->value;
5033 BUG_ON_OPT_NEG(unset);
5034 BUG_ON_OPT_ARG(arg);
5035 enable_patch_output(&options->output_format);
5036 options->flags.binary = 1;
5037 return 0;
5040 static int diff_opt_break_rewrites(const struct option *opt,
5041 const char *arg, int unset)
5043 int *break_opt = opt->value;
5044 int opt1, opt2;
5046 BUG_ON_OPT_NEG(unset);
5047 if (!arg)
5048 arg = "";
5049 opt1 = parse_rename_score(&arg);
5050 if (*arg == 0)
5051 opt2 = 0;
5052 else if (*arg != '/')
5053 return error(_("%s expects <n>/<m> form"), opt->long_name);
5054 else {
5055 arg++;
5056 opt2 = parse_rename_score(&arg);
5058 if (*arg != 0)
5059 return error(_("%s expects <n>/<m> form"), opt->long_name);
5060 *break_opt = opt1 | (opt2 << 16);
5061 return 0;
5064 static int diff_opt_char(const struct option *opt,
5065 const char *arg, int unset)
5067 char *value = opt->value;
5069 BUG_ON_OPT_NEG(unset);
5070 if (arg[1])
5071 return error(_("%s expects a character, got '%s'"),
5072 opt->long_name, arg);
5073 *value = arg[0];
5074 return 0;
5077 static int diff_opt_color_moved(const struct option *opt,
5078 const char *arg, int unset)
5080 struct diff_options *options = opt->value;
5082 if (unset) {
5083 options->color_moved = COLOR_MOVED_NO;
5084 } else if (!arg) {
5085 if (diff_color_moved_default)
5086 options->color_moved = diff_color_moved_default;
5087 if (options->color_moved == COLOR_MOVED_NO)
5088 options->color_moved = COLOR_MOVED_DEFAULT;
5089 } else {
5090 int cm = parse_color_moved(arg);
5091 if (cm < 0)
5092 return error(_("bad --color-moved argument: %s"), arg);
5093 options->color_moved = cm;
5095 return 0;
5098 static int diff_opt_color_moved_ws(const struct option *opt,
5099 const char *arg, int unset)
5101 struct diff_options *options = opt->value;
5102 unsigned cm;
5104 if (unset) {
5105 options->color_moved_ws_handling = 0;
5106 return 0;
5109 cm = parse_color_moved_ws(arg);
5110 if (cm & COLOR_MOVED_WS_ERROR)
5111 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5112 options->color_moved_ws_handling = cm;
5113 return 0;
5116 static int diff_opt_color_words(const struct option *opt,
5117 const char *arg, int unset)
5119 struct diff_options *options = opt->value;
5121 BUG_ON_OPT_NEG(unset);
5122 options->use_color = 1;
5123 options->word_diff = DIFF_WORDS_COLOR;
5124 options->word_regex = arg;
5125 return 0;
5128 static int diff_opt_compact_summary(const struct option *opt,
5129 const char *arg, int unset)
5131 struct diff_options *options = opt->value;
5133 BUG_ON_OPT_ARG(arg);
5134 if (unset) {
5135 options->flags.stat_with_summary = 0;
5136 } else {
5137 options->flags.stat_with_summary = 1;
5138 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5140 return 0;
5143 static int diff_opt_diff_algorithm(const struct option *opt,
5144 const char *arg, int unset)
5146 struct diff_options *options = opt->value;
5148 BUG_ON_OPT_NEG(unset);
5150 if (set_diff_algorithm(options, arg))
5151 return error(_("option diff-algorithm accepts \"myers\", "
5152 "\"minimal\", \"patience\" and \"histogram\""));
5154 options->ignore_driver_algorithm = 1;
5156 return 0;
5159 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5160 const char *arg, int unset)
5162 struct diff_options *options = opt->value;
5164 BUG_ON_OPT_NEG(unset);
5165 BUG_ON_OPT_ARG(arg);
5167 if (set_diff_algorithm(options, opt->long_name))
5168 BUG("available diff algorithms include \"myers\", "
5169 "\"minimal\", \"patience\" and \"histogram\"");
5171 options->ignore_driver_algorithm = 1;
5173 return 0;
5176 static int diff_opt_dirstat(const struct option *opt,
5177 const char *arg, int unset)
5179 struct diff_options *options = opt->value;
5181 BUG_ON_OPT_NEG(unset);
5182 if (!strcmp(opt->long_name, "cumulative")) {
5183 if (arg)
5184 BUG("how come --cumulative take a value?");
5185 arg = "cumulative";
5186 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5187 parse_dirstat_opt(options, "files");
5188 parse_dirstat_opt(options, arg ? arg : "");
5189 return 0;
5192 static int diff_opt_find_copies(const struct option *opt,
5193 const char *arg, int unset)
5195 struct diff_options *options = opt->value;
5197 BUG_ON_OPT_NEG(unset);
5198 if (!arg)
5199 arg = "";
5200 options->rename_score = parse_rename_score(&arg);
5201 if (*arg != 0)
5202 return error(_("invalid argument to %s"), opt->long_name);
5204 if (options->detect_rename == DIFF_DETECT_COPY)
5205 options->flags.find_copies_harder = 1;
5206 else
5207 options->detect_rename = DIFF_DETECT_COPY;
5209 return 0;
5212 static int diff_opt_find_renames(const struct option *opt,
5213 const char *arg, int unset)
5215 struct diff_options *options = opt->value;
5217 BUG_ON_OPT_NEG(unset);
5218 if (!arg)
5219 arg = "";
5220 options->rename_score = parse_rename_score(&arg);
5221 if (*arg != 0)
5222 return error(_("invalid argument to %s"), opt->long_name);
5224 options->detect_rename = DIFF_DETECT_RENAME;
5225 return 0;
5228 static int diff_opt_follow(const struct option *opt,
5229 const char *arg, int unset)
5231 struct diff_options *options = opt->value;
5233 BUG_ON_OPT_ARG(arg);
5234 if (unset) {
5235 options->flags.follow_renames = 0;
5236 options->flags.default_follow_renames = 0;
5237 } else {
5238 options->flags.follow_renames = 1;
5240 return 0;
5243 static int diff_opt_ignore_submodules(const struct option *opt,
5244 const char *arg, int unset)
5246 struct diff_options *options = opt->value;
5248 BUG_ON_OPT_NEG(unset);
5249 if (!arg)
5250 arg = "all";
5251 options->flags.override_submodule_config = 1;
5252 handle_ignore_submodules_arg(options, arg);
5253 return 0;
5256 static int diff_opt_line_prefix(const struct option *opt,
5257 const char *optarg, int unset)
5259 struct diff_options *options = opt->value;
5261 BUG_ON_OPT_NEG(unset);
5262 options->line_prefix = optarg;
5263 options->line_prefix_length = strlen(options->line_prefix);
5264 graph_setup_line_prefix(options);
5265 return 0;
5268 static int diff_opt_no_prefix(const struct option *opt,
5269 const char *optarg, int unset)
5271 struct diff_options *options = opt->value;
5273 BUG_ON_OPT_NEG(unset);
5274 BUG_ON_OPT_ARG(optarg);
5275 options->a_prefix = "";
5276 options->b_prefix = "";
5277 return 0;
5280 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5281 const struct option *opt,
5282 const char *arg, int unset)
5284 struct diff_options *options = opt->value;
5285 char *path;
5287 BUG_ON_OPT_NEG(unset);
5288 path = prefix_filename(ctx->prefix, arg);
5289 options->file = xfopen(path, "w");
5290 options->close_file = 1;
5291 if (options->use_color != GIT_COLOR_ALWAYS)
5292 options->use_color = GIT_COLOR_NEVER;
5293 free(path);
5294 return 0;
5297 static int diff_opt_patience(const struct option *opt,
5298 const char *arg, int unset)
5300 struct diff_options *options = opt->value;
5301 int i;
5303 BUG_ON_OPT_NEG(unset);
5304 BUG_ON_OPT_ARG(arg);
5306 * Both --patience and --anchored use PATIENCE_DIFF
5307 * internally, so remove any anchors previously
5308 * specified.
5310 for (i = 0; i < options->anchors_nr; i++)
5311 free(options->anchors[i]);
5312 options->anchors_nr = 0;
5313 options->ignore_driver_algorithm = 1;
5315 return set_diff_algorithm(options, "patience");
5318 static int diff_opt_ignore_regex(const struct option *opt,
5319 const char *arg, int unset)
5321 struct diff_options *options = opt->value;
5322 regex_t *regex;
5324 BUG_ON_OPT_NEG(unset);
5325 regex = xmalloc(sizeof(*regex));
5326 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5327 return error(_("invalid regex given to -I: '%s'"), arg);
5328 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5329 options->ignore_regex_alloc);
5330 options->ignore_regex[options->ignore_regex_nr++] = regex;
5331 return 0;
5334 static int diff_opt_pickaxe_regex(const struct option *opt,
5335 const char *arg, int unset)
5337 struct diff_options *options = opt->value;
5339 BUG_ON_OPT_NEG(unset);
5340 options->pickaxe = arg;
5341 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5342 return 0;
5345 static int diff_opt_pickaxe_string(const struct option *opt,
5346 const char *arg, int unset)
5348 struct diff_options *options = opt->value;
5350 BUG_ON_OPT_NEG(unset);
5351 options->pickaxe = arg;
5352 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5353 return 0;
5356 static int diff_opt_relative(const struct option *opt,
5357 const char *arg, int unset)
5359 struct diff_options *options = opt->value;
5361 options->flags.relative_name = !unset;
5362 if (arg)
5363 options->prefix = arg;
5364 return 0;
5367 static int diff_opt_submodule(const struct option *opt,
5368 const char *arg, int unset)
5370 struct diff_options *options = opt->value;
5372 BUG_ON_OPT_NEG(unset);
5373 if (!arg)
5374 arg = "log";
5375 if (parse_submodule_params(options, arg))
5376 return error(_("failed to parse --submodule option parameter: '%s'"),
5377 arg);
5378 return 0;
5381 static int diff_opt_textconv(const struct option *opt,
5382 const char *arg, int unset)
5384 struct diff_options *options = opt->value;
5386 BUG_ON_OPT_ARG(arg);
5387 if (unset) {
5388 options->flags.allow_textconv = 0;
5389 } else {
5390 options->flags.allow_textconv = 1;
5391 options->flags.textconv_set_via_cmdline = 1;
5393 return 0;
5396 static int diff_opt_unified(const struct option *opt,
5397 const char *arg, int unset)
5399 struct diff_options *options = opt->value;
5400 char *s;
5402 BUG_ON_OPT_NEG(unset);
5404 if (arg) {
5405 options->context = strtol(arg, &s, 10);
5406 if (*s)
5407 return error(_("%s expects a numerical value"), "--unified");
5409 enable_patch_output(&options->output_format);
5411 return 0;
5414 static int diff_opt_word_diff(const struct option *opt,
5415 const char *arg, int unset)
5417 struct diff_options *options = opt->value;
5419 BUG_ON_OPT_NEG(unset);
5420 if (arg) {
5421 if (!strcmp(arg, "plain"))
5422 options->word_diff = DIFF_WORDS_PLAIN;
5423 else if (!strcmp(arg, "color")) {
5424 options->use_color = 1;
5425 options->word_diff = DIFF_WORDS_COLOR;
5427 else if (!strcmp(arg, "porcelain"))
5428 options->word_diff = DIFF_WORDS_PORCELAIN;
5429 else if (!strcmp(arg, "none"))
5430 options->word_diff = DIFF_WORDS_NONE;
5431 else
5432 return error(_("bad --word-diff argument: %s"), arg);
5433 } else {
5434 if (options->word_diff == DIFF_WORDS_NONE)
5435 options->word_diff = DIFF_WORDS_PLAIN;
5437 return 0;
5440 static int diff_opt_word_diff_regex(const struct option *opt,
5441 const char *arg, int unset)
5443 struct diff_options *options = opt->value;
5445 BUG_ON_OPT_NEG(unset);
5446 if (options->word_diff == DIFF_WORDS_NONE)
5447 options->word_diff = DIFF_WORDS_PLAIN;
5448 options->word_regex = arg;
5449 return 0;
5452 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5454 struct diff_options *options = opt->value;
5456 BUG_ON_OPT_NEG(unset);
5457 if (!strcmp(opt->long_name, "skip-to"))
5458 options->skip_instead_of_rotate = 1;
5459 else
5460 options->skip_instead_of_rotate = 0;
5461 options->rotate_to = arg;
5462 return 0;
5465 struct option *add_diff_options(const struct option *opts,
5466 struct diff_options *options)
5468 struct option parseopts[] = {
5469 OPT_GROUP(N_("Diff output format options")),
5470 OPT_BITOP('p', "patch", &options->output_format,
5471 N_("generate patch"),
5472 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5473 OPT_BIT_F('s', "no-patch", &options->output_format,
5474 N_("suppress diff output"),
5475 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5476 OPT_BITOP('u', NULL, &options->output_format,
5477 N_("generate patch"),
5478 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5479 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5480 N_("generate diffs with <n> lines context"),
5481 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5482 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5483 N_("generate diffs with <n> lines context")),
5484 OPT_BIT_F(0, "raw", &options->output_format,
5485 N_("generate the diff in raw format"),
5486 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5487 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5488 N_("synonym for '-p --raw'"),
5489 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5490 DIFF_FORMAT_NO_OUTPUT),
5491 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5492 N_("synonym for '-p --stat'"),
5493 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5494 DIFF_FORMAT_NO_OUTPUT),
5495 OPT_BIT_F(0, "numstat", &options->output_format,
5496 N_("machine friendly --stat"),
5497 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5498 OPT_BIT_F(0, "shortstat", &options->output_format,
5499 N_("output only the last line of --stat"),
5500 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5501 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5502 N_("output the distribution of relative amount of changes for each sub-directory"),
5503 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5504 diff_opt_dirstat),
5505 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5506 N_("synonym for --dirstat=cumulative"),
5507 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5508 diff_opt_dirstat),
5509 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5510 N_("synonym for --dirstat=files,param1,param2..."),
5511 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5512 diff_opt_dirstat),
5513 OPT_BIT_F(0, "check", &options->output_format,
5514 N_("warn if changes introduce conflict markers or whitespace errors"),
5515 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5516 OPT_BIT_F(0, "summary", &options->output_format,
5517 N_("condensed summary such as creations, renames and mode changes"),
5518 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5519 OPT_BIT_F(0, "name-only", &options->output_format,
5520 N_("show only names of changed files"),
5521 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5522 OPT_BIT_F(0, "name-status", &options->output_format,
5523 N_("show only names and status of changed files"),
5524 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5525 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5526 N_("generate diffstat"),
5527 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5528 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5529 N_("generate diffstat with a given width"),
5530 PARSE_OPT_NONEG, diff_opt_stat),
5531 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5532 N_("generate diffstat with a given name width"),
5533 PARSE_OPT_NONEG, diff_opt_stat),
5534 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5535 N_("generate diffstat with a given graph width"),
5536 PARSE_OPT_NONEG, diff_opt_stat),
5537 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5538 N_("generate diffstat with limited lines"),
5539 PARSE_OPT_NONEG, diff_opt_stat),
5540 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5541 N_("generate compact summary in diffstat"),
5542 PARSE_OPT_NOARG, diff_opt_compact_summary),
5543 OPT_CALLBACK_F(0, "binary", options, NULL,
5544 N_("output a binary diff that can be applied"),
5545 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5546 OPT_BOOL(0, "full-index", &options->flags.full_index,
5547 N_("show full pre- and post-image object names on the \"index\" lines")),
5548 OPT_COLOR_FLAG(0, "color", &options->use_color,
5549 N_("show colored diff")),
5550 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5551 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5552 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5553 OPT_SET_INT('z', NULL, &options->line_termination,
5554 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5556 OPT__ABBREV(&options->abbrev),
5557 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5558 N_("show the given source prefix instead of \"a/\""),
5559 PARSE_OPT_NONEG),
5560 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5561 N_("show the given destination prefix instead of \"b/\""),
5562 PARSE_OPT_NONEG),
5563 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5564 N_("prepend an additional prefix to every line of output"),
5565 PARSE_OPT_NONEG, diff_opt_line_prefix),
5566 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5567 N_("do not show any source or destination prefix"),
5568 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5569 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5570 N_("show context between diff hunks up to the specified number of lines"),
5571 PARSE_OPT_NONEG),
5572 OPT_CALLBACK_F(0, "output-indicator-new",
5573 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5574 N_("<char>"),
5575 N_("specify the character to indicate a new line instead of '+'"),
5576 PARSE_OPT_NONEG, diff_opt_char),
5577 OPT_CALLBACK_F(0, "output-indicator-old",
5578 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5579 N_("<char>"),
5580 N_("specify the character to indicate an old line instead of '-'"),
5581 PARSE_OPT_NONEG, diff_opt_char),
5582 OPT_CALLBACK_F(0, "output-indicator-context",
5583 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5584 N_("<char>"),
5585 N_("specify the character to indicate a context instead of ' '"),
5586 PARSE_OPT_NONEG, diff_opt_char),
5588 OPT_GROUP(N_("Diff rename options")),
5589 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5590 N_("break complete rewrite changes into pairs of delete and create"),
5591 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5592 diff_opt_break_rewrites),
5593 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5594 N_("detect renames"),
5595 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5596 diff_opt_find_renames),
5597 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5598 N_("omit the preimage for deletes"),
5599 1, PARSE_OPT_NONEG),
5600 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5601 N_("detect copies"),
5602 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5603 diff_opt_find_copies),
5604 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5605 N_("use unmodified files as source to find copies")),
5606 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5607 N_("disable rename detection"),
5608 0, PARSE_OPT_NONEG),
5609 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5610 N_("use empty blobs as rename source")),
5611 OPT_CALLBACK_F(0, "follow", options, NULL,
5612 N_("continue listing the history of a file beyond renames"),
5613 PARSE_OPT_NOARG, diff_opt_follow),
5614 OPT_INTEGER('l', NULL, &options->rename_limit,
5615 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5617 OPT_GROUP(N_("Diff algorithm options")),
5618 OPT_CALLBACK_F(0, "minimal", options, NULL,
5619 N_("produce the smallest possible diff"),
5620 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5621 diff_opt_diff_algorithm_no_arg),
5622 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5623 N_("ignore whitespace when comparing lines"),
5624 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5625 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5626 N_("ignore changes in amount of whitespace"),
5627 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5628 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5629 N_("ignore changes in whitespace at EOL"),
5630 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5631 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5632 N_("ignore carrier-return at the end of line"),
5633 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5634 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5635 N_("ignore changes whose lines are all blank"),
5636 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5637 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5638 N_("ignore changes whose all lines match <regex>"),
5639 0, diff_opt_ignore_regex),
5640 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5641 N_("heuristic to shift diff hunk boundaries for easy reading"),
5642 XDF_INDENT_HEURISTIC),
5643 OPT_CALLBACK_F(0, "patience", options, NULL,
5644 N_("generate diff using the \"patience diff\" algorithm"),
5645 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5646 diff_opt_patience),
5647 OPT_CALLBACK_F(0, "histogram", options, NULL,
5648 N_("generate diff using the \"histogram diff\" algorithm"),
5649 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5650 diff_opt_diff_algorithm_no_arg),
5651 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5652 N_("choose a diff algorithm"),
5653 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5654 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5655 N_("generate diff using the \"anchored diff\" algorithm"),
5656 PARSE_OPT_NONEG, diff_opt_anchored),
5657 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5658 N_("show word diff, using <mode> to delimit changed words"),
5659 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5660 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5661 N_("use <regex> to decide what a word is"),
5662 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5663 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5664 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5665 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5666 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5667 N_("moved lines of code are colored differently"),
5668 PARSE_OPT_OPTARG, diff_opt_color_moved),
5669 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5670 N_("how white spaces are ignored in --color-moved"),
5671 0, diff_opt_color_moved_ws),
5673 OPT_GROUP(N_("Other diff options")),
5674 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5675 N_("when run from subdir, exclude changes outside and show relative paths"),
5676 PARSE_OPT_OPTARG,
5677 diff_opt_relative),
5678 OPT_BOOL('a', "text", &options->flags.text,
5679 N_("treat all files as text")),
5680 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5681 N_("swap two inputs, reverse the diff")),
5682 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5683 N_("exit with 1 if there were differences, 0 otherwise")),
5684 OPT_BOOL(0, "quiet", &options->flags.quick,
5685 N_("disable all output of the program")),
5686 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5687 N_("allow an external diff helper to be executed")),
5688 OPT_CALLBACK_F(0, "textconv", options, NULL,
5689 N_("run external text conversion filters when comparing binary files"),
5690 PARSE_OPT_NOARG, diff_opt_textconv),
5691 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5692 N_("ignore changes to submodules in the diff generation"),
5693 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5694 diff_opt_ignore_submodules),
5695 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5696 N_("specify how differences in submodules are shown"),
5697 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5698 diff_opt_submodule),
5699 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5700 N_("hide 'git add -N' entries from the index"),
5701 1, PARSE_OPT_NONEG),
5702 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5703 N_("treat 'git add -N' entries as real in the index"),
5704 0, PARSE_OPT_NONEG),
5705 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5706 N_("look for differences that change the number of occurrences of the specified string"),
5707 0, diff_opt_pickaxe_string),
5708 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5709 N_("look for differences that change the number of occurrences of the specified regex"),
5710 0, diff_opt_pickaxe_regex),
5711 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5712 N_("show all changes in the changeset with -S or -G"),
5713 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5714 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5715 N_("treat <string> in -S as extended POSIX regular expression"),
5716 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5717 OPT_FILENAME('O', NULL, &options->orderfile,
5718 N_("control the order in which files appear in the output")),
5719 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5720 N_("show the change in the specified path first"),
5721 PARSE_OPT_NONEG, diff_opt_rotate_to),
5722 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5723 N_("skip the output to the specified path"),
5724 PARSE_OPT_NONEG, diff_opt_rotate_to),
5725 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5726 N_("look for differences that change the number of occurrences of the specified object"),
5727 PARSE_OPT_NONEG, diff_opt_find_object),
5728 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5729 N_("select files by diff type"),
5730 PARSE_OPT_NONEG, diff_opt_diff_filter),
5731 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5732 N_("output to a specific file"),
5733 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5735 OPT_END()
5738 return parse_options_concat(opts, parseopts);
5741 int diff_opt_parse(struct diff_options *options,
5742 const char **av, int ac, const char *prefix)
5744 struct option no_options[] = { OPT_END() };
5745 struct option *parseopts = add_diff_options(no_options, options);
5747 if (!prefix)
5748 prefix = "";
5750 ac = parse_options(ac, av, prefix, parseopts, NULL,
5751 PARSE_OPT_KEEP_DASHDASH |
5752 PARSE_OPT_KEEP_UNKNOWN_OPT |
5753 PARSE_OPT_NO_INTERNAL_HELP |
5754 PARSE_OPT_ONE_SHOT |
5755 PARSE_OPT_STOP_AT_NON_OPTION);
5756 free(parseopts);
5758 return ac;
5761 int parse_rename_score(const char **cp_p)
5763 unsigned long num, scale;
5764 int ch, dot;
5765 const char *cp = *cp_p;
5767 num = 0;
5768 scale = 1;
5769 dot = 0;
5770 for (;;) {
5771 ch = *cp;
5772 if ( !dot && ch == '.' ) {
5773 scale = 1;
5774 dot = 1;
5775 } else if ( ch == '%' ) {
5776 scale = dot ? scale*100 : 100;
5777 cp++; /* % is always at the end */
5778 break;
5779 } else if ( ch >= '0' && ch <= '9' ) {
5780 if ( scale < 100000 ) {
5781 scale *= 10;
5782 num = (num*10) + (ch-'0');
5784 } else {
5785 break;
5787 cp++;
5789 *cp_p = cp;
5791 /* user says num divided by scale and we say internally that
5792 * is MAX_SCORE * num / scale.
5794 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5797 struct diff_queue_struct diff_queued_diff;
5799 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5801 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5802 queue->queue[queue->nr++] = dp;
5805 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5806 struct diff_filespec *one,
5807 struct diff_filespec *two)
5809 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5810 dp->one = one;
5811 dp->two = two;
5812 if (queue)
5813 diff_q(queue, dp);
5814 return dp;
5817 void diff_free_filepair(struct diff_filepair *p)
5819 free_filespec(p->one);
5820 free_filespec(p->two);
5821 free(p);
5824 void diff_free_queue(struct diff_queue_struct *q)
5826 for (int i = 0; i < q->nr; i++)
5827 diff_free_filepair(q->queue[i]);
5828 free(q->queue);
5831 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5833 int abblen;
5834 const char *abbrev;
5836 /* Do we want all 40 hex characters? */
5837 if (len == the_hash_algo->hexsz)
5838 return oid_to_hex(oid);
5840 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5841 abbrev = diff_abbrev_oid(oid, len);
5843 if (!print_sha1_ellipsis())
5844 return abbrev;
5846 abblen = strlen(abbrev);
5849 * In well-behaved cases, where the abbreviated result is the
5850 * same as the requested length, append three dots after the
5851 * abbreviation (hence the whole logic is limited to the case
5852 * where abblen < 37); when the actual abbreviated result is a
5853 * bit longer than the requested length, we reduce the number
5854 * of dots so that they match the well-behaved ones. However,
5855 * if the actual abbreviation is longer than the requested
5856 * length by more than three, we give up on aligning, and add
5857 * three dots anyway, to indicate that the output is not the
5858 * full object name. Yes, this may be suboptimal, but this
5859 * appears only in "diff --raw --abbrev" output and it is not
5860 * worth the effort to change it now. Note that this would
5861 * likely to work fine when the automatic sizing of default
5862 * abbreviation length is used--we would be fed -1 in "len" in
5863 * that case, and will end up always appending three-dots, but
5864 * the automatic sizing is supposed to give abblen that ensures
5865 * uniqueness across all objects (statistically speaking).
5867 if (abblen < the_hash_algo->hexsz - 3) {
5868 static char hex[GIT_MAX_HEXSZ + 1];
5869 if (len < abblen && abblen <= len + 2)
5870 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5871 else
5872 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5873 return hex;
5876 return oid_to_hex(oid);
5879 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5881 int line_termination = opt->line_termination;
5882 int inter_name_termination = line_termination ? '\t' : '\0';
5884 fprintf(opt->file, "%s", diff_line_prefix(opt));
5885 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5886 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5887 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5888 fprintf(opt->file, "%s ",
5889 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5891 if (p->score) {
5892 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5893 inter_name_termination);
5894 } else {
5895 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5898 if (p->status == DIFF_STATUS_COPIED ||
5899 p->status == DIFF_STATUS_RENAMED) {
5900 const char *name_a, *name_b;
5901 name_a = p->one->path;
5902 name_b = p->two->path;
5903 strip_prefix(opt->prefix_length, &name_a, &name_b);
5904 write_name_quoted(name_a, opt->file, inter_name_termination);
5905 write_name_quoted(name_b, opt->file, line_termination);
5906 } else {
5907 const char *name_a, *name_b;
5908 name_a = p->one->mode ? p->one->path : p->two->path;
5909 name_b = NULL;
5910 strip_prefix(opt->prefix_length, &name_a, &name_b);
5911 write_name_quoted(name_a, opt->file, line_termination);
5915 int diff_unmodified_pair(struct diff_filepair *p)
5917 /* This function is written stricter than necessary to support
5918 * the currently implemented transformers, but the idea is to
5919 * let transformers to produce diff_filepairs any way they want,
5920 * and filter and clean them up here before producing the output.
5922 struct diff_filespec *one = p->one, *two = p->two;
5924 if (DIFF_PAIR_UNMERGED(p))
5925 return 0; /* unmerged is interesting */
5927 /* deletion, addition, mode or type change
5928 * and rename are all interesting.
5930 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5931 DIFF_PAIR_MODE_CHANGED(p) ||
5932 strcmp(one->path, two->path))
5933 return 0;
5935 /* both are valid and point at the same path. that is, we are
5936 * dealing with a change.
5938 if (one->oid_valid && two->oid_valid &&
5939 oideq(&one->oid, &two->oid) &&
5940 !one->dirty_submodule && !two->dirty_submodule)
5941 return 1; /* no change */
5942 if (!one->oid_valid && !two->oid_valid)
5943 return 1; /* both look at the same file on the filesystem. */
5944 return 0;
5947 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5949 int include_conflict_headers =
5950 (additional_headers(o, p->one->path) &&
5951 !o->pickaxe_opts &&
5952 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5955 * Check if we can return early without showing a diff. Note that
5956 * diff_filepair only stores {oid, path, mode, is_valid}
5957 * information for each path, and thus diff_unmodified_pair() only
5958 * considers those bits of info. However, we do not want pairs
5959 * created by create_filepairs_for_header_only_notifications()
5960 * (which always look like unmodified pairs) to be ignored, so
5961 * return early if both p is unmodified AND we don't want to
5962 * include_conflict_headers.
5964 if (diff_unmodified_pair(p) && !include_conflict_headers)
5965 return;
5967 /* Actually, we can also return early to avoid showing tree diffs */
5968 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5969 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5970 return;
5972 run_diff(p, o);
5975 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5976 struct diffstat_t *diffstat)
5978 if (diff_unmodified_pair(p))
5979 return;
5981 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5982 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5983 return; /* no useful stat for tree diffs */
5985 run_diffstat(p, o, diffstat);
5988 static void diff_flush_checkdiff(struct diff_filepair *p,
5989 struct diff_options *o)
5991 if (diff_unmodified_pair(p))
5992 return;
5994 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5995 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5996 return; /* nothing to check in tree diffs */
5998 run_checkdiff(p, o);
6001 int diff_queue_is_empty(struct diff_options *o)
6003 struct diff_queue_struct *q = &diff_queued_diff;
6004 int i;
6005 int include_conflict_headers =
6006 (o->additional_path_headers &&
6007 strmap_get_size(o->additional_path_headers) &&
6008 !o->pickaxe_opts &&
6009 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6011 if (include_conflict_headers)
6012 return 0;
6014 for (i = 0; i < q->nr; i++)
6015 if (!diff_unmodified_pair(q->queue[i]))
6016 return 0;
6017 return 1;
6020 #if DIFF_DEBUG
6021 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6023 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6024 x, one ? one : "",
6025 s->path,
6026 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6027 s->mode,
6028 s->oid_valid ? oid_to_hex(&s->oid) : "");
6029 fprintf(stderr, "queue[%d] %s size %lu\n",
6030 x, one ? one : "",
6031 s->size);
6034 void diff_debug_filepair(const struct diff_filepair *p, int i)
6036 diff_debug_filespec(p->one, i, "one");
6037 diff_debug_filespec(p->two, i, "two");
6038 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6039 p->score, p->status ? p->status : '?',
6040 p->one->rename_used, p->broken_pair);
6043 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6045 int i;
6046 if (msg)
6047 fprintf(stderr, "%s\n", msg);
6048 fprintf(stderr, "q->nr = %d\n", q->nr);
6049 for (i = 0; i < q->nr; i++) {
6050 struct diff_filepair *p = q->queue[i];
6051 diff_debug_filepair(p, i);
6054 #endif
6056 static void diff_resolve_rename_copy(void)
6058 int i;
6059 struct diff_filepair *p;
6060 struct diff_queue_struct *q = &diff_queued_diff;
6062 diff_debug_queue("resolve-rename-copy", q);
6064 for (i = 0; i < q->nr; i++) {
6065 p = q->queue[i];
6066 p->status = 0; /* undecided */
6067 if (DIFF_PAIR_UNMERGED(p))
6068 p->status = DIFF_STATUS_UNMERGED;
6069 else if (!DIFF_FILE_VALID(p->one))
6070 p->status = DIFF_STATUS_ADDED;
6071 else if (!DIFF_FILE_VALID(p->two))
6072 p->status = DIFF_STATUS_DELETED;
6073 else if (DIFF_PAIR_TYPE_CHANGED(p))
6074 p->status = DIFF_STATUS_TYPE_CHANGED;
6076 /* from this point on, we are dealing with a pair
6077 * whose both sides are valid and of the same type, i.e.
6078 * either in-place edit or rename/copy edit.
6080 else if (DIFF_PAIR_RENAME(p)) {
6082 * A rename might have re-connected a broken
6083 * pair up, causing the pathnames to be the
6084 * same again. If so, that's not a rename at
6085 * all, just a modification..
6087 * Otherwise, see if this source was used for
6088 * multiple renames, in which case we decrement
6089 * the count, and call it a copy.
6091 if (!strcmp(p->one->path, p->two->path))
6092 p->status = DIFF_STATUS_MODIFIED;
6093 else if (--p->one->rename_used > 0)
6094 p->status = DIFF_STATUS_COPIED;
6095 else
6096 p->status = DIFF_STATUS_RENAMED;
6098 else if (!oideq(&p->one->oid, &p->two->oid) ||
6099 p->one->mode != p->two->mode ||
6100 p->one->dirty_submodule ||
6101 p->two->dirty_submodule ||
6102 is_null_oid(&p->one->oid))
6103 p->status = DIFF_STATUS_MODIFIED;
6104 else {
6105 /* This is a "no-change" entry and should not
6106 * happen anymore, but prepare for broken callers.
6108 error("feeding unmodified %s to diffcore",
6109 p->one->path);
6110 p->status = DIFF_STATUS_UNKNOWN;
6113 diff_debug_queue("resolve-rename-copy done", q);
6116 static int check_pair_status(struct diff_filepair *p)
6118 switch (p->status) {
6119 case DIFF_STATUS_UNKNOWN:
6120 return 0;
6121 case 0:
6122 die("internal error in diff-resolve-rename-copy");
6123 default:
6124 return 1;
6128 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6130 int fmt = opt->output_format;
6132 if (fmt & DIFF_FORMAT_CHECKDIFF)
6133 diff_flush_checkdiff(p, opt);
6134 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6135 diff_flush_raw(p, opt);
6136 else if (fmt & DIFF_FORMAT_NAME) {
6137 const char *name_a, *name_b;
6138 name_a = p->two->path;
6139 name_b = NULL;
6140 strip_prefix(opt->prefix_length, &name_a, &name_b);
6141 fprintf(opt->file, "%s", diff_line_prefix(opt));
6142 write_name_quoted(name_a, opt->file, opt->line_termination);
6146 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6148 struct strbuf sb = STRBUF_INIT;
6149 if (fs->mode)
6150 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6151 else
6152 strbuf_addf(&sb, " %s ", newdelete);
6154 quote_c_style(fs->path, &sb, NULL, 0);
6155 strbuf_addch(&sb, '\n');
6156 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6157 sb.buf, sb.len, 0);
6158 strbuf_release(&sb);
6161 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6162 int show_name)
6164 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6165 struct strbuf sb = STRBUF_INIT;
6166 strbuf_addf(&sb, " mode change %06o => %06o",
6167 p->one->mode, p->two->mode);
6168 if (show_name) {
6169 strbuf_addch(&sb, ' ');
6170 quote_c_style(p->two->path, &sb, NULL, 0);
6172 strbuf_addch(&sb, '\n');
6173 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6174 sb.buf, sb.len, 0);
6175 strbuf_release(&sb);
6179 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6180 struct diff_filepair *p)
6182 struct strbuf sb = STRBUF_INIT;
6183 struct strbuf names = STRBUF_INIT;
6185 pprint_rename(&names, p->one->path, p->two->path);
6186 strbuf_addf(&sb, " %s %s (%d%%)\n",
6187 renamecopy, names.buf, similarity_index(p));
6188 strbuf_release(&names);
6189 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6190 sb.buf, sb.len, 0);
6191 show_mode_change(opt, p, 0);
6192 strbuf_release(&sb);
6195 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6197 switch(p->status) {
6198 case DIFF_STATUS_DELETED:
6199 show_file_mode_name(opt, "delete", p->one);
6200 break;
6201 case DIFF_STATUS_ADDED:
6202 show_file_mode_name(opt, "create", p->two);
6203 break;
6204 case DIFF_STATUS_COPIED:
6205 show_rename_copy(opt, "copy", p);
6206 break;
6207 case DIFF_STATUS_RENAMED:
6208 show_rename_copy(opt, "rename", p);
6209 break;
6210 default:
6211 if (p->score) {
6212 struct strbuf sb = STRBUF_INIT;
6213 strbuf_addstr(&sb, " rewrite ");
6214 quote_c_style(p->two->path, &sb, NULL, 0);
6215 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6216 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6217 sb.buf, sb.len, 0);
6218 strbuf_release(&sb);
6220 show_mode_change(opt, p, !p->score);
6221 break;
6225 struct patch_id_t {
6226 git_hash_ctx *ctx;
6227 int patchlen;
6230 static int remove_space(char *line, int len)
6232 int i;
6233 char *dst = line;
6234 unsigned char c;
6236 for (i = 0; i < len; i++)
6237 if (!isspace((c = line[i])))
6238 *dst++ = c;
6240 return dst - line;
6243 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6245 unsigned char hash[GIT_MAX_RAWSZ];
6246 unsigned short carry = 0;
6247 int i;
6249 the_hash_algo->final_fn(hash, ctx);
6250 the_hash_algo->init_fn(ctx);
6251 /* 20-byte sum, with carry */
6252 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6253 carry += result->hash[i] + hash[i];
6254 result->hash[i] = carry;
6255 carry >>= 8;
6259 static int patch_id_consume(void *priv, char *line, unsigned long len)
6261 struct patch_id_t *data = priv;
6262 int new_len;
6264 if (len > 12 && starts_with(line, "\\ "))
6265 return 0;
6266 new_len = remove_space(line, len);
6268 the_hash_algo->update_fn(data->ctx, line, new_len);
6269 data->patchlen += new_len;
6270 return 0;
6273 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6275 the_hash_algo->update_fn(ctx, str, strlen(str));
6278 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6280 /* large enough for 2^32 in octal */
6281 char buf[12];
6282 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6283 the_hash_algo->update_fn(ctx, buf, len);
6286 /* returns 0 upon success, and writes result into oid */
6287 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6289 struct diff_queue_struct *q = &diff_queued_diff;
6290 int i;
6291 git_hash_ctx ctx;
6292 struct patch_id_t data;
6294 the_hash_algo->init_fn(&ctx);
6295 memset(&data, 0, sizeof(struct patch_id_t));
6296 data.ctx = &ctx;
6297 oidclr(oid);
6299 for (i = 0; i < q->nr; i++) {
6300 xpparam_t xpp;
6301 xdemitconf_t xecfg;
6302 mmfile_t mf1, mf2;
6303 struct diff_filepair *p = q->queue[i];
6304 int len1, len2;
6306 memset(&xpp, 0, sizeof(xpp));
6307 memset(&xecfg, 0, sizeof(xecfg));
6308 if (p->status == 0)
6309 return error("internal diff status error");
6310 if (p->status == DIFF_STATUS_UNKNOWN)
6311 continue;
6312 if (diff_unmodified_pair(p))
6313 continue;
6314 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6315 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6316 continue;
6317 if (DIFF_PAIR_UNMERGED(p))
6318 continue;
6320 diff_fill_oid_info(p->one, options->repo->index);
6321 diff_fill_oid_info(p->two, options->repo->index);
6323 len1 = remove_space(p->one->path, strlen(p->one->path));
6324 len2 = remove_space(p->two->path, strlen(p->two->path));
6325 patch_id_add_string(&ctx, "diff--git");
6326 patch_id_add_string(&ctx, "a/");
6327 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6328 patch_id_add_string(&ctx, "b/");
6329 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6331 if (p->one->mode == 0) {
6332 patch_id_add_string(&ctx, "newfilemode");
6333 patch_id_add_mode(&ctx, p->two->mode);
6334 } else if (p->two->mode == 0) {
6335 patch_id_add_string(&ctx, "deletedfilemode");
6336 patch_id_add_mode(&ctx, p->one->mode);
6337 } else if (p->one->mode != p->two->mode) {
6338 patch_id_add_string(&ctx, "oldmode");
6339 patch_id_add_mode(&ctx, p->one->mode);
6340 patch_id_add_string(&ctx, "newmode");
6341 patch_id_add_mode(&ctx, p->two->mode);
6344 if (diff_header_only) {
6345 /* don't do anything since we're only populating header info */
6346 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6347 diff_filespec_is_binary(options->repo, p->two)) {
6348 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6349 the_hash_algo->hexsz);
6350 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6351 the_hash_algo->hexsz);
6352 } else {
6353 if (p->one->mode == 0) {
6354 patch_id_add_string(&ctx, "---/dev/null");
6355 patch_id_add_string(&ctx, "+++b/");
6356 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6357 } else if (p->two->mode == 0) {
6358 patch_id_add_string(&ctx, "---a/");
6359 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6360 patch_id_add_string(&ctx, "+++/dev/null");
6361 } else {
6362 patch_id_add_string(&ctx, "---a/");
6363 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6364 patch_id_add_string(&ctx, "+++b/");
6365 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6368 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6369 fill_mmfile(options->repo, &mf2, p->two) < 0)
6370 return error("unable to read files to diff");
6371 xpp.flags = 0;
6372 xecfg.ctxlen = 3;
6373 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6374 if (xdi_diff_outf(&mf1, &mf2, NULL,
6375 patch_id_consume, &data, &xpp, &xecfg))
6376 return error("unable to generate patch-id diff for %s",
6377 p->one->path);
6379 flush_one_hunk(oid, &ctx);
6382 return 0;
6385 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6387 struct diff_queue_struct *q = &diff_queued_diff;
6388 int result = diff_get_patch_id(options, oid, diff_header_only);
6390 diff_free_queue(q);
6391 DIFF_QUEUE_CLEAR(q);
6393 return result;
6396 static int is_summary_empty(const struct diff_queue_struct *q)
6398 int i;
6400 for (i = 0; i < q->nr; i++) {
6401 const struct diff_filepair *p = q->queue[i];
6403 switch (p->status) {
6404 case DIFF_STATUS_DELETED:
6405 case DIFF_STATUS_ADDED:
6406 case DIFF_STATUS_COPIED:
6407 case DIFF_STATUS_RENAMED:
6408 return 0;
6409 default:
6410 if (p->score)
6411 return 0;
6412 if (p->one->mode && p->two->mode &&
6413 p->one->mode != p->two->mode)
6414 return 0;
6415 break;
6418 return 1;
6421 static const char rename_limit_warning[] =
6422 N_("exhaustive rename detection was skipped due to too many files.");
6424 static const char degrade_cc_to_c_warning[] =
6425 N_("only found copies from modified paths due to too many files.");
6427 static const char rename_limit_advice[] =
6428 N_("you may want to set your %s variable to at least "
6429 "%d and retry the command.");
6431 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6433 fflush(stdout);
6434 if (degraded_cc)
6435 warning(_(degrade_cc_to_c_warning));
6436 else if (needed)
6437 warning(_(rename_limit_warning));
6438 else
6439 return;
6440 if (0 < needed)
6441 warning(_(rename_limit_advice), varname, needed);
6444 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6446 struct strset present;
6447 struct diff_queue_struct *q = &diff_queued_diff;
6448 struct hashmap_iter iter;
6449 struct strmap_entry *e;
6450 int i;
6452 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6455 * Find out which paths exist in diff_queued_diff, preferring
6456 * one->path for any pair that has multiple paths.
6458 for (i = 0; i < q->nr; i++) {
6459 struct diff_filepair *p = q->queue[i];
6460 char *path = p->one->path ? p->one->path : p->two->path;
6462 if (strmap_contains(o->additional_path_headers, path))
6463 strset_add(&present, path);
6467 * Loop over paths in additional_path_headers; for each NOT already
6468 * in diff_queued_diff, create a synthetic filepair and insert that
6469 * into diff_queued_diff.
6471 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6472 if (!strset_contains(&present, e->key)) {
6473 struct diff_filespec *one, *two;
6474 struct diff_filepair *p;
6476 one = alloc_filespec(e->key);
6477 two = alloc_filespec(e->key);
6478 fill_filespec(one, null_oid(), 0, 0);
6479 fill_filespec(two, null_oid(), 0, 0);
6480 p = diff_queue(q, one, two);
6481 p->status = DIFF_STATUS_MODIFIED;
6485 /* Re-sort the filepairs */
6486 diffcore_fix_diff_index();
6488 /* Cleanup */
6489 strset_clear(&present);
6492 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6494 int i;
6495 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6496 struct diff_queue_struct *q = &diff_queued_diff;
6498 if (WSEH_NEW & WS_RULE_MASK)
6499 BUG("WS rules bit mask overlaps with diff symbol flags");
6501 if (o->color_moved)
6502 o->emitted_symbols = &esm;
6504 if (o->additional_path_headers)
6505 create_filepairs_for_header_only_notifications(o);
6507 for (i = 0; i < q->nr; i++) {
6508 struct diff_filepair *p = q->queue[i];
6509 if (check_pair_status(p))
6510 diff_flush_patch(p, o);
6513 if (o->emitted_symbols) {
6514 if (o->color_moved) {
6515 struct mem_pool entry_pool;
6516 struct moved_entry_list *entry_list;
6518 mem_pool_init(&entry_pool, 1024 * 1024);
6519 entry_list = add_lines_to_move_detection(o,
6520 &entry_pool);
6521 mark_color_as_moved(o, entry_list);
6522 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6523 dim_moved_lines(o);
6525 mem_pool_discard(&entry_pool, 0);
6526 free(entry_list);
6529 for (i = 0; i < esm.nr; i++)
6530 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6532 for (i = 0; i < esm.nr; i++)
6533 free((void *)esm.buf[i].line);
6534 esm.nr = 0;
6536 o->emitted_symbols = NULL;
6540 static void diff_free_file(struct diff_options *options)
6542 if (options->close_file)
6543 fclose(options->file);
6546 static void diff_free_ignore_regex(struct diff_options *options)
6548 int i;
6550 for (i = 0; i < options->ignore_regex_nr; i++) {
6551 regfree(options->ignore_regex[i]);
6552 free(options->ignore_regex[i]);
6554 free(options->ignore_regex);
6557 void diff_free(struct diff_options *options)
6559 if (options->no_free)
6560 return;
6562 diff_free_file(options);
6563 diff_free_ignore_regex(options);
6564 clear_pathspec(&options->pathspec);
6567 void diff_flush(struct diff_options *options)
6569 struct diff_queue_struct *q = &diff_queued_diff;
6570 int i, output_format = options->output_format;
6571 int separator = 0;
6572 int dirstat_by_line = 0;
6575 * Order: raw, stat, summary, patch
6576 * or: name/name-status/checkdiff (other bits clear)
6578 if (!q->nr && !options->additional_path_headers)
6579 goto free_queue;
6581 if (output_format & (DIFF_FORMAT_RAW |
6582 DIFF_FORMAT_NAME |
6583 DIFF_FORMAT_NAME_STATUS |
6584 DIFF_FORMAT_CHECKDIFF)) {
6585 for (i = 0; i < q->nr; i++) {
6586 struct diff_filepair *p = q->queue[i];
6587 if (check_pair_status(p))
6588 flush_one_pair(p, options);
6590 separator++;
6593 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6594 dirstat_by_line = 1;
6596 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6597 dirstat_by_line) {
6598 struct diffstat_t diffstat;
6600 compute_diffstat(options, &diffstat, q);
6601 if (output_format & DIFF_FORMAT_NUMSTAT)
6602 show_numstat(&diffstat, options);
6603 if (output_format & DIFF_FORMAT_DIFFSTAT)
6604 show_stats(&diffstat, options);
6605 if (output_format & DIFF_FORMAT_SHORTSTAT)
6606 show_shortstats(&diffstat, options);
6607 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6608 show_dirstat_by_line(&diffstat, options);
6609 free_diffstat_info(&diffstat);
6610 separator++;
6612 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6613 show_dirstat(options);
6615 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6616 for (i = 0; i < q->nr; i++) {
6617 diff_summary(options, q->queue[i]);
6619 separator++;
6622 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6623 options->flags.exit_with_status &&
6624 options->flags.diff_from_contents) {
6626 * run diff_flush_patch for the exit status. setting
6627 * options->file to /dev/null should be safe, because we
6628 * aren't supposed to produce any output anyway.
6630 diff_free_file(options);
6631 options->file = xfopen("/dev/null", "w");
6632 options->close_file = 1;
6633 options->color_moved = 0;
6634 for (i = 0; i < q->nr; i++) {
6635 struct diff_filepair *p = q->queue[i];
6636 if (check_pair_status(p))
6637 diff_flush_patch(p, options);
6638 if (options->found_changes)
6639 break;
6643 if (output_format & DIFF_FORMAT_PATCH) {
6644 if (separator) {
6645 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6646 if (options->stat_sep)
6647 /* attach patch instead of inline */
6648 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6649 NULL, 0, 0);
6652 diff_flush_patch_all_file_pairs(options);
6655 if (output_format & DIFF_FORMAT_CALLBACK)
6656 options->format_callback(q, options, options->format_callback_data);
6658 free_queue:
6659 diff_free_queue(q);
6660 DIFF_QUEUE_CLEAR(q);
6661 diff_free(options);
6664 * Report the content-level differences with HAS_CHANGES;
6665 * diff_addremove/diff_change does not set the bit when
6666 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6668 if (options->flags.diff_from_contents) {
6669 if (options->found_changes)
6670 options->flags.has_changes = 1;
6671 else
6672 options->flags.has_changes = 0;
6676 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6678 return (((p->status == DIFF_STATUS_MODIFIED) &&
6679 ((p->score &&
6680 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6681 (!p->score &&
6682 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6683 ((p->status != DIFF_STATUS_MODIFIED) &&
6684 filter_bit_tst(p->status, options)));
6687 static void diffcore_apply_filter(struct diff_options *options)
6689 int i;
6690 struct diff_queue_struct *q = &diff_queued_diff;
6691 struct diff_queue_struct outq;
6693 DIFF_QUEUE_CLEAR(&outq);
6695 if (!options->filter)
6696 return;
6698 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6699 int found;
6700 for (i = found = 0; !found && i < q->nr; i++) {
6701 if (match_filter(options, q->queue[i]))
6702 found++;
6704 if (found)
6705 return;
6707 /* otherwise we will clear the whole queue
6708 * by copying the empty outq at the end of this
6709 * function, but first clear the current entries
6710 * in the queue.
6712 for (i = 0; i < q->nr; i++)
6713 diff_free_filepair(q->queue[i]);
6715 else {
6716 /* Only the matching ones */
6717 for (i = 0; i < q->nr; i++) {
6718 struct diff_filepair *p = q->queue[i];
6719 if (match_filter(options, p))
6720 diff_q(&outq, p);
6721 else
6722 diff_free_filepair(p);
6725 free(q->queue);
6726 *q = outq;
6729 /* Check whether two filespecs with the same mode and size are identical */
6730 static int diff_filespec_is_identical(struct repository *r,
6731 struct diff_filespec *one,
6732 struct diff_filespec *two)
6734 if (S_ISGITLINK(one->mode))
6735 return 0;
6736 if (diff_populate_filespec(r, one, NULL))
6737 return 0;
6738 if (diff_populate_filespec(r, two, NULL))
6739 return 0;
6740 return !memcmp(one->data, two->data, one->size);
6743 static int diff_filespec_check_stat_unmatch(struct repository *r,
6744 struct diff_filepair *p)
6746 struct diff_populate_filespec_options dpf_options = {
6747 .check_size_only = 1,
6748 .missing_object_cb = diff_queued_diff_prefetch,
6749 .missing_object_data = r,
6752 if (p->done_skip_stat_unmatch)
6753 return p->skip_stat_unmatch_result;
6755 p->done_skip_stat_unmatch = 1;
6756 p->skip_stat_unmatch_result = 0;
6758 * 1. Entries that come from stat info dirtiness
6759 * always have both sides (iow, not create/delete),
6760 * one side of the object name is unknown, with
6761 * the same mode and size. Keep the ones that
6762 * do not match these criteria. They have real
6763 * differences.
6765 * 2. At this point, the file is known to be modified,
6766 * with the same mode and size, and the object
6767 * name of one side is unknown. Need to inspect
6768 * the identical contents.
6770 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6771 !DIFF_FILE_VALID(p->two) ||
6772 (p->one->oid_valid && p->two->oid_valid) ||
6773 (p->one->mode != p->two->mode) ||
6774 diff_populate_filespec(r, p->one, &dpf_options) ||
6775 diff_populate_filespec(r, p->two, &dpf_options) ||
6776 (p->one->size != p->two->size) ||
6777 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6778 p->skip_stat_unmatch_result = 1;
6779 return p->skip_stat_unmatch_result;
6782 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6784 int i;
6785 struct diff_queue_struct *q = &diff_queued_diff;
6786 struct diff_queue_struct outq;
6787 DIFF_QUEUE_CLEAR(&outq);
6789 for (i = 0; i < q->nr; i++) {
6790 struct diff_filepair *p = q->queue[i];
6792 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6793 diff_q(&outq, p);
6794 else {
6796 * The caller can subtract 1 from skip_stat_unmatch
6797 * to determine how many paths were dirty only
6798 * due to stat info mismatch.
6800 if (!diffopt->flags.no_index)
6801 diffopt->skip_stat_unmatch++;
6802 diff_free_filepair(p);
6805 free(q->queue);
6806 *q = outq;
6809 static int diffnamecmp(const void *a_, const void *b_)
6811 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6812 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6813 const char *name_a, *name_b;
6815 name_a = a->one ? a->one->path : a->two->path;
6816 name_b = b->one ? b->one->path : b->two->path;
6817 return strcmp(name_a, name_b);
6820 void diffcore_fix_diff_index(void)
6822 struct diff_queue_struct *q = &diff_queued_diff;
6823 QSORT(q->queue, q->nr, diffnamecmp);
6826 void diff_add_if_missing(struct repository *r,
6827 struct oid_array *to_fetch,
6828 const struct diff_filespec *filespec)
6830 if (filespec && filespec->oid_valid &&
6831 !S_ISGITLINK(filespec->mode) &&
6832 oid_object_info_extended(r, &filespec->oid, NULL,
6833 OBJECT_INFO_FOR_PREFETCH))
6834 oid_array_append(to_fetch, &filespec->oid);
6837 void diff_queued_diff_prefetch(void *repository)
6839 struct repository *repo = repository;
6840 int i;
6841 struct diff_queue_struct *q = &diff_queued_diff;
6842 struct oid_array to_fetch = OID_ARRAY_INIT;
6844 for (i = 0; i < q->nr; i++) {
6845 struct diff_filepair *p = q->queue[i];
6846 diff_add_if_missing(repo, &to_fetch, p->one);
6847 diff_add_if_missing(repo, &to_fetch, p->two);
6851 * NEEDSWORK: Consider deduplicating the OIDs sent.
6853 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6855 oid_array_clear(&to_fetch);
6858 void diffcore_std(struct diff_options *options)
6860 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6861 DIFF_FORMAT_NUMSTAT |
6862 DIFF_FORMAT_PATCH |
6863 DIFF_FORMAT_SHORTSTAT |
6864 DIFF_FORMAT_DIRSTAT;
6867 * Check if the user requested a blob-data-requiring diff output and/or
6868 * break-rewrite detection (which requires blob data). If yes, prefetch
6869 * the diff pairs.
6871 * If no prefetching occurs, diffcore_rename() will prefetch if it
6872 * decides that it needs inexact rename detection.
6874 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6875 (options->output_format & output_formats_to_prefetch ||
6876 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6877 diff_queued_diff_prefetch(options->repo);
6879 /* NOTE please keep the following in sync with diff_tree_combined() */
6880 if (options->skip_stat_unmatch)
6881 diffcore_skip_stat_unmatch(options);
6882 if (!options->found_follow) {
6883 /* See try_to_follow_renames() in tree-diff.c */
6884 if (options->break_opt != -1)
6885 diffcore_break(options->repo,
6886 options->break_opt);
6887 if (options->detect_rename)
6888 diffcore_rename(options);
6889 if (options->break_opt != -1)
6890 diffcore_merge_broken();
6892 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6893 diffcore_pickaxe(options);
6894 if (options->orderfile)
6895 diffcore_order(options->orderfile);
6896 if (options->rotate_to)
6897 diffcore_rotate(options);
6898 if (!options->found_follow)
6899 /* See try_to_follow_renames() in tree-diff.c */
6900 diff_resolve_rename_copy();
6901 diffcore_apply_filter(options);
6903 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6904 options->flags.has_changes = 1;
6905 else
6906 options->flags.has_changes = 0;
6908 options->found_follow = 0;
6911 int diff_result_code(struct diff_options *opt, int status)
6913 int result = 0;
6915 diff_warn_rename_limit("diff.renameLimit",
6916 opt->needed_rename_limit,
6917 opt->degraded_cc_to_c);
6918 if (!opt->flags.exit_with_status &&
6919 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6920 return status;
6921 if (opt->flags.exit_with_status &&
6922 opt->flags.has_changes)
6923 result |= 01;
6924 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6925 opt->flags.check_failed)
6926 result |= 02;
6927 return result;
6930 int diff_can_quit_early(struct diff_options *opt)
6932 return (opt->flags.quick &&
6933 !opt->filter &&
6934 opt->flags.has_changes);
6938 * Shall changes to this submodule be ignored?
6940 * Submodule changes can be configured to be ignored separately for each path,
6941 * but that configuration can be overridden from the command line.
6943 static int is_submodule_ignored(const char *path, struct diff_options *options)
6945 int ignored = 0;
6946 struct diff_flags orig_flags = options->flags;
6947 if (!options->flags.override_submodule_config)
6948 set_diffopt_flags_from_submodule_config(options, path);
6949 if (options->flags.ignore_submodules)
6950 ignored = 1;
6951 options->flags = orig_flags;
6952 return ignored;
6955 void compute_diffstat(struct diff_options *options,
6956 struct diffstat_t *diffstat,
6957 struct diff_queue_struct *q)
6959 int i;
6961 memset(diffstat, 0, sizeof(struct diffstat_t));
6962 for (i = 0; i < q->nr; i++) {
6963 struct diff_filepair *p = q->queue[i];
6964 if (check_pair_status(p))
6965 diff_flush_stat(p, options, diffstat);
6969 void diff_addremove(struct diff_options *options,
6970 int addremove, unsigned mode,
6971 const struct object_id *oid,
6972 int oid_valid,
6973 const char *concatpath, unsigned dirty_submodule)
6975 struct diff_filespec *one, *two;
6977 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6978 return;
6980 /* This may look odd, but it is a preparation for
6981 * feeding "there are unchanged files which should
6982 * not produce diffs, but when you are doing copy
6983 * detection you would need them, so here they are"
6984 * entries to the diff-core. They will be prefixed
6985 * with something like '=' or '*' (I haven't decided
6986 * which but should not make any difference).
6987 * Feeding the same new and old to diff_change()
6988 * also has the same effect.
6989 * Before the final output happens, they are pruned after
6990 * merged into rename/copy pairs as appropriate.
6992 if (options->flags.reverse_diff)
6993 addremove = (addremove == '+' ? '-' :
6994 addremove == '-' ? '+' : addremove);
6996 if (options->prefix &&
6997 strncmp(concatpath, options->prefix, options->prefix_length))
6998 return;
7000 one = alloc_filespec(concatpath);
7001 two = alloc_filespec(concatpath);
7003 if (addremove != '+')
7004 fill_filespec(one, oid, oid_valid, mode);
7005 if (addremove != '-') {
7006 fill_filespec(two, oid, oid_valid, mode);
7007 two->dirty_submodule = dirty_submodule;
7010 diff_queue(&diff_queued_diff, one, two);
7011 if (!options->flags.diff_from_contents)
7012 options->flags.has_changes = 1;
7015 void diff_change(struct diff_options *options,
7016 unsigned old_mode, unsigned new_mode,
7017 const struct object_id *old_oid,
7018 const struct object_id *new_oid,
7019 int old_oid_valid, int new_oid_valid,
7020 const char *concatpath,
7021 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7023 struct diff_filespec *one, *two;
7024 struct diff_filepair *p;
7026 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7027 is_submodule_ignored(concatpath, options))
7028 return;
7030 if (options->flags.reverse_diff) {
7031 SWAP(old_mode, new_mode);
7032 SWAP(old_oid, new_oid);
7033 SWAP(old_oid_valid, new_oid_valid);
7034 SWAP(old_dirty_submodule, new_dirty_submodule);
7037 if (options->prefix &&
7038 strncmp(concatpath, options->prefix, options->prefix_length))
7039 return;
7041 one = alloc_filespec(concatpath);
7042 two = alloc_filespec(concatpath);
7043 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7044 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7045 one->dirty_submodule = old_dirty_submodule;
7046 two->dirty_submodule = new_dirty_submodule;
7047 p = diff_queue(&diff_queued_diff, one, two);
7049 if (options->flags.diff_from_contents)
7050 return;
7052 if (options->flags.quick && options->skip_stat_unmatch &&
7053 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7054 diff_free_filespec_data(p->one);
7055 diff_free_filespec_data(p->two);
7056 return;
7059 options->flags.has_changes = 1;
7062 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7064 struct diff_filepair *pair;
7065 struct diff_filespec *one, *two;
7067 if (options->prefix &&
7068 strncmp(path, options->prefix, options->prefix_length))
7069 return NULL;
7071 one = alloc_filespec(path);
7072 two = alloc_filespec(path);
7073 pair = diff_queue(&diff_queued_diff, one, two);
7074 pair->is_unmerged = 1;
7075 return pair;
7078 static char *run_textconv(struct repository *r,
7079 const char *pgm,
7080 struct diff_filespec *spec,
7081 size_t *outsize)
7083 struct diff_tempfile *temp;
7084 struct child_process child = CHILD_PROCESS_INIT;
7085 struct strbuf buf = STRBUF_INIT;
7086 int err = 0;
7088 temp = prepare_temp_file(r, spec);
7089 strvec_push(&child.args, pgm);
7090 strvec_push(&child.args, temp->name);
7092 child.use_shell = 1;
7093 child.out = -1;
7094 if (start_command(&child)) {
7095 remove_tempfile();
7096 return NULL;
7099 if (strbuf_read(&buf, child.out, 0) < 0)
7100 err = error("error reading from textconv command '%s'", pgm);
7101 close(child.out);
7103 if (finish_command(&child) || err) {
7104 strbuf_release(&buf);
7105 remove_tempfile();
7106 return NULL;
7108 remove_tempfile();
7110 return strbuf_detach(&buf, outsize);
7113 size_t fill_textconv(struct repository *r,
7114 struct userdiff_driver *driver,
7115 struct diff_filespec *df,
7116 char **outbuf)
7118 size_t size;
7120 if (!driver) {
7121 if (!DIFF_FILE_VALID(df)) {
7122 *outbuf = "";
7123 return 0;
7125 if (diff_populate_filespec(r, df, NULL))
7126 die("unable to read files to diff");
7127 *outbuf = df->data;
7128 return df->size;
7131 if (!driver->textconv)
7132 BUG("fill_textconv called with non-textconv driver");
7134 if (driver->textconv_cache && df->oid_valid) {
7135 *outbuf = notes_cache_get(driver->textconv_cache,
7136 &df->oid,
7137 &size);
7138 if (*outbuf)
7139 return size;
7142 *outbuf = run_textconv(r, driver->textconv, df, &size);
7143 if (!*outbuf)
7144 die("unable to read files to diff");
7146 if (driver->textconv_cache && df->oid_valid) {
7147 /* ignore errors, as we might be in a readonly repository */
7148 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7149 size);
7151 * we could save up changes and flush them all at the end,
7152 * but we would need an extra call after all diffing is done.
7153 * Since generating a cache entry is the slow path anyway,
7154 * this extra overhead probably isn't a big deal.
7156 notes_cache_write(driver->textconv_cache);
7159 return size;
7162 int textconv_object(struct repository *r,
7163 const char *path,
7164 unsigned mode,
7165 const struct object_id *oid,
7166 int oid_valid,
7167 char **buf,
7168 unsigned long *buf_size)
7170 struct diff_filespec *df;
7171 struct userdiff_driver *textconv;
7173 df = alloc_filespec(path);
7174 fill_filespec(df, oid, oid_valid, mode);
7175 textconv = get_textconv(r, df);
7176 if (!textconv) {
7177 free_filespec(df);
7178 return 0;
7181 *buf_size = fill_textconv(r, textconv, df, buf);
7182 free_filespec(df);
7183 return 1;
7186 void setup_diff_pager(struct diff_options *opt)
7189 * If the user asked for our exit code, then either they want --quiet
7190 * or --exit-code. We should definitely not bother with a pager in the
7191 * former case, as we will generate no output. Since we still properly
7192 * report our exit code even when a pager is run, we _could_ run a
7193 * pager with --exit-code. But since we have not done so historically,
7194 * and because it is easy to find people oneline advising "git diff
7195 * --exit-code" in hooks and other scripts, we do not do so.
7197 if (!opt->flags.exit_with_status &&
7198 check_pager_config("diff") != 0)
7199 setup_pager();