t1502, docs: disallow --no-help
[git/gitster.git] / diff.c
blobee3eb629e3dc5e3010342ed988678d9f0cedd0bd
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 must_show_header = 1;
3568 else if (lbl[1][0] == '/') {
3569 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3570 if (xfrm_msg)
3571 strbuf_addstr(&header, xfrm_msg);
3572 must_show_header = 1;
3574 else {
3575 if (one->mode != two->mode) {
3576 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3577 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3578 must_show_header = 1;
3580 if (xfrm_msg)
3581 strbuf_addstr(&header, xfrm_msg);
3584 * we do not run diff between different kind
3585 * of objects.
3587 if ((one->mode ^ two->mode) & S_IFMT)
3588 goto free_ab_and_return;
3589 if (complete_rewrite &&
3590 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3591 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3592 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3593 header.buf, header.len, 0);
3594 strbuf_reset(&header);
3595 emit_rewrite_diff(name_a, name_b, one, two,
3596 textconv_one, textconv_two, o);
3597 o->found_changes = 1;
3598 goto free_ab_and_return;
3602 if (o->irreversible_delete && lbl[1][0] == '/') {
3603 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3604 header.len, 0);
3605 strbuf_reset(&header);
3606 goto free_ab_and_return;
3607 } else if (!o->flags.text &&
3608 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3609 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3610 struct strbuf sb = STRBUF_INIT;
3611 if (!one->data && !two->data &&
3612 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3613 !o->flags.binary) {
3614 if (oideq(&one->oid, &two->oid)) {
3615 if (must_show_header)
3616 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3617 header.buf, header.len,
3619 goto free_ab_and_return;
3621 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3622 header.buf, header.len, 0);
3623 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3624 diff_line_prefix(o), lbl[0], lbl[1]);
3625 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3626 sb.buf, sb.len, 0);
3627 strbuf_release(&sb);
3628 goto free_ab_and_return;
3630 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3631 fill_mmfile(o->repo, &mf2, two) < 0)
3632 die("unable to read files to diff");
3633 /* Quite common confusing case */
3634 if (mf1.size == mf2.size &&
3635 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3636 if (must_show_header)
3637 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3638 header.buf, header.len, 0);
3639 goto free_ab_and_return;
3641 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3642 strbuf_reset(&header);
3643 if (o->flags.binary)
3644 emit_binary_diff(o, &mf1, &mf2);
3645 else {
3646 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3647 diff_line_prefix(o), lbl[0], lbl[1]);
3648 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3649 sb.buf, sb.len, 0);
3650 strbuf_release(&sb);
3652 o->found_changes = 1;
3653 } else {
3654 /* Crazy xdl interfaces.. */
3655 const char *diffopts;
3656 const char *v;
3657 xpparam_t xpp;
3658 xdemitconf_t xecfg;
3659 struct emit_callback ecbdata;
3660 const struct userdiff_funcname *pe;
3662 if (must_show_header) {
3663 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3664 header.buf, header.len, 0);
3665 strbuf_reset(&header);
3668 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3669 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3671 pe = diff_funcname_pattern(o, one);
3672 if (!pe)
3673 pe = diff_funcname_pattern(o, two);
3675 memset(&xpp, 0, sizeof(xpp));
3676 memset(&xecfg, 0, sizeof(xecfg));
3677 memset(&ecbdata, 0, sizeof(ecbdata));
3678 if (o->flags.suppress_diff_headers)
3679 lbl[0] = NULL;
3680 ecbdata.label_path = lbl;
3681 ecbdata.color_diff = want_color(o->use_color);
3682 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3683 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3684 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3685 ecbdata.opt = o;
3686 if (header.len && !o->flags.suppress_diff_headers)
3687 ecbdata.header = &header;
3688 xpp.flags = o->xdl_opts;
3689 xpp.ignore_regex = o->ignore_regex;
3690 xpp.ignore_regex_nr = o->ignore_regex_nr;
3691 xpp.anchors = o->anchors;
3692 xpp.anchors_nr = o->anchors_nr;
3693 xecfg.ctxlen = o->context;
3694 xecfg.interhunkctxlen = o->interhunkcontext;
3695 xecfg.flags = XDL_EMIT_FUNCNAMES;
3696 if (o->flags.funccontext)
3697 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3698 if (pe)
3699 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3701 diffopts = getenv("GIT_DIFF_OPTS");
3702 if (!diffopts)
3704 else if (skip_prefix(diffopts, "--unified=", &v))
3705 xecfg.ctxlen = strtoul(v, NULL, 10);
3706 else if (skip_prefix(diffopts, "-u", &v))
3707 xecfg.ctxlen = strtoul(v, NULL, 10);
3709 if (o->word_diff)
3710 init_diff_words_data(&ecbdata, o, one, two);
3711 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3712 &ecbdata, &xpp, &xecfg))
3713 die("unable to generate diff for %s", one->path);
3714 if (o->word_diff)
3715 free_diff_words_data(&ecbdata);
3716 if (textconv_one)
3717 free(mf1.ptr);
3718 if (textconv_two)
3719 free(mf2.ptr);
3720 xdiff_clear_find_func(&xecfg);
3723 free_ab_and_return:
3724 strbuf_release(&header);
3725 diff_free_filespec_data(one);
3726 diff_free_filespec_data(two);
3727 free(a_one);
3728 free(b_two);
3729 return;
3732 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3734 if (!is_renamed) {
3735 if (p->status == DIFF_STATUS_ADDED) {
3736 if (S_ISLNK(p->two->mode))
3737 return "new +l";
3738 else if ((p->two->mode & 0777) == 0755)
3739 return "new +x";
3740 else
3741 return "new";
3742 } else if (p->status == DIFF_STATUS_DELETED)
3743 return "gone";
3745 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3746 return "mode -l";
3747 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3748 return "mode +l";
3749 else if ((p->one->mode & 0777) == 0644 &&
3750 (p->two->mode & 0777) == 0755)
3751 return "mode +x";
3752 else if ((p->one->mode & 0777) == 0755 &&
3753 (p->two->mode & 0777) == 0644)
3754 return "mode -x";
3755 return NULL;
3758 static void builtin_diffstat(const char *name_a, const char *name_b,
3759 struct diff_filespec *one,
3760 struct diff_filespec *two,
3761 struct diffstat_t *diffstat,
3762 struct diff_options *o,
3763 struct diff_filepair *p)
3765 mmfile_t mf1, mf2;
3766 struct diffstat_file *data;
3767 int may_differ;
3768 int complete_rewrite = 0;
3770 if (!DIFF_PAIR_UNMERGED(p)) {
3771 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3772 complete_rewrite = 1;
3775 data = diffstat_add(diffstat, name_a, name_b);
3776 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3777 if (o->flags.stat_with_summary)
3778 data->comments = get_compact_summary(p, data->is_renamed);
3780 if (!one || !two) {
3781 data->is_unmerged = 1;
3782 return;
3785 /* saves some reads if true, not a guarantee of diff outcome */
3786 may_differ = !(one->oid_valid && two->oid_valid &&
3787 oideq(&one->oid, &two->oid));
3789 if (diff_filespec_is_binary(o->repo, one) ||
3790 diff_filespec_is_binary(o->repo, two)) {
3791 data->is_binary = 1;
3792 if (!may_differ) {
3793 data->added = 0;
3794 data->deleted = 0;
3795 } else {
3796 data->added = diff_filespec_size(o->repo, two);
3797 data->deleted = diff_filespec_size(o->repo, one);
3801 else if (complete_rewrite) {
3802 diff_populate_filespec(o->repo, one, NULL);
3803 diff_populate_filespec(o->repo, two, NULL);
3804 data->deleted = count_lines(one->data, one->size);
3805 data->added = count_lines(two->data, two->size);
3808 else if (may_differ) {
3809 /* Crazy xdl interfaces.. */
3810 xpparam_t xpp;
3811 xdemitconf_t xecfg;
3813 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3814 fill_mmfile(o->repo, &mf2, two) < 0)
3815 die("unable to read files to diff");
3817 memset(&xpp, 0, sizeof(xpp));
3818 memset(&xecfg, 0, sizeof(xecfg));
3819 xpp.flags = o->xdl_opts;
3820 xpp.ignore_regex = o->ignore_regex;
3821 xpp.ignore_regex_nr = o->ignore_regex_nr;
3822 xpp.anchors = o->anchors;
3823 xpp.anchors_nr = o->anchors_nr;
3824 xecfg.ctxlen = o->context;
3825 xecfg.interhunkctxlen = o->interhunkcontext;
3826 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3827 if (xdi_diff_outf(&mf1, &mf2, NULL,
3828 diffstat_consume, diffstat, &xpp, &xecfg))
3829 die("unable to generate diffstat for %s", one->path);
3831 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3832 struct diffstat_file *file =
3833 diffstat->files[diffstat->nr - 1];
3835 * Omit diffstats of modified files where nothing changed.
3836 * Even if may_differ, this might be the case due to
3837 * ignoring whitespace changes, etc.
3839 * But note that we special-case additions, deletions,
3840 * renames, and mode changes as adding an empty file,
3841 * for example is still of interest.
3843 if ((p->status == DIFF_STATUS_MODIFIED)
3844 && !file->added
3845 && !file->deleted
3846 && one->mode == two->mode) {
3847 free_diffstat_file(file);
3848 diffstat->nr--;
3853 diff_free_filespec_data(one);
3854 diff_free_filespec_data(two);
3857 static void builtin_checkdiff(const char *name_a, const char *name_b,
3858 const char *attr_path,
3859 struct diff_filespec *one,
3860 struct diff_filespec *two,
3861 struct diff_options *o)
3863 mmfile_t mf1, mf2;
3864 struct checkdiff_t data;
3866 if (!two)
3867 return;
3869 memset(&data, 0, sizeof(data));
3870 data.filename = name_b ? name_b : name_a;
3871 data.lineno = 0;
3872 data.o = o;
3873 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3874 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3876 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3877 fill_mmfile(o->repo, &mf2, two) < 0)
3878 die("unable to read files to diff");
3881 * All the other codepaths check both sides, but not checking
3882 * the "old" side here is deliberate. We are checking the newly
3883 * introduced changes, and as long as the "new" side is text, we
3884 * can and should check what it introduces.
3886 if (diff_filespec_is_binary(o->repo, two))
3887 goto free_and_return;
3888 else {
3889 /* Crazy xdl interfaces.. */
3890 xpparam_t xpp;
3891 xdemitconf_t xecfg;
3893 memset(&xpp, 0, sizeof(xpp));
3894 memset(&xecfg, 0, sizeof(xecfg));
3895 xecfg.ctxlen = 1; /* at least one context line */
3896 xpp.flags = 0;
3897 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3898 checkdiff_consume, &data,
3899 &xpp, &xecfg))
3900 die("unable to generate checkdiff for %s", one->path);
3902 if (data.ws_rule & WS_BLANK_AT_EOF) {
3903 struct emit_callback ecbdata;
3904 int blank_at_eof;
3906 ecbdata.ws_rule = data.ws_rule;
3907 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3908 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3910 if (blank_at_eof) {
3911 static char *err;
3912 if (!err)
3913 err = whitespace_error_string(WS_BLANK_AT_EOF);
3914 fprintf(o->file, "%s:%d: %s.\n",
3915 data.filename, blank_at_eof, err);
3916 data.status = 1; /* report errors */
3920 free_and_return:
3921 diff_free_filespec_data(one);
3922 diff_free_filespec_data(two);
3923 if (data.status)
3924 o->flags.check_failed = 1;
3927 struct diff_filespec *alloc_filespec(const char *path)
3929 struct diff_filespec *spec;
3931 FLEXPTR_ALLOC_STR(spec, path, path);
3932 spec->count = 1;
3933 spec->is_binary = -1;
3934 return spec;
3937 void free_filespec(struct diff_filespec *spec)
3939 if (!--spec->count) {
3940 diff_free_filespec_data(spec);
3941 free(spec);
3945 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3946 int oid_valid, unsigned short mode)
3948 if (mode) {
3949 spec->mode = canon_mode(mode);
3950 oidcpy(&spec->oid, oid);
3951 spec->oid_valid = oid_valid;
3956 * Given a name and sha1 pair, if the index tells us the file in
3957 * the work tree has that object contents, return true, so that
3958 * prepare_temp_file() does not have to inflate and extract.
3960 static int reuse_worktree_file(struct index_state *istate,
3961 const char *name,
3962 const struct object_id *oid,
3963 int want_file)
3965 const struct cache_entry *ce;
3966 struct stat st;
3967 int pos, len;
3970 * We do not read the cache ourselves here, because the
3971 * benchmark with my previous version that always reads cache
3972 * shows that it makes things worse for diff-tree comparing
3973 * two linux-2.6 kernel trees in an already checked out work
3974 * tree. This is because most diff-tree comparisons deal with
3975 * only a small number of files, while reading the cache is
3976 * expensive for a large project, and its cost outweighs the
3977 * savings we get by not inflating the object to a temporary
3978 * file. Practically, this code only helps when we are used
3979 * by diff-cache --cached, which does read the cache before
3980 * calling us.
3982 if (!istate->cache)
3983 return 0;
3985 /* We want to avoid the working directory if our caller
3986 * doesn't need the data in a normal file, this system
3987 * is rather slow with its stat/open/mmap/close syscalls,
3988 * and the object is contained in a pack file. The pack
3989 * is probably already open and will be faster to obtain
3990 * the data through than the working directory. Loose
3991 * objects however would tend to be slower as they need
3992 * to be individually opened and inflated.
3994 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3995 return 0;
3998 * Similarly, if we'd have to convert the file contents anyway, that
3999 * makes the optimization not worthwhile.
4001 if (!want_file && would_convert_to_git(istate, name))
4002 return 0;
4005 * If this path does not match our sparse-checkout definition,
4006 * then the file will not be in the working directory.
4008 if (!path_in_sparse_checkout(name, istate))
4009 return 0;
4011 len = strlen(name);
4012 pos = index_name_pos(istate, name, len);
4013 if (pos < 0)
4014 return 0;
4015 ce = istate->cache[pos];
4018 * This is not the sha1 we are looking for, or
4019 * unreusable because it is not a regular file.
4021 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4022 return 0;
4025 * If ce is marked as "assume unchanged", there is no
4026 * guarantee that work tree matches what we are looking for.
4028 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4029 return 0;
4032 * If ce matches the file in the work tree, we can reuse it.
4034 if (ce_uptodate(ce) ||
4035 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4036 return 1;
4038 return 0;
4041 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4043 struct strbuf buf = STRBUF_INIT;
4044 char *dirty = "";
4046 /* Are we looking at the work tree? */
4047 if (s->dirty_submodule)
4048 dirty = "-dirty";
4050 strbuf_addf(&buf, "Subproject commit %s%s\n",
4051 oid_to_hex(&s->oid), dirty);
4052 s->size = buf.len;
4053 if (size_only) {
4054 s->data = NULL;
4055 strbuf_release(&buf);
4056 } else {
4057 s->data = strbuf_detach(&buf, NULL);
4058 s->should_free = 1;
4060 return 0;
4064 * While doing rename detection and pickaxe operation, we may need to
4065 * grab the data for the blob (or file) for our own in-core comparison.
4066 * diff_filespec has data and size fields for this purpose.
4068 int diff_populate_filespec(struct repository *r,
4069 struct diff_filespec *s,
4070 const struct diff_populate_filespec_options *options)
4072 int size_only = options ? options->check_size_only : 0;
4073 int check_binary = options ? options->check_binary : 0;
4074 int err = 0;
4075 int conv_flags = global_conv_flags_eol;
4077 * demote FAIL to WARN to allow inspecting the situation
4078 * instead of refusing.
4080 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4081 conv_flags = CONV_EOL_RNDTRP_WARN;
4083 if (!DIFF_FILE_VALID(s))
4084 die("internal error: asking to populate invalid file.");
4085 if (S_ISDIR(s->mode))
4086 return -1;
4088 if (s->data)
4089 return 0;
4091 if (size_only && 0 < s->size)
4092 return 0;
4094 if (S_ISGITLINK(s->mode))
4095 return diff_populate_gitlink(s, size_only);
4097 if (!s->oid_valid ||
4098 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4099 struct strbuf buf = STRBUF_INIT;
4100 struct stat st;
4101 int fd;
4103 if (lstat(s->path, &st) < 0) {
4104 err_empty:
4105 err = -1;
4106 empty:
4107 s->data = (char *)"";
4108 s->size = 0;
4109 return err;
4111 s->size = xsize_t(st.st_size);
4112 if (!s->size)
4113 goto empty;
4114 if (S_ISLNK(st.st_mode)) {
4115 struct strbuf sb = STRBUF_INIT;
4117 if (strbuf_readlink(&sb, s->path, s->size))
4118 goto err_empty;
4119 s->size = sb.len;
4120 s->data = strbuf_detach(&sb, NULL);
4121 s->should_free = 1;
4122 return 0;
4126 * Even if the caller would be happy with getting
4127 * only the size, we cannot return early at this
4128 * point if the path requires us to run the content
4129 * conversion.
4131 if (size_only && !would_convert_to_git(r->index, s->path))
4132 return 0;
4135 * Note: this check uses xsize_t(st.st_size) that may
4136 * not be the true size of the blob after it goes
4137 * through convert_to_git(). This may not strictly be
4138 * correct, but the whole point of big_file_threshold
4139 * and is_binary check being that we want to avoid
4140 * opening the file and inspecting the contents, this
4141 * is probably fine.
4143 if (check_binary &&
4144 s->size > big_file_threshold && s->is_binary == -1) {
4145 s->is_binary = 1;
4146 return 0;
4148 fd = open(s->path, O_RDONLY);
4149 if (fd < 0)
4150 goto err_empty;
4151 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4152 close(fd);
4153 s->should_munmap = 1;
4156 * Convert from working tree format to canonical git format
4158 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4159 size_t size = 0;
4160 munmap(s->data, s->size);
4161 s->should_munmap = 0;
4162 s->data = strbuf_detach(&buf, &size);
4163 s->size = size;
4164 s->should_free = 1;
4167 else {
4168 struct object_info info = {
4169 .sizep = &s->size
4172 if (!(size_only || check_binary))
4174 * Set contentp, since there is no chance that merely
4175 * the size is sufficient.
4177 info.contentp = &s->data;
4179 if (options && options->missing_object_cb) {
4180 if (!oid_object_info_extended(r, &s->oid, &info,
4181 OBJECT_INFO_LOOKUP_REPLACE |
4182 OBJECT_INFO_SKIP_FETCH_OBJECT))
4183 goto object_read;
4184 options->missing_object_cb(options->missing_object_data);
4186 if (oid_object_info_extended(r, &s->oid, &info,
4187 OBJECT_INFO_LOOKUP_REPLACE))
4188 die("unable to read %s", oid_to_hex(&s->oid));
4190 object_read:
4191 if (size_only || check_binary) {
4192 if (size_only)
4193 return 0;
4194 if (s->size > big_file_threshold && s->is_binary == -1) {
4195 s->is_binary = 1;
4196 return 0;
4199 if (!info.contentp) {
4200 info.contentp = &s->data;
4201 if (oid_object_info_extended(r, &s->oid, &info,
4202 OBJECT_INFO_LOOKUP_REPLACE))
4203 die("unable to read %s", oid_to_hex(&s->oid));
4205 s->should_free = 1;
4207 return 0;
4210 void diff_free_filespec_blob(struct diff_filespec *s)
4212 if (s->should_free)
4213 free(s->data);
4214 else if (s->should_munmap)
4215 munmap(s->data, s->size);
4217 if (s->should_free || s->should_munmap) {
4218 s->should_free = s->should_munmap = 0;
4219 s->data = NULL;
4223 void diff_free_filespec_data(struct diff_filespec *s)
4225 if (!s)
4226 return;
4228 diff_free_filespec_blob(s);
4229 FREE_AND_NULL(s->cnt_data);
4232 static void prep_temp_blob(struct index_state *istate,
4233 const char *path, struct diff_tempfile *temp,
4234 void *blob,
4235 unsigned long size,
4236 const struct object_id *oid,
4237 int mode)
4239 struct strbuf buf = STRBUF_INIT;
4240 char *path_dup = xstrdup(path);
4241 const char *base = basename(path_dup);
4242 struct checkout_metadata meta;
4244 init_checkout_metadata(&meta, NULL, NULL, oid);
4246 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4247 if (!temp->tempfile)
4248 die_errno("unable to create temp-file");
4249 if (convert_to_working_tree(istate, path,
4250 (const char *)blob, (size_t)size, &buf, &meta)) {
4251 blob = buf.buf;
4252 size = buf.len;
4254 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4255 close_tempfile_gently(temp->tempfile))
4256 die_errno("unable to write temp-file");
4257 temp->name = get_tempfile_path(temp->tempfile);
4258 oid_to_hex_r(temp->hex, oid);
4259 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4260 strbuf_release(&buf);
4261 free(path_dup);
4264 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4265 struct diff_filespec *one)
4267 struct diff_tempfile *temp = claim_diff_tempfile();
4269 if (!DIFF_FILE_VALID(one)) {
4270 not_a_valid_file:
4271 /* A '-' entry produces this for file-2, and
4272 * a '+' entry produces this for file-1.
4274 temp->name = "/dev/null";
4275 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4276 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4277 return temp;
4280 if (!S_ISGITLINK(one->mode) &&
4281 (!one->oid_valid ||
4282 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4283 struct stat st;
4284 if (lstat(one->path, &st) < 0) {
4285 if (errno == ENOENT)
4286 goto not_a_valid_file;
4287 die_errno("stat(%s)", one->path);
4289 if (S_ISLNK(st.st_mode)) {
4290 struct strbuf sb = STRBUF_INIT;
4291 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4292 die_errno("readlink(%s)", one->path);
4293 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4294 (one->oid_valid ?
4295 &one->oid : null_oid()),
4296 (one->oid_valid ?
4297 one->mode : S_IFLNK));
4298 strbuf_release(&sb);
4300 else {
4301 /* we can borrow from the file in the work tree */
4302 temp->name = one->path;
4303 if (!one->oid_valid)
4304 oid_to_hex_r(temp->hex, null_oid());
4305 else
4306 oid_to_hex_r(temp->hex, &one->oid);
4307 /* Even though we may sometimes borrow the
4308 * contents from the work tree, we always want
4309 * one->mode. mode is trustworthy even when
4310 * !(one->oid_valid), as long as
4311 * DIFF_FILE_VALID(one).
4313 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4315 return temp;
4317 else {
4318 if (diff_populate_filespec(r, one, NULL))
4319 die("cannot read data blob for %s", one->path);
4320 prep_temp_blob(r->index, one->path, temp,
4321 one->data, one->size,
4322 &one->oid, one->mode);
4324 return temp;
4327 static void add_external_diff_name(struct repository *r,
4328 struct strvec *argv,
4329 struct diff_filespec *df)
4331 struct diff_tempfile *temp = prepare_temp_file(r, df);
4332 strvec_push(argv, temp->name);
4333 strvec_push(argv, temp->hex);
4334 strvec_push(argv, temp->mode);
4337 /* An external diff command takes:
4339 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4340 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4343 static void run_external_diff(const char *pgm,
4344 const char *name,
4345 const char *other,
4346 struct diff_filespec *one,
4347 struct diff_filespec *two,
4348 const char *xfrm_msg,
4349 struct diff_options *o)
4351 struct child_process cmd = CHILD_PROCESS_INIT;
4352 struct diff_queue_struct *q = &diff_queued_diff;
4354 strvec_push(&cmd.args, pgm);
4355 strvec_push(&cmd.args, name);
4357 if (one && two) {
4358 add_external_diff_name(o->repo, &cmd.args, one);
4359 add_external_diff_name(o->repo, &cmd.args, two);
4360 if (other) {
4361 strvec_push(&cmd.args, other);
4362 strvec_push(&cmd.args, xfrm_msg);
4366 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4367 ++o->diff_path_counter);
4368 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4370 diff_free_filespec_data(one);
4371 diff_free_filespec_data(two);
4372 cmd.use_shell = 1;
4373 if (run_command(&cmd))
4374 die(_("external diff died, stopping at %s"), name);
4376 remove_tempfile();
4379 static int similarity_index(struct diff_filepair *p)
4381 return p->score * 100 / MAX_SCORE;
4384 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4386 if (startup_info->have_repository)
4387 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4388 else {
4389 char *hex = oid_to_hex(oid);
4390 if (abbrev < 0)
4391 abbrev = FALLBACK_DEFAULT_ABBREV;
4392 if (abbrev > the_hash_algo->hexsz)
4393 BUG("oid abbreviation out of range: %d", abbrev);
4394 if (abbrev)
4395 hex[abbrev] = '\0';
4396 return hex;
4400 static void fill_metainfo(struct strbuf *msg,
4401 const char *name,
4402 const char *other,
4403 struct diff_filespec *one,
4404 struct diff_filespec *two,
4405 struct diff_options *o,
4406 struct diff_filepair *p,
4407 int *must_show_header,
4408 int use_color)
4410 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4411 const char *reset = diff_get_color(use_color, DIFF_RESET);
4412 const char *line_prefix = diff_line_prefix(o);
4413 struct string_list *more_headers = NULL;
4415 *must_show_header = 1;
4416 strbuf_init(msg, PATH_MAX * 2 + 300);
4417 switch (p->status) {
4418 case DIFF_STATUS_COPIED:
4419 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4420 line_prefix, set, similarity_index(p));
4421 strbuf_addf(msg, "%s\n%s%scopy from ",
4422 reset, line_prefix, set);
4423 quote_c_style(name, msg, NULL, 0);
4424 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4425 quote_c_style(other, msg, NULL, 0);
4426 strbuf_addf(msg, "%s\n", reset);
4427 break;
4428 case DIFF_STATUS_RENAMED:
4429 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4430 line_prefix, set, similarity_index(p));
4431 strbuf_addf(msg, "%s\n%s%srename from ",
4432 reset, line_prefix, set);
4433 quote_c_style(name, msg, NULL, 0);
4434 strbuf_addf(msg, "%s\n%s%srename to ",
4435 reset, line_prefix, set);
4436 quote_c_style(other, msg, NULL, 0);
4437 strbuf_addf(msg, "%s\n", reset);
4438 break;
4439 case DIFF_STATUS_MODIFIED:
4440 if (p->score) {
4441 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4442 line_prefix,
4443 set, similarity_index(p), reset);
4444 break;
4446 /* fallthru */
4447 default:
4448 *must_show_header = 0;
4450 if ((more_headers = additional_headers(o, name))) {
4451 add_formatted_headers(msg, more_headers,
4452 line_prefix, set, reset);
4453 *must_show_header = 1;
4455 if (one && two && !oideq(&one->oid, &two->oid)) {
4456 const unsigned hexsz = the_hash_algo->hexsz;
4457 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4459 if (o->flags.full_index)
4460 abbrev = hexsz;
4462 if (o->flags.binary) {
4463 mmfile_t mf;
4464 if ((!fill_mmfile(o->repo, &mf, one) &&
4465 diff_filespec_is_binary(o->repo, one)) ||
4466 (!fill_mmfile(o->repo, &mf, two) &&
4467 diff_filespec_is_binary(o->repo, two)))
4468 abbrev = hexsz;
4470 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4471 diff_abbrev_oid(&one->oid, abbrev),
4472 diff_abbrev_oid(&two->oid, abbrev));
4473 if (one->mode == two->mode)
4474 strbuf_addf(msg, " %06o", one->mode);
4475 strbuf_addf(msg, "%s\n", reset);
4479 static void run_diff_cmd(const char *pgm,
4480 const char *name,
4481 const char *other,
4482 const char *attr_path,
4483 struct diff_filespec *one,
4484 struct diff_filespec *two,
4485 struct strbuf *msg,
4486 struct diff_options *o,
4487 struct diff_filepair *p)
4489 const char *xfrm_msg = NULL;
4490 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4491 int must_show_header = 0;
4492 struct userdiff_driver *drv = NULL;
4494 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4495 drv = userdiff_find_by_path(o->repo->index, attr_path);
4497 if (o->flags.allow_external && drv && drv->external)
4498 pgm = drv->external;
4500 if (msg) {
4502 * don't use colors when the header is intended for an
4503 * external diff driver
4505 fill_metainfo(msg, name, other, one, two, o, p,
4506 &must_show_header,
4507 want_color(o->use_color) && !pgm);
4508 xfrm_msg = msg->len ? msg->buf : NULL;
4511 if (pgm) {
4512 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4513 return;
4515 if (one && two) {
4516 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4517 set_diff_algorithm(o, drv->algorithm);
4519 builtin_diff(name, other ? other : name,
4520 one, two, xfrm_msg, must_show_header,
4521 o, complete_rewrite);
4522 } else {
4523 fprintf(o->file, "* Unmerged path %s\n", name);
4527 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4529 if (DIFF_FILE_VALID(one)) {
4530 if (!one->oid_valid) {
4531 struct stat st;
4532 if (one->is_stdin) {
4533 oidclr(&one->oid);
4534 return;
4536 if (lstat(one->path, &st) < 0)
4537 die_errno("stat '%s'", one->path);
4538 if (index_path(istate, &one->oid, one->path, &st, 0))
4539 die("cannot hash %s", one->path);
4542 else
4543 oidclr(&one->oid);
4546 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4548 /* Strip the prefix but do not molest /dev/null and absolute paths */
4549 if (*namep && !is_absolute_path(*namep)) {
4550 *namep += prefix_length;
4551 if (**namep == '/')
4552 ++*namep;
4554 if (*otherp && !is_absolute_path(*otherp)) {
4555 *otherp += prefix_length;
4556 if (**otherp == '/')
4557 ++*otherp;
4561 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4563 const char *pgm = external_diff();
4564 struct strbuf msg;
4565 struct diff_filespec *one = p->one;
4566 struct diff_filespec *two = p->two;
4567 const char *name;
4568 const char *other;
4569 const char *attr_path;
4571 name = one->path;
4572 other = (strcmp(name, two->path) ? two->path : NULL);
4573 attr_path = name;
4574 if (o->prefix_length)
4575 strip_prefix(o->prefix_length, &name, &other);
4577 if (!o->flags.allow_external)
4578 pgm = NULL;
4580 if (DIFF_PAIR_UNMERGED(p)) {
4581 run_diff_cmd(pgm, name, NULL, attr_path,
4582 NULL, NULL, NULL, o, p);
4583 return;
4586 diff_fill_oid_info(one, o->repo->index);
4587 diff_fill_oid_info(two, o->repo->index);
4589 if (!pgm &&
4590 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4591 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4593 * a filepair that changes between file and symlink
4594 * needs to be split into deletion and creation.
4596 struct diff_filespec *null = alloc_filespec(two->path);
4597 run_diff_cmd(NULL, name, other, attr_path,
4598 one, null, &msg,
4599 o, p);
4600 free(null);
4601 strbuf_release(&msg);
4603 null = alloc_filespec(one->path);
4604 run_diff_cmd(NULL, name, other, attr_path,
4605 null, two, &msg, o, p);
4606 free(null);
4608 else
4609 run_diff_cmd(pgm, name, other, attr_path,
4610 one, two, &msg, o, p);
4612 strbuf_release(&msg);
4615 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4616 struct diffstat_t *diffstat)
4618 const char *name;
4619 const char *other;
4621 if (!o->ignore_driver_algorithm) {
4622 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4623 p->one->path);
4625 if (drv && drv->algorithm)
4626 set_diff_algorithm(o, drv->algorithm);
4629 if (DIFF_PAIR_UNMERGED(p)) {
4630 /* unmerged */
4631 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4632 diffstat, o, p);
4633 return;
4636 name = p->one->path;
4637 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4639 if (o->prefix_length)
4640 strip_prefix(o->prefix_length, &name, &other);
4642 diff_fill_oid_info(p->one, o->repo->index);
4643 diff_fill_oid_info(p->two, o->repo->index);
4645 builtin_diffstat(name, other, p->one, p->two,
4646 diffstat, o, p);
4649 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4651 const char *name;
4652 const char *other;
4653 const char *attr_path;
4655 if (DIFF_PAIR_UNMERGED(p)) {
4656 /* unmerged */
4657 return;
4660 name = p->one->path;
4661 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4662 attr_path = other ? other : name;
4664 if (o->prefix_length)
4665 strip_prefix(o->prefix_length, &name, &other);
4667 diff_fill_oid_info(p->one, o->repo->index);
4668 diff_fill_oid_info(p->two, o->repo->index);
4670 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4673 void repo_diff_setup(struct repository *r, struct diff_options *options)
4675 memcpy(options, &default_diff_options, sizeof(*options));
4677 options->file = stdout;
4678 options->repo = r;
4680 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4681 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4682 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4683 options->abbrev = DEFAULT_ABBREV;
4684 options->line_termination = '\n';
4685 options->break_opt = -1;
4686 options->rename_limit = -1;
4687 options->dirstat_permille = diff_dirstat_permille_default;
4688 options->context = diff_context_default;
4689 options->interhunkcontext = diff_interhunk_context_default;
4690 options->ws_error_highlight = ws_error_highlight_default;
4691 options->flags.rename_empty = 1;
4692 options->flags.relative_name = diff_relative;
4693 options->objfind = NULL;
4695 /* pathchange left =NULL by default */
4696 options->change = diff_change;
4697 options->add_remove = diff_addremove;
4698 options->use_color = diff_use_color_default;
4699 options->detect_rename = diff_detect_rename_default;
4700 options->xdl_opts |= diff_algorithm;
4701 if (diff_indent_heuristic)
4702 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4704 options->orderfile = diff_order_file_cfg;
4706 if (!options->flags.ignore_submodule_set)
4707 options->flags.ignore_untracked_in_submodules = 1;
4709 if (diff_no_prefix) {
4710 diff_set_noprefix(options);
4711 } else if (!diff_mnemonic_prefix) {
4712 diff_set_default_prefix(options);
4715 options->color_moved = diff_color_moved_default;
4716 options->color_moved_ws_handling = diff_color_moved_ws_default;
4719 static const char diff_status_letters[] = {
4720 DIFF_STATUS_ADDED,
4721 DIFF_STATUS_COPIED,
4722 DIFF_STATUS_DELETED,
4723 DIFF_STATUS_MODIFIED,
4724 DIFF_STATUS_RENAMED,
4725 DIFF_STATUS_TYPE_CHANGED,
4726 DIFF_STATUS_UNKNOWN,
4727 DIFF_STATUS_UNMERGED,
4728 DIFF_STATUS_FILTER_AON,
4729 DIFF_STATUS_FILTER_BROKEN,
4730 '\0',
4733 static unsigned int filter_bit['Z' + 1];
4735 static void prepare_filter_bits(void)
4737 int i;
4739 if (!filter_bit[DIFF_STATUS_ADDED]) {
4740 for (i = 0; diff_status_letters[i]; i++)
4741 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4745 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4747 return opt->filter & filter_bit[(int) status];
4750 unsigned diff_filter_bit(char status)
4752 prepare_filter_bits();
4753 return filter_bit[(int) status];
4756 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4758 unsigned forbidden_magic;
4760 if (ps->nr != 1) {
4761 if (die_on_error)
4762 die(_("--follow requires exactly one pathspec"));
4763 return 0;
4766 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4767 PATHSPEC_LITERAL);
4768 if (forbidden_magic) {
4769 if (die_on_error) {
4770 struct strbuf sb = STRBUF_INIT;
4771 pathspec_magic_names(forbidden_magic, &sb);
4772 die(_("pathspec magic not supported by --follow: %s"),
4773 sb.buf);
4775 return 0;
4778 return 1;
4781 void diff_setup_done(struct diff_options *options)
4783 unsigned check_mask = DIFF_FORMAT_NAME |
4784 DIFF_FORMAT_NAME_STATUS |
4785 DIFF_FORMAT_CHECKDIFF |
4786 DIFF_FORMAT_NO_OUTPUT;
4788 * This must be signed because we're comparing against a potentially
4789 * negative value.
4791 const int hexsz = the_hash_algo->hexsz;
4793 if (options->set_default)
4794 options->set_default(options);
4796 if (HAS_MULTI_BITS(options->output_format & check_mask))
4797 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4798 "--name-only", "--name-status", "--check", "-s");
4800 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4801 die(_("options '%s', '%s', and '%s' cannot be used together"),
4802 "-G", "-S", "--find-object");
4804 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4805 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4806 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4808 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4809 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4810 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4813 * Most of the time we can say "there are changes"
4814 * only by checking if there are changed paths, but
4815 * --ignore-whitespace* options force us to look
4816 * inside contents.
4819 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4820 options->ignore_regex_nr)
4821 options->flags.diff_from_contents = 1;
4822 else
4823 options->flags.diff_from_contents = 0;
4825 if (options->flags.find_copies_harder)
4826 options->detect_rename = DIFF_DETECT_COPY;
4828 if (!options->flags.relative_name)
4829 options->prefix = NULL;
4830 if (options->prefix)
4831 options->prefix_length = strlen(options->prefix);
4832 else
4833 options->prefix_length = 0;
4835 if (options->output_format & (DIFF_FORMAT_NAME |
4836 DIFF_FORMAT_NAME_STATUS |
4837 DIFF_FORMAT_CHECKDIFF |
4838 DIFF_FORMAT_NO_OUTPUT))
4839 options->output_format &= ~(DIFF_FORMAT_RAW |
4840 DIFF_FORMAT_NUMSTAT |
4841 DIFF_FORMAT_DIFFSTAT |
4842 DIFF_FORMAT_SHORTSTAT |
4843 DIFF_FORMAT_DIRSTAT |
4844 DIFF_FORMAT_SUMMARY |
4845 DIFF_FORMAT_PATCH);
4848 * These cases always need recursive; we do not drop caller-supplied
4849 * recursive bits for other formats here.
4851 if (options->output_format & (DIFF_FORMAT_PATCH |
4852 DIFF_FORMAT_NUMSTAT |
4853 DIFF_FORMAT_DIFFSTAT |
4854 DIFF_FORMAT_SHORTSTAT |
4855 DIFF_FORMAT_DIRSTAT |
4856 DIFF_FORMAT_SUMMARY |
4857 DIFF_FORMAT_CHECKDIFF))
4858 options->flags.recursive = 1;
4860 * Also pickaxe would not work very well if you do not say recursive
4862 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4863 options->flags.recursive = 1;
4865 * When patches are generated, submodules diffed against the work tree
4866 * must be checked for dirtiness too so it can be shown in the output
4868 if (options->output_format & DIFF_FORMAT_PATCH)
4869 options->flags.dirty_submodules = 1;
4871 if (options->detect_rename && options->rename_limit < 0)
4872 options->rename_limit = diff_rename_limit_default;
4873 if (hexsz < options->abbrev)
4874 options->abbrev = hexsz; /* full */
4877 * It does not make sense to show the first hit we happened
4878 * to have found. It does not make sense not to return with
4879 * exit code in such a case either.
4881 if (options->flags.quick) {
4882 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4883 options->flags.exit_with_status = 1;
4886 options->diff_path_counter = 0;
4888 if (options->flags.follow_renames)
4889 diff_check_follow_pathspec(&options->pathspec, 1);
4891 if (!options->use_color || external_diff())
4892 options->color_moved = 0;
4894 if (options->filter_not) {
4895 if (!options->filter)
4896 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4897 options->filter &= ~options->filter_not;
4901 int parse_long_opt(const char *opt, const char **argv,
4902 const char **optarg)
4904 const char *arg = argv[0];
4905 if (!skip_prefix(arg, "--", &arg))
4906 return 0;
4907 if (!skip_prefix(arg, opt, &arg))
4908 return 0;
4909 if (*arg == '=') { /* stuck form: --option=value */
4910 *optarg = arg + 1;
4911 return 1;
4913 if (*arg != '\0')
4914 return 0;
4915 /* separate form: --option value */
4916 if (!argv[1])
4917 die("Option '--%s' requires a value", opt);
4918 *optarg = argv[1];
4919 return 2;
4922 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4924 struct diff_options *options = opt->value;
4925 int width = options->stat_width;
4926 int name_width = options->stat_name_width;
4927 int graph_width = options->stat_graph_width;
4928 int count = options->stat_count;
4929 char *end;
4931 BUG_ON_OPT_NEG(unset);
4933 if (!strcmp(opt->long_name, "stat")) {
4934 if (value) {
4935 width = strtoul(value, &end, 10);
4936 if (*end == ',')
4937 name_width = strtoul(end+1, &end, 10);
4938 if (*end == ',')
4939 count = strtoul(end+1, &end, 10);
4940 if (*end)
4941 return error(_("invalid --stat value: %s"), value);
4943 } else if (!strcmp(opt->long_name, "stat-width")) {
4944 width = strtoul(value, &end, 10);
4945 if (*end)
4946 return error(_("%s expects a numerical value"),
4947 opt->long_name);
4948 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4949 name_width = strtoul(value, &end, 10);
4950 if (*end)
4951 return error(_("%s expects a numerical value"),
4952 opt->long_name);
4953 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4954 graph_width = strtoul(value, &end, 10);
4955 if (*end)
4956 return error(_("%s expects a numerical value"),
4957 opt->long_name);
4958 } else if (!strcmp(opt->long_name, "stat-count")) {
4959 count = strtoul(value, &end, 10);
4960 if (*end)
4961 return error(_("%s expects a numerical value"),
4962 opt->long_name);
4963 } else
4964 BUG("%s should not get here", opt->long_name);
4966 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4967 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4968 options->stat_name_width = name_width;
4969 options->stat_graph_width = graph_width;
4970 options->stat_width = width;
4971 options->stat_count = count;
4972 return 0;
4975 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4977 struct strbuf errmsg = STRBUF_INIT;
4978 if (parse_dirstat_params(options, params, &errmsg))
4979 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4980 errmsg.buf);
4981 strbuf_release(&errmsg);
4983 * The caller knows a dirstat-related option is given from the command
4984 * line; allow it to say "return this_function();"
4986 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4987 options->output_format |= DIFF_FORMAT_DIRSTAT;
4988 return 1;
4991 static int diff_opt_diff_filter(const struct option *option,
4992 const char *optarg, int unset)
4994 struct diff_options *opt = option->value;
4995 int i, optch;
4997 BUG_ON_OPT_NEG(unset);
4998 prepare_filter_bits();
5000 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5001 unsigned int bit;
5002 int negate;
5004 if ('a' <= optch && optch <= 'z') {
5005 negate = 1;
5006 optch = toupper(optch);
5007 } else {
5008 negate = 0;
5011 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5012 if (!bit)
5013 return error(_("unknown change class '%c' in --diff-filter=%s"),
5014 optarg[i], optarg);
5015 if (negate)
5016 opt->filter_not |= bit;
5017 else
5018 opt->filter |= bit;
5020 return 0;
5023 static void enable_patch_output(int *fmt)
5025 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5026 *fmt |= DIFF_FORMAT_PATCH;
5029 static int diff_opt_ws_error_highlight(const struct option *option,
5030 const char *arg, int unset)
5032 struct diff_options *opt = option->value;
5033 int val = parse_ws_error_highlight(arg);
5035 BUG_ON_OPT_NEG(unset);
5036 if (val < 0)
5037 return error(_("unknown value after ws-error-highlight=%.*s"),
5038 -1 - val, arg);
5039 opt->ws_error_highlight = val;
5040 return 0;
5043 static int diff_opt_find_object(const struct option *option,
5044 const char *arg, int unset)
5046 struct diff_options *opt = option->value;
5047 struct object_id oid;
5049 BUG_ON_OPT_NEG(unset);
5050 if (repo_get_oid(the_repository, arg, &oid))
5051 return error(_("unable to resolve '%s'"), arg);
5053 if (!opt->objfind)
5054 CALLOC_ARRAY(opt->objfind, 1);
5056 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5057 opt->flags.recursive = 1;
5058 opt->flags.tree_in_recursive = 1;
5059 oidset_insert(opt->objfind, &oid);
5060 return 0;
5063 static int diff_opt_anchored(const struct option *opt,
5064 const char *arg, int unset)
5066 struct diff_options *options = opt->value;
5068 BUG_ON_OPT_NEG(unset);
5069 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5070 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5071 options->anchors_alloc);
5072 options->anchors[options->anchors_nr++] = xstrdup(arg);
5073 return 0;
5076 static int diff_opt_binary(const struct option *opt,
5077 const char *arg, int unset)
5079 struct diff_options *options = opt->value;
5081 BUG_ON_OPT_NEG(unset);
5082 BUG_ON_OPT_ARG(arg);
5083 enable_patch_output(&options->output_format);
5084 options->flags.binary = 1;
5085 return 0;
5088 static int diff_opt_break_rewrites(const struct option *opt,
5089 const char *arg, int unset)
5091 int *break_opt = opt->value;
5092 int opt1, opt2;
5094 BUG_ON_OPT_NEG(unset);
5095 if (!arg)
5096 arg = "";
5097 opt1 = parse_rename_score(&arg);
5098 if (*arg == 0)
5099 opt2 = 0;
5100 else if (*arg != '/')
5101 return error(_("%s expects <n>/<m> form"), opt->long_name);
5102 else {
5103 arg++;
5104 opt2 = parse_rename_score(&arg);
5106 if (*arg != 0)
5107 return error(_("%s expects <n>/<m> form"), opt->long_name);
5108 *break_opt = opt1 | (opt2 << 16);
5109 return 0;
5112 static int diff_opt_char(const struct option *opt,
5113 const char *arg, int unset)
5115 char *value = opt->value;
5117 BUG_ON_OPT_NEG(unset);
5118 if (arg[1])
5119 return error(_("%s expects a character, got '%s'"),
5120 opt->long_name, arg);
5121 *value = arg[0];
5122 return 0;
5125 static int diff_opt_color_moved(const struct option *opt,
5126 const char *arg, int unset)
5128 struct diff_options *options = opt->value;
5130 if (unset) {
5131 options->color_moved = COLOR_MOVED_NO;
5132 } else if (!arg) {
5133 if (diff_color_moved_default)
5134 options->color_moved = diff_color_moved_default;
5135 if (options->color_moved == COLOR_MOVED_NO)
5136 options->color_moved = COLOR_MOVED_DEFAULT;
5137 } else {
5138 int cm = parse_color_moved(arg);
5139 if (cm < 0)
5140 return error(_("bad --color-moved argument: %s"), arg);
5141 options->color_moved = cm;
5143 return 0;
5146 static int diff_opt_color_moved_ws(const struct option *opt,
5147 const char *arg, int unset)
5149 struct diff_options *options = opt->value;
5150 unsigned cm;
5152 if (unset) {
5153 options->color_moved_ws_handling = 0;
5154 return 0;
5157 cm = parse_color_moved_ws(arg);
5158 if (cm & COLOR_MOVED_WS_ERROR)
5159 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5160 options->color_moved_ws_handling = cm;
5161 return 0;
5164 static int diff_opt_color_words(const struct option *opt,
5165 const char *arg, int unset)
5167 struct diff_options *options = opt->value;
5169 BUG_ON_OPT_NEG(unset);
5170 options->use_color = 1;
5171 options->word_diff = DIFF_WORDS_COLOR;
5172 options->word_regex = arg;
5173 return 0;
5176 static int diff_opt_compact_summary(const struct option *opt,
5177 const char *arg, int unset)
5179 struct diff_options *options = opt->value;
5181 BUG_ON_OPT_ARG(arg);
5182 if (unset) {
5183 options->flags.stat_with_summary = 0;
5184 } else {
5185 options->flags.stat_with_summary = 1;
5186 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5187 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5189 return 0;
5192 static int diff_opt_diff_algorithm(const struct option *opt,
5193 const char *arg, int unset)
5195 struct diff_options *options = opt->value;
5197 BUG_ON_OPT_NEG(unset);
5199 if (set_diff_algorithm(options, arg))
5200 return error(_("option diff-algorithm accepts \"myers\", "
5201 "\"minimal\", \"patience\" and \"histogram\""));
5203 options->ignore_driver_algorithm = 1;
5205 return 0;
5208 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5209 const char *arg, int unset)
5211 struct diff_options *options = opt->value;
5213 BUG_ON_OPT_NEG(unset);
5214 BUG_ON_OPT_ARG(arg);
5216 if (set_diff_algorithm(options, opt->long_name))
5217 BUG("available diff algorithms include \"myers\", "
5218 "\"minimal\", \"patience\" and \"histogram\"");
5220 options->ignore_driver_algorithm = 1;
5222 return 0;
5225 static int diff_opt_dirstat(const struct option *opt,
5226 const char *arg, int unset)
5228 struct diff_options *options = opt->value;
5230 BUG_ON_OPT_NEG(unset);
5231 if (!strcmp(opt->long_name, "cumulative")) {
5232 if (arg)
5233 BUG("how come --cumulative take a value?");
5234 arg = "cumulative";
5235 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5236 parse_dirstat_opt(options, "files");
5237 parse_dirstat_opt(options, arg ? arg : "");
5238 return 0;
5241 static int diff_opt_find_copies(const struct option *opt,
5242 const char *arg, int unset)
5244 struct diff_options *options = opt->value;
5246 BUG_ON_OPT_NEG(unset);
5247 if (!arg)
5248 arg = "";
5249 options->rename_score = parse_rename_score(&arg);
5250 if (*arg != 0)
5251 return error(_("invalid argument to %s"), opt->long_name);
5253 if (options->detect_rename == DIFF_DETECT_COPY)
5254 options->flags.find_copies_harder = 1;
5255 else
5256 options->detect_rename = DIFF_DETECT_COPY;
5258 return 0;
5261 static int diff_opt_find_renames(const struct option *opt,
5262 const char *arg, int unset)
5264 struct diff_options *options = opt->value;
5266 BUG_ON_OPT_NEG(unset);
5267 if (!arg)
5268 arg = "";
5269 options->rename_score = parse_rename_score(&arg);
5270 if (*arg != 0)
5271 return error(_("invalid argument to %s"), opt->long_name);
5273 options->detect_rename = DIFF_DETECT_RENAME;
5274 return 0;
5277 static int diff_opt_follow(const struct option *opt,
5278 const char *arg, int unset)
5280 struct diff_options *options = opt->value;
5282 BUG_ON_OPT_ARG(arg);
5283 if (unset) {
5284 options->flags.follow_renames = 0;
5285 options->flags.default_follow_renames = 0;
5286 } else {
5287 options->flags.follow_renames = 1;
5289 return 0;
5292 static int diff_opt_ignore_submodules(const struct option *opt,
5293 const char *arg, int unset)
5295 struct diff_options *options = opt->value;
5297 BUG_ON_OPT_NEG(unset);
5298 if (!arg)
5299 arg = "all";
5300 options->flags.override_submodule_config = 1;
5301 handle_ignore_submodules_arg(options, arg);
5302 return 0;
5305 static int diff_opt_line_prefix(const struct option *opt,
5306 const char *optarg, int unset)
5308 struct diff_options *options = opt->value;
5310 BUG_ON_OPT_NEG(unset);
5311 options->line_prefix = optarg;
5312 options->line_prefix_length = strlen(options->line_prefix);
5313 graph_setup_line_prefix(options);
5314 return 0;
5317 static int diff_opt_no_prefix(const struct option *opt,
5318 const char *optarg, int unset)
5320 struct diff_options *options = opt->value;
5322 BUG_ON_OPT_NEG(unset);
5323 BUG_ON_OPT_ARG(optarg);
5324 diff_set_noprefix(options);
5325 return 0;
5328 static int diff_opt_default_prefix(const struct option *opt,
5329 const char *optarg, int unset)
5331 struct diff_options *options = opt->value;
5333 BUG_ON_OPT_NEG(unset);
5334 BUG_ON_OPT_ARG(optarg);
5335 diff_set_default_prefix(options);
5336 return 0;
5339 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5340 const struct option *opt,
5341 const char *arg, int unset)
5343 struct diff_options *options = opt->value;
5344 char *path;
5346 BUG_ON_OPT_NEG(unset);
5347 path = prefix_filename(ctx->prefix, arg);
5348 options->file = xfopen(path, "w");
5349 options->close_file = 1;
5350 if (options->use_color != GIT_COLOR_ALWAYS)
5351 options->use_color = GIT_COLOR_NEVER;
5352 free(path);
5353 return 0;
5356 static int diff_opt_patience(const struct option *opt,
5357 const char *arg, int unset)
5359 struct diff_options *options = opt->value;
5360 int i;
5362 BUG_ON_OPT_NEG(unset);
5363 BUG_ON_OPT_ARG(arg);
5365 * Both --patience and --anchored use PATIENCE_DIFF
5366 * internally, so remove any anchors previously
5367 * specified.
5369 for (i = 0; i < options->anchors_nr; i++)
5370 free(options->anchors[i]);
5371 options->anchors_nr = 0;
5372 options->ignore_driver_algorithm = 1;
5374 return set_diff_algorithm(options, "patience");
5377 static int diff_opt_ignore_regex(const struct option *opt,
5378 const char *arg, int unset)
5380 struct diff_options *options = opt->value;
5381 regex_t *regex;
5383 BUG_ON_OPT_NEG(unset);
5384 regex = xmalloc(sizeof(*regex));
5385 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5386 return error(_("invalid regex given to -I: '%s'"), arg);
5387 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5388 options->ignore_regex_alloc);
5389 options->ignore_regex[options->ignore_regex_nr++] = regex;
5390 return 0;
5393 static int diff_opt_pickaxe_regex(const struct option *opt,
5394 const char *arg, int unset)
5396 struct diff_options *options = opt->value;
5398 BUG_ON_OPT_NEG(unset);
5399 options->pickaxe = arg;
5400 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5401 return 0;
5404 static int diff_opt_pickaxe_string(const struct option *opt,
5405 const char *arg, int unset)
5407 struct diff_options *options = opt->value;
5409 BUG_ON_OPT_NEG(unset);
5410 options->pickaxe = arg;
5411 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5412 return 0;
5415 static int diff_opt_relative(const struct option *opt,
5416 const char *arg, int unset)
5418 struct diff_options *options = opt->value;
5420 options->flags.relative_name = !unset;
5421 if (arg)
5422 options->prefix = arg;
5423 return 0;
5426 static int diff_opt_submodule(const struct option *opt,
5427 const char *arg, int unset)
5429 struct diff_options *options = opt->value;
5431 BUG_ON_OPT_NEG(unset);
5432 if (!arg)
5433 arg = "log";
5434 if (parse_submodule_params(options, arg))
5435 return error(_("failed to parse --submodule option parameter: '%s'"),
5436 arg);
5437 return 0;
5440 static int diff_opt_textconv(const struct option *opt,
5441 const char *arg, int unset)
5443 struct diff_options *options = opt->value;
5445 BUG_ON_OPT_ARG(arg);
5446 if (unset) {
5447 options->flags.allow_textconv = 0;
5448 } else {
5449 options->flags.allow_textconv = 1;
5450 options->flags.textconv_set_via_cmdline = 1;
5452 return 0;
5455 static int diff_opt_unified(const struct option *opt,
5456 const char *arg, int unset)
5458 struct diff_options *options = opt->value;
5459 char *s;
5461 BUG_ON_OPT_NEG(unset);
5463 if (arg) {
5464 options->context = strtol(arg, &s, 10);
5465 if (*s)
5466 return error(_("%s expects a numerical value"), "--unified");
5468 enable_patch_output(&options->output_format);
5470 return 0;
5473 static int diff_opt_word_diff(const struct option *opt,
5474 const char *arg, int unset)
5476 struct diff_options *options = opt->value;
5478 BUG_ON_OPT_NEG(unset);
5479 if (arg) {
5480 if (!strcmp(arg, "plain"))
5481 options->word_diff = DIFF_WORDS_PLAIN;
5482 else if (!strcmp(arg, "color")) {
5483 options->use_color = 1;
5484 options->word_diff = DIFF_WORDS_COLOR;
5486 else if (!strcmp(arg, "porcelain"))
5487 options->word_diff = DIFF_WORDS_PORCELAIN;
5488 else if (!strcmp(arg, "none"))
5489 options->word_diff = DIFF_WORDS_NONE;
5490 else
5491 return error(_("bad --word-diff argument: %s"), arg);
5492 } else {
5493 if (options->word_diff == DIFF_WORDS_NONE)
5494 options->word_diff = DIFF_WORDS_PLAIN;
5496 return 0;
5499 static int diff_opt_word_diff_regex(const struct option *opt,
5500 const char *arg, int unset)
5502 struct diff_options *options = opt->value;
5504 BUG_ON_OPT_NEG(unset);
5505 if (options->word_diff == DIFF_WORDS_NONE)
5506 options->word_diff = DIFF_WORDS_PLAIN;
5507 options->word_regex = arg;
5508 return 0;
5511 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5513 struct diff_options *options = opt->value;
5515 BUG_ON_OPT_NEG(unset);
5516 if (!strcmp(opt->long_name, "skip-to"))
5517 options->skip_instead_of_rotate = 1;
5518 else
5519 options->skip_instead_of_rotate = 0;
5520 options->rotate_to = arg;
5521 return 0;
5525 * Consider adding new flags to __git_diff_common_options
5526 * in contrib/completion/git-completion.bash
5528 struct option *add_diff_options(const struct option *opts,
5529 struct diff_options *options)
5531 struct option parseopts[] = {
5532 OPT_GROUP(N_("Diff output format options")),
5533 OPT_BITOP('p', "patch", &options->output_format,
5534 N_("generate patch"),
5535 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5536 OPT_SET_INT('s', "no-patch", &options->output_format,
5537 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5538 OPT_BITOP('u', NULL, &options->output_format,
5539 N_("generate patch"),
5540 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5541 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5542 N_("generate diffs with <n> lines context"),
5543 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5544 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5545 N_("generate diffs with <n> lines context")),
5546 OPT_BITOP(0, "raw", &options->output_format,
5547 N_("generate the diff in raw format"),
5548 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5549 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5550 N_("synonym for '-p --raw'"),
5551 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5552 DIFF_FORMAT_NO_OUTPUT),
5553 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5554 N_("synonym for '-p --stat'"),
5555 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5556 DIFF_FORMAT_NO_OUTPUT),
5557 OPT_BITOP(0, "numstat", &options->output_format,
5558 N_("machine friendly --stat"),
5559 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5560 OPT_BITOP(0, "shortstat", &options->output_format,
5561 N_("output only the last line of --stat"),
5562 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5563 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5564 N_("output the distribution of relative amount of changes for each sub-directory"),
5565 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5566 diff_opt_dirstat),
5567 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5568 N_("synonym for --dirstat=cumulative"),
5569 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5570 diff_opt_dirstat),
5571 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5572 N_("synonym for --dirstat=files,param1,param2..."),
5573 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5574 diff_opt_dirstat),
5575 OPT_BIT_F(0, "check", &options->output_format,
5576 N_("warn if changes introduce conflict markers or whitespace errors"),
5577 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5578 OPT_BITOP(0, "summary", &options->output_format,
5579 N_("condensed summary such as creations, renames and mode changes"),
5580 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5581 OPT_BIT_F(0, "name-only", &options->output_format,
5582 N_("show only names of changed files"),
5583 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5584 OPT_BIT_F(0, "name-status", &options->output_format,
5585 N_("show only names and status of changed files"),
5586 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5587 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5588 N_("generate diffstat"),
5589 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5590 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5591 N_("generate diffstat with a given width"),
5592 PARSE_OPT_NONEG, diff_opt_stat),
5593 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5594 N_("generate diffstat with a given name width"),
5595 PARSE_OPT_NONEG, diff_opt_stat),
5596 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5597 N_("generate diffstat with a given graph width"),
5598 PARSE_OPT_NONEG, diff_opt_stat),
5599 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5600 N_("generate diffstat with limited lines"),
5601 PARSE_OPT_NONEG, diff_opt_stat),
5602 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5603 N_("generate compact summary in diffstat"),
5604 PARSE_OPT_NOARG, diff_opt_compact_summary),
5605 OPT_CALLBACK_F(0, "binary", options, NULL,
5606 N_("output a binary diff that can be applied"),
5607 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5608 OPT_BOOL(0, "full-index", &options->flags.full_index,
5609 N_("show full pre- and post-image object names on the \"index\" lines")),
5610 OPT_COLOR_FLAG(0, "color", &options->use_color,
5611 N_("show colored diff")),
5612 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5613 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5614 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5615 OPT_SET_INT('z', NULL, &options->line_termination,
5616 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5618 OPT__ABBREV(&options->abbrev),
5619 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5620 N_("show the given source prefix instead of \"a/\""),
5621 PARSE_OPT_NONEG),
5622 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5623 N_("show the given destination prefix instead of \"b/\""),
5624 PARSE_OPT_NONEG),
5625 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5626 N_("prepend an additional prefix to every line of output"),
5627 PARSE_OPT_NONEG, diff_opt_line_prefix),
5628 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5629 N_("do not show any source or destination prefix"),
5630 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5631 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5632 N_("use default prefixes a/ and b/"),
5633 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5634 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5635 N_("show context between diff hunks up to the specified number of lines"),
5636 PARSE_OPT_NONEG),
5637 OPT_CALLBACK_F(0, "output-indicator-new",
5638 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5639 N_("<char>"),
5640 N_("specify the character to indicate a new line instead of '+'"),
5641 PARSE_OPT_NONEG, diff_opt_char),
5642 OPT_CALLBACK_F(0, "output-indicator-old",
5643 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5644 N_("<char>"),
5645 N_("specify the character to indicate an old line instead of '-'"),
5646 PARSE_OPT_NONEG, diff_opt_char),
5647 OPT_CALLBACK_F(0, "output-indicator-context",
5648 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5649 N_("<char>"),
5650 N_("specify the character to indicate a context instead of ' '"),
5651 PARSE_OPT_NONEG, diff_opt_char),
5653 OPT_GROUP(N_("Diff rename options")),
5654 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5655 N_("break complete rewrite changes into pairs of delete and create"),
5656 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5657 diff_opt_break_rewrites),
5658 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5659 N_("detect renames"),
5660 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5661 diff_opt_find_renames),
5662 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5663 N_("omit the preimage for deletes"),
5664 1, PARSE_OPT_NONEG),
5665 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5666 N_("detect copies"),
5667 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5668 diff_opt_find_copies),
5669 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5670 N_("use unmodified files as source to find copies")),
5671 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5672 N_("disable rename detection"),
5673 0, PARSE_OPT_NONEG),
5674 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5675 N_("use empty blobs as rename source")),
5676 OPT_CALLBACK_F(0, "follow", options, NULL,
5677 N_("continue listing the history of a file beyond renames"),
5678 PARSE_OPT_NOARG, diff_opt_follow),
5679 OPT_INTEGER('l', NULL, &options->rename_limit,
5680 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5682 OPT_GROUP(N_("Diff algorithm options")),
5683 OPT_CALLBACK_F(0, "minimal", options, NULL,
5684 N_("produce the smallest possible diff"),
5685 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5686 diff_opt_diff_algorithm_no_arg),
5687 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5688 N_("ignore whitespace when comparing lines"),
5689 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5690 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5691 N_("ignore changes in amount of whitespace"),
5692 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5693 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5694 N_("ignore changes in whitespace at EOL"),
5695 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5696 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5697 N_("ignore carrier-return at the end of line"),
5698 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5699 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5700 N_("ignore changes whose lines are all blank"),
5701 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5702 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5703 N_("ignore changes whose all lines match <regex>"),
5704 0, diff_opt_ignore_regex),
5705 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5706 N_("heuristic to shift diff hunk boundaries for easy reading"),
5707 XDF_INDENT_HEURISTIC),
5708 OPT_CALLBACK_F(0, "patience", options, NULL,
5709 N_("generate diff using the \"patience diff\" algorithm"),
5710 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5711 diff_opt_patience),
5712 OPT_CALLBACK_F(0, "histogram", options, NULL,
5713 N_("generate diff using the \"histogram diff\" algorithm"),
5714 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5715 diff_opt_diff_algorithm_no_arg),
5716 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5717 N_("choose a diff algorithm"),
5718 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5719 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5720 N_("generate diff using the \"anchored diff\" algorithm"),
5721 PARSE_OPT_NONEG, diff_opt_anchored),
5722 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5723 N_("show word diff, using <mode> to delimit changed words"),
5724 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5725 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5726 N_("use <regex> to decide what a word is"),
5727 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5728 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5729 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5730 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5731 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5732 N_("moved lines of code are colored differently"),
5733 PARSE_OPT_OPTARG, diff_opt_color_moved),
5734 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5735 N_("how white spaces are ignored in --color-moved"),
5736 0, diff_opt_color_moved_ws),
5738 OPT_GROUP(N_("Other diff options")),
5739 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5740 N_("when run from subdir, exclude changes outside and show relative paths"),
5741 PARSE_OPT_OPTARG,
5742 diff_opt_relative),
5743 OPT_BOOL('a', "text", &options->flags.text,
5744 N_("treat all files as text")),
5745 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5746 N_("swap two inputs, reverse the diff")),
5747 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5748 N_("exit with 1 if there were differences, 0 otherwise")),
5749 OPT_BOOL(0, "quiet", &options->flags.quick,
5750 N_("disable all output of the program")),
5751 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5752 N_("allow an external diff helper to be executed")),
5753 OPT_CALLBACK_F(0, "textconv", options, NULL,
5754 N_("run external text conversion filters when comparing binary files"),
5755 PARSE_OPT_NOARG, diff_opt_textconv),
5756 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5757 N_("ignore changes to submodules in the diff generation"),
5758 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5759 diff_opt_ignore_submodules),
5760 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5761 N_("specify how differences in submodules are shown"),
5762 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5763 diff_opt_submodule),
5764 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5765 N_("hide 'git add -N' entries from the index"),
5766 1, PARSE_OPT_NONEG),
5767 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5768 N_("treat 'git add -N' entries as real in the index"),
5769 0, PARSE_OPT_NONEG),
5770 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5771 N_("look for differences that change the number of occurrences of the specified string"),
5772 0, diff_opt_pickaxe_string),
5773 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5774 N_("look for differences that change the number of occurrences of the specified regex"),
5775 0, diff_opt_pickaxe_regex),
5776 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5777 N_("show all changes in the changeset with -S or -G"),
5778 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5779 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5780 N_("treat <string> in -S as extended POSIX regular expression"),
5781 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5782 OPT_FILENAME('O', NULL, &options->orderfile,
5783 N_("control the order in which files appear in the output")),
5784 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5785 N_("show the change in the specified path first"),
5786 PARSE_OPT_NONEG, diff_opt_rotate_to),
5787 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5788 N_("skip the output to the specified path"),
5789 PARSE_OPT_NONEG, diff_opt_rotate_to),
5790 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5791 N_("look for differences that change the number of occurrences of the specified object"),
5792 PARSE_OPT_NONEG, diff_opt_find_object),
5793 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5794 N_("select files by diff type"),
5795 PARSE_OPT_NONEG, diff_opt_diff_filter),
5796 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5797 N_("output to a specific file"),
5798 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5800 OPT_END()
5803 return parse_options_concat(opts, parseopts);
5806 int diff_opt_parse(struct diff_options *options,
5807 const char **av, int ac, const char *prefix)
5809 struct option no_options[] = { OPT_END() };
5810 struct option *parseopts = add_diff_options(no_options, options);
5812 if (!prefix)
5813 prefix = "";
5815 ac = parse_options(ac, av, prefix, parseopts, NULL,
5816 PARSE_OPT_KEEP_DASHDASH |
5817 PARSE_OPT_KEEP_UNKNOWN_OPT |
5818 PARSE_OPT_NO_INTERNAL_HELP |
5819 PARSE_OPT_ONE_SHOT |
5820 PARSE_OPT_STOP_AT_NON_OPTION);
5821 free(parseopts);
5823 return ac;
5826 int parse_rename_score(const char **cp_p)
5828 unsigned long num, scale;
5829 int ch, dot;
5830 const char *cp = *cp_p;
5832 num = 0;
5833 scale = 1;
5834 dot = 0;
5835 for (;;) {
5836 ch = *cp;
5837 if ( !dot && ch == '.' ) {
5838 scale = 1;
5839 dot = 1;
5840 } else if ( ch == '%' ) {
5841 scale = dot ? scale*100 : 100;
5842 cp++; /* % is always at the end */
5843 break;
5844 } else if ( ch >= '0' && ch <= '9' ) {
5845 if ( scale < 100000 ) {
5846 scale *= 10;
5847 num = (num*10) + (ch-'0');
5849 } else {
5850 break;
5852 cp++;
5854 *cp_p = cp;
5856 /* user says num divided by scale and we say internally that
5857 * is MAX_SCORE * num / scale.
5859 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5862 struct diff_queue_struct diff_queued_diff;
5864 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5866 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5867 queue->queue[queue->nr++] = dp;
5870 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5871 struct diff_filespec *one,
5872 struct diff_filespec *two)
5874 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5875 dp->one = one;
5876 dp->two = two;
5877 if (queue)
5878 diff_q(queue, dp);
5879 return dp;
5882 void diff_free_filepair(struct diff_filepair *p)
5884 free_filespec(p->one);
5885 free_filespec(p->two);
5886 free(p);
5889 void diff_free_queue(struct diff_queue_struct *q)
5891 for (int i = 0; i < q->nr; i++)
5892 diff_free_filepair(q->queue[i]);
5893 free(q->queue);
5896 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5898 int abblen;
5899 const char *abbrev;
5901 /* Do we want all 40 hex characters? */
5902 if (len == the_hash_algo->hexsz)
5903 return oid_to_hex(oid);
5905 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5906 abbrev = diff_abbrev_oid(oid, len);
5908 if (!print_sha1_ellipsis())
5909 return abbrev;
5911 abblen = strlen(abbrev);
5914 * In well-behaved cases, where the abbreviated result is the
5915 * same as the requested length, append three dots after the
5916 * abbreviation (hence the whole logic is limited to the case
5917 * where abblen < 37); when the actual abbreviated result is a
5918 * bit longer than the requested length, we reduce the number
5919 * of dots so that they match the well-behaved ones. However,
5920 * if the actual abbreviation is longer than the requested
5921 * length by more than three, we give up on aligning, and add
5922 * three dots anyway, to indicate that the output is not the
5923 * full object name. Yes, this may be suboptimal, but this
5924 * appears only in "diff --raw --abbrev" output and it is not
5925 * worth the effort to change it now. Note that this would
5926 * likely to work fine when the automatic sizing of default
5927 * abbreviation length is used--we would be fed -1 in "len" in
5928 * that case, and will end up always appending three-dots, but
5929 * the automatic sizing is supposed to give abblen that ensures
5930 * uniqueness across all objects (statistically speaking).
5932 if (abblen < the_hash_algo->hexsz - 3) {
5933 static char hex[GIT_MAX_HEXSZ + 1];
5934 if (len < abblen && abblen <= len + 2)
5935 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5936 else
5937 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5938 return hex;
5941 return oid_to_hex(oid);
5944 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5946 int line_termination = opt->line_termination;
5947 int inter_name_termination = line_termination ? '\t' : '\0';
5949 fprintf(opt->file, "%s", diff_line_prefix(opt));
5950 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5951 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5952 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5953 fprintf(opt->file, "%s ",
5954 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5956 if (p->score) {
5957 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5958 inter_name_termination);
5959 } else {
5960 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5963 if (p->status == DIFF_STATUS_COPIED ||
5964 p->status == DIFF_STATUS_RENAMED) {
5965 const char *name_a, *name_b;
5966 name_a = p->one->path;
5967 name_b = p->two->path;
5968 strip_prefix(opt->prefix_length, &name_a, &name_b);
5969 write_name_quoted(name_a, opt->file, inter_name_termination);
5970 write_name_quoted(name_b, opt->file, line_termination);
5971 } else {
5972 const char *name_a, *name_b;
5973 name_a = p->one->mode ? p->one->path : p->two->path;
5974 name_b = NULL;
5975 strip_prefix(opt->prefix_length, &name_a, &name_b);
5976 write_name_quoted(name_a, opt->file, line_termination);
5980 int diff_unmodified_pair(struct diff_filepair *p)
5982 /* This function is written stricter than necessary to support
5983 * the currently implemented transformers, but the idea is to
5984 * let transformers to produce diff_filepairs any way they want,
5985 * and filter and clean them up here before producing the output.
5987 struct diff_filespec *one = p->one, *two = p->two;
5989 if (DIFF_PAIR_UNMERGED(p))
5990 return 0; /* unmerged is interesting */
5992 /* deletion, addition, mode or type change
5993 * and rename are all interesting.
5995 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5996 DIFF_PAIR_MODE_CHANGED(p) ||
5997 strcmp(one->path, two->path))
5998 return 0;
6000 /* both are valid and point at the same path. that is, we are
6001 * dealing with a change.
6003 if (one->oid_valid && two->oid_valid &&
6004 oideq(&one->oid, &two->oid) &&
6005 !one->dirty_submodule && !two->dirty_submodule)
6006 return 1; /* no change */
6007 if (!one->oid_valid && !two->oid_valid)
6008 return 1; /* both look at the same file on the filesystem. */
6009 return 0;
6012 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6014 int include_conflict_headers =
6015 (additional_headers(o, p->one->path) &&
6016 !o->pickaxe_opts &&
6017 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6020 * Check if we can return early without showing a diff. Note that
6021 * diff_filepair only stores {oid, path, mode, is_valid}
6022 * information for each path, and thus diff_unmodified_pair() only
6023 * considers those bits of info. However, we do not want pairs
6024 * created by create_filepairs_for_header_only_notifications()
6025 * (which always look like unmodified pairs) to be ignored, so
6026 * return early if both p is unmodified AND we don't want to
6027 * include_conflict_headers.
6029 if (diff_unmodified_pair(p) && !include_conflict_headers)
6030 return;
6032 /* Actually, we can also return early to avoid showing tree diffs */
6033 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6034 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6035 return;
6037 run_diff(p, o);
6040 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6041 struct diffstat_t *diffstat)
6043 if (diff_unmodified_pair(p))
6044 return;
6046 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6047 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6048 return; /* no useful stat for tree diffs */
6050 run_diffstat(p, o, diffstat);
6053 static void diff_flush_checkdiff(struct diff_filepair *p,
6054 struct diff_options *o)
6056 if (diff_unmodified_pair(p))
6057 return;
6059 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6060 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6061 return; /* nothing to check in tree diffs */
6063 run_checkdiff(p, o);
6066 int diff_queue_is_empty(struct diff_options *o)
6068 struct diff_queue_struct *q = &diff_queued_diff;
6069 int i;
6070 int include_conflict_headers =
6071 (o->additional_path_headers &&
6072 strmap_get_size(o->additional_path_headers) &&
6073 !o->pickaxe_opts &&
6074 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6076 if (include_conflict_headers)
6077 return 0;
6079 for (i = 0; i < q->nr; i++)
6080 if (!diff_unmodified_pair(q->queue[i]))
6081 return 0;
6082 return 1;
6085 #if DIFF_DEBUG
6086 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6088 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6089 x, one ? one : "",
6090 s->path,
6091 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6092 s->mode,
6093 s->oid_valid ? oid_to_hex(&s->oid) : "");
6094 fprintf(stderr, "queue[%d] %s size %lu\n",
6095 x, one ? one : "",
6096 s->size);
6099 void diff_debug_filepair(const struct diff_filepair *p, int i)
6101 diff_debug_filespec(p->one, i, "one");
6102 diff_debug_filespec(p->two, i, "two");
6103 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6104 p->score, p->status ? p->status : '?',
6105 p->one->rename_used, p->broken_pair);
6108 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6110 int i;
6111 if (msg)
6112 fprintf(stderr, "%s\n", msg);
6113 fprintf(stderr, "q->nr = %d\n", q->nr);
6114 for (i = 0; i < q->nr; i++) {
6115 struct diff_filepair *p = q->queue[i];
6116 diff_debug_filepair(p, i);
6119 #endif
6121 static void diff_resolve_rename_copy(void)
6123 int i;
6124 struct diff_filepair *p;
6125 struct diff_queue_struct *q = &diff_queued_diff;
6127 diff_debug_queue("resolve-rename-copy", q);
6129 for (i = 0; i < q->nr; i++) {
6130 p = q->queue[i];
6131 p->status = 0; /* undecided */
6132 if (DIFF_PAIR_UNMERGED(p))
6133 p->status = DIFF_STATUS_UNMERGED;
6134 else if (!DIFF_FILE_VALID(p->one))
6135 p->status = DIFF_STATUS_ADDED;
6136 else if (!DIFF_FILE_VALID(p->two))
6137 p->status = DIFF_STATUS_DELETED;
6138 else if (DIFF_PAIR_TYPE_CHANGED(p))
6139 p->status = DIFF_STATUS_TYPE_CHANGED;
6141 /* from this point on, we are dealing with a pair
6142 * whose both sides are valid and of the same type, i.e.
6143 * either in-place edit or rename/copy edit.
6145 else if (DIFF_PAIR_RENAME(p)) {
6147 * A rename might have re-connected a broken
6148 * pair up, causing the pathnames to be the
6149 * same again. If so, that's not a rename at
6150 * all, just a modification..
6152 * Otherwise, see if this source was used for
6153 * multiple renames, in which case we decrement
6154 * the count, and call it a copy.
6156 if (!strcmp(p->one->path, p->two->path))
6157 p->status = DIFF_STATUS_MODIFIED;
6158 else if (--p->one->rename_used > 0)
6159 p->status = DIFF_STATUS_COPIED;
6160 else
6161 p->status = DIFF_STATUS_RENAMED;
6163 else if (!oideq(&p->one->oid, &p->two->oid) ||
6164 p->one->mode != p->two->mode ||
6165 p->one->dirty_submodule ||
6166 p->two->dirty_submodule ||
6167 is_null_oid(&p->one->oid))
6168 p->status = DIFF_STATUS_MODIFIED;
6169 else {
6170 /* This is a "no-change" entry and should not
6171 * happen anymore, but prepare for broken callers.
6173 error("feeding unmodified %s to diffcore",
6174 p->one->path);
6175 p->status = DIFF_STATUS_UNKNOWN;
6178 diff_debug_queue("resolve-rename-copy done", q);
6181 static int check_pair_status(struct diff_filepair *p)
6183 switch (p->status) {
6184 case DIFF_STATUS_UNKNOWN:
6185 return 0;
6186 case 0:
6187 die("internal error in diff-resolve-rename-copy");
6188 default:
6189 return 1;
6193 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6195 int fmt = opt->output_format;
6197 if (fmt & DIFF_FORMAT_CHECKDIFF)
6198 diff_flush_checkdiff(p, opt);
6199 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6200 diff_flush_raw(p, opt);
6201 else if (fmt & DIFF_FORMAT_NAME) {
6202 const char *name_a, *name_b;
6203 name_a = p->two->path;
6204 name_b = NULL;
6205 strip_prefix(opt->prefix_length, &name_a, &name_b);
6206 fprintf(opt->file, "%s", diff_line_prefix(opt));
6207 write_name_quoted(name_a, opt->file, opt->line_termination);
6211 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6213 struct strbuf sb = STRBUF_INIT;
6214 if (fs->mode)
6215 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6216 else
6217 strbuf_addf(&sb, " %s ", newdelete);
6219 quote_c_style(fs->path, &sb, NULL, 0);
6220 strbuf_addch(&sb, '\n');
6221 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6222 sb.buf, sb.len, 0);
6223 strbuf_release(&sb);
6226 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6227 int show_name)
6229 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6230 struct strbuf sb = STRBUF_INIT;
6231 strbuf_addf(&sb, " mode change %06o => %06o",
6232 p->one->mode, p->two->mode);
6233 if (show_name) {
6234 strbuf_addch(&sb, ' ');
6235 quote_c_style(p->two->path, &sb, NULL, 0);
6237 strbuf_addch(&sb, '\n');
6238 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6239 sb.buf, sb.len, 0);
6240 strbuf_release(&sb);
6244 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6245 struct diff_filepair *p)
6247 struct strbuf sb = STRBUF_INIT;
6248 struct strbuf names = STRBUF_INIT;
6250 pprint_rename(&names, p->one->path, p->two->path);
6251 strbuf_addf(&sb, " %s %s (%d%%)\n",
6252 renamecopy, names.buf, similarity_index(p));
6253 strbuf_release(&names);
6254 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6255 sb.buf, sb.len, 0);
6256 show_mode_change(opt, p, 0);
6257 strbuf_release(&sb);
6260 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6262 switch(p->status) {
6263 case DIFF_STATUS_DELETED:
6264 show_file_mode_name(opt, "delete", p->one);
6265 break;
6266 case DIFF_STATUS_ADDED:
6267 show_file_mode_name(opt, "create", p->two);
6268 break;
6269 case DIFF_STATUS_COPIED:
6270 show_rename_copy(opt, "copy", p);
6271 break;
6272 case DIFF_STATUS_RENAMED:
6273 show_rename_copy(opt, "rename", p);
6274 break;
6275 default:
6276 if (p->score) {
6277 struct strbuf sb = STRBUF_INIT;
6278 strbuf_addstr(&sb, " rewrite ");
6279 quote_c_style(p->two->path, &sb, NULL, 0);
6280 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6281 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6282 sb.buf, sb.len, 0);
6283 strbuf_release(&sb);
6285 show_mode_change(opt, p, !p->score);
6286 break;
6290 struct patch_id_t {
6291 git_hash_ctx *ctx;
6292 int patchlen;
6295 static int remove_space(char *line, int len)
6297 int i;
6298 char *dst = line;
6299 unsigned char c;
6301 for (i = 0; i < len; i++)
6302 if (!isspace((c = line[i])))
6303 *dst++ = c;
6305 return dst - line;
6308 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6310 unsigned char hash[GIT_MAX_RAWSZ];
6311 unsigned short carry = 0;
6312 int i;
6314 the_hash_algo->final_fn(hash, ctx);
6315 the_hash_algo->init_fn(ctx);
6316 /* 20-byte sum, with carry */
6317 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6318 carry += result->hash[i] + hash[i];
6319 result->hash[i] = carry;
6320 carry >>= 8;
6324 static int patch_id_consume(void *priv, char *line, unsigned long len)
6326 struct patch_id_t *data = priv;
6327 int new_len;
6329 if (len > 12 && starts_with(line, "\\ "))
6330 return 0;
6331 new_len = remove_space(line, len);
6333 the_hash_algo->update_fn(data->ctx, line, new_len);
6334 data->patchlen += new_len;
6335 return 0;
6338 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6340 the_hash_algo->update_fn(ctx, str, strlen(str));
6343 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6345 /* large enough for 2^32 in octal */
6346 char buf[12];
6347 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6348 the_hash_algo->update_fn(ctx, buf, len);
6351 /* returns 0 upon success, and writes result into oid */
6352 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6354 struct diff_queue_struct *q = &diff_queued_diff;
6355 int i;
6356 git_hash_ctx ctx;
6357 struct patch_id_t data;
6359 the_hash_algo->init_fn(&ctx);
6360 memset(&data, 0, sizeof(struct patch_id_t));
6361 data.ctx = &ctx;
6362 oidclr(oid);
6364 for (i = 0; i < q->nr; i++) {
6365 xpparam_t xpp;
6366 xdemitconf_t xecfg;
6367 mmfile_t mf1, mf2;
6368 struct diff_filepair *p = q->queue[i];
6369 int len1, len2;
6371 memset(&xpp, 0, sizeof(xpp));
6372 memset(&xecfg, 0, sizeof(xecfg));
6373 if (p->status == 0)
6374 return error("internal diff status error");
6375 if (p->status == DIFF_STATUS_UNKNOWN)
6376 continue;
6377 if (diff_unmodified_pair(p))
6378 continue;
6379 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6380 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6381 continue;
6382 if (DIFF_PAIR_UNMERGED(p))
6383 continue;
6385 diff_fill_oid_info(p->one, options->repo->index);
6386 diff_fill_oid_info(p->two, options->repo->index);
6388 len1 = remove_space(p->one->path, strlen(p->one->path));
6389 len2 = remove_space(p->two->path, strlen(p->two->path));
6390 patch_id_add_string(&ctx, "diff--git");
6391 patch_id_add_string(&ctx, "a/");
6392 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6393 patch_id_add_string(&ctx, "b/");
6394 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6396 if (p->one->mode == 0) {
6397 patch_id_add_string(&ctx, "newfilemode");
6398 patch_id_add_mode(&ctx, p->two->mode);
6399 } else if (p->two->mode == 0) {
6400 patch_id_add_string(&ctx, "deletedfilemode");
6401 patch_id_add_mode(&ctx, p->one->mode);
6402 } else if (p->one->mode != p->two->mode) {
6403 patch_id_add_string(&ctx, "oldmode");
6404 patch_id_add_mode(&ctx, p->one->mode);
6405 patch_id_add_string(&ctx, "newmode");
6406 patch_id_add_mode(&ctx, p->two->mode);
6409 if (diff_header_only) {
6410 /* don't do anything since we're only populating header info */
6411 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6412 diff_filespec_is_binary(options->repo, p->two)) {
6413 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6414 the_hash_algo->hexsz);
6415 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6416 the_hash_algo->hexsz);
6417 } else {
6418 if (p->one->mode == 0) {
6419 patch_id_add_string(&ctx, "---/dev/null");
6420 patch_id_add_string(&ctx, "+++b/");
6421 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6422 } else if (p->two->mode == 0) {
6423 patch_id_add_string(&ctx, "---a/");
6424 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6425 patch_id_add_string(&ctx, "+++/dev/null");
6426 } else {
6427 patch_id_add_string(&ctx, "---a/");
6428 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6429 patch_id_add_string(&ctx, "+++b/");
6430 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6433 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6434 fill_mmfile(options->repo, &mf2, p->two) < 0)
6435 return error("unable to read files to diff");
6436 xpp.flags = 0;
6437 xecfg.ctxlen = 3;
6438 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6439 if (xdi_diff_outf(&mf1, &mf2, NULL,
6440 patch_id_consume, &data, &xpp, &xecfg))
6441 return error("unable to generate patch-id diff for %s",
6442 p->one->path);
6444 flush_one_hunk(oid, &ctx);
6447 return 0;
6450 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6452 struct diff_queue_struct *q = &diff_queued_diff;
6453 int result = diff_get_patch_id(options, oid, diff_header_only);
6455 diff_free_queue(q);
6456 DIFF_QUEUE_CLEAR(q);
6458 return result;
6461 static int is_summary_empty(const struct diff_queue_struct *q)
6463 int i;
6465 for (i = 0; i < q->nr; i++) {
6466 const struct diff_filepair *p = q->queue[i];
6468 switch (p->status) {
6469 case DIFF_STATUS_DELETED:
6470 case DIFF_STATUS_ADDED:
6471 case DIFF_STATUS_COPIED:
6472 case DIFF_STATUS_RENAMED:
6473 return 0;
6474 default:
6475 if (p->score)
6476 return 0;
6477 if (p->one->mode && p->two->mode &&
6478 p->one->mode != p->two->mode)
6479 return 0;
6480 break;
6483 return 1;
6486 static const char rename_limit_warning[] =
6487 N_("exhaustive rename detection was skipped due to too many files.");
6489 static const char degrade_cc_to_c_warning[] =
6490 N_("only found copies from modified paths due to too many files.");
6492 static const char rename_limit_advice[] =
6493 N_("you may want to set your %s variable to at least "
6494 "%d and retry the command.");
6496 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6498 fflush(stdout);
6499 if (degraded_cc)
6500 warning(_(degrade_cc_to_c_warning));
6501 else if (needed)
6502 warning(_(rename_limit_warning));
6503 else
6504 return;
6505 if (0 < needed)
6506 warning(_(rename_limit_advice), varname, needed);
6509 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6511 struct strset present;
6512 struct diff_queue_struct *q = &diff_queued_diff;
6513 struct hashmap_iter iter;
6514 struct strmap_entry *e;
6515 int i;
6517 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6520 * Find out which paths exist in diff_queued_diff, preferring
6521 * one->path for any pair that has multiple paths.
6523 for (i = 0; i < q->nr; i++) {
6524 struct diff_filepair *p = q->queue[i];
6525 char *path = p->one->path ? p->one->path : p->two->path;
6527 if (strmap_contains(o->additional_path_headers, path))
6528 strset_add(&present, path);
6532 * Loop over paths in additional_path_headers; for each NOT already
6533 * in diff_queued_diff, create a synthetic filepair and insert that
6534 * into diff_queued_diff.
6536 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6537 if (!strset_contains(&present, e->key)) {
6538 struct diff_filespec *one, *two;
6539 struct diff_filepair *p;
6541 one = alloc_filespec(e->key);
6542 two = alloc_filespec(e->key);
6543 fill_filespec(one, null_oid(), 0, 0);
6544 fill_filespec(two, null_oid(), 0, 0);
6545 p = diff_queue(q, one, two);
6546 p->status = DIFF_STATUS_MODIFIED;
6550 /* Re-sort the filepairs */
6551 diffcore_fix_diff_index();
6553 /* Cleanup */
6554 strset_clear(&present);
6557 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6559 int i;
6560 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6561 struct diff_queue_struct *q = &diff_queued_diff;
6563 if (WSEH_NEW & WS_RULE_MASK)
6564 BUG("WS rules bit mask overlaps with diff symbol flags");
6566 if (o->color_moved)
6567 o->emitted_symbols = &esm;
6569 if (o->additional_path_headers)
6570 create_filepairs_for_header_only_notifications(o);
6572 for (i = 0; i < q->nr; i++) {
6573 struct diff_filepair *p = q->queue[i];
6574 if (check_pair_status(p))
6575 diff_flush_patch(p, o);
6578 if (o->emitted_symbols) {
6579 if (o->color_moved) {
6580 struct mem_pool entry_pool;
6581 struct moved_entry_list *entry_list;
6583 mem_pool_init(&entry_pool, 1024 * 1024);
6584 entry_list = add_lines_to_move_detection(o,
6585 &entry_pool);
6586 mark_color_as_moved(o, entry_list);
6587 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6588 dim_moved_lines(o);
6590 mem_pool_discard(&entry_pool, 0);
6591 free(entry_list);
6594 for (i = 0; i < esm.nr; i++)
6595 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6597 for (i = 0; i < esm.nr; i++)
6598 free((void *)esm.buf[i].line);
6599 esm.nr = 0;
6601 o->emitted_symbols = NULL;
6605 static void diff_free_file(struct diff_options *options)
6607 if (options->close_file)
6608 fclose(options->file);
6611 static void diff_free_ignore_regex(struct diff_options *options)
6613 int i;
6615 for (i = 0; i < options->ignore_regex_nr; i++) {
6616 regfree(options->ignore_regex[i]);
6617 free(options->ignore_regex[i]);
6619 free(options->ignore_regex);
6622 void diff_free(struct diff_options *options)
6624 if (options->no_free)
6625 return;
6627 diff_free_file(options);
6628 diff_free_ignore_regex(options);
6629 clear_pathspec(&options->pathspec);
6632 void diff_flush(struct diff_options *options)
6634 struct diff_queue_struct *q = &diff_queued_diff;
6635 int i, output_format = options->output_format;
6636 int separator = 0;
6637 int dirstat_by_line = 0;
6640 * Order: raw, stat, summary, patch
6641 * or: name/name-status/checkdiff (other bits clear)
6643 if (!q->nr && !options->additional_path_headers)
6644 goto free_queue;
6646 if (output_format & (DIFF_FORMAT_RAW |
6647 DIFF_FORMAT_NAME |
6648 DIFF_FORMAT_NAME_STATUS |
6649 DIFF_FORMAT_CHECKDIFF)) {
6650 for (i = 0; i < q->nr; i++) {
6651 struct diff_filepair *p = q->queue[i];
6652 if (check_pair_status(p))
6653 flush_one_pair(p, options);
6655 separator++;
6658 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6659 dirstat_by_line = 1;
6661 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6662 dirstat_by_line) {
6663 struct diffstat_t diffstat;
6665 compute_diffstat(options, &diffstat, q);
6666 if (output_format & DIFF_FORMAT_NUMSTAT)
6667 show_numstat(&diffstat, options);
6668 if (output_format & DIFF_FORMAT_DIFFSTAT)
6669 show_stats(&diffstat, options);
6670 if (output_format & DIFF_FORMAT_SHORTSTAT)
6671 show_shortstats(&diffstat, options);
6672 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6673 show_dirstat_by_line(&diffstat, options);
6674 free_diffstat_info(&diffstat);
6675 separator++;
6677 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6678 show_dirstat(options);
6680 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6681 for (i = 0; i < q->nr; i++) {
6682 diff_summary(options, q->queue[i]);
6684 separator++;
6687 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6688 options->flags.exit_with_status &&
6689 options->flags.diff_from_contents) {
6691 * run diff_flush_patch for the exit status. setting
6692 * options->file to /dev/null should be safe, because we
6693 * aren't supposed to produce any output anyway.
6695 diff_free_file(options);
6696 options->file = xfopen("/dev/null", "w");
6697 options->close_file = 1;
6698 options->color_moved = 0;
6699 for (i = 0; i < q->nr; i++) {
6700 struct diff_filepair *p = q->queue[i];
6701 if (check_pair_status(p))
6702 diff_flush_patch(p, options);
6703 if (options->found_changes)
6704 break;
6708 if (output_format & DIFF_FORMAT_PATCH) {
6709 if (separator) {
6710 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6711 if (options->stat_sep)
6712 /* attach patch instead of inline */
6713 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6714 NULL, 0, 0);
6717 diff_flush_patch_all_file_pairs(options);
6720 if (output_format & DIFF_FORMAT_CALLBACK)
6721 options->format_callback(q, options, options->format_callback_data);
6723 free_queue:
6724 diff_free_queue(q);
6725 DIFF_QUEUE_CLEAR(q);
6726 diff_free(options);
6729 * Report the content-level differences with HAS_CHANGES;
6730 * diff_addremove/diff_change does not set the bit when
6731 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6733 if (options->flags.diff_from_contents) {
6734 if (options->found_changes)
6735 options->flags.has_changes = 1;
6736 else
6737 options->flags.has_changes = 0;
6741 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6743 return (((p->status == DIFF_STATUS_MODIFIED) &&
6744 ((p->score &&
6745 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6746 (!p->score &&
6747 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6748 ((p->status != DIFF_STATUS_MODIFIED) &&
6749 filter_bit_tst(p->status, options)));
6752 static void diffcore_apply_filter(struct diff_options *options)
6754 int i;
6755 struct diff_queue_struct *q = &diff_queued_diff;
6756 struct diff_queue_struct outq;
6758 DIFF_QUEUE_CLEAR(&outq);
6760 if (!options->filter)
6761 return;
6763 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6764 int found;
6765 for (i = found = 0; !found && i < q->nr; i++) {
6766 if (match_filter(options, q->queue[i]))
6767 found++;
6769 if (found)
6770 return;
6772 /* otherwise we will clear the whole queue
6773 * by copying the empty outq at the end of this
6774 * function, but first clear the current entries
6775 * in the queue.
6777 for (i = 0; i < q->nr; i++)
6778 diff_free_filepair(q->queue[i]);
6780 else {
6781 /* Only the matching ones */
6782 for (i = 0; i < q->nr; i++) {
6783 struct diff_filepair *p = q->queue[i];
6784 if (match_filter(options, p))
6785 diff_q(&outq, p);
6786 else
6787 diff_free_filepair(p);
6790 free(q->queue);
6791 *q = outq;
6794 /* Check whether two filespecs with the same mode and size are identical */
6795 static int diff_filespec_is_identical(struct repository *r,
6796 struct diff_filespec *one,
6797 struct diff_filespec *two)
6799 if (S_ISGITLINK(one->mode))
6800 return 0;
6801 if (diff_populate_filespec(r, one, NULL))
6802 return 0;
6803 if (diff_populate_filespec(r, two, NULL))
6804 return 0;
6805 return !memcmp(one->data, two->data, one->size);
6808 static int diff_filespec_check_stat_unmatch(struct repository *r,
6809 struct diff_filepair *p)
6811 struct diff_populate_filespec_options dpf_options = {
6812 .check_size_only = 1,
6813 .missing_object_cb = diff_queued_diff_prefetch,
6814 .missing_object_data = r,
6817 if (p->done_skip_stat_unmatch)
6818 return p->skip_stat_unmatch_result;
6820 p->done_skip_stat_unmatch = 1;
6821 p->skip_stat_unmatch_result = 0;
6823 * 1. Entries that come from stat info dirtiness
6824 * always have both sides (iow, not create/delete),
6825 * one side of the object name is unknown, with
6826 * the same mode and size. Keep the ones that
6827 * do not match these criteria. They have real
6828 * differences.
6830 * 2. At this point, the file is known to be modified,
6831 * with the same mode and size, and the object
6832 * name of one side is unknown. Need to inspect
6833 * the identical contents.
6835 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6836 !DIFF_FILE_VALID(p->two) ||
6837 (p->one->oid_valid && p->two->oid_valid) ||
6838 (p->one->mode != p->two->mode) ||
6839 diff_populate_filespec(r, p->one, &dpf_options) ||
6840 diff_populate_filespec(r, p->two, &dpf_options) ||
6841 (p->one->size != p->two->size) ||
6842 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6843 p->skip_stat_unmatch_result = 1;
6844 return p->skip_stat_unmatch_result;
6847 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6849 int i;
6850 struct diff_queue_struct *q = &diff_queued_diff;
6851 struct diff_queue_struct outq;
6852 DIFF_QUEUE_CLEAR(&outq);
6854 for (i = 0; i < q->nr; i++) {
6855 struct diff_filepair *p = q->queue[i];
6857 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6858 diff_q(&outq, p);
6859 else {
6861 * The caller can subtract 1 from skip_stat_unmatch
6862 * to determine how many paths were dirty only
6863 * due to stat info mismatch.
6865 if (!diffopt->flags.no_index)
6866 diffopt->skip_stat_unmatch++;
6867 diff_free_filepair(p);
6870 free(q->queue);
6871 *q = outq;
6874 static int diffnamecmp(const void *a_, const void *b_)
6876 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6877 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6878 const char *name_a, *name_b;
6880 name_a = a->one ? a->one->path : a->two->path;
6881 name_b = b->one ? b->one->path : b->two->path;
6882 return strcmp(name_a, name_b);
6885 void diffcore_fix_diff_index(void)
6887 struct diff_queue_struct *q = &diff_queued_diff;
6888 QSORT(q->queue, q->nr, diffnamecmp);
6891 void diff_add_if_missing(struct repository *r,
6892 struct oid_array *to_fetch,
6893 const struct diff_filespec *filespec)
6895 if (filespec && filespec->oid_valid &&
6896 !S_ISGITLINK(filespec->mode) &&
6897 oid_object_info_extended(r, &filespec->oid, NULL,
6898 OBJECT_INFO_FOR_PREFETCH))
6899 oid_array_append(to_fetch, &filespec->oid);
6902 void diff_queued_diff_prefetch(void *repository)
6904 struct repository *repo = repository;
6905 int i;
6906 struct diff_queue_struct *q = &diff_queued_diff;
6907 struct oid_array to_fetch = OID_ARRAY_INIT;
6909 for (i = 0; i < q->nr; i++) {
6910 struct diff_filepair *p = q->queue[i];
6911 diff_add_if_missing(repo, &to_fetch, p->one);
6912 diff_add_if_missing(repo, &to_fetch, p->two);
6916 * NEEDSWORK: Consider deduplicating the OIDs sent.
6918 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6920 oid_array_clear(&to_fetch);
6923 void diffcore_std(struct diff_options *options)
6925 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6926 DIFF_FORMAT_NUMSTAT |
6927 DIFF_FORMAT_PATCH |
6928 DIFF_FORMAT_SHORTSTAT |
6929 DIFF_FORMAT_DIRSTAT;
6932 * Check if the user requested a blob-data-requiring diff output and/or
6933 * break-rewrite detection (which requires blob data). If yes, prefetch
6934 * the diff pairs.
6936 * If no prefetching occurs, diffcore_rename() will prefetch if it
6937 * decides that it needs inexact rename detection.
6939 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6940 (options->output_format & output_formats_to_prefetch ||
6941 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6942 diff_queued_diff_prefetch(options->repo);
6944 /* NOTE please keep the following in sync with diff_tree_combined() */
6945 if (options->skip_stat_unmatch)
6946 diffcore_skip_stat_unmatch(options);
6947 if (!options->found_follow) {
6948 /* See try_to_follow_renames() in tree-diff.c */
6949 if (options->break_opt != -1)
6950 diffcore_break(options->repo,
6951 options->break_opt);
6952 if (options->detect_rename)
6953 diffcore_rename(options);
6954 if (options->break_opt != -1)
6955 diffcore_merge_broken();
6957 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6958 diffcore_pickaxe(options);
6959 if (options->orderfile)
6960 diffcore_order(options->orderfile);
6961 if (options->rotate_to)
6962 diffcore_rotate(options);
6963 if (!options->found_follow)
6964 /* See try_to_follow_renames() in tree-diff.c */
6965 diff_resolve_rename_copy();
6966 diffcore_apply_filter(options);
6968 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6969 options->flags.has_changes = 1;
6970 else
6971 options->flags.has_changes = 0;
6973 options->found_follow = 0;
6976 int diff_result_code(struct diff_options *opt, int status)
6978 int result = 0;
6980 diff_warn_rename_limit("diff.renameLimit",
6981 opt->needed_rename_limit,
6982 opt->degraded_cc_to_c);
6983 if (!opt->flags.exit_with_status &&
6984 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6985 return status;
6986 if (opt->flags.exit_with_status &&
6987 opt->flags.has_changes)
6988 result |= 01;
6989 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6990 opt->flags.check_failed)
6991 result |= 02;
6992 return result;
6995 int diff_can_quit_early(struct diff_options *opt)
6997 return (opt->flags.quick &&
6998 !opt->filter &&
6999 opt->flags.has_changes);
7003 * Shall changes to this submodule be ignored?
7005 * Submodule changes can be configured to be ignored separately for each path,
7006 * but that configuration can be overridden from the command line.
7008 static int is_submodule_ignored(const char *path, struct diff_options *options)
7010 int ignored = 0;
7011 struct diff_flags orig_flags = options->flags;
7012 if (!options->flags.override_submodule_config)
7013 set_diffopt_flags_from_submodule_config(options, path);
7014 if (options->flags.ignore_submodules)
7015 ignored = 1;
7016 options->flags = orig_flags;
7017 return ignored;
7020 void compute_diffstat(struct diff_options *options,
7021 struct diffstat_t *diffstat,
7022 struct diff_queue_struct *q)
7024 int i;
7026 memset(diffstat, 0, sizeof(struct diffstat_t));
7027 for (i = 0; i < q->nr; i++) {
7028 struct diff_filepair *p = q->queue[i];
7029 if (check_pair_status(p))
7030 diff_flush_stat(p, options, diffstat);
7034 void diff_addremove(struct diff_options *options,
7035 int addremove, unsigned mode,
7036 const struct object_id *oid,
7037 int oid_valid,
7038 const char *concatpath, unsigned dirty_submodule)
7040 struct diff_filespec *one, *two;
7042 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7043 return;
7045 /* This may look odd, but it is a preparation for
7046 * feeding "there are unchanged files which should
7047 * not produce diffs, but when you are doing copy
7048 * detection you would need them, so here they are"
7049 * entries to the diff-core. They will be prefixed
7050 * with something like '=' or '*' (I haven't decided
7051 * which but should not make any difference).
7052 * Feeding the same new and old to diff_change()
7053 * also has the same effect.
7054 * Before the final output happens, they are pruned after
7055 * merged into rename/copy pairs as appropriate.
7057 if (options->flags.reverse_diff)
7058 addremove = (addremove == '+' ? '-' :
7059 addremove == '-' ? '+' : addremove);
7061 if (options->prefix &&
7062 strncmp(concatpath, options->prefix, options->prefix_length))
7063 return;
7065 one = alloc_filespec(concatpath);
7066 two = alloc_filespec(concatpath);
7068 if (addremove != '+')
7069 fill_filespec(one, oid, oid_valid, mode);
7070 if (addremove != '-') {
7071 fill_filespec(two, oid, oid_valid, mode);
7072 two->dirty_submodule = dirty_submodule;
7075 diff_queue(&diff_queued_diff, one, two);
7076 if (!options->flags.diff_from_contents)
7077 options->flags.has_changes = 1;
7080 void diff_change(struct diff_options *options,
7081 unsigned old_mode, unsigned new_mode,
7082 const struct object_id *old_oid,
7083 const struct object_id *new_oid,
7084 int old_oid_valid, int new_oid_valid,
7085 const char *concatpath,
7086 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7088 struct diff_filespec *one, *two;
7089 struct diff_filepair *p;
7091 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7092 is_submodule_ignored(concatpath, options))
7093 return;
7095 if (options->flags.reverse_diff) {
7096 SWAP(old_mode, new_mode);
7097 SWAP(old_oid, new_oid);
7098 SWAP(old_oid_valid, new_oid_valid);
7099 SWAP(old_dirty_submodule, new_dirty_submodule);
7102 if (options->prefix &&
7103 strncmp(concatpath, options->prefix, options->prefix_length))
7104 return;
7106 one = alloc_filespec(concatpath);
7107 two = alloc_filespec(concatpath);
7108 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7109 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7110 one->dirty_submodule = old_dirty_submodule;
7111 two->dirty_submodule = new_dirty_submodule;
7112 p = diff_queue(&diff_queued_diff, one, two);
7114 if (options->flags.diff_from_contents)
7115 return;
7117 if (options->flags.quick && options->skip_stat_unmatch &&
7118 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7119 diff_free_filespec_data(p->one);
7120 diff_free_filespec_data(p->two);
7121 return;
7124 options->flags.has_changes = 1;
7127 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7129 struct diff_filepair *pair;
7130 struct diff_filespec *one, *two;
7132 if (options->prefix &&
7133 strncmp(path, options->prefix, options->prefix_length))
7134 return NULL;
7136 one = alloc_filespec(path);
7137 two = alloc_filespec(path);
7138 pair = diff_queue(&diff_queued_diff, one, two);
7139 pair->is_unmerged = 1;
7140 return pair;
7143 static char *run_textconv(struct repository *r,
7144 const char *pgm,
7145 struct diff_filespec *spec,
7146 size_t *outsize)
7148 struct diff_tempfile *temp;
7149 struct child_process child = CHILD_PROCESS_INIT;
7150 struct strbuf buf = STRBUF_INIT;
7151 int err = 0;
7153 temp = prepare_temp_file(r, spec);
7154 strvec_push(&child.args, pgm);
7155 strvec_push(&child.args, temp->name);
7157 child.use_shell = 1;
7158 child.out = -1;
7159 if (start_command(&child)) {
7160 remove_tempfile();
7161 return NULL;
7164 if (strbuf_read(&buf, child.out, 0) < 0)
7165 err = error("error reading from textconv command '%s'", pgm);
7166 close(child.out);
7168 if (finish_command(&child) || err) {
7169 strbuf_release(&buf);
7170 remove_tempfile();
7171 return NULL;
7173 remove_tempfile();
7175 return strbuf_detach(&buf, outsize);
7178 size_t fill_textconv(struct repository *r,
7179 struct userdiff_driver *driver,
7180 struct diff_filespec *df,
7181 char **outbuf)
7183 size_t size;
7185 if (!driver) {
7186 if (!DIFF_FILE_VALID(df)) {
7187 *outbuf = "";
7188 return 0;
7190 if (diff_populate_filespec(r, df, NULL))
7191 die("unable to read files to diff");
7192 *outbuf = df->data;
7193 return df->size;
7196 if (!driver->textconv)
7197 BUG("fill_textconv called with non-textconv driver");
7199 if (driver->textconv_cache && df->oid_valid) {
7200 *outbuf = notes_cache_get(driver->textconv_cache,
7201 &df->oid,
7202 &size);
7203 if (*outbuf)
7204 return size;
7207 *outbuf = run_textconv(r, driver->textconv, df, &size);
7208 if (!*outbuf)
7209 die("unable to read files to diff");
7211 if (driver->textconv_cache && df->oid_valid) {
7212 /* ignore errors, as we might be in a readonly repository */
7213 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7214 size);
7216 * we could save up changes and flush them all at the end,
7217 * but we would need an extra call after all diffing is done.
7218 * Since generating a cache entry is the slow path anyway,
7219 * this extra overhead probably isn't a big deal.
7221 notes_cache_write(driver->textconv_cache);
7224 return size;
7227 int textconv_object(struct repository *r,
7228 const char *path,
7229 unsigned mode,
7230 const struct object_id *oid,
7231 int oid_valid,
7232 char **buf,
7233 unsigned long *buf_size)
7235 struct diff_filespec *df;
7236 struct userdiff_driver *textconv;
7238 df = alloc_filespec(path);
7239 fill_filespec(df, oid, oid_valid, mode);
7240 textconv = get_textconv(r, df);
7241 if (!textconv) {
7242 free_filespec(df);
7243 return 0;
7246 *buf_size = fill_textconv(r, textconv, df, buf);
7247 free_filespec(df);
7248 return 1;
7251 void setup_diff_pager(struct diff_options *opt)
7254 * If the user asked for our exit code, then either they want --quiet
7255 * or --exit-code. We should definitely not bother with a pager in the
7256 * former case, as we will generate no output. Since we still properly
7257 * report our exit code even when a pager is run, we _could_ run a
7258 * pager with --exit-code. But since we have not done so historically,
7259 * and because it is easy to find people oneline advising "git diff
7260 * --exit-code" in hooks and other scripts, we do not do so.
7262 if (!opt->flags.exit_with_status &&
7263 check_pager_config("diff") != 0)
7264 setup_pager();