Merge branch 'rs/grep-no-no-or' into maint-2.42
[alt-git.git] / diff.c
blobbccb018da468480615c04d858909891ac59b69e5
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "base85.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-ll.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 "merge-ll.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 "pager.h"
35 #include "parse-options.h"
36 #include "help.h"
37 #include "promisor-remote.h"
38 #include "dir.h"
39 #include "object-file.h"
40 #include "object-name.h"
41 #include "read-cache-ll.h"
42 #include "setup.h"
43 #include "strmap.h"
44 #include "ws.h"
46 #ifdef NO_FAST_WORKING_DIRECTORY
47 #define FAST_WORKING_DIRECTORY 0
48 #else
49 #define FAST_WORKING_DIRECTORY 1
50 #endif
52 static int diff_detect_rename_default;
53 static int diff_indent_heuristic = 1;
54 static int diff_rename_limit_default = 1000;
55 static int diff_suppress_blank_empty;
56 static int diff_use_color_default = -1;
57 static int diff_color_moved_default;
58 static int diff_color_moved_ws_default;
59 static int diff_context_default = 3;
60 static int diff_interhunk_context_default;
61 static const char *diff_word_regex_cfg;
62 static const char *external_diff_cmd_cfg;
63 static const char *diff_order_file_cfg;
64 int diff_auto_refresh_index = 1;
65 static int diff_mnemonic_prefix;
66 static int diff_no_prefix;
67 static int diff_relative;
68 static int diff_stat_graph_width;
69 static int diff_dirstat_permille_default = 30;
70 static struct diff_options default_diff_options;
71 static long diff_algorithm;
72 static unsigned ws_error_highlight_default = WSEH_NEW;
74 static char diff_colors[][COLOR_MAXLEN] = {
75 GIT_COLOR_RESET,
76 GIT_COLOR_NORMAL, /* CONTEXT */
77 GIT_COLOR_BOLD, /* METAINFO */
78 GIT_COLOR_CYAN, /* FRAGINFO */
79 GIT_COLOR_RED, /* OLD */
80 GIT_COLOR_GREEN, /* NEW */
81 GIT_COLOR_YELLOW, /* COMMIT */
82 GIT_COLOR_BG_RED, /* WHITESPACE */
83 GIT_COLOR_NORMAL, /* FUNCINFO */
84 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
85 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
86 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
87 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
88 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
89 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
90 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
91 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
92 GIT_COLOR_FAINT, /* CONTEXT_DIM */
93 GIT_COLOR_FAINT_RED, /* OLD_DIM */
94 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
95 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
96 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
97 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
100 static const char *color_diff_slots[] = {
101 [DIFF_CONTEXT] = "context",
102 [DIFF_METAINFO] = "meta",
103 [DIFF_FRAGINFO] = "frag",
104 [DIFF_FILE_OLD] = "old",
105 [DIFF_FILE_NEW] = "new",
106 [DIFF_COMMIT] = "commit",
107 [DIFF_WHITESPACE] = "whitespace",
108 [DIFF_FUNCINFO] = "func",
109 [DIFF_FILE_OLD_MOVED] = "oldMoved",
110 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
111 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
112 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
113 [DIFF_FILE_NEW_MOVED] = "newMoved",
114 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
115 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
116 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
117 [DIFF_CONTEXT_DIM] = "contextDimmed",
118 [DIFF_FILE_OLD_DIM] = "oldDimmed",
119 [DIFF_FILE_NEW_DIM] = "newDimmed",
120 [DIFF_CONTEXT_BOLD] = "contextBold",
121 [DIFF_FILE_OLD_BOLD] = "oldBold",
122 [DIFF_FILE_NEW_BOLD] = "newBold",
125 define_list_config_array_extra(color_diff_slots, {"plain"});
127 static int parse_diff_color_slot(const char *var)
129 if (!strcasecmp(var, "plain"))
130 return DIFF_CONTEXT;
131 return LOOKUP_CONFIG(color_diff_slots, var);
134 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
135 struct strbuf *errmsg)
137 char *params_copy = xstrdup(params_string);
138 struct string_list params = STRING_LIST_INIT_NODUP;
139 int ret = 0;
140 int i;
142 if (*params_copy)
143 string_list_split_in_place(&params, params_copy, ",", -1);
144 for (i = 0; i < params.nr; i++) {
145 const char *p = params.items[i].string;
146 if (!strcmp(p, "changes")) {
147 options->flags.dirstat_by_line = 0;
148 options->flags.dirstat_by_file = 0;
149 } else if (!strcmp(p, "lines")) {
150 options->flags.dirstat_by_line = 1;
151 options->flags.dirstat_by_file = 0;
152 } else if (!strcmp(p, "files")) {
153 options->flags.dirstat_by_line = 0;
154 options->flags.dirstat_by_file = 1;
155 } else if (!strcmp(p, "noncumulative")) {
156 options->flags.dirstat_cumulative = 0;
157 } else if (!strcmp(p, "cumulative")) {
158 options->flags.dirstat_cumulative = 1;
159 } else if (isdigit(*p)) {
160 char *end;
161 int permille = strtoul(p, &end, 10) * 10;
162 if (*end == '.' && isdigit(*++end)) {
163 /* only use first digit */
164 permille += *end - '0';
165 /* .. and ignore any further digits */
166 while (isdigit(*++end))
167 ; /* nothing */
169 if (!*end)
170 options->dirstat_permille = permille;
171 else {
172 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
174 ret++;
176 } else {
177 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
178 ret++;
182 string_list_clear(&params, 0);
183 free(params_copy);
184 return ret;
187 static int parse_submodule_params(struct diff_options *options, const char *value)
189 if (!strcmp(value, "log"))
190 options->submodule_format = DIFF_SUBMODULE_LOG;
191 else if (!strcmp(value, "short"))
192 options->submodule_format = DIFF_SUBMODULE_SHORT;
193 else if (!strcmp(value, "diff"))
194 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
196 * Please update $__git_diff_submodule_formats in
197 * git-completion.bash when you add new formats.
199 else
200 return -1;
201 return 0;
204 int git_config_rename(const char *var, const char *value)
206 if (!value)
207 return DIFF_DETECT_RENAME;
208 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
209 return DIFF_DETECT_COPY;
210 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
213 long parse_algorithm_value(const char *value)
215 if (!value)
216 return -1;
217 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
218 return 0;
219 else if (!strcasecmp(value, "minimal"))
220 return XDF_NEED_MINIMAL;
221 else if (!strcasecmp(value, "patience"))
222 return XDF_PATIENCE_DIFF;
223 else if (!strcasecmp(value, "histogram"))
224 return XDF_HISTOGRAM_DIFF;
226 * Please update $__git_diff_algorithms in git-completion.bash
227 * when you add new algorithms.
229 return -1;
232 static int parse_one_token(const char **arg, const char *token)
234 const char *rest;
235 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
236 *arg = rest;
237 return 1;
239 return 0;
242 static int parse_ws_error_highlight(const char *arg)
244 const char *orig_arg = arg;
245 unsigned val = 0;
247 while (*arg) {
248 if (parse_one_token(&arg, "none"))
249 val = 0;
250 else if (parse_one_token(&arg, "default"))
251 val = WSEH_NEW;
252 else if (parse_one_token(&arg, "all"))
253 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
254 else if (parse_one_token(&arg, "new"))
255 val |= WSEH_NEW;
256 else if (parse_one_token(&arg, "old"))
257 val |= WSEH_OLD;
258 else if (parse_one_token(&arg, "context"))
259 val |= WSEH_CONTEXT;
260 else {
261 return -1 - (int)(arg - orig_arg);
263 if (*arg)
264 arg++;
266 return val;
270 * These are to give UI layer defaults.
271 * The core-level commands such as git-diff-files should
272 * never be affected by the setting of diff.renames
273 * the user happens to have in the configuration file.
275 void init_diff_ui_defaults(void)
277 diff_detect_rename_default = DIFF_DETECT_RENAME;
280 int git_diff_heuristic_config(const char *var, const char *value,
281 void *cb UNUSED)
283 if (!strcmp(var, "diff.indentheuristic"))
284 diff_indent_heuristic = git_config_bool(var, value);
285 return 0;
288 static int parse_color_moved(const char *arg)
290 switch (git_parse_maybe_bool(arg)) {
291 case 0:
292 return COLOR_MOVED_NO;
293 case 1:
294 return COLOR_MOVED_DEFAULT;
295 default:
296 break;
299 if (!strcmp(arg, "no"))
300 return COLOR_MOVED_NO;
301 else if (!strcmp(arg, "plain"))
302 return COLOR_MOVED_PLAIN;
303 else if (!strcmp(arg, "blocks"))
304 return COLOR_MOVED_BLOCKS;
305 else if (!strcmp(arg, "zebra"))
306 return COLOR_MOVED_ZEBRA;
307 else if (!strcmp(arg, "default"))
308 return COLOR_MOVED_DEFAULT;
309 else if (!strcmp(arg, "dimmed-zebra"))
310 return COLOR_MOVED_ZEBRA_DIM;
311 else if (!strcmp(arg, "dimmed_zebra"))
312 return COLOR_MOVED_ZEBRA_DIM;
313 else
314 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
317 static unsigned parse_color_moved_ws(const char *arg)
319 int ret = 0;
320 struct string_list l = STRING_LIST_INIT_DUP;
321 struct string_list_item *i;
323 string_list_split(&l, arg, ',', -1);
325 for_each_string_list_item(i, &l) {
326 struct strbuf sb = STRBUF_INIT;
327 strbuf_addstr(&sb, i->string);
328 strbuf_trim(&sb);
330 if (!strcmp(sb.buf, "no"))
331 ret = 0;
332 else if (!strcmp(sb.buf, "ignore-space-change"))
333 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
334 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
335 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
336 else if (!strcmp(sb.buf, "ignore-all-space"))
337 ret |= XDF_IGNORE_WHITESPACE;
338 else if (!strcmp(sb.buf, "allow-indentation-change"))
339 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
340 else {
341 ret |= COLOR_MOVED_WS_ERROR;
342 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);
345 strbuf_release(&sb);
348 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
349 (ret & XDF_WHITESPACE_FLAGS)) {
350 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
351 ret |= COLOR_MOVED_WS_ERROR;
354 string_list_clear(&l, 0);
356 return ret;
359 int git_diff_ui_config(const char *var, const char *value,
360 const struct config_context *ctx, void *cb)
362 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
363 diff_use_color_default = git_config_colorbool(var, value);
364 return 0;
366 if (!strcmp(var, "diff.colormoved")) {
367 int cm = parse_color_moved(value);
368 if (cm < 0)
369 return -1;
370 diff_color_moved_default = cm;
371 return 0;
373 if (!strcmp(var, "diff.colormovedws")) {
374 unsigned cm = parse_color_moved_ws(value);
375 if (cm & COLOR_MOVED_WS_ERROR)
376 return -1;
377 diff_color_moved_ws_default = cm;
378 return 0;
380 if (!strcmp(var, "diff.context")) {
381 diff_context_default = git_config_int(var, value, ctx->kvi);
382 if (diff_context_default < 0)
383 return -1;
384 return 0;
386 if (!strcmp(var, "diff.interhunkcontext")) {
387 diff_interhunk_context_default = git_config_int(var, value,
388 ctx->kvi);
389 if (diff_interhunk_context_default < 0)
390 return -1;
391 return 0;
393 if (!strcmp(var, "diff.renames")) {
394 diff_detect_rename_default = git_config_rename(var, value);
395 return 0;
397 if (!strcmp(var, "diff.autorefreshindex")) {
398 diff_auto_refresh_index = git_config_bool(var, value);
399 return 0;
401 if (!strcmp(var, "diff.mnemonicprefix")) {
402 diff_mnemonic_prefix = git_config_bool(var, value);
403 return 0;
405 if (!strcmp(var, "diff.noprefix")) {
406 diff_no_prefix = git_config_bool(var, value);
407 return 0;
409 if (!strcmp(var, "diff.relative")) {
410 diff_relative = git_config_bool(var, value);
411 return 0;
413 if (!strcmp(var, "diff.statgraphwidth")) {
414 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
415 return 0;
417 if (!strcmp(var, "diff.external"))
418 return git_config_string(&external_diff_cmd_cfg, var, value);
419 if (!strcmp(var, "diff.wordregex"))
420 return git_config_string(&diff_word_regex_cfg, var, value);
421 if (!strcmp(var, "diff.orderfile"))
422 return git_config_pathname(&diff_order_file_cfg, var, value);
424 if (!strcmp(var, "diff.ignoresubmodules"))
425 handle_ignore_submodules_arg(&default_diff_options, value);
427 if (!strcmp(var, "diff.submodule")) {
428 if (parse_submodule_params(&default_diff_options, value))
429 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
430 value);
431 return 0;
434 if (!strcmp(var, "diff.algorithm")) {
435 diff_algorithm = parse_algorithm_value(value);
436 if (diff_algorithm < 0)
437 return -1;
438 return 0;
441 if (git_color_config(var, value, cb) < 0)
442 return -1;
444 return git_diff_basic_config(var, value, ctx, cb);
447 int git_diff_basic_config(const char *var, const char *value,
448 const struct config_context *ctx, void *cb)
450 const char *name;
452 if (!strcmp(var, "diff.renamelimit")) {
453 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
454 return 0;
457 if (userdiff_config(var, value) < 0)
458 return -1;
460 if (skip_prefix(var, "diff.color.", &name) ||
461 skip_prefix(var, "color.diff.", &name)) {
462 int slot = parse_diff_color_slot(name);
463 if (slot < 0)
464 return 0;
465 if (!value)
466 return config_error_nonbool(var);
467 return color_parse(value, diff_colors[slot]);
470 if (!strcmp(var, "diff.wserrorhighlight")) {
471 int val = parse_ws_error_highlight(value);
472 if (val < 0)
473 return -1;
474 ws_error_highlight_default = val;
475 return 0;
478 /* like GNU diff's --suppress-blank-empty option */
479 if (!strcmp(var, "diff.suppressblankempty") ||
480 /* for backwards compatibility */
481 !strcmp(var, "diff.suppress-blank-empty")) {
482 diff_suppress_blank_empty = git_config_bool(var, value);
483 return 0;
486 if (!strcmp(var, "diff.dirstat")) {
487 struct strbuf errmsg = STRBUF_INIT;
488 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
489 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
490 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
491 errmsg.buf);
492 strbuf_release(&errmsg);
493 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
494 return 0;
497 if (git_diff_heuristic_config(var, value, cb) < 0)
498 return -1;
500 return git_default_config(var, value, ctx, cb);
503 static char *quote_two(const char *one, const char *two)
505 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
506 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
507 struct strbuf res = STRBUF_INIT;
509 if (need_one + need_two) {
510 strbuf_addch(&res, '"');
511 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
512 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
513 strbuf_addch(&res, '"');
514 } else {
515 strbuf_addstr(&res, one);
516 strbuf_addstr(&res, two);
518 return strbuf_detach(&res, NULL);
521 static const char *external_diff(void)
523 static const char *external_diff_cmd = NULL;
524 static int done_preparing = 0;
526 if (done_preparing)
527 return external_diff_cmd;
528 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
529 if (!external_diff_cmd)
530 external_diff_cmd = external_diff_cmd_cfg;
531 done_preparing = 1;
532 return external_diff_cmd;
536 * Keep track of files used for diffing. Sometimes such an entry
537 * refers to a temporary file, sometimes to an existing file, and
538 * sometimes to "/dev/null".
540 static struct diff_tempfile {
542 * filename external diff should read from, or NULL if this
543 * entry is currently not in use:
545 const char *name;
547 char hex[GIT_MAX_HEXSZ + 1];
548 char mode[10];
551 * If this diff_tempfile instance refers to a temporary file,
552 * this tempfile object is used to manage its lifetime.
554 struct tempfile *tempfile;
555 } diff_temp[2];
557 struct emit_callback {
558 int color_diff;
559 unsigned ws_rule;
560 int blank_at_eof_in_preimage;
561 int blank_at_eof_in_postimage;
562 int lno_in_preimage;
563 int lno_in_postimage;
564 const char **label_path;
565 struct diff_words_data *diff_words;
566 struct diff_options *opt;
567 struct strbuf *header;
570 static int count_lines(const char *data, int size)
572 int count, ch, completely_empty = 1, nl_just_seen = 0;
573 count = 0;
574 while (0 < size--) {
575 ch = *data++;
576 if (ch == '\n') {
577 count++;
578 nl_just_seen = 1;
579 completely_empty = 0;
581 else {
582 nl_just_seen = 0;
583 completely_empty = 0;
586 if (completely_empty)
587 return 0;
588 if (!nl_just_seen)
589 count++; /* no trailing newline */
590 return count;
593 static int fill_mmfile(struct repository *r, mmfile_t *mf,
594 struct diff_filespec *one)
596 if (!DIFF_FILE_VALID(one)) {
597 mf->ptr = (char *)""; /* does not matter */
598 mf->size = 0;
599 return 0;
601 else if (diff_populate_filespec(r, one, NULL))
602 return -1;
604 mf->ptr = one->data;
605 mf->size = one->size;
606 return 0;
609 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
610 static unsigned long diff_filespec_size(struct repository *r,
611 struct diff_filespec *one)
613 struct diff_populate_filespec_options dpf_options = {
614 .check_size_only = 1,
617 if (!DIFF_FILE_VALID(one))
618 return 0;
619 diff_populate_filespec(r, one, &dpf_options);
620 return one->size;
623 static int count_trailing_blank(mmfile_t *mf)
625 char *ptr = mf->ptr;
626 long size = mf->size;
627 int cnt = 0;
629 if (!size)
630 return cnt;
631 ptr += size - 1; /* pointing at the very end */
632 if (*ptr != '\n')
633 ; /* incomplete line */
634 else
635 ptr--; /* skip the last LF */
636 while (mf->ptr < ptr) {
637 char *prev_eol;
638 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
639 if (*prev_eol == '\n')
640 break;
641 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
642 break;
643 cnt++;
644 ptr = prev_eol - 1;
646 return cnt;
649 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
650 struct emit_callback *ecbdata)
652 int l1, l2, at;
653 l1 = count_trailing_blank(mf1);
654 l2 = count_trailing_blank(mf2);
655 if (l2 <= l1) {
656 ecbdata->blank_at_eof_in_preimage = 0;
657 ecbdata->blank_at_eof_in_postimage = 0;
658 return;
660 at = count_lines(mf1->ptr, mf1->size);
661 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
663 at = count_lines(mf2->ptr, mf2->size);
664 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
667 static void emit_line_0(struct diff_options *o,
668 const char *set_sign, const char *set, unsigned reverse, const char *reset,
669 int first, const char *line, int len)
671 int has_trailing_newline, has_trailing_carriage_return;
672 int needs_reset = 0; /* at the end of the line */
673 FILE *file = o->file;
675 fputs(diff_line_prefix(o), file);
677 has_trailing_newline = (len > 0 && line[len-1] == '\n');
678 if (has_trailing_newline)
679 len--;
681 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
682 if (has_trailing_carriage_return)
683 len--;
685 if (!len && !first)
686 goto end_of_line;
688 if (reverse && want_color(o->use_color)) {
689 fputs(GIT_COLOR_REVERSE, file);
690 needs_reset = 1;
693 if (set_sign) {
694 fputs(set_sign, file);
695 needs_reset = 1;
698 if (first)
699 fputc(first, file);
701 if (!len)
702 goto end_of_line;
704 if (set) {
705 if (set_sign && set != set_sign)
706 fputs(reset, file);
707 fputs(set, file);
708 needs_reset = 1;
710 fwrite(line, len, 1, file);
711 needs_reset = 1; /* 'line' may contain color codes. */
713 end_of_line:
714 if (needs_reset)
715 fputs(reset, file);
716 if (has_trailing_carriage_return)
717 fputc('\r', file);
718 if (has_trailing_newline)
719 fputc('\n', file);
722 static void emit_line(struct diff_options *o, const char *set, const char *reset,
723 const char *line, int len)
725 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
728 enum diff_symbol {
729 DIFF_SYMBOL_BINARY_DIFF_HEADER,
730 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
731 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
732 DIFF_SYMBOL_BINARY_DIFF_BODY,
733 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
734 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
735 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
736 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
737 DIFF_SYMBOL_STATS_LINE,
738 DIFF_SYMBOL_WORD_DIFF,
739 DIFF_SYMBOL_STAT_SEP,
740 DIFF_SYMBOL_SUMMARY,
741 DIFF_SYMBOL_SUBMODULE_ADD,
742 DIFF_SYMBOL_SUBMODULE_DEL,
743 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
744 DIFF_SYMBOL_SUBMODULE_MODIFIED,
745 DIFF_SYMBOL_SUBMODULE_HEADER,
746 DIFF_SYMBOL_SUBMODULE_ERROR,
747 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
748 DIFF_SYMBOL_REWRITE_DIFF,
749 DIFF_SYMBOL_BINARY_FILES,
750 DIFF_SYMBOL_HEADER,
751 DIFF_SYMBOL_FILEPAIR_PLUS,
752 DIFF_SYMBOL_FILEPAIR_MINUS,
753 DIFF_SYMBOL_WORDS_PORCELAIN,
754 DIFF_SYMBOL_WORDS,
755 DIFF_SYMBOL_CONTEXT,
756 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
757 DIFF_SYMBOL_PLUS,
758 DIFF_SYMBOL_MINUS,
759 DIFF_SYMBOL_NO_LF_EOF,
760 DIFF_SYMBOL_CONTEXT_FRAGINFO,
761 DIFF_SYMBOL_CONTEXT_MARKER,
762 DIFF_SYMBOL_SEPARATOR
765 * Flags for content lines:
766 * 0..12 are whitespace rules
767 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
768 * 16 is marking if the line is blank at EOF
770 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
771 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
772 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
773 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
774 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
777 * This struct is used when we need to buffer the output of the diff output.
779 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
780 * into the pre/post image file. This pointer could be a union with the
781 * line pointer. By storing an offset into the file instead of the literal line,
782 * we can decrease the memory footprint for the buffered output. At first we
783 * may want to only have indirection for the content lines, but we could also
784 * enhance the state for emitting prefabricated lines, e.g. the similarity
785 * score line or hunk/file headers would only need to store a number or path
786 * and then the output can be constructed later on depending on state.
788 struct emitted_diff_symbol {
789 const char *line;
790 int len;
791 int flags;
792 int indent_off; /* Offset to first non-whitespace character */
793 int indent_width; /* The visual width of the indentation */
794 unsigned id;
795 enum diff_symbol s;
797 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
799 struct emitted_diff_symbols {
800 struct emitted_diff_symbol *buf;
801 int nr, alloc;
803 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
805 static void append_emitted_diff_symbol(struct diff_options *o,
806 struct emitted_diff_symbol *e)
808 struct emitted_diff_symbol *f;
810 ALLOC_GROW(o->emitted_symbols->buf,
811 o->emitted_symbols->nr + 1,
812 o->emitted_symbols->alloc);
813 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
815 memcpy(f, e, sizeof(struct emitted_diff_symbol));
816 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
819 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
821 if (!e)
822 return;
823 free(e->buf);
824 free(e);
827 struct moved_entry {
828 const struct emitted_diff_symbol *es;
829 struct moved_entry *next_line;
830 struct moved_entry *next_match;
833 struct moved_block {
834 struct moved_entry *match;
835 int wsd; /* The whitespace delta of this block */
838 #define INDENT_BLANKLINE INT_MIN
840 static void fill_es_indent_data(struct emitted_diff_symbol *es)
842 unsigned int off = 0, i;
843 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
844 const char *s = es->line;
845 const int len = es->len;
847 /* skip any \v \f \r at start of indentation */
848 while (s[off] == '\f' || s[off] == '\v' ||
849 (s[off] == '\r' && off < len - 1))
850 off++;
852 /* calculate the visual width of indentation */
853 while(1) {
854 if (s[off] == ' ') {
855 width++;
856 off++;
857 } else if (s[off] == '\t') {
858 width += tab_width - (width % tab_width);
859 while (s[++off] == '\t')
860 width += tab_width;
861 } else {
862 break;
866 /* check if this line is blank */
867 for (i = off; i < len; i++)
868 if (!isspace(s[i]))
869 break;
871 if (i == len) {
872 es->indent_width = INDENT_BLANKLINE;
873 es->indent_off = len;
874 } else {
875 es->indent_off = off;
876 es->indent_width = width;
880 static int compute_ws_delta(const struct emitted_diff_symbol *a,
881 const struct emitted_diff_symbol *b)
883 int a_width = a->indent_width,
884 b_width = b->indent_width;
886 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
887 return INDENT_BLANKLINE;
889 return a_width - b_width;
892 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
893 const struct emitted_diff_symbol *l,
894 struct moved_block *pmb)
896 int a_width = cur->es->indent_width, b_width = l->indent_width;
897 int delta;
899 /* The text of each line must match */
900 if (cur->es->id != l->id)
901 return 1;
904 * If 'l' and 'cur' are both blank then we don't need to check the
905 * indent. We only need to check cur as we know the strings match.
906 * */
907 if (a_width == INDENT_BLANKLINE)
908 return 0;
911 * The indent changes of the block are known and stored in pmb->wsd;
912 * however we need to check if the indent changes of the current line
913 * match those of the current block.
915 delta = b_width - a_width;
918 * If the previous lines of this block were all blank then set its
919 * whitespace delta.
921 if (pmb->wsd == INDENT_BLANKLINE)
922 pmb->wsd = delta;
924 return delta != pmb->wsd;
927 struct interned_diff_symbol {
928 struct hashmap_entry ent;
929 struct emitted_diff_symbol *es;
932 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
933 const struct hashmap_entry *eptr,
934 const struct hashmap_entry *entry_or_key,
935 const void *keydata UNUSED)
937 const struct diff_options *diffopt = hashmap_cmp_fn_data;
938 const struct emitted_diff_symbol *a, *b;
939 unsigned flags = diffopt->color_moved_ws_handling
940 & XDF_WHITESPACE_FLAGS;
942 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
943 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
945 return !xdiff_compare_lines(a->line + a->indent_off,
946 a->len - a->indent_off,
947 b->line + b->indent_off,
948 b->len - b->indent_off, flags);
951 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
952 struct interned_diff_symbol *s)
954 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
955 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
956 l->len - l->indent_off, flags);
958 hashmap_entry_init(&s->ent, hash);
959 s->es = l;
962 struct moved_entry_list {
963 struct moved_entry *add, *del;
966 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
967 struct mem_pool *entry_mem_pool)
969 struct moved_entry *prev_line = NULL;
970 struct mem_pool interned_pool;
971 struct hashmap interned_map;
972 struct moved_entry_list *entry_list = NULL;
973 size_t entry_list_alloc = 0;
974 unsigned id = 0;
975 int n;
977 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
978 mem_pool_init(&interned_pool, 1024 * 1024);
980 for (n = 0; n < o->emitted_symbols->nr; n++) {
981 struct interned_diff_symbol key;
982 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
983 struct interned_diff_symbol *s;
984 struct moved_entry *entry;
986 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
987 prev_line = NULL;
988 continue;
991 if (o->color_moved_ws_handling &
992 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
993 fill_es_indent_data(l);
995 prepare_entry(o, l, &key);
996 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
997 if (s) {
998 l->id = s->es->id;
999 } else {
1000 l->id = id;
1001 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1002 hashmap_add(&interned_map,
1003 memcpy(mem_pool_alloc(&interned_pool,
1004 sizeof(key)),
1005 &key, sizeof(key)));
1007 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1008 entry->es = l;
1009 entry->next_line = NULL;
1010 if (prev_line && prev_line->es->s == l->s)
1011 prev_line->next_line = entry;
1012 prev_line = entry;
1013 if (l->s == DIFF_SYMBOL_PLUS) {
1014 entry->next_match = entry_list[l->id].add;
1015 entry_list[l->id].add = entry;
1016 } else {
1017 entry->next_match = entry_list[l->id].del;
1018 entry_list[l->id].del = entry;
1022 hashmap_clear(&interned_map);
1023 mem_pool_discard(&interned_pool, 0);
1025 return entry_list;
1028 static void pmb_advance_or_null(struct diff_options *o,
1029 struct emitted_diff_symbol *l,
1030 struct moved_block *pmb,
1031 int *pmb_nr)
1033 int i, j;
1035 for (i = 0, j = 0; i < *pmb_nr; i++) {
1036 int match;
1037 struct moved_entry *prev = pmb[i].match;
1038 struct moved_entry *cur = (prev && prev->next_line) ?
1039 prev->next_line : NULL;
1041 if (o->color_moved_ws_handling &
1042 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1043 match = cur &&
1044 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1045 else
1046 match = cur && cur->es->id == l->id;
1048 if (match) {
1049 pmb[j] = pmb[i];
1050 pmb[j++].match = cur;
1053 *pmb_nr = j;
1056 static void fill_potential_moved_blocks(struct diff_options *o,
1057 struct moved_entry *match,
1058 struct emitted_diff_symbol *l,
1059 struct moved_block **pmb_p,
1060 int *pmb_alloc_p, int *pmb_nr_p)
1063 struct moved_block *pmb = *pmb_p;
1064 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1067 * The current line is the start of a new block.
1068 * Setup the set of potential blocks.
1070 for (; match; match = match->next_match) {
1071 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1072 if (o->color_moved_ws_handling &
1073 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1074 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1075 else
1076 pmb[pmb_nr].wsd = 0;
1077 pmb[pmb_nr++].match = match;
1080 *pmb_p = pmb;
1081 *pmb_alloc_p = pmb_alloc;
1082 *pmb_nr_p = pmb_nr;
1086 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1088 * Otherwise, if the last block has fewer alphanumeric characters than
1089 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1090 * that block.
1092 * The last block consists of the (n - block_length)'th line up to but not
1093 * including the nth line.
1095 * Returns 0 if the last block is empty or is unset by this function, non zero
1096 * otherwise.
1098 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1099 * Think of a way to unify them.
1101 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1102 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1103 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1105 int i, alnum_count = 0;
1106 if (o->color_moved == COLOR_MOVED_PLAIN)
1107 return block_length;
1108 for (i = 1; i < block_length + 1; i++) {
1109 const char *c = o->emitted_symbols->buf[n - i].line;
1110 for (; *c; c++) {
1111 if (!isalnum(*c))
1112 continue;
1113 alnum_count++;
1114 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1115 return 1;
1118 for (i = 1; i < block_length + 1; i++)
1119 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1120 return 0;
1123 /* Find blocks of moved code, delegate actual coloring decision to helper */
1124 static void mark_color_as_moved(struct diff_options *o,
1125 struct moved_entry_list *entry_list)
1127 struct moved_block *pmb = NULL; /* potentially moved blocks */
1128 int pmb_nr = 0, pmb_alloc = 0;
1129 int n, flipped_block = 0, block_length = 0;
1130 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1133 for (n = 0; n < o->emitted_symbols->nr; n++) {
1134 struct moved_entry *match = NULL;
1135 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1137 switch (l->s) {
1138 case DIFF_SYMBOL_PLUS:
1139 match = entry_list[l->id].del;
1140 break;
1141 case DIFF_SYMBOL_MINUS:
1142 match = entry_list[l->id].add;
1143 break;
1144 default:
1145 flipped_block = 0;
1148 if (pmb_nr && (!match || l->s != moved_symbol)) {
1149 if (!adjust_last_block(o, n, block_length) &&
1150 block_length > 1) {
1152 * Rewind in case there is another match
1153 * starting at the second line of the block
1155 match = NULL;
1156 n -= block_length;
1158 pmb_nr = 0;
1159 block_length = 0;
1160 flipped_block = 0;
1162 if (!match) {
1163 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1164 continue;
1167 if (o->color_moved == COLOR_MOVED_PLAIN) {
1168 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1169 continue;
1172 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1174 if (pmb_nr == 0) {
1175 int contiguous = adjust_last_block(o, n, block_length);
1177 if (!contiguous && block_length > 1)
1179 * Rewind in case there is another match
1180 * starting at the second line of the block
1182 n -= block_length;
1183 else
1184 fill_potential_moved_blocks(o, match, l,
1185 &pmb, &pmb_alloc,
1186 &pmb_nr);
1188 if (contiguous && pmb_nr && moved_symbol == l->s)
1189 flipped_block = (flipped_block + 1) % 2;
1190 else
1191 flipped_block = 0;
1193 if (pmb_nr)
1194 moved_symbol = l->s;
1195 else
1196 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1198 block_length = 0;
1201 if (pmb_nr) {
1202 block_length++;
1203 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1204 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1205 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1208 adjust_last_block(o, n, block_length);
1210 free(pmb);
1213 static void dim_moved_lines(struct diff_options *o)
1215 int n;
1216 for (n = 0; n < o->emitted_symbols->nr; n++) {
1217 struct emitted_diff_symbol *prev = (n != 0) ?
1218 &o->emitted_symbols->buf[n - 1] : NULL;
1219 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1220 struct emitted_diff_symbol *next =
1221 (n < o->emitted_symbols->nr - 1) ?
1222 &o->emitted_symbols->buf[n + 1] : NULL;
1224 /* Not a plus or minus line? */
1225 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1226 continue;
1228 /* Not a moved line? */
1229 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1230 continue;
1233 * If prev or next are not a plus or minus line,
1234 * pretend they don't exist
1236 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1237 prev->s != DIFF_SYMBOL_MINUS)
1238 prev = NULL;
1239 if (next && next->s != DIFF_SYMBOL_PLUS &&
1240 next->s != DIFF_SYMBOL_MINUS)
1241 next = NULL;
1243 /* Inside a block? */
1244 if ((prev &&
1245 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1246 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1247 (next &&
1248 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1249 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1250 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1251 continue;
1254 /* Check if we are at an interesting bound: */
1255 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1256 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1257 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1258 continue;
1259 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1260 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1261 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1262 continue;
1265 * The boundary to prev and next are not interesting,
1266 * so this line is not interesting as a whole
1268 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1272 static void emit_line_ws_markup(struct diff_options *o,
1273 const char *set_sign, const char *set,
1274 const char *reset,
1275 int sign_index, const char *line, int len,
1276 unsigned ws_rule, int blank_at_eof)
1278 const char *ws = NULL;
1279 int sign = o->output_indicators[sign_index];
1281 if (o->ws_error_highlight & ws_rule) {
1282 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1283 if (!*ws)
1284 ws = NULL;
1287 if (!ws && !set_sign)
1288 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1289 else if (!ws) {
1290 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1291 } else if (blank_at_eof)
1292 /* Blank line at EOF - paint '+' as well */
1293 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1294 else {
1295 /* Emit just the prefix, then the rest. */
1296 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1297 sign, "", 0);
1298 ws_check_emit(line, len, ws_rule,
1299 o->file, set, reset, ws);
1303 static void emit_diff_symbol_from_struct(struct diff_options *o,
1304 struct emitted_diff_symbol *eds)
1306 static const char *nneof = " No newline at end of file\n";
1307 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1309 enum diff_symbol s = eds->s;
1310 const char *line = eds->line;
1311 int len = eds->len;
1312 unsigned flags = eds->flags;
1314 switch (s) {
1315 case DIFF_SYMBOL_NO_LF_EOF:
1316 context = diff_get_color_opt(o, DIFF_CONTEXT);
1317 reset = diff_get_color_opt(o, DIFF_RESET);
1318 putc('\n', o->file);
1319 emit_line_0(o, context, NULL, 0, reset, '\\',
1320 nneof, strlen(nneof));
1321 break;
1322 case DIFF_SYMBOL_SUBMODULE_HEADER:
1323 case DIFF_SYMBOL_SUBMODULE_ERROR:
1324 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1325 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1326 case DIFF_SYMBOL_SUMMARY:
1327 case DIFF_SYMBOL_STATS_LINE:
1328 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1329 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1330 emit_line(o, "", "", line, len);
1331 break;
1332 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1333 case DIFF_SYMBOL_CONTEXT_MARKER:
1334 context = diff_get_color_opt(o, DIFF_CONTEXT);
1335 reset = diff_get_color_opt(o, DIFF_RESET);
1336 emit_line(o, context, reset, line, len);
1337 break;
1338 case DIFF_SYMBOL_SEPARATOR:
1339 fprintf(o->file, "%s%c",
1340 diff_line_prefix(o),
1341 o->line_termination);
1342 break;
1343 case DIFF_SYMBOL_CONTEXT:
1344 set = diff_get_color_opt(o, DIFF_CONTEXT);
1345 reset = diff_get_color_opt(o, DIFF_RESET);
1346 set_sign = NULL;
1347 if (o->flags.dual_color_diffed_diffs) {
1348 char c = !len ? 0 : line[0];
1350 if (c == '+')
1351 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1352 else if (c == '@')
1353 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1354 else if (c == '-')
1355 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1357 emit_line_ws_markup(o, set_sign, set, reset,
1358 OUTPUT_INDICATOR_CONTEXT, line, len,
1359 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1360 break;
1361 case DIFF_SYMBOL_PLUS:
1362 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1363 DIFF_SYMBOL_MOVED_LINE_ALT |
1364 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1365 case DIFF_SYMBOL_MOVED_LINE |
1366 DIFF_SYMBOL_MOVED_LINE_ALT |
1367 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1368 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1369 break;
1370 case DIFF_SYMBOL_MOVED_LINE |
1371 DIFF_SYMBOL_MOVED_LINE_ALT:
1372 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1373 break;
1374 case DIFF_SYMBOL_MOVED_LINE |
1375 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1376 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1377 break;
1378 case DIFF_SYMBOL_MOVED_LINE:
1379 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1380 break;
1381 default:
1382 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1384 reset = diff_get_color_opt(o, DIFF_RESET);
1385 if (!o->flags.dual_color_diffed_diffs)
1386 set_sign = NULL;
1387 else {
1388 char c = !len ? 0 : line[0];
1390 set_sign = set;
1391 if (c == '-')
1392 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1393 else if (c == '@')
1394 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1395 else if (c == '+')
1396 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1397 else
1398 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1399 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1401 emit_line_ws_markup(o, set_sign, set, reset,
1402 OUTPUT_INDICATOR_NEW, line, len,
1403 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1404 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1405 break;
1406 case DIFF_SYMBOL_MINUS:
1407 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1408 DIFF_SYMBOL_MOVED_LINE_ALT |
1409 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1410 case DIFF_SYMBOL_MOVED_LINE |
1411 DIFF_SYMBOL_MOVED_LINE_ALT |
1412 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1413 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1414 break;
1415 case DIFF_SYMBOL_MOVED_LINE |
1416 DIFF_SYMBOL_MOVED_LINE_ALT:
1417 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1418 break;
1419 case DIFF_SYMBOL_MOVED_LINE |
1420 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1421 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1422 break;
1423 case DIFF_SYMBOL_MOVED_LINE:
1424 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1425 break;
1426 default:
1427 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1429 reset = diff_get_color_opt(o, DIFF_RESET);
1430 if (!o->flags.dual_color_diffed_diffs)
1431 set_sign = NULL;
1432 else {
1433 char c = !len ? 0 : line[0];
1435 set_sign = set;
1436 if (c == '+')
1437 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1438 else if (c == '@')
1439 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1440 else if (c == '-')
1441 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1442 else
1443 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1445 emit_line_ws_markup(o, set_sign, set, reset,
1446 OUTPUT_INDICATOR_OLD, line, len,
1447 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1448 break;
1449 case DIFF_SYMBOL_WORDS_PORCELAIN:
1450 context = diff_get_color_opt(o, DIFF_CONTEXT);
1451 reset = diff_get_color_opt(o, DIFF_RESET);
1452 emit_line(o, context, reset, line, len);
1453 fputs("~\n", o->file);
1454 break;
1455 case DIFF_SYMBOL_WORDS:
1456 context = diff_get_color_opt(o, DIFF_CONTEXT);
1457 reset = diff_get_color_opt(o, DIFF_RESET);
1459 * Skip the prefix character, if any. With
1460 * diff_suppress_blank_empty, there may be
1461 * none.
1463 if (line[0] != '\n') {
1464 line++;
1465 len--;
1467 emit_line(o, context, reset, line, len);
1468 break;
1469 case DIFF_SYMBOL_FILEPAIR_PLUS:
1470 meta = diff_get_color_opt(o, DIFF_METAINFO);
1471 reset = diff_get_color_opt(o, DIFF_RESET);
1472 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1473 line, reset,
1474 strchr(line, ' ') ? "\t" : "");
1475 break;
1476 case DIFF_SYMBOL_FILEPAIR_MINUS:
1477 meta = diff_get_color_opt(o, DIFF_METAINFO);
1478 reset = diff_get_color_opt(o, DIFF_RESET);
1479 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1480 line, reset,
1481 strchr(line, ' ') ? "\t" : "");
1482 break;
1483 case DIFF_SYMBOL_BINARY_FILES:
1484 case DIFF_SYMBOL_HEADER:
1485 fprintf(o->file, "%s", line);
1486 break;
1487 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1488 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1489 break;
1490 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1491 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1492 break;
1493 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1494 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1495 break;
1496 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1497 fputs(diff_line_prefix(o), o->file);
1498 fputc('\n', o->file);
1499 break;
1500 case DIFF_SYMBOL_REWRITE_DIFF:
1501 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1502 reset = diff_get_color_opt(o, DIFF_RESET);
1503 emit_line(o, fraginfo, reset, line, len);
1504 break;
1505 case DIFF_SYMBOL_SUBMODULE_ADD:
1506 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1507 reset = diff_get_color_opt(o, DIFF_RESET);
1508 emit_line(o, set, reset, line, len);
1509 break;
1510 case DIFF_SYMBOL_SUBMODULE_DEL:
1511 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1512 reset = diff_get_color_opt(o, DIFF_RESET);
1513 emit_line(o, set, reset, line, len);
1514 break;
1515 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1516 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1517 diff_line_prefix(o), line);
1518 break;
1519 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1520 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1521 diff_line_prefix(o), line);
1522 break;
1523 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1524 emit_line(o, "", "", " 0 files changed\n",
1525 strlen(" 0 files changed\n"));
1526 break;
1527 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1528 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1529 break;
1530 case DIFF_SYMBOL_WORD_DIFF:
1531 fprintf(o->file, "%.*s", len, line);
1532 break;
1533 case DIFF_SYMBOL_STAT_SEP:
1534 fputs(o->stat_sep, o->file);
1535 break;
1536 default:
1537 BUG("unknown diff symbol");
1541 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1542 const char *line, int len, unsigned flags)
1544 struct emitted_diff_symbol e = {
1545 .line = line, .len = len, .flags = flags, .s = s
1548 if (o->emitted_symbols)
1549 append_emitted_diff_symbol(o, &e);
1550 else
1551 emit_diff_symbol_from_struct(o, &e);
1554 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1556 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1559 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1561 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1564 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1566 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1567 path, strlen(path), 0);
1570 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1572 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1573 path, strlen(path), 0);
1576 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1578 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1579 header, strlen(header), 0);
1582 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1584 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1587 void diff_emit_submodule_pipethrough(struct diff_options *o,
1588 const char *line, int len)
1590 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1593 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1595 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1596 ecbdata->blank_at_eof_in_preimage &&
1597 ecbdata->blank_at_eof_in_postimage &&
1598 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1599 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1600 return 0;
1601 return ws_blank_line(line, len);
1604 static void emit_add_line(struct emit_callback *ecbdata,
1605 const char *line, int len)
1607 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1608 if (new_blank_line_at_eof(ecbdata, line, len))
1609 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1611 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1614 static void emit_del_line(struct emit_callback *ecbdata,
1615 const char *line, int len)
1617 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1618 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1621 static void emit_context_line(struct emit_callback *ecbdata,
1622 const char *line, int len)
1624 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1625 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1628 static void emit_hunk_header(struct emit_callback *ecbdata,
1629 const char *line, int len)
1631 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1632 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1633 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1634 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1635 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1636 static const char atat[2] = { '@', '@' };
1637 const char *cp, *ep;
1638 struct strbuf msgbuf = STRBUF_INIT;
1639 int org_len = len;
1640 int i = 1;
1643 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1644 * it always is at least 10 bytes long.
1646 if (len < 10 ||
1647 memcmp(line, atat, 2) ||
1648 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1649 emit_diff_symbol(ecbdata->opt,
1650 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1651 return;
1653 ep += 2; /* skip over @@ */
1655 /* The hunk header in fraginfo color */
1656 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1657 strbuf_addstr(&msgbuf, reverse);
1658 strbuf_addstr(&msgbuf, frag);
1659 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1660 strbuf_add(&msgbuf, atat, sizeof(atat));
1661 else
1662 strbuf_add(&msgbuf, line, ep - line);
1663 strbuf_addstr(&msgbuf, reset);
1666 * trailing "\r\n"
1668 for ( ; i < 3; i++)
1669 if (line[len - i] == '\r' || line[len - i] == '\n')
1670 len--;
1672 /* blank before the func header */
1673 for (cp = ep; ep - line < len; ep++)
1674 if (*ep != ' ' && *ep != '\t')
1675 break;
1676 if (ep != cp) {
1677 strbuf_addstr(&msgbuf, context);
1678 strbuf_add(&msgbuf, cp, ep - cp);
1679 strbuf_addstr(&msgbuf, reset);
1682 if (ep < line + len) {
1683 strbuf_addstr(&msgbuf, func);
1684 strbuf_add(&msgbuf, ep, line + len - ep);
1685 strbuf_addstr(&msgbuf, reset);
1688 strbuf_add(&msgbuf, line + len, org_len - len);
1689 strbuf_complete_line(&msgbuf);
1690 emit_diff_symbol(ecbdata->opt,
1691 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1692 strbuf_release(&msgbuf);
1695 static struct diff_tempfile *claim_diff_tempfile(void)
1697 int i;
1698 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1699 if (!diff_temp[i].name)
1700 return diff_temp + i;
1701 BUG("diff is failing to clean up its tempfiles");
1704 static void remove_tempfile(void)
1706 int i;
1707 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1708 if (is_tempfile_active(diff_temp[i].tempfile))
1709 delete_tempfile(&diff_temp[i].tempfile);
1710 diff_temp[i].name = NULL;
1714 static void add_line_count(struct strbuf *out, int count)
1716 switch (count) {
1717 case 0:
1718 strbuf_addstr(out, "0,0");
1719 break;
1720 case 1:
1721 strbuf_addstr(out, "1");
1722 break;
1723 default:
1724 strbuf_addf(out, "1,%d", count);
1725 break;
1729 static void emit_rewrite_lines(struct emit_callback *ecb,
1730 int prefix, const char *data, int size)
1732 const char *endp = NULL;
1734 while (0 < size) {
1735 int len;
1737 endp = memchr(data, '\n', size);
1738 len = endp ? (endp - data + 1) : size;
1739 if (prefix != '+') {
1740 ecb->lno_in_preimage++;
1741 emit_del_line(ecb, data, len);
1742 } else {
1743 ecb->lno_in_postimage++;
1744 emit_add_line(ecb, data, len);
1746 size -= len;
1747 data += len;
1749 if (!endp)
1750 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1753 static void emit_rewrite_diff(const char *name_a,
1754 const char *name_b,
1755 struct diff_filespec *one,
1756 struct diff_filespec *two,
1757 struct userdiff_driver *textconv_one,
1758 struct userdiff_driver *textconv_two,
1759 struct diff_options *o)
1761 int lc_a, lc_b;
1762 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1763 const char *a_prefix, *b_prefix;
1764 char *data_one, *data_two;
1765 size_t size_one, size_two;
1766 struct emit_callback ecbdata;
1767 struct strbuf out = STRBUF_INIT;
1769 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1770 a_prefix = o->b_prefix;
1771 b_prefix = o->a_prefix;
1772 } else {
1773 a_prefix = o->a_prefix;
1774 b_prefix = o->b_prefix;
1777 name_a += (*name_a == '/');
1778 name_b += (*name_b == '/');
1780 strbuf_reset(&a_name);
1781 strbuf_reset(&b_name);
1782 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1783 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1785 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1786 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1788 memset(&ecbdata, 0, sizeof(ecbdata));
1789 ecbdata.color_diff = want_color(o->use_color);
1790 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1791 ecbdata.opt = o;
1792 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1793 mmfile_t mf1, mf2;
1794 mf1.ptr = (char *)data_one;
1795 mf2.ptr = (char *)data_two;
1796 mf1.size = size_one;
1797 mf2.size = size_two;
1798 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1800 ecbdata.lno_in_preimage = 1;
1801 ecbdata.lno_in_postimage = 1;
1803 lc_a = count_lines(data_one, size_one);
1804 lc_b = count_lines(data_two, size_two);
1806 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1807 a_name.buf, a_name.len, 0);
1808 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1809 b_name.buf, b_name.len, 0);
1811 strbuf_addstr(&out, "@@ -");
1812 if (!o->irreversible_delete)
1813 add_line_count(&out, lc_a);
1814 else
1815 strbuf_addstr(&out, "?,?");
1816 strbuf_addstr(&out, " +");
1817 add_line_count(&out, lc_b);
1818 strbuf_addstr(&out, " @@\n");
1819 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1820 strbuf_release(&out);
1822 if (lc_a && !o->irreversible_delete)
1823 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1824 if (lc_b)
1825 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1826 if (textconv_one)
1827 free((char *)data_one);
1828 if (textconv_two)
1829 free((char *)data_two);
1832 struct diff_words_buffer {
1833 mmfile_t text;
1834 unsigned long alloc;
1835 struct diff_words_orig {
1836 const char *begin, *end;
1837 } *orig;
1838 int orig_nr, orig_alloc;
1841 static void diff_words_append(char *line, unsigned long len,
1842 struct diff_words_buffer *buffer)
1844 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1845 line++;
1846 len--;
1847 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1848 buffer->text.size += len;
1849 buffer->text.ptr[buffer->text.size] = '\0';
1852 struct diff_words_style_elem {
1853 const char *prefix;
1854 const char *suffix;
1855 const char *color; /* NULL; filled in by the setup code if
1856 * color is enabled */
1859 struct diff_words_style {
1860 enum diff_words_type type;
1861 struct diff_words_style_elem new_word, old_word, ctx;
1862 const char *newline;
1865 static struct diff_words_style diff_words_styles[] = {
1866 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1867 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1868 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1871 struct diff_words_data {
1872 struct diff_words_buffer minus, plus;
1873 const char *current_plus;
1874 int last_minus;
1875 struct diff_options *opt;
1876 regex_t *word_regex;
1877 enum diff_words_type type;
1878 struct diff_words_style *style;
1881 static int fn_out_diff_words_write_helper(struct diff_options *o,
1882 struct diff_words_style_elem *st_el,
1883 const char *newline,
1884 size_t count, const char *buf)
1886 int print = 0;
1887 struct strbuf sb = STRBUF_INIT;
1889 while (count) {
1890 char *p = memchr(buf, '\n', count);
1891 if (print)
1892 strbuf_addstr(&sb, diff_line_prefix(o));
1894 if (p != buf) {
1895 const char *reset = st_el->color && *st_el->color ?
1896 GIT_COLOR_RESET : NULL;
1897 if (st_el->color && *st_el->color)
1898 strbuf_addstr(&sb, st_el->color);
1899 strbuf_addstr(&sb, st_el->prefix);
1900 strbuf_add(&sb, buf, p ? p - buf : count);
1901 strbuf_addstr(&sb, st_el->suffix);
1902 if (reset)
1903 strbuf_addstr(&sb, reset);
1905 if (!p)
1906 goto out;
1908 strbuf_addstr(&sb, newline);
1909 count -= p + 1 - buf;
1910 buf = p + 1;
1911 print = 1;
1912 if (count) {
1913 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1914 sb.buf, sb.len, 0);
1915 strbuf_reset(&sb);
1919 out:
1920 if (sb.len)
1921 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1922 sb.buf, sb.len, 0);
1923 strbuf_release(&sb);
1924 return 0;
1928 * '--color-words' algorithm can be described as:
1930 * 1. collect the minus/plus lines of a diff hunk, divided into
1931 * minus-lines and plus-lines;
1933 * 2. break both minus-lines and plus-lines into words and
1934 * place them into two mmfile_t with one word for each line;
1936 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1938 * And for the common parts of the both file, we output the plus side text.
1939 * diff_words->current_plus is used to trace the current position of the plus file
1940 * which printed. diff_words->last_minus is used to trace the last minus word
1941 * printed.
1943 * For '--graph' to work with '--color-words', we need to output the graph prefix
1944 * on each line of color words output. Generally, there are two conditions on
1945 * which we should output the prefix.
1947 * 1. diff_words->last_minus == 0 &&
1948 * diff_words->current_plus == diff_words->plus.text.ptr
1950 * that is: the plus text must start as a new line, and if there is no minus
1951 * word printed, a graph prefix must be printed.
1953 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1954 * *(diff_words->current_plus - 1) == '\n'
1956 * that is: a graph prefix must be printed following a '\n'
1958 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1960 if ((diff_words->last_minus == 0 &&
1961 diff_words->current_plus == diff_words->plus.text.ptr) ||
1962 (diff_words->current_plus > diff_words->plus.text.ptr &&
1963 *(diff_words->current_plus - 1) == '\n')) {
1964 return 1;
1965 } else {
1966 return 0;
1970 static void fn_out_diff_words_aux(void *priv,
1971 long minus_first, long minus_len,
1972 long plus_first, long plus_len,
1973 const char *func UNUSED, long funclen UNUSED)
1975 struct diff_words_data *diff_words = priv;
1976 struct diff_words_style *style = diff_words->style;
1977 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1978 struct diff_options *opt = diff_words->opt;
1979 const char *line_prefix;
1981 assert(opt);
1982 line_prefix = diff_line_prefix(opt);
1984 /* POSIX requires that first be decremented by one if len == 0... */
1985 if (minus_len) {
1986 minus_begin = diff_words->minus.orig[minus_first].begin;
1987 minus_end =
1988 diff_words->minus.orig[minus_first + minus_len - 1].end;
1989 } else
1990 minus_begin = minus_end =
1991 diff_words->minus.orig[minus_first].end;
1993 if (plus_len) {
1994 plus_begin = diff_words->plus.orig[plus_first].begin;
1995 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1996 } else
1997 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1999 if (color_words_output_graph_prefix(diff_words)) {
2000 fputs(line_prefix, diff_words->opt->file);
2002 if (diff_words->current_plus != plus_begin) {
2003 fn_out_diff_words_write_helper(diff_words->opt,
2004 &style->ctx, style->newline,
2005 plus_begin - diff_words->current_plus,
2006 diff_words->current_plus);
2008 if (minus_begin != minus_end) {
2009 fn_out_diff_words_write_helper(diff_words->opt,
2010 &style->old_word, style->newline,
2011 minus_end - minus_begin, minus_begin);
2013 if (plus_begin != plus_end) {
2014 fn_out_diff_words_write_helper(diff_words->opt,
2015 &style->new_word, style->newline,
2016 plus_end - plus_begin, plus_begin);
2019 diff_words->current_plus = plus_end;
2020 diff_words->last_minus = minus_first;
2023 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2024 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2025 int *begin, int *end)
2027 while (word_regex && *begin < buffer->size) {
2028 regmatch_t match[1];
2029 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2030 buffer->size - *begin, 1, match, 0)) {
2031 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2032 '\n', match[0].rm_eo - match[0].rm_so);
2033 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2034 *begin += match[0].rm_so;
2035 if (*begin == *end)
2036 (*begin)++;
2037 else
2038 return *begin > *end;
2039 } else {
2040 return -1;
2044 /* find the next word */
2045 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2046 (*begin)++;
2047 if (*begin >= buffer->size)
2048 return -1;
2050 /* find the end of the word */
2051 *end = *begin + 1;
2052 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2053 (*end)++;
2055 return 0;
2059 * This function splits the words in buffer->text, stores the list with
2060 * newline separator into out, and saves the offsets of the original words
2061 * in buffer->orig.
2063 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2064 regex_t *word_regex)
2066 int i, j;
2067 long alloc = 0;
2069 out->size = 0;
2070 out->ptr = NULL;
2072 /* fake an empty "0th" word */
2073 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2074 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2075 buffer->orig_nr = 1;
2077 for (i = 0; i < buffer->text.size; i++) {
2078 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2079 return;
2081 /* store original boundaries */
2082 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2083 buffer->orig_alloc);
2084 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2085 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2086 buffer->orig_nr++;
2088 /* store one word */
2089 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2090 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2091 out->ptr[out->size + j - i] = '\n';
2092 out->size += j - i + 1;
2094 i = j - 1;
2098 /* this executes the word diff on the accumulated buffers */
2099 static void diff_words_show(struct diff_words_data *diff_words)
2101 xpparam_t xpp;
2102 xdemitconf_t xecfg;
2103 mmfile_t minus, plus;
2104 struct diff_words_style *style = diff_words->style;
2106 struct diff_options *opt = diff_words->opt;
2107 const char *line_prefix;
2109 assert(opt);
2110 line_prefix = diff_line_prefix(opt);
2112 /* special case: only removal */
2113 if (!diff_words->plus.text.size) {
2114 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2115 line_prefix, strlen(line_prefix), 0);
2116 fn_out_diff_words_write_helper(diff_words->opt,
2117 &style->old_word, style->newline,
2118 diff_words->minus.text.size,
2119 diff_words->minus.text.ptr);
2120 diff_words->minus.text.size = 0;
2121 return;
2124 diff_words->current_plus = diff_words->plus.text.ptr;
2125 diff_words->last_minus = 0;
2127 memset(&xpp, 0, sizeof(xpp));
2128 memset(&xecfg, 0, sizeof(xecfg));
2129 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2130 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2131 xpp.flags = 0;
2132 /* as only the hunk header will be parsed, we need a 0-context */
2133 xecfg.ctxlen = 0;
2134 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2135 diff_words, &xpp, &xecfg))
2136 die("unable to generate word diff");
2137 free(minus.ptr);
2138 free(plus.ptr);
2139 if (diff_words->current_plus != diff_words->plus.text.ptr +
2140 diff_words->plus.text.size) {
2141 if (color_words_output_graph_prefix(diff_words))
2142 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2143 line_prefix, strlen(line_prefix), 0);
2144 fn_out_diff_words_write_helper(diff_words->opt,
2145 &style->ctx, style->newline,
2146 diff_words->plus.text.ptr + diff_words->plus.text.size
2147 - diff_words->current_plus, diff_words->current_plus);
2149 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2152 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2153 static void diff_words_flush(struct emit_callback *ecbdata)
2155 struct diff_options *wo = ecbdata->diff_words->opt;
2157 if (ecbdata->diff_words->minus.text.size ||
2158 ecbdata->diff_words->plus.text.size)
2159 diff_words_show(ecbdata->diff_words);
2161 if (wo->emitted_symbols) {
2162 struct diff_options *o = ecbdata->opt;
2163 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2164 int i;
2167 * NEEDSWORK:
2168 * Instead of appending each, concat all words to a line?
2170 for (i = 0; i < wol->nr; i++)
2171 append_emitted_diff_symbol(o, &wol->buf[i]);
2173 for (i = 0; i < wol->nr; i++)
2174 free((void *)wol->buf[i].line);
2176 wol->nr = 0;
2180 static void diff_filespec_load_driver(struct diff_filespec *one,
2181 struct index_state *istate)
2183 /* Use already-loaded driver */
2184 if (one->driver)
2185 return;
2187 if (S_ISREG(one->mode))
2188 one->driver = userdiff_find_by_path(istate, one->path);
2190 /* Fallback to default settings */
2191 if (!one->driver)
2192 one->driver = userdiff_find_by_name("default");
2195 static const char *userdiff_word_regex(struct diff_filespec *one,
2196 struct index_state *istate)
2198 diff_filespec_load_driver(one, istate);
2199 return one->driver->word_regex;
2202 static void init_diff_words_data(struct emit_callback *ecbdata,
2203 struct diff_options *orig_opts,
2204 struct diff_filespec *one,
2205 struct diff_filespec *two)
2207 int i;
2208 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2209 memcpy(o, orig_opts, sizeof(struct diff_options));
2211 CALLOC_ARRAY(ecbdata->diff_words, 1);
2212 ecbdata->diff_words->type = o->word_diff;
2213 ecbdata->diff_words->opt = o;
2215 if (orig_opts->emitted_symbols)
2216 CALLOC_ARRAY(o->emitted_symbols, 1);
2218 if (!o->word_regex)
2219 o->word_regex = userdiff_word_regex(one, o->repo->index);
2220 if (!o->word_regex)
2221 o->word_regex = userdiff_word_regex(two, o->repo->index);
2222 if (!o->word_regex)
2223 o->word_regex = diff_word_regex_cfg;
2224 if (o->word_regex) {
2225 ecbdata->diff_words->word_regex = (regex_t *)
2226 xmalloc(sizeof(regex_t));
2227 if (regcomp(ecbdata->diff_words->word_regex,
2228 o->word_regex,
2229 REG_EXTENDED | REG_NEWLINE))
2230 die("invalid regular expression: %s",
2231 o->word_regex);
2233 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2234 if (o->word_diff == diff_words_styles[i].type) {
2235 ecbdata->diff_words->style =
2236 &diff_words_styles[i];
2237 break;
2240 if (want_color(o->use_color)) {
2241 struct diff_words_style *st = ecbdata->diff_words->style;
2242 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2243 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2244 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2248 static void free_diff_words_data(struct emit_callback *ecbdata)
2250 if (ecbdata->diff_words) {
2251 diff_words_flush(ecbdata);
2252 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2253 free (ecbdata->diff_words->opt);
2254 free (ecbdata->diff_words->minus.text.ptr);
2255 free (ecbdata->diff_words->minus.orig);
2256 free (ecbdata->diff_words->plus.text.ptr);
2257 free (ecbdata->diff_words->plus.orig);
2258 if (ecbdata->diff_words->word_regex) {
2259 regfree(ecbdata->diff_words->word_regex);
2260 free(ecbdata->diff_words->word_regex);
2262 FREE_AND_NULL(ecbdata->diff_words);
2266 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2268 if (want_color(diff_use_color))
2269 return diff_colors[ix];
2270 return "";
2273 const char *diff_line_prefix(struct diff_options *opt)
2275 struct strbuf *msgbuf;
2276 if (!opt->output_prefix)
2277 return "";
2279 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2280 return msgbuf->buf;
2283 static unsigned long sane_truncate_line(char *line, unsigned long len)
2285 const char *cp;
2286 unsigned long allot;
2287 size_t l = len;
2289 cp = line;
2290 allot = l;
2291 while (0 < l) {
2292 (void) utf8_width(&cp, &l);
2293 if (!cp)
2294 break; /* truncated in the middle? */
2296 return allot - l;
2299 static void find_lno(const char *line, struct emit_callback *ecbdata)
2301 const char *p;
2302 ecbdata->lno_in_preimage = 0;
2303 ecbdata->lno_in_postimage = 0;
2304 p = strchr(line, '-');
2305 if (!p)
2306 return; /* cannot happen */
2307 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2308 p = strchr(p, '+');
2309 if (!p)
2310 return; /* cannot happen */
2311 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2314 static int fn_out_consume(void *priv, char *line, unsigned long len)
2316 struct emit_callback *ecbdata = priv;
2317 struct diff_options *o = ecbdata->opt;
2319 o->found_changes = 1;
2321 if (ecbdata->header) {
2322 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2323 ecbdata->header->buf, ecbdata->header->len, 0);
2324 strbuf_reset(ecbdata->header);
2325 ecbdata->header = NULL;
2328 if (ecbdata->label_path[0]) {
2329 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2330 ecbdata->label_path[0],
2331 strlen(ecbdata->label_path[0]), 0);
2332 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2333 ecbdata->label_path[1],
2334 strlen(ecbdata->label_path[1]), 0);
2335 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2338 if (diff_suppress_blank_empty
2339 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2340 line[0] = '\n';
2341 len = 1;
2344 if (line[0] == '@') {
2345 if (ecbdata->diff_words)
2346 diff_words_flush(ecbdata);
2347 len = sane_truncate_line(line, len);
2348 find_lno(line, ecbdata);
2349 emit_hunk_header(ecbdata, line, len);
2350 return 0;
2353 if (ecbdata->diff_words) {
2354 enum diff_symbol s =
2355 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2356 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2357 if (line[0] == '-') {
2358 diff_words_append(line, len,
2359 &ecbdata->diff_words->minus);
2360 return 0;
2361 } else if (line[0] == '+') {
2362 diff_words_append(line, len,
2363 &ecbdata->diff_words->plus);
2364 return 0;
2365 } else if (starts_with(line, "\\ ")) {
2367 * Eat the "no newline at eof" marker as if we
2368 * saw a "+" or "-" line with nothing on it,
2369 * and return without diff_words_flush() to
2370 * defer processing. If this is the end of
2371 * preimage, more "+" lines may come after it.
2373 return 0;
2375 diff_words_flush(ecbdata);
2376 emit_diff_symbol(o, s, line, len, 0);
2377 return 0;
2380 switch (line[0]) {
2381 case '+':
2382 ecbdata->lno_in_postimage++;
2383 emit_add_line(ecbdata, line + 1, len - 1);
2384 break;
2385 case '-':
2386 ecbdata->lno_in_preimage++;
2387 emit_del_line(ecbdata, line + 1, len - 1);
2388 break;
2389 case ' ':
2390 ecbdata->lno_in_postimage++;
2391 ecbdata->lno_in_preimage++;
2392 emit_context_line(ecbdata, line + 1, len - 1);
2393 break;
2394 default:
2395 /* incomplete line at the end */
2396 ecbdata->lno_in_preimage++;
2397 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2398 line, len, 0);
2399 break;
2401 return 0;
2404 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2406 const char *old_name = a;
2407 const char *new_name = b;
2408 int pfx_length, sfx_length;
2409 int pfx_adjust_for_slash;
2410 int len_a = strlen(a);
2411 int len_b = strlen(b);
2412 int a_midlen, b_midlen;
2413 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2414 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2416 if (qlen_a || qlen_b) {
2417 quote_c_style(a, name, NULL, 0);
2418 strbuf_addstr(name, " => ");
2419 quote_c_style(b, name, NULL, 0);
2420 return;
2423 /* Find common prefix */
2424 pfx_length = 0;
2425 while (*old_name && *new_name && *old_name == *new_name) {
2426 if (*old_name == '/')
2427 pfx_length = old_name - a + 1;
2428 old_name++;
2429 new_name++;
2432 /* Find common suffix */
2433 old_name = a + len_a;
2434 new_name = b + len_b;
2435 sfx_length = 0;
2437 * If there is a common prefix, it must end in a slash. In
2438 * that case we let this loop run 1 into the prefix to see the
2439 * same slash.
2441 * If there is no common prefix, we cannot do this as it would
2442 * underrun the input strings.
2444 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2445 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2446 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2447 *old_name == *new_name) {
2448 if (*old_name == '/')
2449 sfx_length = len_a - (old_name - a);
2450 old_name--;
2451 new_name--;
2455 * pfx{mid-a => mid-b}sfx
2456 * {pfx-a => pfx-b}sfx
2457 * pfx{sfx-a => sfx-b}
2458 * name-a => name-b
2460 a_midlen = len_a - pfx_length - sfx_length;
2461 b_midlen = len_b - pfx_length - sfx_length;
2462 if (a_midlen < 0)
2463 a_midlen = 0;
2464 if (b_midlen < 0)
2465 b_midlen = 0;
2467 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2468 if (pfx_length + sfx_length) {
2469 strbuf_add(name, a, pfx_length);
2470 strbuf_addch(name, '{');
2472 strbuf_add(name, a + pfx_length, a_midlen);
2473 strbuf_addstr(name, " => ");
2474 strbuf_add(name, b + pfx_length, b_midlen);
2475 if (pfx_length + sfx_length) {
2476 strbuf_addch(name, '}');
2477 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2481 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2482 const char *name_a,
2483 const char *name_b)
2485 struct diffstat_file *x;
2486 CALLOC_ARRAY(x, 1);
2487 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2488 diffstat->files[diffstat->nr++] = x;
2489 if (name_b) {
2490 x->from_name = xstrdup(name_a);
2491 x->name = xstrdup(name_b);
2492 x->is_renamed = 1;
2494 else {
2495 x->from_name = NULL;
2496 x->name = xstrdup(name_a);
2498 return x;
2501 static int diffstat_consume(void *priv, char *line, unsigned long len)
2503 struct diffstat_t *diffstat = priv;
2504 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2506 if (!len)
2507 BUG("xdiff fed us an empty line");
2509 if (line[0] == '+')
2510 x->added++;
2511 else if (line[0] == '-')
2512 x->deleted++;
2513 return 0;
2516 const char mime_boundary_leader[] = "------------";
2518 static int scale_linear(int it, int width, int max_change)
2520 if (!it)
2521 return 0;
2523 * make sure that at least one '-' or '+' is printed if
2524 * there is any change to this path. The easiest way is to
2525 * scale linearly as if the allotted width is one column shorter
2526 * than it is, and then add 1 to the result.
2528 return 1 + (it * (width - 1) / max_change);
2531 static void show_graph(struct strbuf *out, char ch, int cnt,
2532 const char *set, const char *reset)
2534 if (cnt <= 0)
2535 return;
2536 strbuf_addstr(out, set);
2537 strbuf_addchars(out, ch, cnt);
2538 strbuf_addstr(out, reset);
2541 static void fill_print_name(struct diffstat_file *file)
2543 struct strbuf pname = STRBUF_INIT;
2545 if (file->print_name)
2546 return;
2548 if (file->is_renamed)
2549 pprint_rename(&pname, file->from_name, file->name);
2550 else
2551 quote_c_style(file->name, &pname, NULL, 0);
2553 if (file->comments)
2554 strbuf_addf(&pname, " (%s)", file->comments);
2556 file->print_name = strbuf_detach(&pname, NULL);
2559 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2560 int files, int insertions, int deletions)
2562 struct strbuf sb = STRBUF_INIT;
2564 if (!files) {
2565 assert(insertions == 0 && deletions == 0);
2566 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2567 NULL, 0, 0);
2568 return;
2571 strbuf_addf(&sb,
2572 (files == 1) ? " %d file changed" : " %d files changed",
2573 files);
2576 * For binary diff, the caller may want to print "x files
2577 * changed" with insertions == 0 && deletions == 0.
2579 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2580 * is probably less confusing (i.e skip over "2 files changed
2581 * but nothing about added/removed lines? Is this a bug in Git?").
2583 if (insertions || deletions == 0) {
2584 strbuf_addf(&sb,
2585 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2586 insertions);
2589 if (deletions || insertions == 0) {
2590 strbuf_addf(&sb,
2591 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2592 deletions);
2594 strbuf_addch(&sb, '\n');
2595 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2596 sb.buf, sb.len, 0);
2597 strbuf_release(&sb);
2600 void print_stat_summary(FILE *fp, int files,
2601 int insertions, int deletions)
2603 struct diff_options o;
2604 memset(&o, 0, sizeof(o));
2605 o.file = fp;
2607 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2610 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2612 int i, len, add, del, adds = 0, dels = 0;
2613 uintmax_t max_change = 0, max_len = 0;
2614 int total_files = data->nr, count;
2615 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2616 const char *reset, *add_c, *del_c;
2617 int extra_shown = 0;
2618 const char *line_prefix = diff_line_prefix(options);
2619 struct strbuf out = STRBUF_INIT;
2621 if (data->nr == 0)
2622 return;
2624 count = options->stat_count ? options->stat_count : data->nr;
2626 reset = diff_get_color_opt(options, DIFF_RESET);
2627 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2628 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2631 * Find the longest filename and max number of changes
2633 for (i = 0; (i < count) && (i < data->nr); i++) {
2634 struct diffstat_file *file = data->files[i];
2635 uintmax_t change = file->added + file->deleted;
2637 if (!file->is_interesting && (change == 0)) {
2638 count++; /* not shown == room for one more */
2639 continue;
2641 fill_print_name(file);
2642 len = utf8_strwidth(file->print_name);
2643 if (max_len < len)
2644 max_len = len;
2646 if (file->is_unmerged) {
2647 /* "Unmerged" is 8 characters */
2648 bin_width = bin_width < 8 ? 8 : bin_width;
2649 continue;
2651 if (file->is_binary) {
2652 /* "Bin XXX -> YYY bytes" */
2653 int w = 14 + decimal_width(file->added)
2654 + decimal_width(file->deleted);
2655 bin_width = bin_width < w ? w : bin_width;
2656 /* Display change counts aligned with "Bin" */
2657 number_width = 3;
2658 continue;
2661 if (max_change < change)
2662 max_change = change;
2664 count = i; /* where we can stop scanning in data->files[] */
2667 * We have width = stat_width or term_columns() columns total.
2668 * We want a maximum of min(max_len, stat_name_width) for the name part.
2669 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2670 * We also need 1 for " " and 4 + decimal_width(max_change)
2671 * for " | NNNN " and one the empty column at the end, altogether
2672 * 6 + decimal_width(max_change).
2674 * If there's not enough space, we will use the smaller of
2675 * stat_name_width (if set) and 5/8*width for the filename,
2676 * and the rest for constant elements + graph part, but no more
2677 * than stat_graph_width for the graph part.
2678 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2679 * for the standard terminal size).
2681 * In other words: stat_width limits the maximum width, and
2682 * stat_name_width fixes the maximum width of the filename,
2683 * and is also used to divide available columns if there
2684 * aren't enough.
2686 * Binary files are displayed with "Bin XXX -> YYY bytes"
2687 * instead of the change count and graph. This part is treated
2688 * similarly to the graph part, except that it is not
2689 * "scaled". If total width is too small to accommodate the
2690 * guaranteed minimum width of the filename part and the
2691 * separators and this message, this message will "overflow"
2692 * making the line longer than the maximum width.
2696 * NEEDSWORK: line_prefix is often used for "log --graph" output
2697 * and contains ANSI-colored string. utf8_strnwidth() should be
2698 * used to correctly count the display width instead of strlen().
2700 if (options->stat_width == -1)
2701 width = term_columns() - strlen(line_prefix);
2702 else
2703 width = options->stat_width ? options->stat_width : 80;
2704 number_width = decimal_width(max_change) > number_width ?
2705 decimal_width(max_change) : number_width;
2707 if (options->stat_graph_width == -1)
2708 options->stat_graph_width = diff_stat_graph_width;
2711 * Guarantee 3/8*16==6 for the graph part
2712 * and 5/8*16==10 for the filename part
2714 if (width < 16 + 6 + number_width)
2715 width = 16 + 6 + number_width;
2718 * First assign sizes that are wanted, ignoring available width.
2719 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2720 * starting from "XXX" should fit in graph_width.
2722 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2723 if (options->stat_graph_width &&
2724 options->stat_graph_width < graph_width)
2725 graph_width = options->stat_graph_width;
2727 name_width = (options->stat_name_width > 0 &&
2728 options->stat_name_width < max_len) ?
2729 options->stat_name_width : max_len;
2732 * Adjust adjustable widths not to exceed maximum width
2734 if (name_width + number_width + 6 + graph_width > width) {
2735 if (graph_width > width * 3/8 - number_width - 6) {
2736 graph_width = width * 3/8 - number_width - 6;
2737 if (graph_width < 6)
2738 graph_width = 6;
2741 if (options->stat_graph_width &&
2742 graph_width > options->stat_graph_width)
2743 graph_width = options->stat_graph_width;
2744 if (name_width > width - number_width - 6 - graph_width)
2745 name_width = width - number_width - 6 - graph_width;
2746 else
2747 graph_width = width - number_width - 6 - name_width;
2751 * From here name_width is the width of the name area,
2752 * and graph_width is the width of the graph area.
2753 * max_change is used to scale graph properly.
2755 for (i = 0; i < count; i++) {
2756 const char *prefix = "";
2757 struct diffstat_file *file = data->files[i];
2758 char *name = file->print_name;
2759 uintmax_t added = file->added;
2760 uintmax_t deleted = file->deleted;
2761 int name_len, padding;
2763 if (!file->is_interesting && (added + deleted == 0))
2764 continue;
2767 * "scale" the filename
2769 len = name_width;
2770 name_len = utf8_strwidth(name);
2771 if (name_width < name_len) {
2772 char *slash;
2773 prefix = "...";
2774 len -= 3;
2776 * NEEDSWORK: (name_len - len) counts the display
2777 * width, which would be shorter than the byte
2778 * length of the corresponding substring.
2779 * Advancing "name" by that number of bytes does
2780 * *NOT* skip over that many columns, so it is
2781 * very likely that chomping the pathname at the
2782 * slash we will find starting from "name" will
2783 * leave the resulting string still too long.
2785 name += name_len - len;
2786 slash = strchr(name, '/');
2787 if (slash)
2788 name = slash;
2790 padding = len - utf8_strwidth(name);
2791 if (padding < 0)
2792 padding = 0;
2794 if (file->is_binary) {
2795 strbuf_addf(&out, " %s%s%*s | %*s",
2796 prefix, name, padding, "",
2797 number_width, "Bin");
2798 if (!added && !deleted) {
2799 strbuf_addch(&out, '\n');
2800 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2801 out.buf, out.len, 0);
2802 strbuf_reset(&out);
2803 continue;
2805 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2806 del_c, deleted, reset);
2807 strbuf_addstr(&out, " -> ");
2808 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2809 add_c, added, reset);
2810 strbuf_addstr(&out, " bytes\n");
2811 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2812 out.buf, out.len, 0);
2813 strbuf_reset(&out);
2814 continue;
2816 else if (file->is_unmerged) {
2817 strbuf_addf(&out, " %s%s%*s | %*s",
2818 prefix, name, padding, "",
2819 number_width, "Unmerged\n");
2820 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2821 out.buf, out.len, 0);
2822 strbuf_reset(&out);
2823 continue;
2827 * scale the add/delete
2829 add = added;
2830 del = deleted;
2832 if (graph_width <= max_change) {
2833 int total = scale_linear(add + del, graph_width, max_change);
2834 if (total < 2 && add && del)
2835 /* width >= 2 due to the sanity check */
2836 total = 2;
2837 if (add < del) {
2838 add = scale_linear(add, graph_width, max_change);
2839 del = total - add;
2840 } else {
2841 del = scale_linear(del, graph_width, max_change);
2842 add = total - del;
2845 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2846 prefix, name, padding, "",
2847 number_width, added + deleted,
2848 added + deleted ? " " : "");
2849 show_graph(&out, '+', add, add_c, reset);
2850 show_graph(&out, '-', del, del_c, reset);
2851 strbuf_addch(&out, '\n');
2852 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2853 out.buf, out.len, 0);
2854 strbuf_reset(&out);
2857 for (i = 0; i < data->nr; i++) {
2858 struct diffstat_file *file = data->files[i];
2859 uintmax_t added = file->added;
2860 uintmax_t deleted = file->deleted;
2862 if (file->is_unmerged ||
2863 (!file->is_interesting && (added + deleted == 0))) {
2864 total_files--;
2865 continue;
2868 if (!file->is_binary) {
2869 adds += added;
2870 dels += deleted;
2872 if (i < count)
2873 continue;
2874 if (!extra_shown)
2875 emit_diff_symbol(options,
2876 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2877 NULL, 0, 0);
2878 extra_shown = 1;
2881 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2882 strbuf_release(&out);
2885 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2887 int i, adds = 0, dels = 0, total_files = data->nr;
2889 if (data->nr == 0)
2890 return;
2892 for (i = 0; i < data->nr; i++) {
2893 int added = data->files[i]->added;
2894 int deleted = data->files[i]->deleted;
2896 if (data->files[i]->is_unmerged ||
2897 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2898 total_files--;
2899 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2900 adds += added;
2901 dels += deleted;
2904 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2907 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2909 int i;
2911 if (data->nr == 0)
2912 return;
2914 for (i = 0; i < data->nr; i++) {
2915 struct diffstat_file *file = data->files[i];
2917 fprintf(options->file, "%s", diff_line_prefix(options));
2919 if (file->is_binary)
2920 fprintf(options->file, "-\t-\t");
2921 else
2922 fprintf(options->file,
2923 "%"PRIuMAX"\t%"PRIuMAX"\t",
2924 file->added, file->deleted);
2925 if (options->line_termination) {
2926 fill_print_name(file);
2927 if (!file->is_renamed)
2928 write_name_quoted(file->name, options->file,
2929 options->line_termination);
2930 else {
2931 fputs(file->print_name, options->file);
2932 putc(options->line_termination, options->file);
2934 } else {
2935 if (file->is_renamed) {
2936 putc('\0', options->file);
2937 write_name_quoted(file->from_name, options->file, '\0');
2939 write_name_quoted(file->name, options->file, '\0');
2944 struct dirstat_file {
2945 const char *name;
2946 unsigned long changed;
2949 struct dirstat_dir {
2950 struct dirstat_file *files;
2951 int alloc, nr, permille, cumulative;
2954 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2955 unsigned long changed, const char *base, int baselen)
2957 unsigned long sum_changes = 0;
2958 unsigned int sources = 0;
2959 const char *line_prefix = diff_line_prefix(opt);
2961 while (dir->nr) {
2962 struct dirstat_file *f = dir->files;
2963 int namelen = strlen(f->name);
2964 unsigned long changes;
2965 char *slash;
2967 if (namelen < baselen)
2968 break;
2969 if (memcmp(f->name, base, baselen))
2970 break;
2971 slash = strchr(f->name + baselen, '/');
2972 if (slash) {
2973 int newbaselen = slash + 1 - f->name;
2974 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2975 sources++;
2976 } else {
2977 changes = f->changed;
2978 dir->files++;
2979 dir->nr--;
2980 sources += 2;
2982 sum_changes += changes;
2986 * We don't report dirstat's for
2987 * - the top level
2988 * - or cases where everything came from a single directory
2989 * under this directory (sources == 1).
2991 if (baselen && sources != 1) {
2992 if (sum_changes) {
2993 int permille = sum_changes * 1000 / changed;
2994 if (permille >= dir->permille) {
2995 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2996 permille / 10, permille % 10, baselen, base);
2997 if (!dir->cumulative)
2998 return 0;
3002 return sum_changes;
3005 static int dirstat_compare(const void *_a, const void *_b)
3007 const struct dirstat_file *a = _a;
3008 const struct dirstat_file *b = _b;
3009 return strcmp(a->name, b->name);
3012 static void conclude_dirstat(struct diff_options *options,
3013 struct dirstat_dir *dir,
3014 unsigned long changed)
3016 struct dirstat_file *to_free = dir->files;
3018 if (!changed) {
3019 /* This can happen even with many files, if everything was renames */
3021 } else {
3022 /* Show all directories with more than x% of the changes */
3023 QSORT(dir->files, dir->nr, dirstat_compare);
3024 gather_dirstat(options, dir, changed, "", 0);
3027 free(to_free);
3030 static void show_dirstat(struct diff_options *options)
3032 int i;
3033 unsigned long changed;
3034 struct dirstat_dir dir;
3035 struct diff_queue_struct *q = &diff_queued_diff;
3037 dir.files = NULL;
3038 dir.alloc = 0;
3039 dir.nr = 0;
3040 dir.permille = options->dirstat_permille;
3041 dir.cumulative = options->flags.dirstat_cumulative;
3043 changed = 0;
3044 for (i = 0; i < q->nr; i++) {
3045 struct diff_filepair *p = q->queue[i];
3046 const char *name;
3047 unsigned long copied, added, damage;
3048 struct diff_populate_filespec_options dpf_options = {
3049 .check_size_only = 1,
3052 name = p->two->path ? p->two->path : p->one->path;
3054 if (p->one->oid_valid && p->two->oid_valid &&
3055 oideq(&p->one->oid, &p->two->oid)) {
3057 * The SHA1 has not changed, so pre-/post-content is
3058 * identical. We can therefore skip looking at the
3059 * file contents altogether.
3061 damage = 0;
3062 goto found_damage;
3065 if (options->flags.dirstat_by_file) {
3067 * In --dirstat-by-file mode, we don't really need to
3068 * look at the actual file contents at all.
3069 * The fact that the SHA1 changed is enough for us to
3070 * add this file to the list of results
3071 * (with each file contributing equal damage).
3073 damage = 1;
3074 goto found_damage;
3077 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3078 diff_populate_filespec(options->repo, p->one, NULL);
3079 diff_populate_filespec(options->repo, p->two, NULL);
3080 diffcore_count_changes(options->repo,
3081 p->one, p->two, NULL, NULL,
3082 &copied, &added);
3083 diff_free_filespec_data(p->one);
3084 diff_free_filespec_data(p->two);
3085 } else if (DIFF_FILE_VALID(p->one)) {
3086 diff_populate_filespec(options->repo, p->one, &dpf_options);
3087 copied = added = 0;
3088 diff_free_filespec_data(p->one);
3089 } else if (DIFF_FILE_VALID(p->two)) {
3090 diff_populate_filespec(options->repo, p->two, &dpf_options);
3091 copied = 0;
3092 added = p->two->size;
3093 diff_free_filespec_data(p->two);
3094 } else
3095 continue;
3098 * Original minus copied is the removed material,
3099 * added is the new material. They are both damages
3100 * made to the preimage.
3101 * If the resulting damage is zero, we know that
3102 * diffcore_count_changes() considers the two entries to
3103 * be identical, but since the oid changed, we
3104 * know that there must have been _some_ kind of change,
3105 * so we force all entries to have damage > 0.
3107 damage = (p->one->size - copied) + added;
3108 if (!damage)
3109 damage = 1;
3111 found_damage:
3112 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3113 dir.files[dir.nr].name = name;
3114 dir.files[dir.nr].changed = damage;
3115 changed += damage;
3116 dir.nr++;
3119 conclude_dirstat(options, &dir, changed);
3122 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3124 int i;
3125 unsigned long changed;
3126 struct dirstat_dir dir;
3128 if (data->nr == 0)
3129 return;
3131 dir.files = NULL;
3132 dir.alloc = 0;
3133 dir.nr = 0;
3134 dir.permille = options->dirstat_permille;
3135 dir.cumulative = options->flags.dirstat_cumulative;
3137 changed = 0;
3138 for (i = 0; i < data->nr; i++) {
3139 struct diffstat_file *file = data->files[i];
3140 unsigned long damage = file->added + file->deleted;
3141 if (file->is_binary)
3143 * binary files counts bytes, not lines. Must find some
3144 * way to normalize binary bytes vs. textual lines.
3145 * The following heuristic assumes that there are 64
3146 * bytes per "line".
3147 * This is stupid and ugly, but very cheap...
3149 damage = DIV_ROUND_UP(damage, 64);
3150 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3151 dir.files[dir.nr].name = file->name;
3152 dir.files[dir.nr].changed = damage;
3153 changed += damage;
3154 dir.nr++;
3157 conclude_dirstat(options, &dir, changed);
3160 static void free_diffstat_file(struct diffstat_file *f)
3162 free(f->print_name);
3163 free(f->name);
3164 free(f->from_name);
3165 free(f);
3168 void free_diffstat_info(struct diffstat_t *diffstat)
3170 int i;
3171 for (i = 0; i < diffstat->nr; i++)
3172 free_diffstat_file(diffstat->files[i]);
3173 free(diffstat->files);
3176 struct checkdiff_t {
3177 const char *filename;
3178 int lineno;
3179 int conflict_marker_size;
3180 struct diff_options *o;
3181 unsigned ws_rule;
3182 unsigned status;
3185 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3187 char firstchar;
3188 int cnt;
3190 if (len < marker_size + 1)
3191 return 0;
3192 firstchar = line[0];
3193 switch (firstchar) {
3194 case '=': case '>': case '<': case '|':
3195 break;
3196 default:
3197 return 0;
3199 for (cnt = 1; cnt < marker_size; cnt++)
3200 if (line[cnt] != firstchar)
3201 return 0;
3202 /* line[1] through line[marker_size-1] are same as firstchar */
3203 if (len < marker_size + 1 || !isspace(line[marker_size]))
3204 return 0;
3205 return 1;
3208 static void checkdiff_consume_hunk(void *priv,
3209 long ob UNUSED, long on UNUSED,
3210 long nb, long nn UNUSED,
3211 const char *func UNUSED, long funclen UNUSED)
3214 struct checkdiff_t *data = priv;
3215 data->lineno = nb - 1;
3218 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3220 struct checkdiff_t *data = priv;
3221 int marker_size = data->conflict_marker_size;
3222 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3223 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3224 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3225 char *err;
3226 const char *line_prefix;
3228 assert(data->o);
3229 line_prefix = diff_line_prefix(data->o);
3231 if (line[0] == '+') {
3232 unsigned bad;
3233 data->lineno++;
3234 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3235 data->status |= 1;
3236 fprintf(data->o->file,
3237 "%s%s:%d: leftover conflict marker\n",
3238 line_prefix, data->filename, data->lineno);
3240 bad = ws_check(line + 1, len - 1, data->ws_rule);
3241 if (!bad)
3242 return 0;
3243 data->status |= bad;
3244 err = whitespace_error_string(bad);
3245 fprintf(data->o->file, "%s%s:%d: %s.\n",
3246 line_prefix, data->filename, data->lineno, err);
3247 free(err);
3248 emit_line(data->o, set, reset, line, 1);
3249 ws_check_emit(line + 1, len - 1, data->ws_rule,
3250 data->o->file, set, reset, ws);
3251 } else if (line[0] == ' ') {
3252 data->lineno++;
3254 return 0;
3257 static unsigned char *deflate_it(char *data,
3258 unsigned long size,
3259 unsigned long *result_size)
3261 int bound;
3262 unsigned char *deflated;
3263 git_zstream stream;
3265 git_deflate_init(&stream, zlib_compression_level);
3266 bound = git_deflate_bound(&stream, size);
3267 deflated = xmalloc(bound);
3268 stream.next_out = deflated;
3269 stream.avail_out = bound;
3271 stream.next_in = (unsigned char *)data;
3272 stream.avail_in = size;
3273 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3274 ; /* nothing */
3275 git_deflate_end(&stream);
3276 *result_size = stream.total_out;
3277 return deflated;
3280 static void emit_binary_diff_body(struct diff_options *o,
3281 mmfile_t *one, mmfile_t *two)
3283 void *cp;
3284 void *delta;
3285 void *deflated;
3286 void *data;
3287 unsigned long orig_size;
3288 unsigned long delta_size;
3289 unsigned long deflate_size;
3290 unsigned long data_size;
3292 /* We could do deflated delta, or we could do just deflated two,
3293 * whichever is smaller.
3295 delta = NULL;
3296 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3297 if (one->size && two->size) {
3298 delta = diff_delta(one->ptr, one->size,
3299 two->ptr, two->size,
3300 &delta_size, deflate_size);
3301 if (delta) {
3302 void *to_free = delta;
3303 orig_size = delta_size;
3304 delta = deflate_it(delta, delta_size, &delta_size);
3305 free(to_free);
3309 if (delta && delta_size < deflate_size) {
3310 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3311 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3312 s, strlen(s), 0);
3313 free(s);
3314 free(deflated);
3315 data = delta;
3316 data_size = delta_size;
3317 } else {
3318 char *s = xstrfmt("%lu", two->size);
3319 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3320 s, strlen(s), 0);
3321 free(s);
3322 free(delta);
3323 data = deflated;
3324 data_size = deflate_size;
3327 /* emit data encoded in base85 */
3328 cp = data;
3329 while (data_size) {
3330 int len;
3331 int bytes = (52 < data_size) ? 52 : data_size;
3332 char line[71];
3333 data_size -= bytes;
3334 if (bytes <= 26)
3335 line[0] = bytes + 'A' - 1;
3336 else
3337 line[0] = bytes - 26 + 'a' - 1;
3338 encode_85(line + 1, cp, bytes);
3339 cp = (char *) cp + bytes;
3341 len = strlen(line);
3342 line[len++] = '\n';
3343 line[len] = '\0';
3345 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3346 line, len, 0);
3348 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3349 free(data);
3352 static void emit_binary_diff(struct diff_options *o,
3353 mmfile_t *one, mmfile_t *two)
3355 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3356 emit_binary_diff_body(o, one, two);
3357 emit_binary_diff_body(o, two, one);
3360 int diff_filespec_is_binary(struct repository *r,
3361 struct diff_filespec *one)
3363 struct diff_populate_filespec_options dpf_options = {
3364 .check_binary = 1,
3367 if (one->is_binary == -1) {
3368 diff_filespec_load_driver(one, r->index);
3369 if (one->driver->binary != -1)
3370 one->is_binary = one->driver->binary;
3371 else {
3372 if (!one->data && DIFF_FILE_VALID(one))
3373 diff_populate_filespec(r, one, &dpf_options);
3374 if (one->is_binary == -1 && one->data)
3375 one->is_binary = buffer_is_binary(one->data,
3376 one->size);
3377 if (one->is_binary == -1)
3378 one->is_binary = 0;
3381 return one->is_binary;
3384 static const struct userdiff_funcname *
3385 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3387 diff_filespec_load_driver(one, o->repo->index);
3388 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3391 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3393 if (!options->a_prefix)
3394 options->a_prefix = a;
3395 if (!options->b_prefix)
3396 options->b_prefix = b;
3399 void diff_set_noprefix(struct diff_options *options)
3401 options->a_prefix = options->b_prefix = "";
3404 void diff_set_default_prefix(struct diff_options *options)
3406 options->a_prefix = "a/";
3407 options->b_prefix = "b/";
3410 struct userdiff_driver *get_textconv(struct repository *r,
3411 struct diff_filespec *one)
3413 if (!DIFF_FILE_VALID(one))
3414 return NULL;
3416 diff_filespec_load_driver(one, r->index);
3417 return userdiff_get_textconv(r, one->driver);
3420 static struct string_list *additional_headers(struct diff_options *o,
3421 const char *path)
3423 if (!o->additional_path_headers)
3424 return NULL;
3425 return strmap_get(o->additional_path_headers, path);
3428 static void add_formatted_header(struct strbuf *msg,
3429 const char *header,
3430 const char *line_prefix,
3431 const char *meta,
3432 const char *reset)
3434 const char *next, *newline;
3436 for (next = header; *next; next = newline) {
3437 newline = strchrnul(next, '\n');
3438 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3439 (int)(newline - next), next, reset);
3440 if (*newline)
3441 newline++;
3445 static void add_formatted_headers(struct strbuf *msg,
3446 struct string_list *more_headers,
3447 const char *line_prefix,
3448 const char *meta,
3449 const char *reset)
3451 int i;
3453 for (i = 0; i < more_headers->nr; i++)
3454 add_formatted_header(msg, more_headers->items[i].string,
3455 line_prefix, meta, reset);
3458 static int diff_filepair_is_phoney(struct diff_filespec *one,
3459 struct diff_filespec *two)
3462 * This function specifically looks for pairs injected by
3463 * create_filepairs_for_header_only_notifications(). Such
3464 * pairs are "phoney" in that they do not represent any
3465 * content or even mode difference, but were inserted because
3466 * diff_queued_diff previously had no pair associated with
3467 * that path but we needed some pair to avoid losing the
3468 * "remerge CONFLICT" header associated with the path.
3470 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3473 static int set_diff_algorithm(struct diff_options *opts,
3474 const char *alg)
3476 long value = parse_algorithm_value(alg);
3478 if (value < 0)
3479 return -1;
3481 /* clear out previous settings */
3482 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3483 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3484 opts->xdl_opts |= value;
3486 return 0;
3489 static void builtin_diff(const char *name_a,
3490 const char *name_b,
3491 struct diff_filespec *one,
3492 struct diff_filespec *two,
3493 const char *xfrm_msg,
3494 int must_show_header,
3495 struct diff_options *o,
3496 int complete_rewrite)
3498 mmfile_t mf1, mf2;
3499 const char *lbl[2];
3500 char *a_one, *b_two;
3501 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3502 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3503 const char *a_prefix, *b_prefix;
3504 struct userdiff_driver *textconv_one = NULL;
3505 struct userdiff_driver *textconv_two = NULL;
3506 struct strbuf header = STRBUF_INIT;
3507 const char *line_prefix = diff_line_prefix(o);
3509 diff_set_mnemonic_prefix(o, "a/", "b/");
3510 if (o->flags.reverse_diff) {
3511 a_prefix = o->b_prefix;
3512 b_prefix = o->a_prefix;
3513 } else {
3514 a_prefix = o->a_prefix;
3515 b_prefix = o->b_prefix;
3518 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3519 (!one->mode || S_ISGITLINK(one->mode)) &&
3520 (!two->mode || S_ISGITLINK(two->mode)) &&
3521 (!diff_filepair_is_phoney(one, two))) {
3522 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3523 &one->oid, &two->oid,
3524 two->dirty_submodule);
3525 return;
3526 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3527 (!one->mode || S_ISGITLINK(one->mode)) &&
3528 (!two->mode || S_ISGITLINK(two->mode)) &&
3529 (!diff_filepair_is_phoney(one, two))) {
3530 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3531 &one->oid, &two->oid,
3532 two->dirty_submodule);
3533 return;
3536 if (o->flags.allow_textconv) {
3537 textconv_one = get_textconv(o->repo, one);
3538 textconv_two = get_textconv(o->repo, two);
3541 /* Never use a non-valid filename anywhere if at all possible */
3542 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3543 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3545 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3546 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3547 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3548 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3549 if (diff_filepair_is_phoney(one, two)) {
3551 * We should only reach this point for pairs generated from
3552 * create_filepairs_for_header_only_notifications(). For
3553 * these, we want to avoid the "/dev/null" special casing
3554 * above, because we do not want such pairs shown as either
3555 * "new file" or "deleted file" below.
3557 lbl[0] = a_one;
3558 lbl[1] = b_two;
3560 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3561 if (lbl[0][0] == '/') {
3562 /* /dev/null */
3563 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3564 if (xfrm_msg)
3565 strbuf_addstr(&header, xfrm_msg);
3566 o->found_changes = 1;
3567 must_show_header = 1;
3569 else if (lbl[1][0] == '/') {
3570 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3571 if (xfrm_msg)
3572 strbuf_addstr(&header, xfrm_msg);
3573 o->found_changes = 1;
3574 must_show_header = 1;
3576 else {
3577 if (one->mode != two->mode) {
3578 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3579 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3580 o->found_changes = 1;
3581 must_show_header = 1;
3583 if (xfrm_msg)
3584 strbuf_addstr(&header, xfrm_msg);
3587 * we do not run diff between different kind
3588 * of objects.
3590 if ((one->mode ^ two->mode) & S_IFMT)
3591 goto free_ab_and_return;
3592 if (complete_rewrite &&
3593 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3594 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3595 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3596 header.buf, header.len, 0);
3597 strbuf_reset(&header);
3598 emit_rewrite_diff(name_a, name_b, one, two,
3599 textconv_one, textconv_two, o);
3600 o->found_changes = 1;
3601 goto free_ab_and_return;
3605 if (o->irreversible_delete && lbl[1][0] == '/') {
3606 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3607 header.len, 0);
3608 strbuf_reset(&header);
3609 goto free_ab_and_return;
3610 } else if (!o->flags.text &&
3611 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3612 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3613 struct strbuf sb = STRBUF_INIT;
3614 if (!one->data && !two->data &&
3615 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3616 !o->flags.binary) {
3617 if (oideq(&one->oid, &two->oid)) {
3618 if (must_show_header)
3619 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3620 header.buf, header.len,
3622 goto free_ab_and_return;
3624 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3625 header.buf, header.len, 0);
3626 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3627 diff_line_prefix(o), lbl[0], lbl[1]);
3628 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3629 sb.buf, sb.len, 0);
3630 strbuf_release(&sb);
3631 goto free_ab_and_return;
3633 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3634 fill_mmfile(o->repo, &mf2, two) < 0)
3635 die("unable to read files to diff");
3636 /* Quite common confusing case */
3637 if (mf1.size == mf2.size &&
3638 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3639 if (must_show_header)
3640 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3641 header.buf, header.len, 0);
3642 goto free_ab_and_return;
3644 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3645 strbuf_reset(&header);
3646 if (o->flags.binary)
3647 emit_binary_diff(o, &mf1, &mf2);
3648 else {
3649 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3650 diff_line_prefix(o), lbl[0], lbl[1]);
3651 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3652 sb.buf, sb.len, 0);
3653 strbuf_release(&sb);
3655 o->found_changes = 1;
3656 } else {
3657 /* Crazy xdl interfaces.. */
3658 const char *diffopts;
3659 const char *v;
3660 xpparam_t xpp;
3661 xdemitconf_t xecfg;
3662 struct emit_callback ecbdata;
3663 const struct userdiff_funcname *pe;
3665 if (must_show_header) {
3666 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3667 header.buf, header.len, 0);
3668 strbuf_reset(&header);
3671 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3672 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3674 pe = diff_funcname_pattern(o, one);
3675 if (!pe)
3676 pe = diff_funcname_pattern(o, two);
3678 memset(&xpp, 0, sizeof(xpp));
3679 memset(&xecfg, 0, sizeof(xecfg));
3680 memset(&ecbdata, 0, sizeof(ecbdata));
3681 if (o->flags.suppress_diff_headers)
3682 lbl[0] = NULL;
3683 ecbdata.label_path = lbl;
3684 ecbdata.color_diff = want_color(o->use_color);
3685 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3686 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3687 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3688 ecbdata.opt = o;
3689 if (header.len && !o->flags.suppress_diff_headers)
3690 ecbdata.header = &header;
3691 xpp.flags = o->xdl_opts;
3692 xpp.ignore_regex = o->ignore_regex;
3693 xpp.ignore_regex_nr = o->ignore_regex_nr;
3694 xpp.anchors = o->anchors;
3695 xpp.anchors_nr = o->anchors_nr;
3696 xecfg.ctxlen = o->context;
3697 xecfg.interhunkctxlen = o->interhunkcontext;
3698 xecfg.flags = XDL_EMIT_FUNCNAMES;
3699 if (o->flags.funccontext)
3700 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3701 if (pe)
3702 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3704 diffopts = getenv("GIT_DIFF_OPTS");
3705 if (!diffopts)
3707 else if (skip_prefix(diffopts, "--unified=", &v))
3708 xecfg.ctxlen = strtoul(v, NULL, 10);
3709 else if (skip_prefix(diffopts, "-u", &v))
3710 xecfg.ctxlen = strtoul(v, NULL, 10);
3712 if (o->word_diff)
3713 init_diff_words_data(&ecbdata, o, one, two);
3714 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3715 &ecbdata, &xpp, &xecfg))
3716 die("unable to generate diff for %s", one->path);
3717 if (o->word_diff)
3718 free_diff_words_data(&ecbdata);
3719 if (textconv_one)
3720 free(mf1.ptr);
3721 if (textconv_two)
3722 free(mf2.ptr);
3723 xdiff_clear_find_func(&xecfg);
3726 free_ab_and_return:
3727 strbuf_release(&header);
3728 diff_free_filespec_data(one);
3729 diff_free_filespec_data(two);
3730 free(a_one);
3731 free(b_two);
3732 return;
3735 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3737 if (!is_renamed) {
3738 if (p->status == DIFF_STATUS_ADDED) {
3739 if (S_ISLNK(p->two->mode))
3740 return "new +l";
3741 else if ((p->two->mode & 0777) == 0755)
3742 return "new +x";
3743 else
3744 return "new";
3745 } else if (p->status == DIFF_STATUS_DELETED)
3746 return "gone";
3748 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3749 return "mode -l";
3750 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3751 return "mode +l";
3752 else if ((p->one->mode & 0777) == 0644 &&
3753 (p->two->mode & 0777) == 0755)
3754 return "mode +x";
3755 else if ((p->one->mode & 0777) == 0755 &&
3756 (p->two->mode & 0777) == 0644)
3757 return "mode -x";
3758 return NULL;
3761 static void builtin_diffstat(const char *name_a, const char *name_b,
3762 struct diff_filespec *one,
3763 struct diff_filespec *two,
3764 struct diffstat_t *diffstat,
3765 struct diff_options *o,
3766 struct diff_filepair *p)
3768 mmfile_t mf1, mf2;
3769 struct diffstat_file *data;
3770 int may_differ;
3771 int complete_rewrite = 0;
3773 if (!DIFF_PAIR_UNMERGED(p)) {
3774 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3775 complete_rewrite = 1;
3778 data = diffstat_add(diffstat, name_a, name_b);
3779 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3780 if (o->flags.stat_with_summary)
3781 data->comments = get_compact_summary(p, data->is_renamed);
3783 if (!one || !two) {
3784 data->is_unmerged = 1;
3785 return;
3788 /* saves some reads if true, not a guarantee of diff outcome */
3789 may_differ = !(one->oid_valid && two->oid_valid &&
3790 oideq(&one->oid, &two->oid));
3792 if (diff_filespec_is_binary(o->repo, one) ||
3793 diff_filespec_is_binary(o->repo, two)) {
3794 data->is_binary = 1;
3795 if (!may_differ) {
3796 data->added = 0;
3797 data->deleted = 0;
3798 } else {
3799 data->added = diff_filespec_size(o->repo, two);
3800 data->deleted = diff_filespec_size(o->repo, one);
3804 else if (complete_rewrite) {
3805 diff_populate_filespec(o->repo, one, NULL);
3806 diff_populate_filespec(o->repo, two, NULL);
3807 data->deleted = count_lines(one->data, one->size);
3808 data->added = count_lines(two->data, two->size);
3811 else if (may_differ) {
3812 /* Crazy xdl interfaces.. */
3813 xpparam_t xpp;
3814 xdemitconf_t xecfg;
3816 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3817 fill_mmfile(o->repo, &mf2, two) < 0)
3818 die("unable to read files to diff");
3820 memset(&xpp, 0, sizeof(xpp));
3821 memset(&xecfg, 0, sizeof(xecfg));
3822 xpp.flags = o->xdl_opts;
3823 xpp.ignore_regex = o->ignore_regex;
3824 xpp.ignore_regex_nr = o->ignore_regex_nr;
3825 xpp.anchors = o->anchors;
3826 xpp.anchors_nr = o->anchors_nr;
3827 xecfg.ctxlen = o->context;
3828 xecfg.interhunkctxlen = o->interhunkcontext;
3829 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3830 if (xdi_diff_outf(&mf1, &mf2, NULL,
3831 diffstat_consume, diffstat, &xpp, &xecfg))
3832 die("unable to generate diffstat for %s", one->path);
3834 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3835 struct diffstat_file *file =
3836 diffstat->files[diffstat->nr - 1];
3838 * Omit diffstats of modified files where nothing changed.
3839 * Even if may_differ, this might be the case due to
3840 * ignoring whitespace changes, etc.
3842 * But note that we special-case additions, deletions,
3843 * renames, and mode changes as adding an empty file,
3844 * for example is still of interest.
3846 if ((p->status == DIFF_STATUS_MODIFIED)
3847 && !file->added
3848 && !file->deleted
3849 && one->mode == two->mode) {
3850 free_diffstat_file(file);
3851 diffstat->nr--;
3856 diff_free_filespec_data(one);
3857 diff_free_filespec_data(two);
3860 static void builtin_checkdiff(const char *name_a, const char *name_b,
3861 const char *attr_path,
3862 struct diff_filespec *one,
3863 struct diff_filespec *two,
3864 struct diff_options *o)
3866 mmfile_t mf1, mf2;
3867 struct checkdiff_t data;
3869 if (!two)
3870 return;
3872 memset(&data, 0, sizeof(data));
3873 data.filename = name_b ? name_b : name_a;
3874 data.lineno = 0;
3875 data.o = o;
3876 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3877 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3879 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3880 fill_mmfile(o->repo, &mf2, two) < 0)
3881 die("unable to read files to diff");
3884 * All the other codepaths check both sides, but not checking
3885 * the "old" side here is deliberate. We are checking the newly
3886 * introduced changes, and as long as the "new" side is text, we
3887 * can and should check what it introduces.
3889 if (diff_filespec_is_binary(o->repo, two))
3890 goto free_and_return;
3891 else {
3892 /* Crazy xdl interfaces.. */
3893 xpparam_t xpp;
3894 xdemitconf_t xecfg;
3896 memset(&xpp, 0, sizeof(xpp));
3897 memset(&xecfg, 0, sizeof(xecfg));
3898 xecfg.ctxlen = 1; /* at least one context line */
3899 xpp.flags = 0;
3900 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3901 checkdiff_consume, &data,
3902 &xpp, &xecfg))
3903 die("unable to generate checkdiff for %s", one->path);
3905 if (data.ws_rule & WS_BLANK_AT_EOF) {
3906 struct emit_callback ecbdata;
3907 int blank_at_eof;
3909 ecbdata.ws_rule = data.ws_rule;
3910 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3911 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3913 if (blank_at_eof) {
3914 static char *err;
3915 if (!err)
3916 err = whitespace_error_string(WS_BLANK_AT_EOF);
3917 fprintf(o->file, "%s:%d: %s.\n",
3918 data.filename, blank_at_eof, err);
3919 data.status = 1; /* report errors */
3923 free_and_return:
3924 diff_free_filespec_data(one);
3925 diff_free_filespec_data(two);
3926 if (data.status)
3927 o->flags.check_failed = 1;
3930 struct diff_filespec *alloc_filespec(const char *path)
3932 struct diff_filespec *spec;
3934 FLEXPTR_ALLOC_STR(spec, path, path);
3935 spec->count = 1;
3936 spec->is_binary = -1;
3937 return spec;
3940 void free_filespec(struct diff_filespec *spec)
3942 if (!--spec->count) {
3943 diff_free_filespec_data(spec);
3944 free(spec);
3948 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3949 int oid_valid, unsigned short mode)
3951 if (mode) {
3952 spec->mode = canon_mode(mode);
3953 oidcpy(&spec->oid, oid);
3954 spec->oid_valid = oid_valid;
3959 * Given a name and sha1 pair, if the index tells us the file in
3960 * the work tree has that object contents, return true, so that
3961 * prepare_temp_file() does not have to inflate and extract.
3963 static int reuse_worktree_file(struct index_state *istate,
3964 const char *name,
3965 const struct object_id *oid,
3966 int want_file)
3968 const struct cache_entry *ce;
3969 struct stat st;
3970 int pos, len;
3973 * We do not read the cache ourselves here, because the
3974 * benchmark with my previous version that always reads cache
3975 * shows that it makes things worse for diff-tree comparing
3976 * two linux-2.6 kernel trees in an already checked out work
3977 * tree. This is because most diff-tree comparisons deal with
3978 * only a small number of files, while reading the cache is
3979 * expensive for a large project, and its cost outweighs the
3980 * savings we get by not inflating the object to a temporary
3981 * file. Practically, this code only helps when we are used
3982 * by diff-cache --cached, which does read the cache before
3983 * calling us.
3985 if (!istate->cache)
3986 return 0;
3988 /* We want to avoid the working directory if our caller
3989 * doesn't need the data in a normal file, this system
3990 * is rather slow with its stat/open/mmap/close syscalls,
3991 * and the object is contained in a pack file. The pack
3992 * is probably already open and will be faster to obtain
3993 * the data through than the working directory. Loose
3994 * objects however would tend to be slower as they need
3995 * to be individually opened and inflated.
3997 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3998 return 0;
4001 * Similarly, if we'd have to convert the file contents anyway, that
4002 * makes the optimization not worthwhile.
4004 if (!want_file && would_convert_to_git(istate, name))
4005 return 0;
4008 * If this path does not match our sparse-checkout definition,
4009 * then the file will not be in the working directory.
4011 if (!path_in_sparse_checkout(name, istate))
4012 return 0;
4014 len = strlen(name);
4015 pos = index_name_pos(istate, name, len);
4016 if (pos < 0)
4017 return 0;
4018 ce = istate->cache[pos];
4021 * This is not the sha1 we are looking for, or
4022 * unreusable because it is not a regular file.
4024 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4025 return 0;
4028 * If ce is marked as "assume unchanged", there is no
4029 * guarantee that work tree matches what we are looking for.
4031 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4032 return 0;
4035 * If ce matches the file in the work tree, we can reuse it.
4037 if (ce_uptodate(ce) ||
4038 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4039 return 1;
4041 return 0;
4044 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4046 struct strbuf buf = STRBUF_INIT;
4047 char *dirty = "";
4049 /* Are we looking at the work tree? */
4050 if (s->dirty_submodule)
4051 dirty = "-dirty";
4053 strbuf_addf(&buf, "Subproject commit %s%s\n",
4054 oid_to_hex(&s->oid), dirty);
4055 s->size = buf.len;
4056 if (size_only) {
4057 s->data = NULL;
4058 strbuf_release(&buf);
4059 } else {
4060 s->data = strbuf_detach(&buf, NULL);
4061 s->should_free = 1;
4063 return 0;
4067 * While doing rename detection and pickaxe operation, we may need to
4068 * grab the data for the blob (or file) for our own in-core comparison.
4069 * diff_filespec has data and size fields for this purpose.
4071 int diff_populate_filespec(struct repository *r,
4072 struct diff_filespec *s,
4073 const struct diff_populate_filespec_options *options)
4075 int size_only = options ? options->check_size_only : 0;
4076 int check_binary = options ? options->check_binary : 0;
4077 int err = 0;
4078 int conv_flags = global_conv_flags_eol;
4080 * demote FAIL to WARN to allow inspecting the situation
4081 * instead of refusing.
4083 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4084 conv_flags = CONV_EOL_RNDTRP_WARN;
4086 if (!DIFF_FILE_VALID(s))
4087 die("internal error: asking to populate invalid file.");
4088 if (S_ISDIR(s->mode))
4089 return -1;
4091 if (s->data)
4092 return 0;
4094 if (size_only && 0 < s->size)
4095 return 0;
4097 if (S_ISGITLINK(s->mode))
4098 return diff_populate_gitlink(s, size_only);
4100 if (!s->oid_valid ||
4101 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4102 struct strbuf buf = STRBUF_INIT;
4103 struct stat st;
4104 int fd;
4106 if (lstat(s->path, &st) < 0) {
4107 err_empty:
4108 err = -1;
4109 empty:
4110 s->data = (char *)"";
4111 s->size = 0;
4112 return err;
4114 s->size = xsize_t(st.st_size);
4115 if (!s->size)
4116 goto empty;
4117 if (S_ISLNK(st.st_mode)) {
4118 struct strbuf sb = STRBUF_INIT;
4120 if (strbuf_readlink(&sb, s->path, s->size))
4121 goto err_empty;
4122 s->size = sb.len;
4123 s->data = strbuf_detach(&sb, NULL);
4124 s->should_free = 1;
4125 return 0;
4129 * Even if the caller would be happy with getting
4130 * only the size, we cannot return early at this
4131 * point if the path requires us to run the content
4132 * conversion.
4134 if (size_only && !would_convert_to_git(r->index, s->path))
4135 return 0;
4138 * Note: this check uses xsize_t(st.st_size) that may
4139 * not be the true size of the blob after it goes
4140 * through convert_to_git(). This may not strictly be
4141 * correct, but the whole point of big_file_threshold
4142 * and is_binary check being that we want to avoid
4143 * opening the file and inspecting the contents, this
4144 * is probably fine.
4146 if (check_binary &&
4147 s->size > big_file_threshold && s->is_binary == -1) {
4148 s->is_binary = 1;
4149 return 0;
4151 fd = open(s->path, O_RDONLY);
4152 if (fd < 0)
4153 goto err_empty;
4154 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4155 close(fd);
4156 s->should_munmap = 1;
4159 * Convert from working tree format to canonical git format
4161 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4162 size_t size = 0;
4163 munmap(s->data, s->size);
4164 s->should_munmap = 0;
4165 s->data = strbuf_detach(&buf, &size);
4166 s->size = size;
4167 s->should_free = 1;
4170 else {
4171 struct object_info info = {
4172 .sizep = &s->size
4175 if (!(size_only || check_binary))
4177 * Set contentp, since there is no chance that merely
4178 * the size is sufficient.
4180 info.contentp = &s->data;
4182 if (options && options->missing_object_cb) {
4183 if (!oid_object_info_extended(r, &s->oid, &info,
4184 OBJECT_INFO_LOOKUP_REPLACE |
4185 OBJECT_INFO_SKIP_FETCH_OBJECT))
4186 goto object_read;
4187 options->missing_object_cb(options->missing_object_data);
4189 if (oid_object_info_extended(r, &s->oid, &info,
4190 OBJECT_INFO_LOOKUP_REPLACE))
4191 die("unable to read %s", oid_to_hex(&s->oid));
4193 object_read:
4194 if (size_only || check_binary) {
4195 if (size_only)
4196 return 0;
4197 if (s->size > big_file_threshold && s->is_binary == -1) {
4198 s->is_binary = 1;
4199 return 0;
4202 if (!info.contentp) {
4203 info.contentp = &s->data;
4204 if (oid_object_info_extended(r, &s->oid, &info,
4205 OBJECT_INFO_LOOKUP_REPLACE))
4206 die("unable to read %s", oid_to_hex(&s->oid));
4208 s->should_free = 1;
4210 return 0;
4213 void diff_free_filespec_blob(struct diff_filespec *s)
4215 if (s->should_free)
4216 free(s->data);
4217 else if (s->should_munmap)
4218 munmap(s->data, s->size);
4220 if (s->should_free || s->should_munmap) {
4221 s->should_free = s->should_munmap = 0;
4222 s->data = NULL;
4226 void diff_free_filespec_data(struct diff_filespec *s)
4228 if (!s)
4229 return;
4231 diff_free_filespec_blob(s);
4232 FREE_AND_NULL(s->cnt_data);
4235 static void prep_temp_blob(struct index_state *istate,
4236 const char *path, struct diff_tempfile *temp,
4237 void *blob,
4238 unsigned long size,
4239 const struct object_id *oid,
4240 int mode)
4242 struct strbuf buf = STRBUF_INIT;
4243 char *path_dup = xstrdup(path);
4244 const char *base = basename(path_dup);
4245 struct checkout_metadata meta;
4247 init_checkout_metadata(&meta, NULL, NULL, oid);
4249 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4250 if (!temp->tempfile)
4251 die_errno("unable to create temp-file");
4252 if (convert_to_working_tree(istate, path,
4253 (const char *)blob, (size_t)size, &buf, &meta)) {
4254 blob = buf.buf;
4255 size = buf.len;
4257 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4258 close_tempfile_gently(temp->tempfile))
4259 die_errno("unable to write temp-file");
4260 temp->name = get_tempfile_path(temp->tempfile);
4261 oid_to_hex_r(temp->hex, oid);
4262 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4263 strbuf_release(&buf);
4264 free(path_dup);
4267 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4268 struct diff_filespec *one)
4270 struct diff_tempfile *temp = claim_diff_tempfile();
4272 if (!DIFF_FILE_VALID(one)) {
4273 not_a_valid_file:
4274 /* A '-' entry produces this for file-2, and
4275 * a '+' entry produces this for file-1.
4277 temp->name = "/dev/null";
4278 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4279 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4280 return temp;
4283 if (!S_ISGITLINK(one->mode) &&
4284 (!one->oid_valid ||
4285 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4286 struct stat st;
4287 if (lstat(one->path, &st) < 0) {
4288 if (errno == ENOENT)
4289 goto not_a_valid_file;
4290 die_errno("stat(%s)", one->path);
4292 if (S_ISLNK(st.st_mode)) {
4293 struct strbuf sb = STRBUF_INIT;
4294 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4295 die_errno("readlink(%s)", one->path);
4296 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4297 (one->oid_valid ?
4298 &one->oid : null_oid()),
4299 (one->oid_valid ?
4300 one->mode : S_IFLNK));
4301 strbuf_release(&sb);
4303 else {
4304 /* we can borrow from the file in the work tree */
4305 temp->name = one->path;
4306 if (!one->oid_valid)
4307 oid_to_hex_r(temp->hex, null_oid());
4308 else
4309 oid_to_hex_r(temp->hex, &one->oid);
4310 /* Even though we may sometimes borrow the
4311 * contents from the work tree, we always want
4312 * one->mode. mode is trustworthy even when
4313 * !(one->oid_valid), as long as
4314 * DIFF_FILE_VALID(one).
4316 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4318 return temp;
4320 else {
4321 if (diff_populate_filespec(r, one, NULL))
4322 die("cannot read data blob for %s", one->path);
4323 prep_temp_blob(r->index, one->path, temp,
4324 one->data, one->size,
4325 &one->oid, one->mode);
4327 return temp;
4330 static void add_external_diff_name(struct repository *r,
4331 struct strvec *argv,
4332 struct diff_filespec *df)
4334 struct diff_tempfile *temp = prepare_temp_file(r, df);
4335 strvec_push(argv, temp->name);
4336 strvec_push(argv, temp->hex);
4337 strvec_push(argv, temp->mode);
4340 /* An external diff command takes:
4342 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4343 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4346 static void run_external_diff(const char *pgm,
4347 const char *name,
4348 const char *other,
4349 struct diff_filespec *one,
4350 struct diff_filespec *two,
4351 const char *xfrm_msg,
4352 struct diff_options *o)
4354 struct child_process cmd = CHILD_PROCESS_INIT;
4355 struct diff_queue_struct *q = &diff_queued_diff;
4357 strvec_push(&cmd.args, pgm);
4358 strvec_push(&cmd.args, name);
4360 if (one && two) {
4361 add_external_diff_name(o->repo, &cmd.args, one);
4362 add_external_diff_name(o->repo, &cmd.args, two);
4363 if (other) {
4364 strvec_push(&cmd.args, other);
4365 strvec_push(&cmd.args, xfrm_msg);
4369 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4370 ++o->diff_path_counter);
4371 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4373 diff_free_filespec_data(one);
4374 diff_free_filespec_data(two);
4375 cmd.use_shell = 1;
4376 if (run_command(&cmd))
4377 die(_("external diff died, stopping at %s"), name);
4379 remove_tempfile();
4382 static int similarity_index(struct diff_filepair *p)
4384 return p->score * 100 / MAX_SCORE;
4387 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4389 if (startup_info->have_repository)
4390 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4391 else {
4392 char *hex = oid_to_hex(oid);
4393 if (abbrev < 0)
4394 abbrev = FALLBACK_DEFAULT_ABBREV;
4395 if (abbrev > the_hash_algo->hexsz)
4396 BUG("oid abbreviation out of range: %d", abbrev);
4397 if (abbrev)
4398 hex[abbrev] = '\0';
4399 return hex;
4403 static void fill_metainfo(struct strbuf *msg,
4404 const char *name,
4405 const char *other,
4406 struct diff_filespec *one,
4407 struct diff_filespec *two,
4408 struct diff_options *o,
4409 struct diff_filepair *p,
4410 int *must_show_header,
4411 int use_color)
4413 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4414 const char *reset = diff_get_color(use_color, DIFF_RESET);
4415 const char *line_prefix = diff_line_prefix(o);
4416 struct string_list *more_headers = NULL;
4418 *must_show_header = 1;
4419 strbuf_init(msg, PATH_MAX * 2 + 300);
4420 switch (p->status) {
4421 case DIFF_STATUS_COPIED:
4422 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4423 line_prefix, set, similarity_index(p));
4424 strbuf_addf(msg, "%s\n%s%scopy from ",
4425 reset, line_prefix, set);
4426 quote_c_style(name, msg, NULL, 0);
4427 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4428 quote_c_style(other, msg, NULL, 0);
4429 strbuf_addf(msg, "%s\n", reset);
4430 break;
4431 case DIFF_STATUS_RENAMED:
4432 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4433 line_prefix, set, similarity_index(p));
4434 strbuf_addf(msg, "%s\n%s%srename from ",
4435 reset, line_prefix, set);
4436 quote_c_style(name, msg, NULL, 0);
4437 strbuf_addf(msg, "%s\n%s%srename to ",
4438 reset, line_prefix, set);
4439 quote_c_style(other, msg, NULL, 0);
4440 strbuf_addf(msg, "%s\n", reset);
4441 break;
4442 case DIFF_STATUS_MODIFIED:
4443 if (p->score) {
4444 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4445 line_prefix,
4446 set, similarity_index(p), reset);
4447 break;
4449 /* fallthru */
4450 default:
4451 *must_show_header = 0;
4453 if ((more_headers = additional_headers(o, name))) {
4454 add_formatted_headers(msg, more_headers,
4455 line_prefix, set, reset);
4456 *must_show_header = 1;
4458 if (one && two && !oideq(&one->oid, &two->oid)) {
4459 const unsigned hexsz = the_hash_algo->hexsz;
4460 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4462 if (o->flags.full_index)
4463 abbrev = hexsz;
4465 if (o->flags.binary) {
4466 mmfile_t mf;
4467 if ((!fill_mmfile(o->repo, &mf, one) &&
4468 diff_filespec_is_binary(o->repo, one)) ||
4469 (!fill_mmfile(o->repo, &mf, two) &&
4470 diff_filespec_is_binary(o->repo, two)))
4471 abbrev = hexsz;
4473 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4474 diff_abbrev_oid(&one->oid, abbrev),
4475 diff_abbrev_oid(&two->oid, abbrev));
4476 if (one->mode == two->mode)
4477 strbuf_addf(msg, " %06o", one->mode);
4478 strbuf_addf(msg, "%s\n", reset);
4482 static void run_diff_cmd(const char *pgm,
4483 const char *name,
4484 const char *other,
4485 const char *attr_path,
4486 struct diff_filespec *one,
4487 struct diff_filespec *two,
4488 struct strbuf *msg,
4489 struct diff_options *o,
4490 struct diff_filepair *p)
4492 const char *xfrm_msg = NULL;
4493 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4494 int must_show_header = 0;
4495 struct userdiff_driver *drv = NULL;
4497 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4498 drv = userdiff_find_by_path(o->repo->index, attr_path);
4500 if (o->flags.allow_external && drv && drv->external)
4501 pgm = drv->external;
4503 if (msg) {
4505 * don't use colors when the header is intended for an
4506 * external diff driver
4508 fill_metainfo(msg, name, other, one, two, o, p,
4509 &must_show_header,
4510 want_color(o->use_color) && !pgm);
4511 xfrm_msg = msg->len ? msg->buf : NULL;
4514 if (pgm) {
4515 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4516 return;
4518 if (one && two) {
4519 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4520 set_diff_algorithm(o, drv->algorithm);
4522 builtin_diff(name, other ? other : name,
4523 one, two, xfrm_msg, must_show_header,
4524 o, complete_rewrite);
4525 } else {
4526 fprintf(o->file, "* Unmerged path %s\n", name);
4530 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4532 if (DIFF_FILE_VALID(one)) {
4533 if (!one->oid_valid) {
4534 struct stat st;
4535 if (one->is_stdin) {
4536 oidclr(&one->oid);
4537 return;
4539 if (lstat(one->path, &st) < 0)
4540 die_errno("stat '%s'", one->path);
4541 if (index_path(istate, &one->oid, one->path, &st, 0))
4542 die("cannot hash %s", one->path);
4545 else
4546 oidclr(&one->oid);
4549 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4551 /* Strip the prefix but do not molest /dev/null and absolute paths */
4552 if (*namep && !is_absolute_path(*namep)) {
4553 *namep += prefix_length;
4554 if (**namep == '/')
4555 ++*namep;
4557 if (*otherp && !is_absolute_path(*otherp)) {
4558 *otherp += prefix_length;
4559 if (**otherp == '/')
4560 ++*otherp;
4564 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4566 const char *pgm = external_diff();
4567 struct strbuf msg;
4568 struct diff_filespec *one = p->one;
4569 struct diff_filespec *two = p->two;
4570 const char *name;
4571 const char *other;
4572 const char *attr_path;
4574 name = one->path;
4575 other = (strcmp(name, two->path) ? two->path : NULL);
4576 attr_path = name;
4577 if (o->prefix_length)
4578 strip_prefix(o->prefix_length, &name, &other);
4580 if (!o->flags.allow_external)
4581 pgm = NULL;
4583 if (DIFF_PAIR_UNMERGED(p)) {
4584 run_diff_cmd(pgm, name, NULL, attr_path,
4585 NULL, NULL, NULL, o, p);
4586 return;
4589 diff_fill_oid_info(one, o->repo->index);
4590 diff_fill_oid_info(two, o->repo->index);
4592 if (!pgm &&
4593 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4594 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4596 * a filepair that changes between file and symlink
4597 * needs to be split into deletion and creation.
4599 struct diff_filespec *null = alloc_filespec(two->path);
4600 run_diff_cmd(NULL, name, other, attr_path,
4601 one, null, &msg,
4602 o, p);
4603 free(null);
4604 strbuf_release(&msg);
4606 null = alloc_filespec(one->path);
4607 run_diff_cmd(NULL, name, other, attr_path,
4608 null, two, &msg, o, p);
4609 free(null);
4611 else
4612 run_diff_cmd(pgm, name, other, attr_path,
4613 one, two, &msg, o, p);
4615 strbuf_release(&msg);
4618 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4619 struct diffstat_t *diffstat)
4621 const char *name;
4622 const char *other;
4624 if (!o->ignore_driver_algorithm) {
4625 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4626 p->one->path);
4628 if (drv && drv->algorithm)
4629 set_diff_algorithm(o, drv->algorithm);
4632 if (DIFF_PAIR_UNMERGED(p)) {
4633 /* unmerged */
4634 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4635 diffstat, o, p);
4636 return;
4639 name = p->one->path;
4640 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
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_diffstat(name, other, p->one, p->two,
4649 diffstat, o, p);
4652 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4654 const char *name;
4655 const char *other;
4656 const char *attr_path;
4658 if (DIFF_PAIR_UNMERGED(p)) {
4659 /* unmerged */
4660 return;
4663 name = p->one->path;
4664 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4665 attr_path = other ? other : name;
4667 if (o->prefix_length)
4668 strip_prefix(o->prefix_length, &name, &other);
4670 diff_fill_oid_info(p->one, o->repo->index);
4671 diff_fill_oid_info(p->two, o->repo->index);
4673 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4676 void repo_diff_setup(struct repository *r, struct diff_options *options)
4678 memcpy(options, &default_diff_options, sizeof(*options));
4680 options->file = stdout;
4681 options->repo = r;
4683 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4684 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4685 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4686 options->abbrev = DEFAULT_ABBREV;
4687 options->line_termination = '\n';
4688 options->break_opt = -1;
4689 options->rename_limit = -1;
4690 options->dirstat_permille = diff_dirstat_permille_default;
4691 options->context = diff_context_default;
4692 options->interhunkcontext = diff_interhunk_context_default;
4693 options->ws_error_highlight = ws_error_highlight_default;
4694 options->flags.rename_empty = 1;
4695 options->flags.relative_name = diff_relative;
4696 options->objfind = NULL;
4698 /* pathchange left =NULL by default */
4699 options->change = diff_change;
4700 options->add_remove = diff_addremove;
4701 options->use_color = diff_use_color_default;
4702 options->detect_rename = diff_detect_rename_default;
4703 options->xdl_opts |= diff_algorithm;
4704 if (diff_indent_heuristic)
4705 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4707 options->orderfile = diff_order_file_cfg;
4709 if (!options->flags.ignore_submodule_set)
4710 options->flags.ignore_untracked_in_submodules = 1;
4712 if (diff_no_prefix) {
4713 diff_set_noprefix(options);
4714 } else if (!diff_mnemonic_prefix) {
4715 diff_set_default_prefix(options);
4718 options->color_moved = diff_color_moved_default;
4719 options->color_moved_ws_handling = diff_color_moved_ws_default;
4722 static const char diff_status_letters[] = {
4723 DIFF_STATUS_ADDED,
4724 DIFF_STATUS_COPIED,
4725 DIFF_STATUS_DELETED,
4726 DIFF_STATUS_MODIFIED,
4727 DIFF_STATUS_RENAMED,
4728 DIFF_STATUS_TYPE_CHANGED,
4729 DIFF_STATUS_UNKNOWN,
4730 DIFF_STATUS_UNMERGED,
4731 DIFF_STATUS_FILTER_AON,
4732 DIFF_STATUS_FILTER_BROKEN,
4733 '\0',
4736 static unsigned int filter_bit['Z' + 1];
4738 static void prepare_filter_bits(void)
4740 int i;
4742 if (!filter_bit[DIFF_STATUS_ADDED]) {
4743 for (i = 0; diff_status_letters[i]; i++)
4744 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4748 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4750 return opt->filter & filter_bit[(int) status];
4753 unsigned diff_filter_bit(char status)
4755 prepare_filter_bits();
4756 return filter_bit[(int) status];
4759 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4761 unsigned forbidden_magic;
4763 if (ps->nr != 1) {
4764 if (die_on_error)
4765 die(_("--follow requires exactly one pathspec"));
4766 return 0;
4769 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4770 PATHSPEC_LITERAL);
4771 if (forbidden_magic) {
4772 if (die_on_error) {
4773 struct strbuf sb = STRBUF_INIT;
4774 pathspec_magic_names(forbidden_magic, &sb);
4775 die(_("pathspec magic not supported by --follow: %s"),
4776 sb.buf);
4778 return 0;
4781 return 1;
4784 void diff_setup_done(struct diff_options *options)
4786 unsigned check_mask = DIFF_FORMAT_NAME |
4787 DIFF_FORMAT_NAME_STATUS |
4788 DIFF_FORMAT_CHECKDIFF |
4789 DIFF_FORMAT_NO_OUTPUT;
4791 * This must be signed because we're comparing against a potentially
4792 * negative value.
4794 const int hexsz = the_hash_algo->hexsz;
4796 if (options->set_default)
4797 options->set_default(options);
4799 if (HAS_MULTI_BITS(options->output_format & check_mask))
4800 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4801 "--name-only", "--name-status", "--check", "-s");
4803 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4804 die(_("options '%s', '%s', and '%s' cannot be used together"),
4805 "-G", "-S", "--find-object");
4807 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4808 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4809 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4811 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4812 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4813 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4816 * Most of the time we can say "there are changes"
4817 * only by checking if there are changed paths, but
4818 * --ignore-whitespace* options force us to look
4819 * inside contents.
4822 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4823 options->ignore_regex_nr)
4824 options->flags.diff_from_contents = 1;
4825 else
4826 options->flags.diff_from_contents = 0;
4828 if (options->flags.find_copies_harder)
4829 options->detect_rename = DIFF_DETECT_COPY;
4831 if (!options->flags.relative_name)
4832 options->prefix = NULL;
4833 if (options->prefix)
4834 options->prefix_length = strlen(options->prefix);
4835 else
4836 options->prefix_length = 0;
4839 * --name-only, --name-status, --checkdiff, and -s
4840 * turn other output format off.
4842 if (options->output_format & (DIFF_FORMAT_NAME |
4843 DIFF_FORMAT_NAME_STATUS |
4844 DIFF_FORMAT_CHECKDIFF |
4845 DIFF_FORMAT_NO_OUTPUT))
4846 options->output_format &= ~(DIFF_FORMAT_RAW |
4847 DIFF_FORMAT_NUMSTAT |
4848 DIFF_FORMAT_DIFFSTAT |
4849 DIFF_FORMAT_SHORTSTAT |
4850 DIFF_FORMAT_DIRSTAT |
4851 DIFF_FORMAT_SUMMARY |
4852 DIFF_FORMAT_PATCH);
4855 * These cases always need recursive; we do not drop caller-supplied
4856 * recursive bits for other formats here.
4858 if (options->output_format & (DIFF_FORMAT_PATCH |
4859 DIFF_FORMAT_NUMSTAT |
4860 DIFF_FORMAT_DIFFSTAT |
4861 DIFF_FORMAT_SHORTSTAT |
4862 DIFF_FORMAT_DIRSTAT |
4863 DIFF_FORMAT_SUMMARY |
4864 DIFF_FORMAT_CHECKDIFF))
4865 options->flags.recursive = 1;
4867 * Also pickaxe would not work very well if you do not say recursive
4869 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4870 options->flags.recursive = 1;
4872 * When patches are generated, submodules diffed against the work tree
4873 * must be checked for dirtiness too so it can be shown in the output
4875 if (options->output_format & DIFF_FORMAT_PATCH)
4876 options->flags.dirty_submodules = 1;
4878 if (options->detect_rename && options->rename_limit < 0)
4879 options->rename_limit = diff_rename_limit_default;
4880 if (hexsz < options->abbrev)
4881 options->abbrev = hexsz; /* full */
4884 * It does not make sense to show the first hit we happened
4885 * to have found. It does not make sense not to return with
4886 * exit code in such a case either.
4888 if (options->flags.quick) {
4889 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4890 options->flags.exit_with_status = 1;
4893 options->diff_path_counter = 0;
4895 if (options->flags.follow_renames)
4896 diff_check_follow_pathspec(&options->pathspec, 1);
4898 if (!options->use_color || external_diff())
4899 options->color_moved = 0;
4901 if (options->filter_not) {
4902 if (!options->filter)
4903 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4904 options->filter &= ~options->filter_not;
4908 int parse_long_opt(const char *opt, const char **argv,
4909 const char **optarg)
4911 const char *arg = argv[0];
4912 if (!skip_prefix(arg, "--", &arg))
4913 return 0;
4914 if (!skip_prefix(arg, opt, &arg))
4915 return 0;
4916 if (*arg == '=') { /* stuck form: --option=value */
4917 *optarg = arg + 1;
4918 return 1;
4920 if (*arg != '\0')
4921 return 0;
4922 /* separate form: --option value */
4923 if (!argv[1])
4924 die("Option '--%s' requires a value", opt);
4925 *optarg = argv[1];
4926 return 2;
4929 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4931 struct diff_options *options = opt->value;
4932 int width = options->stat_width;
4933 int name_width = options->stat_name_width;
4934 int graph_width = options->stat_graph_width;
4935 int count = options->stat_count;
4936 char *end;
4938 BUG_ON_OPT_NEG(unset);
4940 if (!strcmp(opt->long_name, "stat")) {
4941 if (value) {
4942 width = strtoul(value, &end, 10);
4943 if (*end == ',')
4944 name_width = strtoul(end+1, &end, 10);
4945 if (*end == ',')
4946 count = strtoul(end+1, &end, 10);
4947 if (*end)
4948 return error(_("invalid --stat value: %s"), value);
4950 } else if (!strcmp(opt->long_name, "stat-width")) {
4951 width = strtoul(value, &end, 10);
4952 if (*end)
4953 return error(_("%s expects a numerical value"),
4954 opt->long_name);
4955 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4956 name_width = strtoul(value, &end, 10);
4957 if (*end)
4958 return error(_("%s expects a numerical value"),
4959 opt->long_name);
4960 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4961 graph_width = strtoul(value, &end, 10);
4962 if (*end)
4963 return error(_("%s expects a numerical value"),
4964 opt->long_name);
4965 } else if (!strcmp(opt->long_name, "stat-count")) {
4966 count = strtoul(value, &end, 10);
4967 if (*end)
4968 return error(_("%s expects a numerical value"),
4969 opt->long_name);
4970 } else
4971 BUG("%s should not get here", opt->long_name);
4973 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4974 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4975 options->stat_name_width = name_width;
4976 options->stat_graph_width = graph_width;
4977 options->stat_width = width;
4978 options->stat_count = count;
4979 return 0;
4982 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4984 struct strbuf errmsg = STRBUF_INIT;
4985 if (parse_dirstat_params(options, params, &errmsg))
4986 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4987 errmsg.buf);
4988 strbuf_release(&errmsg);
4990 * The caller knows a dirstat-related option is given from the command
4991 * line; allow it to say "return this_function();"
4993 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4994 options->output_format |= DIFF_FORMAT_DIRSTAT;
4995 return 1;
4998 static int diff_opt_diff_filter(const struct option *option,
4999 const char *optarg, int unset)
5001 struct diff_options *opt = option->value;
5002 int i, optch;
5004 BUG_ON_OPT_NEG(unset);
5005 prepare_filter_bits();
5007 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5008 unsigned int bit;
5009 int negate;
5011 if ('a' <= optch && optch <= 'z') {
5012 negate = 1;
5013 optch = toupper(optch);
5014 } else {
5015 negate = 0;
5018 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5019 if (!bit)
5020 return error(_("unknown change class '%c' in --diff-filter=%s"),
5021 optarg[i], optarg);
5022 if (negate)
5023 opt->filter_not |= bit;
5024 else
5025 opt->filter |= bit;
5027 return 0;
5030 static void enable_patch_output(int *fmt)
5032 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5033 *fmt |= DIFF_FORMAT_PATCH;
5036 static int diff_opt_ws_error_highlight(const struct option *option,
5037 const char *arg, int unset)
5039 struct diff_options *opt = option->value;
5040 int val = parse_ws_error_highlight(arg);
5042 BUG_ON_OPT_NEG(unset);
5043 if (val < 0)
5044 return error(_("unknown value after ws-error-highlight=%.*s"),
5045 -1 - val, arg);
5046 opt->ws_error_highlight = val;
5047 return 0;
5050 static int diff_opt_find_object(const struct option *option,
5051 const char *arg, int unset)
5053 struct diff_options *opt = option->value;
5054 struct object_id oid;
5056 BUG_ON_OPT_NEG(unset);
5057 if (repo_get_oid(the_repository, arg, &oid))
5058 return error(_("unable to resolve '%s'"), arg);
5060 if (!opt->objfind)
5061 CALLOC_ARRAY(opt->objfind, 1);
5063 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5064 opt->flags.recursive = 1;
5065 opt->flags.tree_in_recursive = 1;
5066 oidset_insert(opt->objfind, &oid);
5067 return 0;
5070 static int diff_opt_anchored(const struct option *opt,
5071 const char *arg, int unset)
5073 struct diff_options *options = opt->value;
5075 BUG_ON_OPT_NEG(unset);
5076 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5077 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5078 options->anchors_alloc);
5079 options->anchors[options->anchors_nr++] = xstrdup(arg);
5080 return 0;
5083 static int diff_opt_binary(const struct option *opt,
5084 const char *arg, int unset)
5086 struct diff_options *options = opt->value;
5088 BUG_ON_OPT_NEG(unset);
5089 BUG_ON_OPT_ARG(arg);
5090 enable_patch_output(&options->output_format);
5091 options->flags.binary = 1;
5092 return 0;
5095 static int diff_opt_break_rewrites(const struct option *opt,
5096 const char *arg, int unset)
5098 int *break_opt = opt->value;
5099 int opt1, opt2;
5101 BUG_ON_OPT_NEG(unset);
5102 if (!arg)
5103 arg = "";
5104 opt1 = parse_rename_score(&arg);
5105 if (*arg == 0)
5106 opt2 = 0;
5107 else if (*arg != '/')
5108 return error(_("%s expects <n>/<m> form"), opt->long_name);
5109 else {
5110 arg++;
5111 opt2 = parse_rename_score(&arg);
5113 if (*arg != 0)
5114 return error(_("%s expects <n>/<m> form"), opt->long_name);
5115 *break_opt = opt1 | (opt2 << 16);
5116 return 0;
5119 static int diff_opt_char(const struct option *opt,
5120 const char *arg, int unset)
5122 char *value = opt->value;
5124 BUG_ON_OPT_NEG(unset);
5125 if (arg[1])
5126 return error(_("%s expects a character, got '%s'"),
5127 opt->long_name, arg);
5128 *value = arg[0];
5129 return 0;
5132 static int diff_opt_color_moved(const struct option *opt,
5133 const char *arg, int unset)
5135 struct diff_options *options = opt->value;
5137 if (unset) {
5138 options->color_moved = COLOR_MOVED_NO;
5139 } else if (!arg) {
5140 if (diff_color_moved_default)
5141 options->color_moved = diff_color_moved_default;
5142 if (options->color_moved == COLOR_MOVED_NO)
5143 options->color_moved = COLOR_MOVED_DEFAULT;
5144 } else {
5145 int cm = parse_color_moved(arg);
5146 if (cm < 0)
5147 return error(_("bad --color-moved argument: %s"), arg);
5148 options->color_moved = cm;
5150 return 0;
5153 static int diff_opt_color_moved_ws(const struct option *opt,
5154 const char *arg, int unset)
5156 struct diff_options *options = opt->value;
5157 unsigned cm;
5159 if (unset) {
5160 options->color_moved_ws_handling = 0;
5161 return 0;
5164 cm = parse_color_moved_ws(arg);
5165 if (cm & COLOR_MOVED_WS_ERROR)
5166 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5167 options->color_moved_ws_handling = cm;
5168 return 0;
5171 static int diff_opt_color_words(const struct option *opt,
5172 const char *arg, int unset)
5174 struct diff_options *options = opt->value;
5176 BUG_ON_OPT_NEG(unset);
5177 options->use_color = 1;
5178 options->word_diff = DIFF_WORDS_COLOR;
5179 options->word_regex = arg;
5180 return 0;
5183 static int diff_opt_compact_summary(const struct option *opt,
5184 const char *arg, int unset)
5186 struct diff_options *options = opt->value;
5188 BUG_ON_OPT_ARG(arg);
5189 if (unset) {
5190 options->flags.stat_with_summary = 0;
5191 } else {
5192 options->flags.stat_with_summary = 1;
5193 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5194 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5196 return 0;
5199 static int diff_opt_diff_algorithm(const struct option *opt,
5200 const char *arg, int unset)
5202 struct diff_options *options = opt->value;
5204 BUG_ON_OPT_NEG(unset);
5206 if (set_diff_algorithm(options, arg))
5207 return error(_("option diff-algorithm accepts \"myers\", "
5208 "\"minimal\", \"patience\" and \"histogram\""));
5210 options->ignore_driver_algorithm = 1;
5212 return 0;
5215 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5216 const char *arg, int unset)
5218 struct diff_options *options = opt->value;
5220 BUG_ON_OPT_NEG(unset);
5221 BUG_ON_OPT_ARG(arg);
5223 if (set_diff_algorithm(options, opt->long_name))
5224 BUG("available diff algorithms include \"myers\", "
5225 "\"minimal\", \"patience\" and \"histogram\"");
5227 options->ignore_driver_algorithm = 1;
5229 return 0;
5232 static int diff_opt_dirstat(const struct option *opt,
5233 const char *arg, int unset)
5235 struct diff_options *options = opt->value;
5237 BUG_ON_OPT_NEG(unset);
5238 if (!strcmp(opt->long_name, "cumulative")) {
5239 if (arg)
5240 BUG("how come --cumulative take a value?");
5241 arg = "cumulative";
5242 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5243 parse_dirstat_opt(options, "files");
5244 parse_dirstat_opt(options, arg ? arg : "");
5245 return 0;
5248 static int diff_opt_find_copies(const struct option *opt,
5249 const char *arg, int unset)
5251 struct diff_options *options = opt->value;
5253 BUG_ON_OPT_NEG(unset);
5254 if (!arg)
5255 arg = "";
5256 options->rename_score = parse_rename_score(&arg);
5257 if (*arg != 0)
5258 return error(_("invalid argument to %s"), opt->long_name);
5260 if (options->detect_rename == DIFF_DETECT_COPY)
5261 options->flags.find_copies_harder = 1;
5262 else
5263 options->detect_rename = DIFF_DETECT_COPY;
5265 return 0;
5268 static int diff_opt_find_renames(const struct option *opt,
5269 const char *arg, int unset)
5271 struct diff_options *options = opt->value;
5273 BUG_ON_OPT_NEG(unset);
5274 if (!arg)
5275 arg = "";
5276 options->rename_score = parse_rename_score(&arg);
5277 if (*arg != 0)
5278 return error(_("invalid argument to %s"), opt->long_name);
5280 options->detect_rename = DIFF_DETECT_RENAME;
5281 return 0;
5284 static int diff_opt_follow(const struct option *opt,
5285 const char *arg, int unset)
5287 struct diff_options *options = opt->value;
5289 BUG_ON_OPT_ARG(arg);
5290 if (unset) {
5291 options->flags.follow_renames = 0;
5292 options->flags.default_follow_renames = 0;
5293 } else {
5294 options->flags.follow_renames = 1;
5296 return 0;
5299 static int diff_opt_ignore_submodules(const struct option *opt,
5300 const char *arg, int unset)
5302 struct diff_options *options = opt->value;
5304 BUG_ON_OPT_NEG(unset);
5305 if (!arg)
5306 arg = "all";
5307 options->flags.override_submodule_config = 1;
5308 handle_ignore_submodules_arg(options, arg);
5309 return 0;
5312 static int diff_opt_line_prefix(const struct option *opt,
5313 const char *optarg, int unset)
5315 struct diff_options *options = opt->value;
5317 BUG_ON_OPT_NEG(unset);
5318 options->line_prefix = optarg;
5319 options->line_prefix_length = strlen(options->line_prefix);
5320 graph_setup_line_prefix(options);
5321 return 0;
5324 static int diff_opt_no_prefix(const struct option *opt,
5325 const char *optarg, int unset)
5327 struct diff_options *options = opt->value;
5329 BUG_ON_OPT_NEG(unset);
5330 BUG_ON_OPT_ARG(optarg);
5331 diff_set_noprefix(options);
5332 return 0;
5335 static int diff_opt_default_prefix(const struct option *opt,
5336 const char *optarg, int unset)
5338 struct diff_options *options = opt->value;
5340 BUG_ON_OPT_NEG(unset);
5341 BUG_ON_OPT_ARG(optarg);
5342 diff_set_default_prefix(options);
5343 return 0;
5346 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5347 const struct option *opt,
5348 const char *arg, int unset)
5350 struct diff_options *options = opt->value;
5351 char *path;
5353 BUG_ON_OPT_NEG(unset);
5354 path = prefix_filename(ctx->prefix, arg);
5355 options->file = xfopen(path, "w");
5356 options->close_file = 1;
5357 if (options->use_color != GIT_COLOR_ALWAYS)
5358 options->use_color = GIT_COLOR_NEVER;
5359 free(path);
5360 return 0;
5363 static int diff_opt_patience(const struct option *opt,
5364 const char *arg, int unset)
5366 struct diff_options *options = opt->value;
5367 int i;
5369 BUG_ON_OPT_NEG(unset);
5370 BUG_ON_OPT_ARG(arg);
5372 * Both --patience and --anchored use PATIENCE_DIFF
5373 * internally, so remove any anchors previously
5374 * specified.
5376 for (i = 0; i < options->anchors_nr; i++)
5377 free(options->anchors[i]);
5378 options->anchors_nr = 0;
5379 options->ignore_driver_algorithm = 1;
5381 return set_diff_algorithm(options, "patience");
5384 static int diff_opt_ignore_regex(const struct option *opt,
5385 const char *arg, int unset)
5387 struct diff_options *options = opt->value;
5388 regex_t *regex;
5390 BUG_ON_OPT_NEG(unset);
5391 regex = xmalloc(sizeof(*regex));
5392 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5393 return error(_("invalid regex given to -I: '%s'"), arg);
5394 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5395 options->ignore_regex_alloc);
5396 options->ignore_regex[options->ignore_regex_nr++] = regex;
5397 return 0;
5400 static int diff_opt_pickaxe_regex(const struct option *opt,
5401 const char *arg, int unset)
5403 struct diff_options *options = opt->value;
5405 BUG_ON_OPT_NEG(unset);
5406 options->pickaxe = arg;
5407 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5408 return 0;
5411 static int diff_opt_pickaxe_string(const struct option *opt,
5412 const char *arg, int unset)
5414 struct diff_options *options = opt->value;
5416 BUG_ON_OPT_NEG(unset);
5417 options->pickaxe = arg;
5418 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5419 return 0;
5422 static int diff_opt_relative(const struct option *opt,
5423 const char *arg, int unset)
5425 struct diff_options *options = opt->value;
5427 options->flags.relative_name = !unset;
5428 if (arg)
5429 options->prefix = arg;
5430 return 0;
5433 static int diff_opt_submodule(const struct option *opt,
5434 const char *arg, int unset)
5436 struct diff_options *options = opt->value;
5438 BUG_ON_OPT_NEG(unset);
5439 if (!arg)
5440 arg = "log";
5441 if (parse_submodule_params(options, arg))
5442 return error(_("failed to parse --submodule option parameter: '%s'"),
5443 arg);
5444 return 0;
5447 static int diff_opt_textconv(const struct option *opt,
5448 const char *arg, int unset)
5450 struct diff_options *options = opt->value;
5452 BUG_ON_OPT_ARG(arg);
5453 if (unset) {
5454 options->flags.allow_textconv = 0;
5455 } else {
5456 options->flags.allow_textconv = 1;
5457 options->flags.textconv_set_via_cmdline = 1;
5459 return 0;
5462 static int diff_opt_unified(const struct option *opt,
5463 const char *arg, int unset)
5465 struct diff_options *options = opt->value;
5466 char *s;
5468 BUG_ON_OPT_NEG(unset);
5470 if (arg) {
5471 options->context = strtol(arg, &s, 10);
5472 if (*s)
5473 return error(_("%s expects a numerical value"), "--unified");
5475 enable_patch_output(&options->output_format);
5477 return 0;
5480 static int diff_opt_word_diff(const struct option *opt,
5481 const char *arg, int unset)
5483 struct diff_options *options = opt->value;
5485 BUG_ON_OPT_NEG(unset);
5486 if (arg) {
5487 if (!strcmp(arg, "plain"))
5488 options->word_diff = DIFF_WORDS_PLAIN;
5489 else if (!strcmp(arg, "color")) {
5490 options->use_color = 1;
5491 options->word_diff = DIFF_WORDS_COLOR;
5493 else if (!strcmp(arg, "porcelain"))
5494 options->word_diff = DIFF_WORDS_PORCELAIN;
5495 else if (!strcmp(arg, "none"))
5496 options->word_diff = DIFF_WORDS_NONE;
5497 else
5498 return error(_("bad --word-diff argument: %s"), arg);
5499 } else {
5500 if (options->word_diff == DIFF_WORDS_NONE)
5501 options->word_diff = DIFF_WORDS_PLAIN;
5503 return 0;
5506 static int diff_opt_word_diff_regex(const struct option *opt,
5507 const char *arg, int unset)
5509 struct diff_options *options = opt->value;
5511 BUG_ON_OPT_NEG(unset);
5512 if (options->word_diff == DIFF_WORDS_NONE)
5513 options->word_diff = DIFF_WORDS_PLAIN;
5514 options->word_regex = arg;
5515 return 0;
5518 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5520 struct diff_options *options = opt->value;
5522 BUG_ON_OPT_NEG(unset);
5523 if (!strcmp(opt->long_name, "skip-to"))
5524 options->skip_instead_of_rotate = 1;
5525 else
5526 options->skip_instead_of_rotate = 0;
5527 options->rotate_to = arg;
5528 return 0;
5532 * Consider adding new flags to __git_diff_common_options
5533 * in contrib/completion/git-completion.bash
5535 struct option *add_diff_options(const struct option *opts,
5536 struct diff_options *options)
5538 struct option parseopts[] = {
5539 OPT_GROUP(N_("Diff output format options")),
5540 OPT_BITOP('p', "patch", &options->output_format,
5541 N_("generate patch"),
5542 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5543 OPT_SET_INT('s', "no-patch", &options->output_format,
5544 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5545 OPT_BITOP('u', NULL, &options->output_format,
5546 N_("generate patch"),
5547 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5548 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5549 N_("generate diffs with <n> lines context"),
5550 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5551 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5552 N_("generate diffs with <n> lines context")),
5553 OPT_BITOP(0, "raw", &options->output_format,
5554 N_("generate the diff in raw format"),
5555 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5556 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5557 N_("synonym for '-p --raw'"),
5558 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5559 DIFF_FORMAT_NO_OUTPUT),
5560 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5561 N_("synonym for '-p --stat'"),
5562 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5563 DIFF_FORMAT_NO_OUTPUT),
5564 OPT_BITOP(0, "numstat", &options->output_format,
5565 N_("machine friendly --stat"),
5566 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5567 OPT_BITOP(0, "shortstat", &options->output_format,
5568 N_("output only the last line of --stat"),
5569 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5570 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5571 N_("output the distribution of relative amount of changes for each sub-directory"),
5572 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5573 diff_opt_dirstat),
5574 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5575 N_("synonym for --dirstat=cumulative"),
5576 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5577 diff_opt_dirstat),
5578 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5579 N_("synonym for --dirstat=files,param1,param2..."),
5580 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5581 diff_opt_dirstat),
5582 OPT_BIT_F(0, "check", &options->output_format,
5583 N_("warn if changes introduce conflict markers or whitespace errors"),
5584 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5585 OPT_BITOP(0, "summary", &options->output_format,
5586 N_("condensed summary such as creations, renames and mode changes"),
5587 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5588 OPT_BIT_F(0, "name-only", &options->output_format,
5589 N_("show only names of changed files"),
5590 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5591 OPT_BIT_F(0, "name-status", &options->output_format,
5592 N_("show only names and status of changed files"),
5593 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5594 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5595 N_("generate diffstat"),
5596 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5597 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5598 N_("generate diffstat with a given width"),
5599 PARSE_OPT_NONEG, diff_opt_stat),
5600 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5601 N_("generate diffstat with a given name width"),
5602 PARSE_OPT_NONEG, diff_opt_stat),
5603 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5604 N_("generate diffstat with a given graph width"),
5605 PARSE_OPT_NONEG, diff_opt_stat),
5606 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5607 N_("generate diffstat with limited lines"),
5608 PARSE_OPT_NONEG, diff_opt_stat),
5609 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5610 N_("generate compact summary in diffstat"),
5611 PARSE_OPT_NOARG, diff_opt_compact_summary),
5612 OPT_CALLBACK_F(0, "binary", options, NULL,
5613 N_("output a binary diff that can be applied"),
5614 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5615 OPT_BOOL(0, "full-index", &options->flags.full_index,
5616 N_("show full pre- and post-image object names on the \"index\" lines")),
5617 OPT_COLOR_FLAG(0, "color", &options->use_color,
5618 N_("show colored diff")),
5619 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5620 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5621 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5622 OPT_SET_INT('z', NULL, &options->line_termination,
5623 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5625 OPT__ABBREV(&options->abbrev),
5626 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5627 N_("show the given source prefix instead of \"a/\""),
5628 PARSE_OPT_NONEG),
5629 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5630 N_("show the given destination prefix instead of \"b/\""),
5631 PARSE_OPT_NONEG),
5632 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5633 N_("prepend an additional prefix to every line of output"),
5634 PARSE_OPT_NONEG, diff_opt_line_prefix),
5635 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5636 N_("do not show any source or destination prefix"),
5637 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5638 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5639 N_("use default prefixes a/ and b/"),
5640 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5641 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5642 N_("show context between diff hunks up to the specified number of lines"),
5643 PARSE_OPT_NONEG),
5644 OPT_CALLBACK_F(0, "output-indicator-new",
5645 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5646 N_("<char>"),
5647 N_("specify the character to indicate a new line instead of '+'"),
5648 PARSE_OPT_NONEG, diff_opt_char),
5649 OPT_CALLBACK_F(0, "output-indicator-old",
5650 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5651 N_("<char>"),
5652 N_("specify the character to indicate an old line instead of '-'"),
5653 PARSE_OPT_NONEG, diff_opt_char),
5654 OPT_CALLBACK_F(0, "output-indicator-context",
5655 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5656 N_("<char>"),
5657 N_("specify the character to indicate a context instead of ' '"),
5658 PARSE_OPT_NONEG, diff_opt_char),
5660 OPT_GROUP(N_("Diff rename options")),
5661 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5662 N_("break complete rewrite changes into pairs of delete and create"),
5663 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5664 diff_opt_break_rewrites),
5665 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5666 N_("detect renames"),
5667 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5668 diff_opt_find_renames),
5669 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5670 N_("omit the preimage for deletes"),
5671 1, PARSE_OPT_NONEG),
5672 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5673 N_("detect copies"),
5674 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5675 diff_opt_find_copies),
5676 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5677 N_("use unmodified files as source to find copies")),
5678 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5679 N_("disable rename detection"),
5680 0, PARSE_OPT_NONEG),
5681 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5682 N_("use empty blobs as rename source")),
5683 OPT_CALLBACK_F(0, "follow", options, NULL,
5684 N_("continue listing the history of a file beyond renames"),
5685 PARSE_OPT_NOARG, diff_opt_follow),
5686 OPT_INTEGER('l', NULL, &options->rename_limit,
5687 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5689 OPT_GROUP(N_("Diff algorithm options")),
5690 OPT_CALLBACK_F(0, "minimal", options, NULL,
5691 N_("produce the smallest possible diff"),
5692 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5693 diff_opt_diff_algorithm_no_arg),
5694 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5695 N_("ignore whitespace when comparing lines"),
5696 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5697 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5698 N_("ignore changes in amount of whitespace"),
5699 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5700 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5701 N_("ignore changes in whitespace at EOL"),
5702 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5703 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5704 N_("ignore carrier-return at the end of line"),
5705 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5706 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5707 N_("ignore changes whose lines are all blank"),
5708 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5709 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5710 N_("ignore changes whose all lines match <regex>"),
5711 0, diff_opt_ignore_regex),
5712 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5713 N_("heuristic to shift diff hunk boundaries for easy reading"),
5714 XDF_INDENT_HEURISTIC),
5715 OPT_CALLBACK_F(0, "patience", options, NULL,
5716 N_("generate diff using the \"patience diff\" algorithm"),
5717 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5718 diff_opt_patience),
5719 OPT_CALLBACK_F(0, "histogram", options, NULL,
5720 N_("generate diff using the \"histogram diff\" algorithm"),
5721 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5722 diff_opt_diff_algorithm_no_arg),
5723 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5724 N_("choose a diff algorithm"),
5725 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5726 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5727 N_("generate diff using the \"anchored diff\" algorithm"),
5728 PARSE_OPT_NONEG, diff_opt_anchored),
5729 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5730 N_("show word diff, using <mode> to delimit changed words"),
5731 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5732 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5733 N_("use <regex> to decide what a word is"),
5734 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5735 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5736 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5737 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5738 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5739 N_("moved lines of code are colored differently"),
5740 PARSE_OPT_OPTARG, diff_opt_color_moved),
5741 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5742 N_("how white spaces are ignored in --color-moved"),
5743 0, diff_opt_color_moved_ws),
5745 OPT_GROUP(N_("Other diff options")),
5746 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5747 N_("when run from subdir, exclude changes outside and show relative paths"),
5748 PARSE_OPT_OPTARG,
5749 diff_opt_relative),
5750 OPT_BOOL('a', "text", &options->flags.text,
5751 N_("treat all files as text")),
5752 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5753 N_("swap two inputs, reverse the diff")),
5754 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5755 N_("exit with 1 if there were differences, 0 otherwise")),
5756 OPT_BOOL(0, "quiet", &options->flags.quick,
5757 N_("disable all output of the program")),
5758 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5759 N_("allow an external diff helper to be executed")),
5760 OPT_CALLBACK_F(0, "textconv", options, NULL,
5761 N_("run external text conversion filters when comparing binary files"),
5762 PARSE_OPT_NOARG, diff_opt_textconv),
5763 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5764 N_("ignore changes to submodules in the diff generation"),
5765 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5766 diff_opt_ignore_submodules),
5767 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5768 N_("specify how differences in submodules are shown"),
5769 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5770 diff_opt_submodule),
5771 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5772 N_("hide 'git add -N' entries from the index"),
5773 1, PARSE_OPT_NONEG),
5774 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5775 N_("treat 'git add -N' entries as real in the index"),
5776 0, PARSE_OPT_NONEG),
5777 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5778 N_("look for differences that change the number of occurrences of the specified string"),
5779 0, diff_opt_pickaxe_string),
5780 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5781 N_("look for differences that change the number of occurrences of the specified regex"),
5782 0, diff_opt_pickaxe_regex),
5783 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5784 N_("show all changes in the changeset with -S or -G"),
5785 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5786 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5787 N_("treat <string> in -S as extended POSIX regular expression"),
5788 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5789 OPT_FILENAME('O', NULL, &options->orderfile,
5790 N_("control the order in which files appear in the output")),
5791 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5792 N_("show the change in the specified path first"),
5793 PARSE_OPT_NONEG, diff_opt_rotate_to),
5794 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5795 N_("skip the output to the specified path"),
5796 PARSE_OPT_NONEG, diff_opt_rotate_to),
5797 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5798 N_("look for differences that change the number of occurrences of the specified object"),
5799 PARSE_OPT_NONEG, diff_opt_find_object),
5800 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5801 N_("select files by diff type"),
5802 PARSE_OPT_NONEG, diff_opt_diff_filter),
5803 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5804 N_("output to a specific file"),
5805 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5807 OPT_END()
5810 return parse_options_concat(opts, parseopts);
5813 int diff_opt_parse(struct diff_options *options,
5814 const char **av, int ac, const char *prefix)
5816 struct option no_options[] = { OPT_END() };
5817 struct option *parseopts = add_diff_options(no_options, options);
5819 if (!prefix)
5820 prefix = "";
5822 ac = parse_options(ac, av, prefix, parseopts, NULL,
5823 PARSE_OPT_KEEP_DASHDASH |
5824 PARSE_OPT_KEEP_UNKNOWN_OPT |
5825 PARSE_OPT_NO_INTERNAL_HELP |
5826 PARSE_OPT_ONE_SHOT |
5827 PARSE_OPT_STOP_AT_NON_OPTION);
5828 free(parseopts);
5830 return ac;
5833 int parse_rename_score(const char **cp_p)
5835 unsigned long num, scale;
5836 int ch, dot;
5837 const char *cp = *cp_p;
5839 num = 0;
5840 scale = 1;
5841 dot = 0;
5842 for (;;) {
5843 ch = *cp;
5844 if ( !dot && ch == '.' ) {
5845 scale = 1;
5846 dot = 1;
5847 } else if ( ch == '%' ) {
5848 scale = dot ? scale*100 : 100;
5849 cp++; /* % is always at the end */
5850 break;
5851 } else if ( ch >= '0' && ch <= '9' ) {
5852 if ( scale < 100000 ) {
5853 scale *= 10;
5854 num = (num*10) + (ch-'0');
5856 } else {
5857 break;
5859 cp++;
5861 *cp_p = cp;
5863 /* user says num divided by scale and we say internally that
5864 * is MAX_SCORE * num / scale.
5866 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5869 struct diff_queue_struct diff_queued_diff;
5871 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5873 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5874 queue->queue[queue->nr++] = dp;
5877 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5878 struct diff_filespec *one,
5879 struct diff_filespec *two)
5881 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5882 dp->one = one;
5883 dp->two = two;
5884 if (queue)
5885 diff_q(queue, dp);
5886 return dp;
5889 void diff_free_filepair(struct diff_filepair *p)
5891 free_filespec(p->one);
5892 free_filespec(p->two);
5893 free(p);
5896 void diff_free_queue(struct diff_queue_struct *q)
5898 for (int i = 0; i < q->nr; i++)
5899 diff_free_filepair(q->queue[i]);
5900 free(q->queue);
5903 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5905 int abblen;
5906 const char *abbrev;
5908 /* Do we want all 40 hex characters? */
5909 if (len == the_hash_algo->hexsz)
5910 return oid_to_hex(oid);
5912 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5913 abbrev = diff_abbrev_oid(oid, len);
5915 if (!print_sha1_ellipsis())
5916 return abbrev;
5918 abblen = strlen(abbrev);
5921 * In well-behaved cases, where the abbreviated result is the
5922 * same as the requested length, append three dots after the
5923 * abbreviation (hence the whole logic is limited to the case
5924 * where abblen < 37); when the actual abbreviated result is a
5925 * bit longer than the requested length, we reduce the number
5926 * of dots so that they match the well-behaved ones. However,
5927 * if the actual abbreviation is longer than the requested
5928 * length by more than three, we give up on aligning, and add
5929 * three dots anyway, to indicate that the output is not the
5930 * full object name. Yes, this may be suboptimal, but this
5931 * appears only in "diff --raw --abbrev" output and it is not
5932 * worth the effort to change it now. Note that this would
5933 * likely to work fine when the automatic sizing of default
5934 * abbreviation length is used--we would be fed -1 in "len" in
5935 * that case, and will end up always appending three-dots, but
5936 * the automatic sizing is supposed to give abblen that ensures
5937 * uniqueness across all objects (statistically speaking).
5939 if (abblen < the_hash_algo->hexsz - 3) {
5940 static char hex[GIT_MAX_HEXSZ + 1];
5941 if (len < abblen && abblen <= len + 2)
5942 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5943 else
5944 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5945 return hex;
5948 return oid_to_hex(oid);
5951 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5953 int line_termination = opt->line_termination;
5954 int inter_name_termination = line_termination ? '\t' : '\0';
5956 fprintf(opt->file, "%s", diff_line_prefix(opt));
5957 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5958 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5959 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5960 fprintf(opt->file, "%s ",
5961 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5963 if (p->score) {
5964 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5965 inter_name_termination);
5966 } else {
5967 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5970 if (p->status == DIFF_STATUS_COPIED ||
5971 p->status == DIFF_STATUS_RENAMED) {
5972 const char *name_a, *name_b;
5973 name_a = p->one->path;
5974 name_b = p->two->path;
5975 strip_prefix(opt->prefix_length, &name_a, &name_b);
5976 write_name_quoted(name_a, opt->file, inter_name_termination);
5977 write_name_quoted(name_b, opt->file, line_termination);
5978 } else {
5979 const char *name_a, *name_b;
5980 name_a = p->one->mode ? p->one->path : p->two->path;
5981 name_b = NULL;
5982 strip_prefix(opt->prefix_length, &name_a, &name_b);
5983 write_name_quoted(name_a, opt->file, line_termination);
5987 int diff_unmodified_pair(struct diff_filepair *p)
5989 /* This function is written stricter than necessary to support
5990 * the currently implemented transformers, but the idea is to
5991 * let transformers to produce diff_filepairs any way they want,
5992 * and filter and clean them up here before producing the output.
5994 struct diff_filespec *one = p->one, *two = p->two;
5996 if (DIFF_PAIR_UNMERGED(p))
5997 return 0; /* unmerged is interesting */
5999 /* deletion, addition, mode or type change
6000 * and rename are all interesting.
6002 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6003 DIFF_PAIR_MODE_CHANGED(p) ||
6004 strcmp(one->path, two->path))
6005 return 0;
6007 /* both are valid and point at the same path. that is, we are
6008 * dealing with a change.
6010 if (one->oid_valid && two->oid_valid &&
6011 oideq(&one->oid, &two->oid) &&
6012 !one->dirty_submodule && !two->dirty_submodule)
6013 return 1; /* no change */
6014 if (!one->oid_valid && !two->oid_valid)
6015 return 1; /* both look at the same file on the filesystem. */
6016 return 0;
6019 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6021 int include_conflict_headers =
6022 (additional_headers(o, p->one->path) &&
6023 !o->pickaxe_opts &&
6024 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6027 * Check if we can return early without showing a diff. Note that
6028 * diff_filepair only stores {oid, path, mode, is_valid}
6029 * information for each path, and thus diff_unmodified_pair() only
6030 * considers those bits of info. However, we do not want pairs
6031 * created by create_filepairs_for_header_only_notifications()
6032 * (which always look like unmodified pairs) to be ignored, so
6033 * return early if both p is unmodified AND we don't want to
6034 * include_conflict_headers.
6036 if (diff_unmodified_pair(p) && !include_conflict_headers)
6037 return;
6039 /* Actually, we can also return early to avoid showing tree diffs */
6040 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6041 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6042 return;
6044 run_diff(p, o);
6047 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6048 struct diffstat_t *diffstat)
6050 if (diff_unmodified_pair(p))
6051 return;
6053 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6054 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6055 return; /* no useful stat for tree diffs */
6057 run_diffstat(p, o, diffstat);
6060 static void diff_flush_checkdiff(struct diff_filepair *p,
6061 struct diff_options *o)
6063 if (diff_unmodified_pair(p))
6064 return;
6066 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6067 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6068 return; /* nothing to check in tree diffs */
6070 run_checkdiff(p, o);
6073 int diff_queue_is_empty(struct diff_options *o)
6075 struct diff_queue_struct *q = &diff_queued_diff;
6076 int i;
6077 int include_conflict_headers =
6078 (o->additional_path_headers &&
6079 strmap_get_size(o->additional_path_headers) &&
6080 !o->pickaxe_opts &&
6081 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6083 if (include_conflict_headers)
6084 return 0;
6086 for (i = 0; i < q->nr; i++)
6087 if (!diff_unmodified_pair(q->queue[i]))
6088 return 0;
6089 return 1;
6092 #if DIFF_DEBUG
6093 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6095 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6096 x, one ? one : "",
6097 s->path,
6098 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6099 s->mode,
6100 s->oid_valid ? oid_to_hex(&s->oid) : "");
6101 fprintf(stderr, "queue[%d] %s size %lu\n",
6102 x, one ? one : "",
6103 s->size);
6106 void diff_debug_filepair(const struct diff_filepair *p, int i)
6108 diff_debug_filespec(p->one, i, "one");
6109 diff_debug_filespec(p->two, i, "two");
6110 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6111 p->score, p->status ? p->status : '?',
6112 p->one->rename_used, p->broken_pair);
6115 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6117 int i;
6118 if (msg)
6119 fprintf(stderr, "%s\n", msg);
6120 fprintf(stderr, "q->nr = %d\n", q->nr);
6121 for (i = 0; i < q->nr; i++) {
6122 struct diff_filepair *p = q->queue[i];
6123 diff_debug_filepair(p, i);
6126 #endif
6128 static void diff_resolve_rename_copy(void)
6130 int i;
6131 struct diff_filepair *p;
6132 struct diff_queue_struct *q = &diff_queued_diff;
6134 diff_debug_queue("resolve-rename-copy", q);
6136 for (i = 0; i < q->nr; i++) {
6137 p = q->queue[i];
6138 p->status = 0; /* undecided */
6139 if (DIFF_PAIR_UNMERGED(p))
6140 p->status = DIFF_STATUS_UNMERGED;
6141 else if (!DIFF_FILE_VALID(p->one))
6142 p->status = DIFF_STATUS_ADDED;
6143 else if (!DIFF_FILE_VALID(p->two))
6144 p->status = DIFF_STATUS_DELETED;
6145 else if (DIFF_PAIR_TYPE_CHANGED(p))
6146 p->status = DIFF_STATUS_TYPE_CHANGED;
6148 /* from this point on, we are dealing with a pair
6149 * whose both sides are valid and of the same type, i.e.
6150 * either in-place edit or rename/copy edit.
6152 else if (DIFF_PAIR_RENAME(p)) {
6154 * A rename might have re-connected a broken
6155 * pair up, causing the pathnames to be the
6156 * same again. If so, that's not a rename at
6157 * all, just a modification..
6159 * Otherwise, see if this source was used for
6160 * multiple renames, in which case we decrement
6161 * the count, and call it a copy.
6163 if (!strcmp(p->one->path, p->two->path))
6164 p->status = DIFF_STATUS_MODIFIED;
6165 else if (--p->one->rename_used > 0)
6166 p->status = DIFF_STATUS_COPIED;
6167 else
6168 p->status = DIFF_STATUS_RENAMED;
6170 else if (!oideq(&p->one->oid, &p->two->oid) ||
6171 p->one->mode != p->two->mode ||
6172 p->one->dirty_submodule ||
6173 p->two->dirty_submodule ||
6174 is_null_oid(&p->one->oid))
6175 p->status = DIFF_STATUS_MODIFIED;
6176 else {
6177 /* This is a "no-change" entry and should not
6178 * happen anymore, but prepare for broken callers.
6180 error("feeding unmodified %s to diffcore",
6181 p->one->path);
6182 p->status = DIFF_STATUS_UNKNOWN;
6185 diff_debug_queue("resolve-rename-copy done", q);
6188 static int check_pair_status(struct diff_filepair *p)
6190 switch (p->status) {
6191 case DIFF_STATUS_UNKNOWN:
6192 return 0;
6193 case 0:
6194 die("internal error in diff-resolve-rename-copy");
6195 default:
6196 return 1;
6200 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6202 int fmt = opt->output_format;
6204 if (fmt & DIFF_FORMAT_CHECKDIFF)
6205 diff_flush_checkdiff(p, opt);
6206 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6207 diff_flush_raw(p, opt);
6208 else if (fmt & DIFF_FORMAT_NAME) {
6209 const char *name_a, *name_b;
6210 name_a = p->two->path;
6211 name_b = NULL;
6212 strip_prefix(opt->prefix_length, &name_a, &name_b);
6213 fprintf(opt->file, "%s", diff_line_prefix(opt));
6214 write_name_quoted(name_a, opt->file, opt->line_termination);
6217 opt->found_changes = 1;
6220 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6222 struct strbuf sb = STRBUF_INIT;
6223 if (fs->mode)
6224 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6225 else
6226 strbuf_addf(&sb, " %s ", newdelete);
6228 quote_c_style(fs->path, &sb, NULL, 0);
6229 strbuf_addch(&sb, '\n');
6230 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6231 sb.buf, sb.len, 0);
6232 strbuf_release(&sb);
6235 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6236 int show_name)
6238 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6239 struct strbuf sb = STRBUF_INIT;
6240 strbuf_addf(&sb, " mode change %06o => %06o",
6241 p->one->mode, p->two->mode);
6242 if (show_name) {
6243 strbuf_addch(&sb, ' ');
6244 quote_c_style(p->two->path, &sb, NULL, 0);
6246 strbuf_addch(&sb, '\n');
6247 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6248 sb.buf, sb.len, 0);
6249 strbuf_release(&sb);
6253 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6254 struct diff_filepair *p)
6256 struct strbuf sb = STRBUF_INIT;
6257 struct strbuf names = STRBUF_INIT;
6259 pprint_rename(&names, p->one->path, p->two->path);
6260 strbuf_addf(&sb, " %s %s (%d%%)\n",
6261 renamecopy, names.buf, similarity_index(p));
6262 strbuf_release(&names);
6263 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6264 sb.buf, sb.len, 0);
6265 show_mode_change(opt, p, 0);
6266 strbuf_release(&sb);
6269 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6271 switch(p->status) {
6272 case DIFF_STATUS_DELETED:
6273 show_file_mode_name(opt, "delete", p->one);
6274 break;
6275 case DIFF_STATUS_ADDED:
6276 show_file_mode_name(opt, "create", p->two);
6277 break;
6278 case DIFF_STATUS_COPIED:
6279 show_rename_copy(opt, "copy", p);
6280 break;
6281 case DIFF_STATUS_RENAMED:
6282 show_rename_copy(opt, "rename", p);
6283 break;
6284 default:
6285 if (p->score) {
6286 struct strbuf sb = STRBUF_INIT;
6287 strbuf_addstr(&sb, " rewrite ");
6288 quote_c_style(p->two->path, &sb, NULL, 0);
6289 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6290 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6291 sb.buf, sb.len, 0);
6292 strbuf_release(&sb);
6294 show_mode_change(opt, p, !p->score);
6295 break;
6299 struct patch_id_t {
6300 git_hash_ctx *ctx;
6301 int patchlen;
6304 static int remove_space(char *line, int len)
6306 int i;
6307 char *dst = line;
6308 unsigned char c;
6310 for (i = 0; i < len; i++)
6311 if (!isspace((c = line[i])))
6312 *dst++ = c;
6314 return dst - line;
6317 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6319 unsigned char hash[GIT_MAX_RAWSZ];
6320 unsigned short carry = 0;
6321 int i;
6323 the_hash_algo->final_fn(hash, ctx);
6324 the_hash_algo->init_fn(ctx);
6325 /* 20-byte sum, with carry */
6326 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6327 carry += result->hash[i] + hash[i];
6328 result->hash[i] = carry;
6329 carry >>= 8;
6333 static int patch_id_consume(void *priv, char *line, unsigned long len)
6335 struct patch_id_t *data = priv;
6336 int new_len;
6338 if (len > 12 && starts_with(line, "\\ "))
6339 return 0;
6340 new_len = remove_space(line, len);
6342 the_hash_algo->update_fn(data->ctx, line, new_len);
6343 data->patchlen += new_len;
6344 return 0;
6347 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6349 the_hash_algo->update_fn(ctx, str, strlen(str));
6352 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6354 /* large enough for 2^32 in octal */
6355 char buf[12];
6356 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6357 the_hash_algo->update_fn(ctx, buf, len);
6360 /* returns 0 upon success, and writes result into oid */
6361 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6363 struct diff_queue_struct *q = &diff_queued_diff;
6364 int i;
6365 git_hash_ctx ctx;
6366 struct patch_id_t data;
6368 the_hash_algo->init_fn(&ctx);
6369 memset(&data, 0, sizeof(struct patch_id_t));
6370 data.ctx = &ctx;
6371 oidclr(oid);
6373 for (i = 0; i < q->nr; i++) {
6374 xpparam_t xpp;
6375 xdemitconf_t xecfg;
6376 mmfile_t mf1, mf2;
6377 struct diff_filepair *p = q->queue[i];
6378 int len1, len2;
6380 memset(&xpp, 0, sizeof(xpp));
6381 memset(&xecfg, 0, sizeof(xecfg));
6382 if (p->status == 0)
6383 return error("internal diff status error");
6384 if (p->status == DIFF_STATUS_UNKNOWN)
6385 continue;
6386 if (diff_unmodified_pair(p))
6387 continue;
6388 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6389 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6390 continue;
6391 if (DIFF_PAIR_UNMERGED(p))
6392 continue;
6394 diff_fill_oid_info(p->one, options->repo->index);
6395 diff_fill_oid_info(p->two, options->repo->index);
6397 len1 = remove_space(p->one->path, strlen(p->one->path));
6398 len2 = remove_space(p->two->path, strlen(p->two->path));
6399 patch_id_add_string(&ctx, "diff--git");
6400 patch_id_add_string(&ctx, "a/");
6401 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6402 patch_id_add_string(&ctx, "b/");
6403 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6405 if (p->one->mode == 0) {
6406 patch_id_add_string(&ctx, "newfilemode");
6407 patch_id_add_mode(&ctx, p->two->mode);
6408 } else if (p->two->mode == 0) {
6409 patch_id_add_string(&ctx, "deletedfilemode");
6410 patch_id_add_mode(&ctx, p->one->mode);
6411 } else if (p->one->mode != p->two->mode) {
6412 patch_id_add_string(&ctx, "oldmode");
6413 patch_id_add_mode(&ctx, p->one->mode);
6414 patch_id_add_string(&ctx, "newmode");
6415 patch_id_add_mode(&ctx, p->two->mode);
6418 if (diff_header_only) {
6419 /* don't do anything since we're only populating header info */
6420 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6421 diff_filespec_is_binary(options->repo, p->two)) {
6422 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6423 the_hash_algo->hexsz);
6424 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6425 the_hash_algo->hexsz);
6426 } else {
6427 if (p->one->mode == 0) {
6428 patch_id_add_string(&ctx, "---/dev/null");
6429 patch_id_add_string(&ctx, "+++b/");
6430 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6431 } else if (p->two->mode == 0) {
6432 patch_id_add_string(&ctx, "---a/");
6433 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6434 patch_id_add_string(&ctx, "+++/dev/null");
6435 } else {
6436 patch_id_add_string(&ctx, "---a/");
6437 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6438 patch_id_add_string(&ctx, "+++b/");
6439 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6442 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6443 fill_mmfile(options->repo, &mf2, p->two) < 0)
6444 return error("unable to read files to diff");
6445 xpp.flags = 0;
6446 xecfg.ctxlen = 3;
6447 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6448 if (xdi_diff_outf(&mf1, &mf2, NULL,
6449 patch_id_consume, &data, &xpp, &xecfg))
6450 return error("unable to generate patch-id diff for %s",
6451 p->one->path);
6453 flush_one_hunk(oid, &ctx);
6456 return 0;
6459 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6461 struct diff_queue_struct *q = &diff_queued_diff;
6462 int result = diff_get_patch_id(options, oid, diff_header_only);
6464 diff_free_queue(q);
6465 DIFF_QUEUE_CLEAR(q);
6467 return result;
6470 static int is_summary_empty(const struct diff_queue_struct *q)
6472 int i;
6474 for (i = 0; i < q->nr; i++) {
6475 const struct diff_filepair *p = q->queue[i];
6477 switch (p->status) {
6478 case DIFF_STATUS_DELETED:
6479 case DIFF_STATUS_ADDED:
6480 case DIFF_STATUS_COPIED:
6481 case DIFF_STATUS_RENAMED:
6482 return 0;
6483 default:
6484 if (p->score)
6485 return 0;
6486 if (p->one->mode && p->two->mode &&
6487 p->one->mode != p->two->mode)
6488 return 0;
6489 break;
6492 return 1;
6495 static const char rename_limit_warning[] =
6496 N_("exhaustive rename detection was skipped due to too many files.");
6498 static const char degrade_cc_to_c_warning[] =
6499 N_("only found copies from modified paths due to too many files.");
6501 static const char rename_limit_advice[] =
6502 N_("you may want to set your %s variable to at least "
6503 "%d and retry the command.");
6505 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6507 fflush(stdout);
6508 if (degraded_cc)
6509 warning(_(degrade_cc_to_c_warning));
6510 else if (needed)
6511 warning(_(rename_limit_warning));
6512 else
6513 return;
6514 if (0 < needed)
6515 warning(_(rename_limit_advice), varname, needed);
6518 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6520 struct strset present;
6521 struct diff_queue_struct *q = &diff_queued_diff;
6522 struct hashmap_iter iter;
6523 struct strmap_entry *e;
6524 int i;
6526 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6529 * Find out which paths exist in diff_queued_diff, preferring
6530 * one->path for any pair that has multiple paths.
6532 for (i = 0; i < q->nr; i++) {
6533 struct diff_filepair *p = q->queue[i];
6534 char *path = p->one->path ? p->one->path : p->two->path;
6536 if (strmap_contains(o->additional_path_headers, path))
6537 strset_add(&present, path);
6541 * Loop over paths in additional_path_headers; for each NOT already
6542 * in diff_queued_diff, create a synthetic filepair and insert that
6543 * into diff_queued_diff.
6545 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6546 if (!strset_contains(&present, e->key)) {
6547 struct diff_filespec *one, *two;
6548 struct diff_filepair *p;
6550 one = alloc_filespec(e->key);
6551 two = alloc_filespec(e->key);
6552 fill_filespec(one, null_oid(), 0, 0);
6553 fill_filespec(two, null_oid(), 0, 0);
6554 p = diff_queue(q, one, two);
6555 p->status = DIFF_STATUS_MODIFIED;
6559 /* Re-sort the filepairs */
6560 diffcore_fix_diff_index();
6562 /* Cleanup */
6563 strset_clear(&present);
6566 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6568 int i;
6569 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6570 struct diff_queue_struct *q = &diff_queued_diff;
6572 if (WSEH_NEW & WS_RULE_MASK)
6573 BUG("WS rules bit mask overlaps with diff symbol flags");
6575 if (o->color_moved)
6576 o->emitted_symbols = &esm;
6578 if (o->additional_path_headers)
6579 create_filepairs_for_header_only_notifications(o);
6581 for (i = 0; i < q->nr; i++) {
6582 struct diff_filepair *p = q->queue[i];
6583 if (check_pair_status(p))
6584 diff_flush_patch(p, o);
6587 if (o->emitted_symbols) {
6588 if (o->color_moved) {
6589 struct mem_pool entry_pool;
6590 struct moved_entry_list *entry_list;
6592 mem_pool_init(&entry_pool, 1024 * 1024);
6593 entry_list = add_lines_to_move_detection(o,
6594 &entry_pool);
6595 mark_color_as_moved(o, entry_list);
6596 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6597 dim_moved_lines(o);
6599 mem_pool_discard(&entry_pool, 0);
6600 free(entry_list);
6603 for (i = 0; i < esm.nr; i++)
6604 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6606 for (i = 0; i < esm.nr; i++)
6607 free((void *)esm.buf[i].line);
6608 esm.nr = 0;
6610 o->emitted_symbols = NULL;
6614 static void diff_free_file(struct diff_options *options)
6616 if (options->close_file)
6617 fclose(options->file);
6620 static void diff_free_ignore_regex(struct diff_options *options)
6622 int i;
6624 for (i = 0; i < options->ignore_regex_nr; i++) {
6625 regfree(options->ignore_regex[i]);
6626 free(options->ignore_regex[i]);
6628 free(options->ignore_regex);
6631 void diff_free(struct diff_options *options)
6633 if (options->no_free)
6634 return;
6636 diff_free_file(options);
6637 diff_free_ignore_regex(options);
6638 clear_pathspec(&options->pathspec);
6641 void diff_flush(struct diff_options *options)
6643 struct diff_queue_struct *q = &diff_queued_diff;
6644 int i, output_format = options->output_format;
6645 int separator = 0;
6646 int dirstat_by_line = 0;
6649 * Order: raw, stat, summary, patch
6650 * or: name/name-status/checkdiff (other bits clear)
6652 if (!q->nr && !options->additional_path_headers)
6653 goto free_queue;
6655 if (output_format & (DIFF_FORMAT_RAW |
6656 DIFF_FORMAT_NAME |
6657 DIFF_FORMAT_NAME_STATUS |
6658 DIFF_FORMAT_CHECKDIFF)) {
6659 for (i = 0; i < q->nr; i++) {
6660 struct diff_filepair *p = q->queue[i];
6661 if (check_pair_status(p))
6662 flush_one_pair(p, options);
6664 separator++;
6667 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6668 dirstat_by_line = 1;
6670 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6671 dirstat_by_line) {
6672 struct diffstat_t diffstat;
6674 compute_diffstat(options, &diffstat, q);
6675 if (output_format & DIFF_FORMAT_NUMSTAT)
6676 show_numstat(&diffstat, options);
6677 if (output_format & DIFF_FORMAT_DIFFSTAT)
6678 show_stats(&diffstat, options);
6679 if (output_format & DIFF_FORMAT_SHORTSTAT)
6680 show_shortstats(&diffstat, options);
6681 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6682 show_dirstat_by_line(&diffstat, options);
6683 free_diffstat_info(&diffstat);
6684 separator++;
6686 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6687 show_dirstat(options);
6689 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6690 for (i = 0; i < q->nr; i++) {
6691 diff_summary(options, q->queue[i]);
6693 separator++;
6696 if (output_format & DIFF_FORMAT_PATCH) {
6697 if (separator) {
6698 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6699 if (options->stat_sep)
6700 /* attach patch instead of inline */
6701 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6702 NULL, 0, 0);
6705 diff_flush_patch_all_file_pairs(options);
6708 if (output_format & DIFF_FORMAT_CALLBACK)
6709 options->format_callback(q, options, options->format_callback_data);
6711 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6712 options->flags.exit_with_status &&
6713 options->flags.diff_from_contents) {
6715 * run diff_flush_patch for the exit status. setting
6716 * options->file to /dev/null should be safe, because we
6717 * aren't supposed to produce any output anyway.
6719 diff_free_file(options);
6720 options->file = xfopen("/dev/null", "w");
6721 options->close_file = 1;
6722 options->color_moved = 0;
6723 for (i = 0; i < q->nr; i++) {
6724 struct diff_filepair *p = q->queue[i];
6725 if (check_pair_status(p))
6726 diff_flush_patch(p, options);
6727 if (options->found_changes)
6728 break;
6732 free_queue:
6733 diff_free_queue(q);
6734 DIFF_QUEUE_CLEAR(q);
6735 diff_free(options);
6738 * Report the content-level differences with HAS_CHANGES;
6739 * diff_addremove/diff_change does not set the bit when
6740 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6742 if (options->flags.diff_from_contents) {
6743 if (options->found_changes)
6744 options->flags.has_changes = 1;
6745 else
6746 options->flags.has_changes = 0;
6750 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6752 return (((p->status == DIFF_STATUS_MODIFIED) &&
6753 ((p->score &&
6754 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6755 (!p->score &&
6756 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6757 ((p->status != DIFF_STATUS_MODIFIED) &&
6758 filter_bit_tst(p->status, options)));
6761 static void diffcore_apply_filter(struct diff_options *options)
6763 int i;
6764 struct diff_queue_struct *q = &diff_queued_diff;
6765 struct diff_queue_struct outq;
6767 DIFF_QUEUE_CLEAR(&outq);
6769 if (!options->filter)
6770 return;
6772 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6773 int found;
6774 for (i = found = 0; !found && i < q->nr; i++) {
6775 if (match_filter(options, q->queue[i]))
6776 found++;
6778 if (found)
6779 return;
6781 /* otherwise we will clear the whole queue
6782 * by copying the empty outq at the end of this
6783 * function, but first clear the current entries
6784 * in the queue.
6786 for (i = 0; i < q->nr; i++)
6787 diff_free_filepair(q->queue[i]);
6789 else {
6790 /* Only the matching ones */
6791 for (i = 0; i < q->nr; i++) {
6792 struct diff_filepair *p = q->queue[i];
6793 if (match_filter(options, p))
6794 diff_q(&outq, p);
6795 else
6796 diff_free_filepair(p);
6799 free(q->queue);
6800 *q = outq;
6803 /* Check whether two filespecs with the same mode and size are identical */
6804 static int diff_filespec_is_identical(struct repository *r,
6805 struct diff_filespec *one,
6806 struct diff_filespec *two)
6808 if (S_ISGITLINK(one->mode))
6809 return 0;
6810 if (diff_populate_filespec(r, one, NULL))
6811 return 0;
6812 if (diff_populate_filespec(r, two, NULL))
6813 return 0;
6814 return !memcmp(one->data, two->data, one->size);
6817 static int diff_filespec_check_stat_unmatch(struct repository *r,
6818 struct diff_filepair *p)
6820 struct diff_populate_filespec_options dpf_options = {
6821 .check_size_only = 1,
6822 .missing_object_cb = diff_queued_diff_prefetch,
6823 .missing_object_data = r,
6826 if (p->done_skip_stat_unmatch)
6827 return p->skip_stat_unmatch_result;
6829 p->done_skip_stat_unmatch = 1;
6830 p->skip_stat_unmatch_result = 0;
6832 * 1. Entries that come from stat info dirtiness
6833 * always have both sides (iow, not create/delete),
6834 * one side of the object name is unknown, with
6835 * the same mode and size. Keep the ones that
6836 * do not match these criteria. They have real
6837 * differences.
6839 * 2. At this point, the file is known to be modified,
6840 * with the same mode and size, and the object
6841 * name of one side is unknown. Need to inspect
6842 * the identical contents.
6844 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6845 !DIFF_FILE_VALID(p->two) ||
6846 (p->one->oid_valid && p->two->oid_valid) ||
6847 (p->one->mode != p->two->mode) ||
6848 diff_populate_filespec(r, p->one, &dpf_options) ||
6849 diff_populate_filespec(r, p->two, &dpf_options) ||
6850 (p->one->size != p->two->size) ||
6851 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6852 p->skip_stat_unmatch_result = 1;
6853 return p->skip_stat_unmatch_result;
6856 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6858 int i;
6859 struct diff_queue_struct *q = &diff_queued_diff;
6860 struct diff_queue_struct outq;
6861 DIFF_QUEUE_CLEAR(&outq);
6863 for (i = 0; i < q->nr; i++) {
6864 struct diff_filepair *p = q->queue[i];
6866 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6867 diff_q(&outq, p);
6868 else {
6870 * The caller can subtract 1 from skip_stat_unmatch
6871 * to determine how many paths were dirty only
6872 * due to stat info mismatch.
6874 if (!diffopt->flags.no_index)
6875 diffopt->skip_stat_unmatch++;
6876 diff_free_filepair(p);
6879 free(q->queue);
6880 *q = outq;
6883 static int diffnamecmp(const void *a_, const void *b_)
6885 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6886 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6887 const char *name_a, *name_b;
6889 name_a = a->one ? a->one->path : a->two->path;
6890 name_b = b->one ? b->one->path : b->two->path;
6891 return strcmp(name_a, name_b);
6894 void diffcore_fix_diff_index(void)
6896 struct diff_queue_struct *q = &diff_queued_diff;
6897 QSORT(q->queue, q->nr, diffnamecmp);
6900 void diff_add_if_missing(struct repository *r,
6901 struct oid_array *to_fetch,
6902 const struct diff_filespec *filespec)
6904 if (filespec && filespec->oid_valid &&
6905 !S_ISGITLINK(filespec->mode) &&
6906 oid_object_info_extended(r, &filespec->oid, NULL,
6907 OBJECT_INFO_FOR_PREFETCH))
6908 oid_array_append(to_fetch, &filespec->oid);
6911 void diff_queued_diff_prefetch(void *repository)
6913 struct repository *repo = repository;
6914 int i;
6915 struct diff_queue_struct *q = &diff_queued_diff;
6916 struct oid_array to_fetch = OID_ARRAY_INIT;
6918 for (i = 0; i < q->nr; i++) {
6919 struct diff_filepair *p = q->queue[i];
6920 diff_add_if_missing(repo, &to_fetch, p->one);
6921 diff_add_if_missing(repo, &to_fetch, p->two);
6925 * NEEDSWORK: Consider deduplicating the OIDs sent.
6927 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6929 oid_array_clear(&to_fetch);
6932 void diffcore_std(struct diff_options *options)
6934 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6935 DIFF_FORMAT_NUMSTAT |
6936 DIFF_FORMAT_PATCH |
6937 DIFF_FORMAT_SHORTSTAT |
6938 DIFF_FORMAT_DIRSTAT;
6941 * Check if the user requested a blob-data-requiring diff output and/or
6942 * break-rewrite detection (which requires blob data). If yes, prefetch
6943 * the diff pairs.
6945 * If no prefetching occurs, diffcore_rename() will prefetch if it
6946 * decides that it needs inexact rename detection.
6948 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6949 (options->output_format & output_formats_to_prefetch ||
6950 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6951 diff_queued_diff_prefetch(options->repo);
6953 /* NOTE please keep the following in sync with diff_tree_combined() */
6954 if (options->skip_stat_unmatch)
6955 diffcore_skip_stat_unmatch(options);
6956 if (!options->found_follow) {
6957 /* See try_to_follow_renames() in tree-diff.c */
6958 if (options->break_opt != -1)
6959 diffcore_break(options->repo,
6960 options->break_opt);
6961 if (options->detect_rename)
6962 diffcore_rename(options);
6963 if (options->break_opt != -1)
6964 diffcore_merge_broken();
6966 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6967 diffcore_pickaxe(options);
6968 if (options->orderfile)
6969 diffcore_order(options->orderfile);
6970 if (options->rotate_to)
6971 diffcore_rotate(options);
6972 if (!options->found_follow)
6973 /* See try_to_follow_renames() in tree-diff.c */
6974 diff_resolve_rename_copy();
6975 diffcore_apply_filter(options);
6977 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6978 options->flags.has_changes = 1;
6979 else
6980 options->flags.has_changes = 0;
6982 options->found_follow = 0;
6985 int diff_result_code(struct diff_options *opt)
6987 int result = 0;
6989 diff_warn_rename_limit("diff.renameLimit",
6990 opt->needed_rename_limit,
6991 opt->degraded_cc_to_c);
6993 if (opt->flags.exit_with_status &&
6994 opt->flags.has_changes)
6995 result |= 01;
6996 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6997 opt->flags.check_failed)
6998 result |= 02;
6999 return result;
7002 int diff_can_quit_early(struct diff_options *opt)
7004 return (opt->flags.quick &&
7005 !opt->filter &&
7006 opt->flags.has_changes);
7010 * Shall changes to this submodule be ignored?
7012 * Submodule changes can be configured to be ignored separately for each path,
7013 * but that configuration can be overridden from the command line.
7015 static int is_submodule_ignored(const char *path, struct diff_options *options)
7017 int ignored = 0;
7018 struct diff_flags orig_flags = options->flags;
7019 if (!options->flags.override_submodule_config)
7020 set_diffopt_flags_from_submodule_config(options, path);
7021 if (options->flags.ignore_submodules)
7022 ignored = 1;
7023 options->flags = orig_flags;
7024 return ignored;
7027 void compute_diffstat(struct diff_options *options,
7028 struct diffstat_t *diffstat,
7029 struct diff_queue_struct *q)
7031 int i;
7033 memset(diffstat, 0, sizeof(struct diffstat_t));
7034 for (i = 0; i < q->nr; i++) {
7035 struct diff_filepair *p = q->queue[i];
7036 if (check_pair_status(p))
7037 diff_flush_stat(p, options, diffstat);
7039 options->found_changes = !!diffstat->nr;
7042 void diff_addremove(struct diff_options *options,
7043 int addremove, unsigned mode,
7044 const struct object_id *oid,
7045 int oid_valid,
7046 const char *concatpath, unsigned dirty_submodule)
7048 struct diff_filespec *one, *two;
7050 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7051 return;
7053 /* This may look odd, but it is a preparation for
7054 * feeding "there are unchanged files which should
7055 * not produce diffs, but when you are doing copy
7056 * detection you would need them, so here they are"
7057 * entries to the diff-core. They will be prefixed
7058 * with something like '=' or '*' (I haven't decided
7059 * which but should not make any difference).
7060 * Feeding the same new and old to diff_change()
7061 * also has the same effect.
7062 * Before the final output happens, they are pruned after
7063 * merged into rename/copy pairs as appropriate.
7065 if (options->flags.reverse_diff)
7066 addremove = (addremove == '+' ? '-' :
7067 addremove == '-' ? '+' : addremove);
7069 if (options->prefix &&
7070 strncmp(concatpath, options->prefix, options->prefix_length))
7071 return;
7073 one = alloc_filespec(concatpath);
7074 two = alloc_filespec(concatpath);
7076 if (addremove != '+')
7077 fill_filespec(one, oid, oid_valid, mode);
7078 if (addremove != '-') {
7079 fill_filespec(two, oid, oid_valid, mode);
7080 two->dirty_submodule = dirty_submodule;
7083 diff_queue(&diff_queued_diff, one, two);
7084 if (!options->flags.diff_from_contents)
7085 options->flags.has_changes = 1;
7088 void diff_change(struct diff_options *options,
7089 unsigned old_mode, unsigned new_mode,
7090 const struct object_id *old_oid,
7091 const struct object_id *new_oid,
7092 int old_oid_valid, int new_oid_valid,
7093 const char *concatpath,
7094 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7096 struct diff_filespec *one, *two;
7097 struct diff_filepair *p;
7099 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7100 is_submodule_ignored(concatpath, options))
7101 return;
7103 if (options->flags.reverse_diff) {
7104 SWAP(old_mode, new_mode);
7105 SWAP(old_oid, new_oid);
7106 SWAP(old_oid_valid, new_oid_valid);
7107 SWAP(old_dirty_submodule, new_dirty_submodule);
7110 if (options->prefix &&
7111 strncmp(concatpath, options->prefix, options->prefix_length))
7112 return;
7114 one = alloc_filespec(concatpath);
7115 two = alloc_filespec(concatpath);
7116 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7117 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7118 one->dirty_submodule = old_dirty_submodule;
7119 two->dirty_submodule = new_dirty_submodule;
7120 p = diff_queue(&diff_queued_diff, one, two);
7122 if (options->flags.diff_from_contents)
7123 return;
7125 if (options->flags.quick && options->skip_stat_unmatch &&
7126 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7127 diff_free_filespec_data(p->one);
7128 diff_free_filespec_data(p->two);
7129 return;
7132 options->flags.has_changes = 1;
7135 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7137 struct diff_filepair *pair;
7138 struct diff_filespec *one, *two;
7140 if (options->prefix &&
7141 strncmp(path, options->prefix, options->prefix_length))
7142 return NULL;
7144 one = alloc_filespec(path);
7145 two = alloc_filespec(path);
7146 pair = diff_queue(&diff_queued_diff, one, two);
7147 pair->is_unmerged = 1;
7148 return pair;
7151 static char *run_textconv(struct repository *r,
7152 const char *pgm,
7153 struct diff_filespec *spec,
7154 size_t *outsize)
7156 struct diff_tempfile *temp;
7157 struct child_process child = CHILD_PROCESS_INIT;
7158 struct strbuf buf = STRBUF_INIT;
7159 int err = 0;
7161 temp = prepare_temp_file(r, spec);
7162 strvec_push(&child.args, pgm);
7163 strvec_push(&child.args, temp->name);
7165 child.use_shell = 1;
7166 child.out = -1;
7167 if (start_command(&child)) {
7168 remove_tempfile();
7169 return NULL;
7172 if (strbuf_read(&buf, child.out, 0) < 0)
7173 err = error("error reading from textconv command '%s'", pgm);
7174 close(child.out);
7176 if (finish_command(&child) || err) {
7177 strbuf_release(&buf);
7178 remove_tempfile();
7179 return NULL;
7181 remove_tempfile();
7183 return strbuf_detach(&buf, outsize);
7186 size_t fill_textconv(struct repository *r,
7187 struct userdiff_driver *driver,
7188 struct diff_filespec *df,
7189 char **outbuf)
7191 size_t size;
7193 if (!driver) {
7194 if (!DIFF_FILE_VALID(df)) {
7195 *outbuf = "";
7196 return 0;
7198 if (diff_populate_filespec(r, df, NULL))
7199 die("unable to read files to diff");
7200 *outbuf = df->data;
7201 return df->size;
7204 if (!driver->textconv)
7205 BUG("fill_textconv called with non-textconv driver");
7207 if (driver->textconv_cache && df->oid_valid) {
7208 *outbuf = notes_cache_get(driver->textconv_cache,
7209 &df->oid,
7210 &size);
7211 if (*outbuf)
7212 return size;
7215 *outbuf = run_textconv(r, driver->textconv, df, &size);
7216 if (!*outbuf)
7217 die("unable to read files to diff");
7219 if (driver->textconv_cache && df->oid_valid) {
7220 /* ignore errors, as we might be in a readonly repository */
7221 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7222 size);
7224 * we could save up changes and flush them all at the end,
7225 * but we would need an extra call after all diffing is done.
7226 * Since generating a cache entry is the slow path anyway,
7227 * this extra overhead probably isn't a big deal.
7229 notes_cache_write(driver->textconv_cache);
7232 return size;
7235 int textconv_object(struct repository *r,
7236 const char *path,
7237 unsigned mode,
7238 const struct object_id *oid,
7239 int oid_valid,
7240 char **buf,
7241 unsigned long *buf_size)
7243 struct diff_filespec *df;
7244 struct userdiff_driver *textconv;
7246 df = alloc_filespec(path);
7247 fill_filespec(df, oid, oid_valid, mode);
7248 textconv = get_textconv(r, df);
7249 if (!textconv) {
7250 free_filespec(df);
7251 return 0;
7254 *buf_size = fill_textconv(r, textconv, df, buf);
7255 free_filespec(df);
7256 return 1;
7259 void setup_diff_pager(struct diff_options *opt)
7262 * If the user asked for our exit code, then either they want --quiet
7263 * or --exit-code. We should definitely not bother with a pager in the
7264 * former case, as we will generate no output. Since we still properly
7265 * report our exit code even when a pager is run, we _could_ run a
7266 * pager with --exit-code. But since we have not done so historically,
7267 * and because it is easy to find people oneline advising "git diff
7268 * --exit-code" in hooks and other scripts, we do not do so.
7270 if (!opt->flags.exit_with_status &&
7271 check_pager_config("diff") != 0)
7272 setup_pager();