Merge branch 'pb/complete-diff-options'
[git/debian.git] / diff.c
blob788382eea040db4bf6adafdeb824750f4d59b89f
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "alloc.h"
7 #include "base85.h"
8 #include "config.h"
9 #include "convert.h"
10 #include "environment.h"
11 #include "gettext.h"
12 #include "tempfile.h"
13 #include "quote.h"
14 #include "diff.h"
15 #include "diffcore.h"
16 #include "delta.h"
17 #include "hex.h"
18 #include "xdiff-interface.h"
19 #include "color.h"
20 #include "attr.h"
21 #include "run-command.h"
22 #include "utf8.h"
23 #include "object-store-ll.h"
24 #include "userdiff.h"
25 #include "submodule-config.h"
26 #include "submodule.h"
27 #include "hashmap.h"
28 #include "mem-pool.h"
29 #include "merge-ll.h"
30 #include "string-list.h"
31 #include "strvec.h"
32 #include "graph.h"
33 #include "oid-array.h"
34 #include "packfile.h"
35 #include "pager.h"
36 #include "parse-options.h"
37 #include "help.h"
38 #include "promisor-remote.h"
39 #include "dir.h"
40 #include "object-file.h"
41 #include "object-name.h"
42 #include "read-cache-ll.h"
43 #include "setup.h"
44 #include "strmap.h"
45 #include "ws.h"
46 #include "wrapper.h"
48 #ifdef NO_FAST_WORKING_DIRECTORY
49 #define FAST_WORKING_DIRECTORY 0
50 #else
51 #define FAST_WORKING_DIRECTORY 1
52 #endif
54 static int diff_detect_rename_default;
55 static int diff_indent_heuristic = 1;
56 static int diff_rename_limit_default = 1000;
57 static int diff_suppress_blank_empty;
58 static int diff_use_color_default = -1;
59 static int diff_color_moved_default;
60 static int diff_color_moved_ws_default;
61 static int diff_context_default = 3;
62 static int diff_interhunk_context_default;
63 static const char *diff_word_regex_cfg;
64 static const char *external_diff_cmd_cfg;
65 static const char *diff_order_file_cfg;
66 int diff_auto_refresh_index = 1;
67 static int diff_mnemonic_prefix;
68 static int diff_no_prefix;
69 static int diff_relative;
70 static int diff_stat_graph_width;
71 static int diff_dirstat_permille_default = 30;
72 static struct diff_options default_diff_options;
73 static long diff_algorithm;
74 static unsigned ws_error_highlight_default = WSEH_NEW;
76 static char diff_colors[][COLOR_MAXLEN] = {
77 GIT_COLOR_RESET,
78 GIT_COLOR_NORMAL, /* CONTEXT */
79 GIT_COLOR_BOLD, /* METAINFO */
80 GIT_COLOR_CYAN, /* FRAGINFO */
81 GIT_COLOR_RED, /* OLD */
82 GIT_COLOR_GREEN, /* NEW */
83 GIT_COLOR_YELLOW, /* COMMIT */
84 GIT_COLOR_BG_RED, /* WHITESPACE */
85 GIT_COLOR_NORMAL, /* FUNCINFO */
86 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
87 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
88 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
89 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
90 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
91 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
92 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
93 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
94 GIT_COLOR_FAINT, /* CONTEXT_DIM */
95 GIT_COLOR_FAINT_RED, /* OLD_DIM */
96 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
97 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
98 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
99 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
102 static const char *color_diff_slots[] = {
103 [DIFF_CONTEXT] = "context",
104 [DIFF_METAINFO] = "meta",
105 [DIFF_FRAGINFO] = "frag",
106 [DIFF_FILE_OLD] = "old",
107 [DIFF_FILE_NEW] = "new",
108 [DIFF_COMMIT] = "commit",
109 [DIFF_WHITESPACE] = "whitespace",
110 [DIFF_FUNCINFO] = "func",
111 [DIFF_FILE_OLD_MOVED] = "oldMoved",
112 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
113 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
114 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
115 [DIFF_FILE_NEW_MOVED] = "newMoved",
116 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
117 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
118 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
119 [DIFF_CONTEXT_DIM] = "contextDimmed",
120 [DIFF_FILE_OLD_DIM] = "oldDimmed",
121 [DIFF_FILE_NEW_DIM] = "newDimmed",
122 [DIFF_CONTEXT_BOLD] = "contextBold",
123 [DIFF_FILE_OLD_BOLD] = "oldBold",
124 [DIFF_FILE_NEW_BOLD] = "newBold",
127 define_list_config_array_extra(color_diff_slots, {"plain"});
129 static int parse_diff_color_slot(const char *var)
131 if (!strcasecmp(var, "plain"))
132 return DIFF_CONTEXT;
133 return LOOKUP_CONFIG(color_diff_slots, var);
136 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
137 struct strbuf *errmsg)
139 char *params_copy = xstrdup(params_string);
140 struct string_list params = STRING_LIST_INIT_NODUP;
141 int ret = 0;
142 int i;
144 if (*params_copy)
145 string_list_split_in_place(&params, params_copy, ",", -1);
146 for (i = 0; i < params.nr; i++) {
147 const char *p = params.items[i].string;
148 if (!strcmp(p, "changes")) {
149 options->flags.dirstat_by_line = 0;
150 options->flags.dirstat_by_file = 0;
151 } else if (!strcmp(p, "lines")) {
152 options->flags.dirstat_by_line = 1;
153 options->flags.dirstat_by_file = 0;
154 } else if (!strcmp(p, "files")) {
155 options->flags.dirstat_by_line = 0;
156 options->flags.dirstat_by_file = 1;
157 } else if (!strcmp(p, "noncumulative")) {
158 options->flags.dirstat_cumulative = 0;
159 } else if (!strcmp(p, "cumulative")) {
160 options->flags.dirstat_cumulative = 1;
161 } else if (isdigit(*p)) {
162 char *end;
163 int permille = strtoul(p, &end, 10) * 10;
164 if (*end == '.' && isdigit(*++end)) {
165 /* only use first digit */
166 permille += *end - '0';
167 /* .. and ignore any further digits */
168 while (isdigit(*++end))
169 ; /* nothing */
171 if (!*end)
172 options->dirstat_permille = permille;
173 else {
174 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
176 ret++;
178 } else {
179 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
180 ret++;
184 string_list_clear(&params, 0);
185 free(params_copy);
186 return ret;
189 static int parse_submodule_params(struct diff_options *options, const char *value)
191 if (!strcmp(value, "log"))
192 options->submodule_format = DIFF_SUBMODULE_LOG;
193 else if (!strcmp(value, "short"))
194 options->submodule_format = DIFF_SUBMODULE_SHORT;
195 else if (!strcmp(value, "diff"))
196 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
198 * Please update $__git_diff_submodule_formats in
199 * git-completion.bash when you add new formats.
201 else
202 return -1;
203 return 0;
206 int git_config_rename(const char *var, const char *value)
208 if (!value)
209 return DIFF_DETECT_RENAME;
210 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
211 return DIFF_DETECT_COPY;
212 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
215 long parse_algorithm_value(const char *value)
217 if (!value)
218 return -1;
219 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
220 return 0;
221 else if (!strcasecmp(value, "minimal"))
222 return XDF_NEED_MINIMAL;
223 else if (!strcasecmp(value, "patience"))
224 return XDF_PATIENCE_DIFF;
225 else if (!strcasecmp(value, "histogram"))
226 return XDF_HISTOGRAM_DIFF;
228 * Please update $__git_diff_algorithms in git-completion.bash
229 * when you add new algorithms.
231 return -1;
234 static int parse_one_token(const char **arg, const char *token)
236 const char *rest;
237 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
238 *arg = rest;
239 return 1;
241 return 0;
244 static int parse_ws_error_highlight(const char *arg)
246 const char *orig_arg = arg;
247 unsigned val = 0;
249 while (*arg) {
250 if (parse_one_token(&arg, "none"))
251 val = 0;
252 else if (parse_one_token(&arg, "default"))
253 val = WSEH_NEW;
254 else if (parse_one_token(&arg, "all"))
255 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
256 else if (parse_one_token(&arg, "new"))
257 val |= WSEH_NEW;
258 else if (parse_one_token(&arg, "old"))
259 val |= WSEH_OLD;
260 else if (parse_one_token(&arg, "context"))
261 val |= WSEH_CONTEXT;
262 else {
263 return -1 - (int)(arg - orig_arg);
265 if (*arg)
266 arg++;
268 return val;
272 * These are to give UI layer defaults.
273 * The core-level commands such as git-diff-files should
274 * never be affected by the setting of diff.renames
275 * the user happens to have in the configuration file.
277 void init_diff_ui_defaults(void)
279 diff_detect_rename_default = DIFF_DETECT_RENAME;
282 int git_diff_heuristic_config(const char *var, const char *value,
283 void *cb UNUSED)
285 if (!strcmp(var, "diff.indentheuristic"))
286 diff_indent_heuristic = git_config_bool(var, value);
287 return 0;
290 static int parse_color_moved(const char *arg)
292 switch (git_parse_maybe_bool(arg)) {
293 case 0:
294 return COLOR_MOVED_NO;
295 case 1:
296 return COLOR_MOVED_DEFAULT;
297 default:
298 break;
301 if (!strcmp(arg, "no"))
302 return COLOR_MOVED_NO;
303 else if (!strcmp(arg, "plain"))
304 return COLOR_MOVED_PLAIN;
305 else if (!strcmp(arg, "blocks"))
306 return COLOR_MOVED_BLOCKS;
307 else if (!strcmp(arg, "zebra"))
308 return COLOR_MOVED_ZEBRA;
309 else if (!strcmp(arg, "default"))
310 return COLOR_MOVED_DEFAULT;
311 else if (!strcmp(arg, "dimmed-zebra"))
312 return COLOR_MOVED_ZEBRA_DIM;
313 else if (!strcmp(arg, "dimmed_zebra"))
314 return COLOR_MOVED_ZEBRA_DIM;
315 else
316 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
319 static unsigned parse_color_moved_ws(const char *arg)
321 int ret = 0;
322 struct string_list l = STRING_LIST_INIT_DUP;
323 struct string_list_item *i;
325 string_list_split(&l, arg, ',', -1);
327 for_each_string_list_item(i, &l) {
328 struct strbuf sb = STRBUF_INIT;
329 strbuf_addstr(&sb, i->string);
330 strbuf_trim(&sb);
332 if (!strcmp(sb.buf, "no"))
333 ret = 0;
334 else if (!strcmp(sb.buf, "ignore-space-change"))
335 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
336 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
337 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
338 else if (!strcmp(sb.buf, "ignore-all-space"))
339 ret |= XDF_IGNORE_WHITESPACE;
340 else if (!strcmp(sb.buf, "allow-indentation-change"))
341 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
342 else {
343 ret |= COLOR_MOVED_WS_ERROR;
344 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);
347 strbuf_release(&sb);
350 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
351 (ret & XDF_WHITESPACE_FLAGS)) {
352 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
353 ret |= COLOR_MOVED_WS_ERROR;
356 string_list_clear(&l, 0);
358 return ret;
361 int git_diff_ui_config(const char *var, const char *value, void *cb)
363 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
364 diff_use_color_default = git_config_colorbool(var, value);
365 return 0;
367 if (!strcmp(var, "diff.colormoved")) {
368 int cm = parse_color_moved(value);
369 if (cm < 0)
370 return -1;
371 diff_color_moved_default = cm;
372 return 0;
374 if (!strcmp(var, "diff.colormovedws")) {
375 unsigned cm = parse_color_moved_ws(value);
376 if (cm & COLOR_MOVED_WS_ERROR)
377 return -1;
378 diff_color_moved_ws_default = cm;
379 return 0;
381 if (!strcmp(var, "diff.context")) {
382 diff_context_default = git_config_int(var, value);
383 if (diff_context_default < 0)
384 return -1;
385 return 0;
387 if (!strcmp(var, "diff.interhunkcontext")) {
388 diff_interhunk_context_default = git_config_int(var, value);
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);
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, cb);
447 int git_diff_basic_config(const char *var, const char *value, void *cb)
449 const char *name;
451 if (!strcmp(var, "diff.renamelimit")) {
452 diff_rename_limit_default = git_config_int(var, value);
453 return 0;
456 if (userdiff_config(var, value) < 0)
457 return -1;
459 if (skip_prefix(var, "diff.color.", &name) ||
460 skip_prefix(var, "color.diff.", &name)) {
461 int slot = parse_diff_color_slot(name);
462 if (slot < 0)
463 return 0;
464 if (!value)
465 return config_error_nonbool(var);
466 return color_parse(value, diff_colors[slot]);
469 if (!strcmp(var, "diff.wserrorhighlight")) {
470 int val = parse_ws_error_highlight(value);
471 if (val < 0)
472 return -1;
473 ws_error_highlight_default = val;
474 return 0;
477 /* like GNU diff's --suppress-blank-empty option */
478 if (!strcmp(var, "diff.suppressblankempty") ||
479 /* for backwards compatibility */
480 !strcmp(var, "diff.suppress-blank-empty")) {
481 diff_suppress_blank_empty = git_config_bool(var, value);
482 return 0;
485 if (!strcmp(var, "diff.dirstat")) {
486 struct strbuf errmsg = STRBUF_INIT;
487 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
488 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
489 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
490 errmsg.buf);
491 strbuf_release(&errmsg);
492 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
493 return 0;
496 if (git_diff_heuristic_config(var, value, cb) < 0)
497 return -1;
499 return git_default_config(var, value, cb);
502 static char *quote_two(const char *one, const char *two)
504 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
505 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
506 struct strbuf res = STRBUF_INIT;
508 if (need_one + need_two) {
509 strbuf_addch(&res, '"');
510 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
511 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
512 strbuf_addch(&res, '"');
513 } else {
514 strbuf_addstr(&res, one);
515 strbuf_addstr(&res, two);
517 return strbuf_detach(&res, NULL);
520 static const char *external_diff(void)
522 static const char *external_diff_cmd = NULL;
523 static int done_preparing = 0;
525 if (done_preparing)
526 return external_diff_cmd;
527 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
528 if (!external_diff_cmd)
529 external_diff_cmd = external_diff_cmd_cfg;
530 done_preparing = 1;
531 return external_diff_cmd;
535 * Keep track of files used for diffing. Sometimes such an entry
536 * refers to a temporary file, sometimes to an existing file, and
537 * sometimes to "/dev/null".
539 static struct diff_tempfile {
541 * filename external diff should read from, or NULL if this
542 * entry is currently not in use:
544 const char *name;
546 char hex[GIT_MAX_HEXSZ + 1];
547 char mode[10];
550 * If this diff_tempfile instance refers to a temporary file,
551 * this tempfile object is used to manage its lifetime.
553 struct tempfile *tempfile;
554 } diff_temp[2];
556 struct emit_callback {
557 int color_diff;
558 unsigned ws_rule;
559 int blank_at_eof_in_preimage;
560 int blank_at_eof_in_postimage;
561 int lno_in_preimage;
562 int lno_in_postimage;
563 const char **label_path;
564 struct diff_words_data *diff_words;
565 struct diff_options *opt;
566 struct strbuf *header;
569 static int count_lines(const char *data, int size)
571 int count, ch, completely_empty = 1, nl_just_seen = 0;
572 count = 0;
573 while (0 < size--) {
574 ch = *data++;
575 if (ch == '\n') {
576 count++;
577 nl_just_seen = 1;
578 completely_empty = 0;
580 else {
581 nl_just_seen = 0;
582 completely_empty = 0;
585 if (completely_empty)
586 return 0;
587 if (!nl_just_seen)
588 count++; /* no trailing newline */
589 return count;
592 static int fill_mmfile(struct repository *r, mmfile_t *mf,
593 struct diff_filespec *one)
595 if (!DIFF_FILE_VALID(one)) {
596 mf->ptr = (char *)""; /* does not matter */
597 mf->size = 0;
598 return 0;
600 else if (diff_populate_filespec(r, one, NULL))
601 return -1;
603 mf->ptr = one->data;
604 mf->size = one->size;
605 return 0;
608 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
609 static unsigned long diff_filespec_size(struct repository *r,
610 struct diff_filespec *one)
612 struct diff_populate_filespec_options dpf_options = {
613 .check_size_only = 1,
616 if (!DIFF_FILE_VALID(one))
617 return 0;
618 diff_populate_filespec(r, one, &dpf_options);
619 return one->size;
622 static int count_trailing_blank(mmfile_t *mf)
624 char *ptr = mf->ptr;
625 long size = mf->size;
626 int cnt = 0;
628 if (!size)
629 return cnt;
630 ptr += size - 1; /* pointing at the very end */
631 if (*ptr != '\n')
632 ; /* incomplete line */
633 else
634 ptr--; /* skip the last LF */
635 while (mf->ptr < ptr) {
636 char *prev_eol;
637 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
638 if (*prev_eol == '\n')
639 break;
640 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
641 break;
642 cnt++;
643 ptr = prev_eol - 1;
645 return cnt;
648 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
649 struct emit_callback *ecbdata)
651 int l1, l2, at;
652 l1 = count_trailing_blank(mf1);
653 l2 = count_trailing_blank(mf2);
654 if (l2 <= l1) {
655 ecbdata->blank_at_eof_in_preimage = 0;
656 ecbdata->blank_at_eof_in_postimage = 0;
657 return;
659 at = count_lines(mf1->ptr, mf1->size);
660 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
662 at = count_lines(mf2->ptr, mf2->size);
663 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
666 static void emit_line_0(struct diff_options *o,
667 const char *set_sign, const char *set, unsigned reverse, const char *reset,
668 int first, const char *line, int len)
670 int has_trailing_newline, has_trailing_carriage_return;
671 int needs_reset = 0; /* at the end of the line */
672 FILE *file = o->file;
674 fputs(diff_line_prefix(o), file);
676 has_trailing_newline = (len > 0 && line[len-1] == '\n');
677 if (has_trailing_newline)
678 len--;
680 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
681 if (has_trailing_carriage_return)
682 len--;
684 if (!len && !first)
685 goto end_of_line;
687 if (reverse && want_color(o->use_color)) {
688 fputs(GIT_COLOR_REVERSE, file);
689 needs_reset = 1;
692 if (set_sign) {
693 fputs(set_sign, file);
694 needs_reset = 1;
697 if (first)
698 fputc(first, file);
700 if (!len)
701 goto end_of_line;
703 if (set) {
704 if (set_sign && set != set_sign)
705 fputs(reset, file);
706 fputs(set, file);
707 needs_reset = 1;
709 fwrite(line, len, 1, file);
710 needs_reset = 1; /* 'line' may contain color codes. */
712 end_of_line:
713 if (needs_reset)
714 fputs(reset, file);
715 if (has_trailing_carriage_return)
716 fputc('\r', file);
717 if (has_trailing_newline)
718 fputc('\n', file);
721 static void emit_line(struct diff_options *o, const char *set, const char *reset,
722 const char *line, int len)
724 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
727 enum diff_symbol {
728 DIFF_SYMBOL_BINARY_DIFF_HEADER,
729 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
730 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
731 DIFF_SYMBOL_BINARY_DIFF_BODY,
732 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
733 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
734 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
735 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
736 DIFF_SYMBOL_STATS_LINE,
737 DIFF_SYMBOL_WORD_DIFF,
738 DIFF_SYMBOL_STAT_SEP,
739 DIFF_SYMBOL_SUMMARY,
740 DIFF_SYMBOL_SUBMODULE_ADD,
741 DIFF_SYMBOL_SUBMODULE_DEL,
742 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
743 DIFF_SYMBOL_SUBMODULE_MODIFIED,
744 DIFF_SYMBOL_SUBMODULE_HEADER,
745 DIFF_SYMBOL_SUBMODULE_ERROR,
746 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
747 DIFF_SYMBOL_REWRITE_DIFF,
748 DIFF_SYMBOL_BINARY_FILES,
749 DIFF_SYMBOL_HEADER,
750 DIFF_SYMBOL_FILEPAIR_PLUS,
751 DIFF_SYMBOL_FILEPAIR_MINUS,
752 DIFF_SYMBOL_WORDS_PORCELAIN,
753 DIFF_SYMBOL_WORDS,
754 DIFF_SYMBOL_CONTEXT,
755 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
756 DIFF_SYMBOL_PLUS,
757 DIFF_SYMBOL_MINUS,
758 DIFF_SYMBOL_NO_LF_EOF,
759 DIFF_SYMBOL_CONTEXT_FRAGINFO,
760 DIFF_SYMBOL_CONTEXT_MARKER,
761 DIFF_SYMBOL_SEPARATOR
764 * Flags for content lines:
765 * 0..12 are whitespace rules
766 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
767 * 16 is marking if the line is blank at EOF
769 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
770 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
771 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
772 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
773 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
776 * This struct is used when we need to buffer the output of the diff output.
778 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
779 * into the pre/post image file. This pointer could be a union with the
780 * line pointer. By storing an offset into the file instead of the literal line,
781 * we can decrease the memory footprint for the buffered output. At first we
782 * may want to only have indirection for the content lines, but we could also
783 * enhance the state for emitting prefabricated lines, e.g. the similarity
784 * score line or hunk/file headers would only need to store a number or path
785 * and then the output can be constructed later on depending on state.
787 struct emitted_diff_symbol {
788 const char *line;
789 int len;
790 int flags;
791 int indent_off; /* Offset to first non-whitespace character */
792 int indent_width; /* The visual width of the indentation */
793 unsigned id;
794 enum diff_symbol s;
796 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
798 struct emitted_diff_symbols {
799 struct emitted_diff_symbol *buf;
800 int nr, alloc;
802 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
804 static void append_emitted_diff_symbol(struct diff_options *o,
805 struct emitted_diff_symbol *e)
807 struct emitted_diff_symbol *f;
809 ALLOC_GROW(o->emitted_symbols->buf,
810 o->emitted_symbols->nr + 1,
811 o->emitted_symbols->alloc);
812 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
814 memcpy(f, e, sizeof(struct emitted_diff_symbol));
815 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
818 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
820 if (!e)
821 return;
822 free(e->buf);
823 free(e);
826 struct moved_entry {
827 const struct emitted_diff_symbol *es;
828 struct moved_entry *next_line;
829 struct moved_entry *next_match;
832 struct moved_block {
833 struct moved_entry *match;
834 int wsd; /* The whitespace delta of this block */
837 #define INDENT_BLANKLINE INT_MIN
839 static void fill_es_indent_data(struct emitted_diff_symbol *es)
841 unsigned int off = 0, i;
842 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
843 const char *s = es->line;
844 const int len = es->len;
846 /* skip any \v \f \r at start of indentation */
847 while (s[off] == '\f' || s[off] == '\v' ||
848 (s[off] == '\r' && off < len - 1))
849 off++;
851 /* calculate the visual width of indentation */
852 while(1) {
853 if (s[off] == ' ') {
854 width++;
855 off++;
856 } else if (s[off] == '\t') {
857 width += tab_width - (width % tab_width);
858 while (s[++off] == '\t')
859 width += tab_width;
860 } else {
861 break;
865 /* check if this line is blank */
866 for (i = off; i < len; i++)
867 if (!isspace(s[i]))
868 break;
870 if (i == len) {
871 es->indent_width = INDENT_BLANKLINE;
872 es->indent_off = len;
873 } else {
874 es->indent_off = off;
875 es->indent_width = width;
879 static int compute_ws_delta(const struct emitted_diff_symbol *a,
880 const struct emitted_diff_symbol *b)
882 int a_width = a->indent_width,
883 b_width = b->indent_width;
885 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
886 return INDENT_BLANKLINE;
888 return a_width - b_width;
891 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
892 const struct emitted_diff_symbol *l,
893 struct moved_block *pmb)
895 int a_width = cur->es->indent_width, b_width = l->indent_width;
896 int delta;
898 /* The text of each line must match */
899 if (cur->es->id != l->id)
900 return 1;
903 * If 'l' and 'cur' are both blank then we don't need to check the
904 * indent. We only need to check cur as we know the strings match.
905 * */
906 if (a_width == INDENT_BLANKLINE)
907 return 0;
910 * The indent changes of the block are known and stored in pmb->wsd;
911 * however we need to check if the indent changes of the current line
912 * match those of the current block.
914 delta = b_width - a_width;
917 * If the previous lines of this block were all blank then set its
918 * whitespace delta.
920 if (pmb->wsd == INDENT_BLANKLINE)
921 pmb->wsd = delta;
923 return delta != pmb->wsd;
926 struct interned_diff_symbol {
927 struct hashmap_entry ent;
928 struct emitted_diff_symbol *es;
931 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
932 const struct hashmap_entry *eptr,
933 const struct hashmap_entry *entry_or_key,
934 const void *keydata UNUSED)
936 const struct diff_options *diffopt = hashmap_cmp_fn_data;
937 const struct emitted_diff_symbol *a, *b;
938 unsigned flags = diffopt->color_moved_ws_handling
939 & XDF_WHITESPACE_FLAGS;
941 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
942 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
944 return !xdiff_compare_lines(a->line + a->indent_off,
945 a->len - a->indent_off,
946 b->line + b->indent_off,
947 b->len - b->indent_off, flags);
950 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
951 struct interned_diff_symbol *s)
953 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
954 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
955 l->len - l->indent_off, flags);
957 hashmap_entry_init(&s->ent, hash);
958 s->es = l;
961 struct moved_entry_list {
962 struct moved_entry *add, *del;
965 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
966 struct mem_pool *entry_mem_pool)
968 struct moved_entry *prev_line = NULL;
969 struct mem_pool interned_pool;
970 struct hashmap interned_map;
971 struct moved_entry_list *entry_list = NULL;
972 size_t entry_list_alloc = 0;
973 unsigned id = 0;
974 int n;
976 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
977 mem_pool_init(&interned_pool, 1024 * 1024);
979 for (n = 0; n < o->emitted_symbols->nr; n++) {
980 struct interned_diff_symbol key;
981 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
982 struct interned_diff_symbol *s;
983 struct moved_entry *entry;
985 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
986 prev_line = NULL;
987 continue;
990 if (o->color_moved_ws_handling &
991 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
992 fill_es_indent_data(l);
994 prepare_entry(o, l, &key);
995 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
996 if (s) {
997 l->id = s->es->id;
998 } else {
999 l->id = id;
1000 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1001 hashmap_add(&interned_map,
1002 memcpy(mem_pool_alloc(&interned_pool,
1003 sizeof(key)),
1004 &key, sizeof(key)));
1006 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1007 entry->es = l;
1008 entry->next_line = NULL;
1009 if (prev_line && prev_line->es->s == l->s)
1010 prev_line->next_line = entry;
1011 prev_line = entry;
1012 if (l->s == DIFF_SYMBOL_PLUS) {
1013 entry->next_match = entry_list[l->id].add;
1014 entry_list[l->id].add = entry;
1015 } else {
1016 entry->next_match = entry_list[l->id].del;
1017 entry_list[l->id].del = entry;
1021 hashmap_clear(&interned_map);
1022 mem_pool_discard(&interned_pool, 0);
1024 return entry_list;
1027 static void pmb_advance_or_null(struct diff_options *o,
1028 struct emitted_diff_symbol *l,
1029 struct moved_block *pmb,
1030 int *pmb_nr)
1032 int i, j;
1034 for (i = 0, j = 0; i < *pmb_nr; i++) {
1035 int match;
1036 struct moved_entry *prev = pmb[i].match;
1037 struct moved_entry *cur = (prev && prev->next_line) ?
1038 prev->next_line : NULL;
1040 if (o->color_moved_ws_handling &
1041 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1042 match = cur &&
1043 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1044 else
1045 match = cur && cur->es->id == l->id;
1047 if (match) {
1048 pmb[j] = pmb[i];
1049 pmb[j++].match = cur;
1052 *pmb_nr = j;
1055 static void fill_potential_moved_blocks(struct diff_options *o,
1056 struct moved_entry *match,
1057 struct emitted_diff_symbol *l,
1058 struct moved_block **pmb_p,
1059 int *pmb_alloc_p, int *pmb_nr_p)
1062 struct moved_block *pmb = *pmb_p;
1063 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1066 * The current line is the start of a new block.
1067 * Setup the set of potential blocks.
1069 for (; match; match = match->next_match) {
1070 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1071 if (o->color_moved_ws_handling &
1072 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1073 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1074 else
1075 pmb[pmb_nr].wsd = 0;
1076 pmb[pmb_nr++].match = match;
1079 *pmb_p = pmb;
1080 *pmb_alloc_p = pmb_alloc;
1081 *pmb_nr_p = pmb_nr;
1085 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1087 * Otherwise, if the last block has fewer alphanumeric characters than
1088 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1089 * that block.
1091 * The last block consists of the (n - block_length)'th line up to but not
1092 * including the nth line.
1094 * Returns 0 if the last block is empty or is unset by this function, non zero
1095 * otherwise.
1097 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1098 * Think of a way to unify them.
1100 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1101 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1102 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1104 int i, alnum_count = 0;
1105 if (o->color_moved == COLOR_MOVED_PLAIN)
1106 return block_length;
1107 for (i = 1; i < block_length + 1; i++) {
1108 const char *c = o->emitted_symbols->buf[n - i].line;
1109 for (; *c; c++) {
1110 if (!isalnum(*c))
1111 continue;
1112 alnum_count++;
1113 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1114 return 1;
1117 for (i = 1; i < block_length + 1; i++)
1118 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1119 return 0;
1122 /* Find blocks of moved code, delegate actual coloring decision to helper */
1123 static void mark_color_as_moved(struct diff_options *o,
1124 struct moved_entry_list *entry_list)
1126 struct moved_block *pmb = NULL; /* potentially moved blocks */
1127 int pmb_nr = 0, pmb_alloc = 0;
1128 int n, flipped_block = 0, block_length = 0;
1129 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1132 for (n = 0; n < o->emitted_symbols->nr; n++) {
1133 struct moved_entry *match = NULL;
1134 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1136 switch (l->s) {
1137 case DIFF_SYMBOL_PLUS:
1138 match = entry_list[l->id].del;
1139 break;
1140 case DIFF_SYMBOL_MINUS:
1141 match = entry_list[l->id].add;
1142 break;
1143 default:
1144 flipped_block = 0;
1147 if (pmb_nr && (!match || l->s != moved_symbol)) {
1148 if (!adjust_last_block(o, n, block_length) &&
1149 block_length > 1) {
1151 * Rewind in case there is another match
1152 * starting at the second line of the block
1154 match = NULL;
1155 n -= block_length;
1157 pmb_nr = 0;
1158 block_length = 0;
1159 flipped_block = 0;
1161 if (!match) {
1162 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1163 continue;
1166 if (o->color_moved == COLOR_MOVED_PLAIN) {
1167 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1168 continue;
1171 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1173 if (pmb_nr == 0) {
1174 int contiguous = adjust_last_block(o, n, block_length);
1176 if (!contiguous && block_length > 1)
1178 * Rewind in case there is another match
1179 * starting at the second line of the block
1181 n -= block_length;
1182 else
1183 fill_potential_moved_blocks(o, match, l,
1184 &pmb, &pmb_alloc,
1185 &pmb_nr);
1187 if (contiguous && pmb_nr && moved_symbol == l->s)
1188 flipped_block = (flipped_block + 1) % 2;
1189 else
1190 flipped_block = 0;
1192 if (pmb_nr)
1193 moved_symbol = l->s;
1194 else
1195 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1197 block_length = 0;
1200 if (pmb_nr) {
1201 block_length++;
1202 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1203 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1204 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1207 adjust_last_block(o, n, block_length);
1209 free(pmb);
1212 static void dim_moved_lines(struct diff_options *o)
1214 int n;
1215 for (n = 0; n < o->emitted_symbols->nr; n++) {
1216 struct emitted_diff_symbol *prev = (n != 0) ?
1217 &o->emitted_symbols->buf[n - 1] : NULL;
1218 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1219 struct emitted_diff_symbol *next =
1220 (n < o->emitted_symbols->nr - 1) ?
1221 &o->emitted_symbols->buf[n + 1] : NULL;
1223 /* Not a plus or minus line? */
1224 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1225 continue;
1227 /* Not a moved line? */
1228 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1229 continue;
1232 * If prev or next are not a plus or minus line,
1233 * pretend they don't exist
1235 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1236 prev->s != DIFF_SYMBOL_MINUS)
1237 prev = NULL;
1238 if (next && next->s != DIFF_SYMBOL_PLUS &&
1239 next->s != DIFF_SYMBOL_MINUS)
1240 next = NULL;
1242 /* Inside a block? */
1243 if ((prev &&
1244 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1245 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1246 (next &&
1247 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1248 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1249 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1250 continue;
1253 /* Check if we are at an interesting bound: */
1254 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1255 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1256 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1257 continue;
1258 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1259 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1260 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1261 continue;
1264 * The boundary to prev and next are not interesting,
1265 * so this line is not interesting as a whole
1267 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1271 static void emit_line_ws_markup(struct diff_options *o,
1272 const char *set_sign, const char *set,
1273 const char *reset,
1274 int sign_index, const char *line, int len,
1275 unsigned ws_rule, int blank_at_eof)
1277 const char *ws = NULL;
1278 int sign = o->output_indicators[sign_index];
1280 if (o->ws_error_highlight & ws_rule) {
1281 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1282 if (!*ws)
1283 ws = NULL;
1286 if (!ws && !set_sign)
1287 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1288 else if (!ws) {
1289 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1290 } else if (blank_at_eof)
1291 /* Blank line at EOF - paint '+' as well */
1292 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1293 else {
1294 /* Emit just the prefix, then the rest. */
1295 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1296 sign, "", 0);
1297 ws_check_emit(line, len, ws_rule,
1298 o->file, set, reset, ws);
1302 static void emit_diff_symbol_from_struct(struct diff_options *o,
1303 struct emitted_diff_symbol *eds)
1305 static const char *nneof = " No newline at end of file\n";
1306 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1308 enum diff_symbol s = eds->s;
1309 const char *line = eds->line;
1310 int len = eds->len;
1311 unsigned flags = eds->flags;
1313 switch (s) {
1314 case DIFF_SYMBOL_NO_LF_EOF:
1315 context = diff_get_color_opt(o, DIFF_CONTEXT);
1316 reset = diff_get_color_opt(o, DIFF_RESET);
1317 putc('\n', o->file);
1318 emit_line_0(o, context, NULL, 0, reset, '\\',
1319 nneof, strlen(nneof));
1320 break;
1321 case DIFF_SYMBOL_SUBMODULE_HEADER:
1322 case DIFF_SYMBOL_SUBMODULE_ERROR:
1323 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1324 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1325 case DIFF_SYMBOL_SUMMARY:
1326 case DIFF_SYMBOL_STATS_LINE:
1327 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1328 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1329 emit_line(o, "", "", line, len);
1330 break;
1331 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1332 case DIFF_SYMBOL_CONTEXT_MARKER:
1333 context = diff_get_color_opt(o, DIFF_CONTEXT);
1334 reset = diff_get_color_opt(o, DIFF_RESET);
1335 emit_line(o, context, reset, line, len);
1336 break;
1337 case DIFF_SYMBOL_SEPARATOR:
1338 fprintf(o->file, "%s%c",
1339 diff_line_prefix(o),
1340 o->line_termination);
1341 break;
1342 case DIFF_SYMBOL_CONTEXT:
1343 set = diff_get_color_opt(o, DIFF_CONTEXT);
1344 reset = diff_get_color_opt(o, DIFF_RESET);
1345 set_sign = NULL;
1346 if (o->flags.dual_color_diffed_diffs) {
1347 char c = !len ? 0 : line[0];
1349 if (c == '+')
1350 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1351 else if (c == '@')
1352 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1353 else if (c == '-')
1354 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1356 emit_line_ws_markup(o, set_sign, set, reset,
1357 OUTPUT_INDICATOR_CONTEXT, line, len,
1358 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1359 break;
1360 case DIFF_SYMBOL_PLUS:
1361 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1362 DIFF_SYMBOL_MOVED_LINE_ALT |
1363 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1364 case DIFF_SYMBOL_MOVED_LINE |
1365 DIFF_SYMBOL_MOVED_LINE_ALT |
1366 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1367 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1368 break;
1369 case DIFF_SYMBOL_MOVED_LINE |
1370 DIFF_SYMBOL_MOVED_LINE_ALT:
1371 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1372 break;
1373 case DIFF_SYMBOL_MOVED_LINE |
1374 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1375 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1376 break;
1377 case DIFF_SYMBOL_MOVED_LINE:
1378 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1379 break;
1380 default:
1381 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1383 reset = diff_get_color_opt(o, DIFF_RESET);
1384 if (!o->flags.dual_color_diffed_diffs)
1385 set_sign = NULL;
1386 else {
1387 char c = !len ? 0 : line[0];
1389 set_sign = set;
1390 if (c == '-')
1391 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1392 else if (c == '@')
1393 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1394 else if (c == '+')
1395 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1396 else
1397 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1398 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1400 emit_line_ws_markup(o, set_sign, set, reset,
1401 OUTPUT_INDICATOR_NEW, line, len,
1402 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1403 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1404 break;
1405 case DIFF_SYMBOL_MINUS:
1406 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1407 DIFF_SYMBOL_MOVED_LINE_ALT |
1408 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1409 case DIFF_SYMBOL_MOVED_LINE |
1410 DIFF_SYMBOL_MOVED_LINE_ALT |
1411 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1412 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1413 break;
1414 case DIFF_SYMBOL_MOVED_LINE |
1415 DIFF_SYMBOL_MOVED_LINE_ALT:
1416 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1417 break;
1418 case DIFF_SYMBOL_MOVED_LINE |
1419 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1420 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1421 break;
1422 case DIFF_SYMBOL_MOVED_LINE:
1423 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1424 break;
1425 default:
1426 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1428 reset = diff_get_color_opt(o, DIFF_RESET);
1429 if (!o->flags.dual_color_diffed_diffs)
1430 set_sign = NULL;
1431 else {
1432 char c = !len ? 0 : line[0];
1434 set_sign = set;
1435 if (c == '+')
1436 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1437 else if (c == '@')
1438 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1439 else if (c == '-')
1440 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1441 else
1442 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1444 emit_line_ws_markup(o, set_sign, set, reset,
1445 OUTPUT_INDICATOR_OLD, line, len,
1446 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1447 break;
1448 case DIFF_SYMBOL_WORDS_PORCELAIN:
1449 context = diff_get_color_opt(o, DIFF_CONTEXT);
1450 reset = diff_get_color_opt(o, DIFF_RESET);
1451 emit_line(o, context, reset, line, len);
1452 fputs("~\n", o->file);
1453 break;
1454 case DIFF_SYMBOL_WORDS:
1455 context = diff_get_color_opt(o, DIFF_CONTEXT);
1456 reset = diff_get_color_opt(o, DIFF_RESET);
1458 * Skip the prefix character, if any. With
1459 * diff_suppress_blank_empty, there may be
1460 * none.
1462 if (line[0] != '\n') {
1463 line++;
1464 len--;
1466 emit_line(o, context, reset, line, len);
1467 break;
1468 case DIFF_SYMBOL_FILEPAIR_PLUS:
1469 meta = diff_get_color_opt(o, DIFF_METAINFO);
1470 reset = diff_get_color_opt(o, DIFF_RESET);
1471 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1472 line, reset,
1473 strchr(line, ' ') ? "\t" : "");
1474 break;
1475 case DIFF_SYMBOL_FILEPAIR_MINUS:
1476 meta = diff_get_color_opt(o, DIFF_METAINFO);
1477 reset = diff_get_color_opt(o, DIFF_RESET);
1478 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1479 line, reset,
1480 strchr(line, ' ') ? "\t" : "");
1481 break;
1482 case DIFF_SYMBOL_BINARY_FILES:
1483 case DIFF_SYMBOL_HEADER:
1484 fprintf(o->file, "%s", line);
1485 break;
1486 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1487 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1488 break;
1489 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1490 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1491 break;
1492 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1493 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1494 break;
1495 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1496 fputs(diff_line_prefix(o), o->file);
1497 fputc('\n', o->file);
1498 break;
1499 case DIFF_SYMBOL_REWRITE_DIFF:
1500 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1501 reset = diff_get_color_opt(o, DIFF_RESET);
1502 emit_line(o, fraginfo, reset, line, len);
1503 break;
1504 case DIFF_SYMBOL_SUBMODULE_ADD:
1505 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1506 reset = diff_get_color_opt(o, DIFF_RESET);
1507 emit_line(o, set, reset, line, len);
1508 break;
1509 case DIFF_SYMBOL_SUBMODULE_DEL:
1510 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1511 reset = diff_get_color_opt(o, DIFF_RESET);
1512 emit_line(o, set, reset, line, len);
1513 break;
1514 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1515 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1516 diff_line_prefix(o), line);
1517 break;
1518 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1519 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1520 diff_line_prefix(o), line);
1521 break;
1522 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1523 emit_line(o, "", "", " 0 files changed\n",
1524 strlen(" 0 files changed\n"));
1525 break;
1526 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1527 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1528 break;
1529 case DIFF_SYMBOL_WORD_DIFF:
1530 fprintf(o->file, "%.*s", len, line);
1531 break;
1532 case DIFF_SYMBOL_STAT_SEP:
1533 fputs(o->stat_sep, o->file);
1534 break;
1535 default:
1536 BUG("unknown diff symbol");
1540 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1541 const char *line, int len, unsigned flags)
1543 struct emitted_diff_symbol e = {
1544 .line = line, .len = len, .flags = flags, .s = s
1547 if (o->emitted_symbols)
1548 append_emitted_diff_symbol(o, &e);
1549 else
1550 emit_diff_symbol_from_struct(o, &e);
1553 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1555 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1558 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1560 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1563 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1565 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1566 path, strlen(path), 0);
1569 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1571 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1572 path, strlen(path), 0);
1575 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1577 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1578 header, strlen(header), 0);
1581 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1583 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1586 void diff_emit_submodule_pipethrough(struct diff_options *o,
1587 const char *line, int len)
1589 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1592 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1594 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1595 ecbdata->blank_at_eof_in_preimage &&
1596 ecbdata->blank_at_eof_in_postimage &&
1597 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1598 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1599 return 0;
1600 return ws_blank_line(line, len);
1603 static void emit_add_line(struct emit_callback *ecbdata,
1604 const char *line, int len)
1606 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1607 if (new_blank_line_at_eof(ecbdata, line, len))
1608 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1610 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1613 static void emit_del_line(struct emit_callback *ecbdata,
1614 const char *line, int len)
1616 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1617 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1620 static void emit_context_line(struct emit_callback *ecbdata,
1621 const char *line, int len)
1623 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1624 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1627 static void emit_hunk_header(struct emit_callback *ecbdata,
1628 const char *line, int len)
1630 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1631 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1632 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1633 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1634 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1635 static const char atat[2] = { '@', '@' };
1636 const char *cp, *ep;
1637 struct strbuf msgbuf = STRBUF_INIT;
1638 int org_len = len;
1639 int i = 1;
1642 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1643 * it always is at least 10 bytes long.
1645 if (len < 10 ||
1646 memcmp(line, atat, 2) ||
1647 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1648 emit_diff_symbol(ecbdata->opt,
1649 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1650 return;
1652 ep += 2; /* skip over @@ */
1654 /* The hunk header in fraginfo color */
1655 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1656 strbuf_addstr(&msgbuf, reverse);
1657 strbuf_addstr(&msgbuf, frag);
1658 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1659 strbuf_add(&msgbuf, atat, sizeof(atat));
1660 else
1661 strbuf_add(&msgbuf, line, ep - line);
1662 strbuf_addstr(&msgbuf, reset);
1665 * trailing "\r\n"
1667 for ( ; i < 3; i++)
1668 if (line[len - i] == '\r' || line[len - i] == '\n')
1669 len--;
1671 /* blank before the func header */
1672 for (cp = ep; ep - line < len; ep++)
1673 if (*ep != ' ' && *ep != '\t')
1674 break;
1675 if (ep != cp) {
1676 strbuf_addstr(&msgbuf, context);
1677 strbuf_add(&msgbuf, cp, ep - cp);
1678 strbuf_addstr(&msgbuf, reset);
1681 if (ep < line + len) {
1682 strbuf_addstr(&msgbuf, func);
1683 strbuf_add(&msgbuf, ep, line + len - ep);
1684 strbuf_addstr(&msgbuf, reset);
1687 strbuf_add(&msgbuf, line + len, org_len - len);
1688 strbuf_complete_line(&msgbuf);
1689 emit_diff_symbol(ecbdata->opt,
1690 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1691 strbuf_release(&msgbuf);
1694 static struct diff_tempfile *claim_diff_tempfile(void)
1696 int i;
1697 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1698 if (!diff_temp[i].name)
1699 return diff_temp + i;
1700 BUG("diff is failing to clean up its tempfiles");
1703 static void remove_tempfile(void)
1705 int i;
1706 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1707 if (is_tempfile_active(diff_temp[i].tempfile))
1708 delete_tempfile(&diff_temp[i].tempfile);
1709 diff_temp[i].name = NULL;
1713 static void add_line_count(struct strbuf *out, int count)
1715 switch (count) {
1716 case 0:
1717 strbuf_addstr(out, "0,0");
1718 break;
1719 case 1:
1720 strbuf_addstr(out, "1");
1721 break;
1722 default:
1723 strbuf_addf(out, "1,%d", count);
1724 break;
1728 static void emit_rewrite_lines(struct emit_callback *ecb,
1729 int prefix, const char *data, int size)
1731 const char *endp = NULL;
1733 while (0 < size) {
1734 int len;
1736 endp = memchr(data, '\n', size);
1737 len = endp ? (endp - data + 1) : size;
1738 if (prefix != '+') {
1739 ecb->lno_in_preimage++;
1740 emit_del_line(ecb, data, len);
1741 } else {
1742 ecb->lno_in_postimage++;
1743 emit_add_line(ecb, data, len);
1745 size -= len;
1746 data += len;
1748 if (!endp)
1749 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1752 static void emit_rewrite_diff(const char *name_a,
1753 const char *name_b,
1754 struct diff_filespec *one,
1755 struct diff_filespec *two,
1756 struct userdiff_driver *textconv_one,
1757 struct userdiff_driver *textconv_two,
1758 struct diff_options *o)
1760 int lc_a, lc_b;
1761 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1762 const char *a_prefix, *b_prefix;
1763 char *data_one, *data_two;
1764 size_t size_one, size_two;
1765 struct emit_callback ecbdata;
1766 struct strbuf out = STRBUF_INIT;
1768 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1769 a_prefix = o->b_prefix;
1770 b_prefix = o->a_prefix;
1771 } else {
1772 a_prefix = o->a_prefix;
1773 b_prefix = o->b_prefix;
1776 name_a += (*name_a == '/');
1777 name_b += (*name_b == '/');
1779 strbuf_reset(&a_name);
1780 strbuf_reset(&b_name);
1781 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1782 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1784 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1785 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1787 memset(&ecbdata, 0, sizeof(ecbdata));
1788 ecbdata.color_diff = want_color(o->use_color);
1789 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1790 ecbdata.opt = o;
1791 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1792 mmfile_t mf1, mf2;
1793 mf1.ptr = (char *)data_one;
1794 mf2.ptr = (char *)data_two;
1795 mf1.size = size_one;
1796 mf2.size = size_two;
1797 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1799 ecbdata.lno_in_preimage = 1;
1800 ecbdata.lno_in_postimage = 1;
1802 lc_a = count_lines(data_one, size_one);
1803 lc_b = count_lines(data_two, size_two);
1805 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1806 a_name.buf, a_name.len, 0);
1807 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1808 b_name.buf, b_name.len, 0);
1810 strbuf_addstr(&out, "@@ -");
1811 if (!o->irreversible_delete)
1812 add_line_count(&out, lc_a);
1813 else
1814 strbuf_addstr(&out, "?,?");
1815 strbuf_addstr(&out, " +");
1816 add_line_count(&out, lc_b);
1817 strbuf_addstr(&out, " @@\n");
1818 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1819 strbuf_release(&out);
1821 if (lc_a && !o->irreversible_delete)
1822 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1823 if (lc_b)
1824 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1825 if (textconv_one)
1826 free((char *)data_one);
1827 if (textconv_two)
1828 free((char *)data_two);
1831 struct diff_words_buffer {
1832 mmfile_t text;
1833 unsigned long alloc;
1834 struct diff_words_orig {
1835 const char *begin, *end;
1836 } *orig;
1837 int orig_nr, orig_alloc;
1840 static void diff_words_append(char *line, unsigned long len,
1841 struct diff_words_buffer *buffer)
1843 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1844 line++;
1845 len--;
1846 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1847 buffer->text.size += len;
1848 buffer->text.ptr[buffer->text.size] = '\0';
1851 struct diff_words_style_elem {
1852 const char *prefix;
1853 const char *suffix;
1854 const char *color; /* NULL; filled in by the setup code if
1855 * color is enabled */
1858 struct diff_words_style {
1859 enum diff_words_type type;
1860 struct diff_words_style_elem new_word, old_word, ctx;
1861 const char *newline;
1864 static struct diff_words_style diff_words_styles[] = {
1865 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1866 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1867 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1870 struct diff_words_data {
1871 struct diff_words_buffer minus, plus;
1872 const char *current_plus;
1873 int last_minus;
1874 struct diff_options *opt;
1875 regex_t *word_regex;
1876 enum diff_words_type type;
1877 struct diff_words_style *style;
1880 static int fn_out_diff_words_write_helper(struct diff_options *o,
1881 struct diff_words_style_elem *st_el,
1882 const char *newline,
1883 size_t count, const char *buf)
1885 int print = 0;
1886 struct strbuf sb = STRBUF_INIT;
1888 while (count) {
1889 char *p = memchr(buf, '\n', count);
1890 if (print)
1891 strbuf_addstr(&sb, diff_line_prefix(o));
1893 if (p != buf) {
1894 const char *reset = st_el->color && *st_el->color ?
1895 GIT_COLOR_RESET : NULL;
1896 if (st_el->color && *st_el->color)
1897 strbuf_addstr(&sb, st_el->color);
1898 strbuf_addstr(&sb, st_el->prefix);
1899 strbuf_add(&sb, buf, p ? p - buf : count);
1900 strbuf_addstr(&sb, st_el->suffix);
1901 if (reset)
1902 strbuf_addstr(&sb, reset);
1904 if (!p)
1905 goto out;
1907 strbuf_addstr(&sb, newline);
1908 count -= p + 1 - buf;
1909 buf = p + 1;
1910 print = 1;
1911 if (count) {
1912 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1913 sb.buf, sb.len, 0);
1914 strbuf_reset(&sb);
1918 out:
1919 if (sb.len)
1920 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1921 sb.buf, sb.len, 0);
1922 strbuf_release(&sb);
1923 return 0;
1927 * '--color-words' algorithm can be described as:
1929 * 1. collect the minus/plus lines of a diff hunk, divided into
1930 * minus-lines and plus-lines;
1932 * 2. break both minus-lines and plus-lines into words and
1933 * place them into two mmfile_t with one word for each line;
1935 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1937 * And for the common parts of the both file, we output the plus side text.
1938 * diff_words->current_plus is used to trace the current position of the plus file
1939 * which printed. diff_words->last_minus is used to trace the last minus word
1940 * printed.
1942 * For '--graph' to work with '--color-words', we need to output the graph prefix
1943 * on each line of color words output. Generally, there are two conditions on
1944 * which we should output the prefix.
1946 * 1. diff_words->last_minus == 0 &&
1947 * diff_words->current_plus == diff_words->plus.text.ptr
1949 * that is: the plus text must start as a new line, and if there is no minus
1950 * word printed, a graph prefix must be printed.
1952 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1953 * *(diff_words->current_plus - 1) == '\n'
1955 * that is: a graph prefix must be printed following a '\n'
1957 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1959 if ((diff_words->last_minus == 0 &&
1960 diff_words->current_plus == diff_words->plus.text.ptr) ||
1961 (diff_words->current_plus > diff_words->plus.text.ptr &&
1962 *(diff_words->current_plus - 1) == '\n')) {
1963 return 1;
1964 } else {
1965 return 0;
1969 static void fn_out_diff_words_aux(void *priv,
1970 long minus_first, long minus_len,
1971 long plus_first, long plus_len,
1972 const char *func UNUSED, long funclen UNUSED)
1974 struct diff_words_data *diff_words = priv;
1975 struct diff_words_style *style = diff_words->style;
1976 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1977 struct diff_options *opt = diff_words->opt;
1978 const char *line_prefix;
1980 assert(opt);
1981 line_prefix = diff_line_prefix(opt);
1983 /* POSIX requires that first be decremented by one if len == 0... */
1984 if (minus_len) {
1985 minus_begin = diff_words->minus.orig[minus_first].begin;
1986 minus_end =
1987 diff_words->minus.orig[minus_first + minus_len - 1].end;
1988 } else
1989 minus_begin = minus_end =
1990 diff_words->minus.orig[minus_first].end;
1992 if (plus_len) {
1993 plus_begin = diff_words->plus.orig[plus_first].begin;
1994 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1995 } else
1996 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1998 if (color_words_output_graph_prefix(diff_words)) {
1999 fputs(line_prefix, diff_words->opt->file);
2001 if (diff_words->current_plus != plus_begin) {
2002 fn_out_diff_words_write_helper(diff_words->opt,
2003 &style->ctx, style->newline,
2004 plus_begin - diff_words->current_plus,
2005 diff_words->current_plus);
2007 if (minus_begin != minus_end) {
2008 fn_out_diff_words_write_helper(diff_words->opt,
2009 &style->old_word, style->newline,
2010 minus_end - minus_begin, minus_begin);
2012 if (plus_begin != plus_end) {
2013 fn_out_diff_words_write_helper(diff_words->opt,
2014 &style->new_word, style->newline,
2015 plus_end - plus_begin, plus_begin);
2018 diff_words->current_plus = plus_end;
2019 diff_words->last_minus = minus_first;
2022 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2023 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2024 int *begin, int *end)
2026 while (word_regex && *begin < buffer->size) {
2027 regmatch_t match[1];
2028 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2029 buffer->size - *begin, 1, match, 0)) {
2030 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2031 '\n', match[0].rm_eo - match[0].rm_so);
2032 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2033 *begin += match[0].rm_so;
2034 if (*begin == *end)
2035 (*begin)++;
2036 else
2037 return *begin > *end;
2038 } else {
2039 return -1;
2043 /* find the next word */
2044 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2045 (*begin)++;
2046 if (*begin >= buffer->size)
2047 return -1;
2049 /* find the end of the word */
2050 *end = *begin + 1;
2051 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2052 (*end)++;
2054 return 0;
2058 * This function splits the words in buffer->text, stores the list with
2059 * newline separator into out, and saves the offsets of the original words
2060 * in buffer->orig.
2062 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2063 regex_t *word_regex)
2065 int i, j;
2066 long alloc = 0;
2068 out->size = 0;
2069 out->ptr = NULL;
2071 /* fake an empty "0th" word */
2072 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2073 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2074 buffer->orig_nr = 1;
2076 for (i = 0; i < buffer->text.size; i++) {
2077 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2078 return;
2080 /* store original boundaries */
2081 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2082 buffer->orig_alloc);
2083 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2084 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2085 buffer->orig_nr++;
2087 /* store one word */
2088 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2089 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2090 out->ptr[out->size + j - i] = '\n';
2091 out->size += j - i + 1;
2093 i = j - 1;
2097 /* this executes the word diff on the accumulated buffers */
2098 static void diff_words_show(struct diff_words_data *diff_words)
2100 xpparam_t xpp;
2101 xdemitconf_t xecfg;
2102 mmfile_t minus, plus;
2103 struct diff_words_style *style = diff_words->style;
2105 struct diff_options *opt = diff_words->opt;
2106 const char *line_prefix;
2108 assert(opt);
2109 line_prefix = diff_line_prefix(opt);
2111 /* special case: only removal */
2112 if (!diff_words->plus.text.size) {
2113 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2114 line_prefix, strlen(line_prefix), 0);
2115 fn_out_diff_words_write_helper(diff_words->opt,
2116 &style->old_word, style->newline,
2117 diff_words->minus.text.size,
2118 diff_words->minus.text.ptr);
2119 diff_words->minus.text.size = 0;
2120 return;
2123 diff_words->current_plus = diff_words->plus.text.ptr;
2124 diff_words->last_minus = 0;
2126 memset(&xpp, 0, sizeof(xpp));
2127 memset(&xecfg, 0, sizeof(xecfg));
2128 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2129 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2130 xpp.flags = 0;
2131 /* as only the hunk header will be parsed, we need a 0-context */
2132 xecfg.ctxlen = 0;
2133 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2134 diff_words, &xpp, &xecfg))
2135 die("unable to generate word diff");
2136 free(minus.ptr);
2137 free(plus.ptr);
2138 if (diff_words->current_plus != diff_words->plus.text.ptr +
2139 diff_words->plus.text.size) {
2140 if (color_words_output_graph_prefix(diff_words))
2141 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2142 line_prefix, strlen(line_prefix), 0);
2143 fn_out_diff_words_write_helper(diff_words->opt,
2144 &style->ctx, style->newline,
2145 diff_words->plus.text.ptr + diff_words->plus.text.size
2146 - diff_words->current_plus, diff_words->current_plus);
2148 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2151 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2152 static void diff_words_flush(struct emit_callback *ecbdata)
2154 struct diff_options *wo = ecbdata->diff_words->opt;
2156 if (ecbdata->diff_words->minus.text.size ||
2157 ecbdata->diff_words->plus.text.size)
2158 diff_words_show(ecbdata->diff_words);
2160 if (wo->emitted_symbols) {
2161 struct diff_options *o = ecbdata->opt;
2162 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2163 int i;
2166 * NEEDSWORK:
2167 * Instead of appending each, concat all words to a line?
2169 for (i = 0; i < wol->nr; i++)
2170 append_emitted_diff_symbol(o, &wol->buf[i]);
2172 for (i = 0; i < wol->nr; i++)
2173 free((void *)wol->buf[i].line);
2175 wol->nr = 0;
2179 static void diff_filespec_load_driver(struct diff_filespec *one,
2180 struct index_state *istate)
2182 /* Use already-loaded driver */
2183 if (one->driver)
2184 return;
2186 if (S_ISREG(one->mode))
2187 one->driver = userdiff_find_by_path(istate, one->path);
2189 /* Fallback to default settings */
2190 if (!one->driver)
2191 one->driver = userdiff_find_by_name("default");
2194 static const char *userdiff_word_regex(struct diff_filespec *one,
2195 struct index_state *istate)
2197 diff_filespec_load_driver(one, istate);
2198 return one->driver->word_regex;
2201 static void init_diff_words_data(struct emit_callback *ecbdata,
2202 struct diff_options *orig_opts,
2203 struct diff_filespec *one,
2204 struct diff_filespec *two)
2206 int i;
2207 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2208 memcpy(o, orig_opts, sizeof(struct diff_options));
2210 CALLOC_ARRAY(ecbdata->diff_words, 1);
2211 ecbdata->diff_words->type = o->word_diff;
2212 ecbdata->diff_words->opt = o;
2214 if (orig_opts->emitted_symbols)
2215 CALLOC_ARRAY(o->emitted_symbols, 1);
2217 if (!o->word_regex)
2218 o->word_regex = userdiff_word_regex(one, o->repo->index);
2219 if (!o->word_regex)
2220 o->word_regex = userdiff_word_regex(two, o->repo->index);
2221 if (!o->word_regex)
2222 o->word_regex = diff_word_regex_cfg;
2223 if (o->word_regex) {
2224 ecbdata->diff_words->word_regex = (regex_t *)
2225 xmalloc(sizeof(regex_t));
2226 if (regcomp(ecbdata->diff_words->word_regex,
2227 o->word_regex,
2228 REG_EXTENDED | REG_NEWLINE))
2229 die("invalid regular expression: %s",
2230 o->word_regex);
2232 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2233 if (o->word_diff == diff_words_styles[i].type) {
2234 ecbdata->diff_words->style =
2235 &diff_words_styles[i];
2236 break;
2239 if (want_color(o->use_color)) {
2240 struct diff_words_style *st = ecbdata->diff_words->style;
2241 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2242 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2243 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2247 static void free_diff_words_data(struct emit_callback *ecbdata)
2249 if (ecbdata->diff_words) {
2250 diff_words_flush(ecbdata);
2251 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2252 free (ecbdata->diff_words->opt);
2253 free (ecbdata->diff_words->minus.text.ptr);
2254 free (ecbdata->diff_words->minus.orig);
2255 free (ecbdata->diff_words->plus.text.ptr);
2256 free (ecbdata->diff_words->plus.orig);
2257 if (ecbdata->diff_words->word_regex) {
2258 regfree(ecbdata->diff_words->word_regex);
2259 free(ecbdata->diff_words->word_regex);
2261 FREE_AND_NULL(ecbdata->diff_words);
2265 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2267 if (want_color(diff_use_color))
2268 return diff_colors[ix];
2269 return "";
2272 const char *diff_line_prefix(struct diff_options *opt)
2274 struct strbuf *msgbuf;
2275 if (!opt->output_prefix)
2276 return "";
2278 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2279 return msgbuf->buf;
2282 static unsigned long sane_truncate_line(char *line, unsigned long len)
2284 const char *cp;
2285 unsigned long allot;
2286 size_t l = len;
2288 cp = line;
2289 allot = l;
2290 while (0 < l) {
2291 (void) utf8_width(&cp, &l);
2292 if (!cp)
2293 break; /* truncated in the middle? */
2295 return allot - l;
2298 static void find_lno(const char *line, struct emit_callback *ecbdata)
2300 const char *p;
2301 ecbdata->lno_in_preimage = 0;
2302 ecbdata->lno_in_postimage = 0;
2303 p = strchr(line, '-');
2304 if (!p)
2305 return; /* cannot happen */
2306 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2307 p = strchr(p, '+');
2308 if (!p)
2309 return; /* cannot happen */
2310 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2313 static int fn_out_consume(void *priv, char *line, unsigned long len)
2315 struct emit_callback *ecbdata = priv;
2316 struct diff_options *o = ecbdata->opt;
2318 o->found_changes = 1;
2320 if (ecbdata->header) {
2321 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2322 ecbdata->header->buf, ecbdata->header->len, 0);
2323 strbuf_reset(ecbdata->header);
2324 ecbdata->header = NULL;
2327 if (ecbdata->label_path[0]) {
2328 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2329 ecbdata->label_path[0],
2330 strlen(ecbdata->label_path[0]), 0);
2331 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2332 ecbdata->label_path[1],
2333 strlen(ecbdata->label_path[1]), 0);
2334 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2337 if (diff_suppress_blank_empty
2338 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2339 line[0] = '\n';
2340 len = 1;
2343 if (line[0] == '@') {
2344 if (ecbdata->diff_words)
2345 diff_words_flush(ecbdata);
2346 len = sane_truncate_line(line, len);
2347 find_lno(line, ecbdata);
2348 emit_hunk_header(ecbdata, line, len);
2349 return 0;
2352 if (ecbdata->diff_words) {
2353 enum diff_symbol s =
2354 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2355 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2356 if (line[0] == '-') {
2357 diff_words_append(line, len,
2358 &ecbdata->diff_words->minus);
2359 return 0;
2360 } else if (line[0] == '+') {
2361 diff_words_append(line, len,
2362 &ecbdata->diff_words->plus);
2363 return 0;
2364 } else if (starts_with(line, "\\ ")) {
2366 * Eat the "no newline at eof" marker as if we
2367 * saw a "+" or "-" line with nothing on it,
2368 * and return without diff_words_flush() to
2369 * defer processing. If this is the end of
2370 * preimage, more "+" lines may come after it.
2372 return 0;
2374 diff_words_flush(ecbdata);
2375 emit_diff_symbol(o, s, line, len, 0);
2376 return 0;
2379 switch (line[0]) {
2380 case '+':
2381 ecbdata->lno_in_postimage++;
2382 emit_add_line(ecbdata, line + 1, len - 1);
2383 break;
2384 case '-':
2385 ecbdata->lno_in_preimage++;
2386 emit_del_line(ecbdata, line + 1, len - 1);
2387 break;
2388 case ' ':
2389 ecbdata->lno_in_postimage++;
2390 ecbdata->lno_in_preimage++;
2391 emit_context_line(ecbdata, line + 1, len - 1);
2392 break;
2393 default:
2394 /* incomplete line at the end */
2395 ecbdata->lno_in_preimage++;
2396 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2397 line, len, 0);
2398 break;
2400 return 0;
2403 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2405 const char *old_name = a;
2406 const char *new_name = b;
2407 int pfx_length, sfx_length;
2408 int pfx_adjust_for_slash;
2409 int len_a = strlen(a);
2410 int len_b = strlen(b);
2411 int a_midlen, b_midlen;
2412 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2413 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2415 if (qlen_a || qlen_b) {
2416 quote_c_style(a, name, NULL, 0);
2417 strbuf_addstr(name, " => ");
2418 quote_c_style(b, name, NULL, 0);
2419 return;
2422 /* Find common prefix */
2423 pfx_length = 0;
2424 while (*old_name && *new_name && *old_name == *new_name) {
2425 if (*old_name == '/')
2426 pfx_length = old_name - a + 1;
2427 old_name++;
2428 new_name++;
2431 /* Find common suffix */
2432 old_name = a + len_a;
2433 new_name = b + len_b;
2434 sfx_length = 0;
2436 * If there is a common prefix, it must end in a slash. In
2437 * that case we let this loop run 1 into the prefix to see the
2438 * same slash.
2440 * If there is no common prefix, we cannot do this as it would
2441 * underrun the input strings.
2443 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2444 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2445 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2446 *old_name == *new_name) {
2447 if (*old_name == '/')
2448 sfx_length = len_a - (old_name - a);
2449 old_name--;
2450 new_name--;
2454 * pfx{mid-a => mid-b}sfx
2455 * {pfx-a => pfx-b}sfx
2456 * pfx{sfx-a => sfx-b}
2457 * name-a => name-b
2459 a_midlen = len_a - pfx_length - sfx_length;
2460 b_midlen = len_b - pfx_length - sfx_length;
2461 if (a_midlen < 0)
2462 a_midlen = 0;
2463 if (b_midlen < 0)
2464 b_midlen = 0;
2466 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2467 if (pfx_length + sfx_length) {
2468 strbuf_add(name, a, pfx_length);
2469 strbuf_addch(name, '{');
2471 strbuf_add(name, a + pfx_length, a_midlen);
2472 strbuf_addstr(name, " => ");
2473 strbuf_add(name, b + pfx_length, b_midlen);
2474 if (pfx_length + sfx_length) {
2475 strbuf_addch(name, '}');
2476 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2480 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2481 const char *name_a,
2482 const char *name_b)
2484 struct diffstat_file *x;
2485 CALLOC_ARRAY(x, 1);
2486 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2487 diffstat->files[diffstat->nr++] = x;
2488 if (name_b) {
2489 x->from_name = xstrdup(name_a);
2490 x->name = xstrdup(name_b);
2491 x->is_renamed = 1;
2493 else {
2494 x->from_name = NULL;
2495 x->name = xstrdup(name_a);
2497 return x;
2500 static int diffstat_consume(void *priv, char *line, unsigned long len)
2502 struct diffstat_t *diffstat = priv;
2503 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2505 if (!len)
2506 BUG("xdiff fed us an empty line");
2508 if (line[0] == '+')
2509 x->added++;
2510 else if (line[0] == '-')
2511 x->deleted++;
2512 return 0;
2515 const char mime_boundary_leader[] = "------------";
2517 static int scale_linear(int it, int width, int max_change)
2519 if (!it)
2520 return 0;
2522 * make sure that at least one '-' or '+' is printed if
2523 * there is any change to this path. The easiest way is to
2524 * scale linearly as if the allotted width is one column shorter
2525 * than it is, and then add 1 to the result.
2527 return 1 + (it * (width - 1) / max_change);
2530 static void show_graph(struct strbuf *out, char ch, int cnt,
2531 const char *set, const char *reset)
2533 if (cnt <= 0)
2534 return;
2535 strbuf_addstr(out, set);
2536 strbuf_addchars(out, ch, cnt);
2537 strbuf_addstr(out, reset);
2540 static void fill_print_name(struct diffstat_file *file)
2542 struct strbuf pname = STRBUF_INIT;
2544 if (file->print_name)
2545 return;
2547 if (file->is_renamed)
2548 pprint_rename(&pname, file->from_name, file->name);
2549 else
2550 quote_c_style(file->name, &pname, NULL, 0);
2552 if (file->comments)
2553 strbuf_addf(&pname, " (%s)", file->comments);
2555 file->print_name = strbuf_detach(&pname, NULL);
2558 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2559 int files, int insertions, int deletions)
2561 struct strbuf sb = STRBUF_INIT;
2563 if (!files) {
2564 assert(insertions == 0 && deletions == 0);
2565 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2566 NULL, 0, 0);
2567 return;
2570 strbuf_addf(&sb,
2571 (files == 1) ? " %d file changed" : " %d files changed",
2572 files);
2575 * For binary diff, the caller may want to print "x files
2576 * changed" with insertions == 0 && deletions == 0.
2578 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2579 * is probably less confusing (i.e skip over "2 files changed
2580 * but nothing about added/removed lines? Is this a bug in Git?").
2582 if (insertions || deletions == 0) {
2583 strbuf_addf(&sb,
2584 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2585 insertions);
2588 if (deletions || insertions == 0) {
2589 strbuf_addf(&sb,
2590 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2591 deletions);
2593 strbuf_addch(&sb, '\n');
2594 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2595 sb.buf, sb.len, 0);
2596 strbuf_release(&sb);
2599 void print_stat_summary(FILE *fp, int files,
2600 int insertions, int deletions)
2602 struct diff_options o;
2603 memset(&o, 0, sizeof(o));
2604 o.file = fp;
2606 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2609 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2611 int i, len, add, del, adds = 0, dels = 0;
2612 uintmax_t max_change = 0, max_len = 0;
2613 int total_files = data->nr, count;
2614 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2615 const char *reset, *add_c, *del_c;
2616 int extra_shown = 0;
2617 const char *line_prefix = diff_line_prefix(options);
2618 struct strbuf out = STRBUF_INIT;
2620 if (data->nr == 0)
2621 return;
2623 count = options->stat_count ? options->stat_count : data->nr;
2625 reset = diff_get_color_opt(options, DIFF_RESET);
2626 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2627 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2630 * Find the longest filename and max number of changes
2632 for (i = 0; (i < count) && (i < data->nr); i++) {
2633 struct diffstat_file *file = data->files[i];
2634 uintmax_t change = file->added + file->deleted;
2636 if (!file->is_interesting && (change == 0)) {
2637 count++; /* not shown == room for one more */
2638 continue;
2640 fill_print_name(file);
2641 len = utf8_strwidth(file->print_name);
2642 if (max_len < len)
2643 max_len = len;
2645 if (file->is_unmerged) {
2646 /* "Unmerged" is 8 characters */
2647 bin_width = bin_width < 8 ? 8 : bin_width;
2648 continue;
2650 if (file->is_binary) {
2651 /* "Bin XXX -> YYY bytes" */
2652 int w = 14 + decimal_width(file->added)
2653 + decimal_width(file->deleted);
2654 bin_width = bin_width < w ? w : bin_width;
2655 /* Display change counts aligned with "Bin" */
2656 number_width = 3;
2657 continue;
2660 if (max_change < change)
2661 max_change = change;
2663 count = i; /* where we can stop scanning in data->files[] */
2666 * We have width = stat_width or term_columns() columns total.
2667 * We want a maximum of min(max_len, stat_name_width) for the name part.
2668 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2669 * We also need 1 for " " and 4 + decimal_width(max_change)
2670 * for " | NNNN " and one the empty column at the end, altogether
2671 * 6 + decimal_width(max_change).
2673 * If there's not enough space, we will use the smaller of
2674 * stat_name_width (if set) and 5/8*width for the filename,
2675 * and the rest for constant elements + graph part, but no more
2676 * than stat_graph_width for the graph part.
2677 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2678 * for the standard terminal size).
2680 * In other words: stat_width limits the maximum width, and
2681 * stat_name_width fixes the maximum width of the filename,
2682 * and is also used to divide available columns if there
2683 * aren't enough.
2685 * Binary files are displayed with "Bin XXX -> YYY bytes"
2686 * instead of the change count and graph. This part is treated
2687 * similarly to the graph part, except that it is not
2688 * "scaled". If total width is too small to accommodate the
2689 * guaranteed minimum width of the filename part and the
2690 * separators and this message, this message will "overflow"
2691 * making the line longer than the maximum width.
2695 * NEEDSWORK: line_prefix is often used for "log --graph" output
2696 * and contains ANSI-colored string. utf8_strnwidth() should be
2697 * used to correctly count the display width instead of strlen().
2699 if (options->stat_width == -1)
2700 width = term_columns() - strlen(line_prefix);
2701 else
2702 width = options->stat_width ? options->stat_width : 80;
2703 number_width = decimal_width(max_change) > number_width ?
2704 decimal_width(max_change) : number_width;
2706 if (options->stat_graph_width == -1)
2707 options->stat_graph_width = diff_stat_graph_width;
2710 * Guarantee 3/8*16==6 for the graph part
2711 * and 5/8*16==10 for the filename part
2713 if (width < 16 + 6 + number_width)
2714 width = 16 + 6 + number_width;
2717 * First assign sizes that are wanted, ignoring available width.
2718 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2719 * starting from "XXX" should fit in graph_width.
2721 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2722 if (options->stat_graph_width &&
2723 options->stat_graph_width < graph_width)
2724 graph_width = options->stat_graph_width;
2726 name_width = (options->stat_name_width > 0 &&
2727 options->stat_name_width < max_len) ?
2728 options->stat_name_width : max_len;
2731 * Adjust adjustable widths not to exceed maximum width
2733 if (name_width + number_width + 6 + graph_width > width) {
2734 if (graph_width > width * 3/8 - number_width - 6) {
2735 graph_width = width * 3/8 - number_width - 6;
2736 if (graph_width < 6)
2737 graph_width = 6;
2740 if (options->stat_graph_width &&
2741 graph_width > options->stat_graph_width)
2742 graph_width = options->stat_graph_width;
2743 if (name_width > width - number_width - 6 - graph_width)
2744 name_width = width - number_width - 6 - graph_width;
2745 else
2746 graph_width = width - number_width - 6 - name_width;
2750 * From here name_width is the width of the name area,
2751 * and graph_width is the width of the graph area.
2752 * max_change is used to scale graph properly.
2754 for (i = 0; i < count; i++) {
2755 const char *prefix = "";
2756 struct diffstat_file *file = data->files[i];
2757 char *name = file->print_name;
2758 uintmax_t added = file->added;
2759 uintmax_t deleted = file->deleted;
2760 int name_len, padding;
2762 if (!file->is_interesting && (added + deleted == 0))
2763 continue;
2766 * "scale" the filename
2768 len = name_width;
2769 name_len = utf8_strwidth(name);
2770 if (name_width < name_len) {
2771 char *slash;
2772 prefix = "...";
2773 len -= 3;
2775 * NEEDSWORK: (name_len - len) counts the display
2776 * width, which would be shorter than the byte
2777 * length of the corresponding substring.
2778 * Advancing "name" by that number of bytes does
2779 * *NOT* skip over that many columns, so it is
2780 * very likely that chomping the pathname at the
2781 * slash we will find starting from "name" will
2782 * leave the resulting string still too long.
2784 name += name_len - len;
2785 slash = strchr(name, '/');
2786 if (slash)
2787 name = slash;
2789 padding = len - utf8_strwidth(name);
2790 if (padding < 0)
2791 padding = 0;
2793 if (file->is_binary) {
2794 strbuf_addf(&out, " %s%s%*s | %*s",
2795 prefix, name, padding, "",
2796 number_width, "Bin");
2797 if (!added && !deleted) {
2798 strbuf_addch(&out, '\n');
2799 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2800 out.buf, out.len, 0);
2801 strbuf_reset(&out);
2802 continue;
2804 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2805 del_c, deleted, reset);
2806 strbuf_addstr(&out, " -> ");
2807 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2808 add_c, added, reset);
2809 strbuf_addstr(&out, " bytes\n");
2810 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2811 out.buf, out.len, 0);
2812 strbuf_reset(&out);
2813 continue;
2815 else if (file->is_unmerged) {
2816 strbuf_addf(&out, " %s%s%*s | %*s",
2817 prefix, name, padding, "",
2818 number_width, "Unmerged\n");
2819 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2820 out.buf, out.len, 0);
2821 strbuf_reset(&out);
2822 continue;
2826 * scale the add/delete
2828 add = added;
2829 del = deleted;
2831 if (graph_width <= max_change) {
2832 int total = scale_linear(add + del, graph_width, max_change);
2833 if (total < 2 && add && del)
2834 /* width >= 2 due to the sanity check */
2835 total = 2;
2836 if (add < del) {
2837 add = scale_linear(add, graph_width, max_change);
2838 del = total - add;
2839 } else {
2840 del = scale_linear(del, graph_width, max_change);
2841 add = total - del;
2844 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2845 prefix, name, padding, "",
2846 number_width, added + deleted,
2847 added + deleted ? " " : "");
2848 show_graph(&out, '+', add, add_c, reset);
2849 show_graph(&out, '-', del, del_c, reset);
2850 strbuf_addch(&out, '\n');
2851 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2852 out.buf, out.len, 0);
2853 strbuf_reset(&out);
2856 for (i = 0; i < data->nr; i++) {
2857 struct diffstat_file *file = data->files[i];
2858 uintmax_t added = file->added;
2859 uintmax_t deleted = file->deleted;
2861 if (file->is_unmerged ||
2862 (!file->is_interesting && (added + deleted == 0))) {
2863 total_files--;
2864 continue;
2867 if (!file->is_binary) {
2868 adds += added;
2869 dels += deleted;
2871 if (i < count)
2872 continue;
2873 if (!extra_shown)
2874 emit_diff_symbol(options,
2875 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2876 NULL, 0, 0);
2877 extra_shown = 1;
2880 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2881 strbuf_release(&out);
2884 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2886 int i, adds = 0, dels = 0, total_files = data->nr;
2888 if (data->nr == 0)
2889 return;
2891 for (i = 0; i < data->nr; i++) {
2892 int added = data->files[i]->added;
2893 int deleted = data->files[i]->deleted;
2895 if (data->files[i]->is_unmerged ||
2896 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2897 total_files--;
2898 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2899 adds += added;
2900 dels += deleted;
2903 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2906 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2908 int i;
2910 if (data->nr == 0)
2911 return;
2913 for (i = 0; i < data->nr; i++) {
2914 struct diffstat_file *file = data->files[i];
2916 fprintf(options->file, "%s", diff_line_prefix(options));
2918 if (file->is_binary)
2919 fprintf(options->file, "-\t-\t");
2920 else
2921 fprintf(options->file,
2922 "%"PRIuMAX"\t%"PRIuMAX"\t",
2923 file->added, file->deleted);
2924 if (options->line_termination) {
2925 fill_print_name(file);
2926 if (!file->is_renamed)
2927 write_name_quoted(file->name, options->file,
2928 options->line_termination);
2929 else {
2930 fputs(file->print_name, options->file);
2931 putc(options->line_termination, options->file);
2933 } else {
2934 if (file->is_renamed) {
2935 putc('\0', options->file);
2936 write_name_quoted(file->from_name, options->file, '\0');
2938 write_name_quoted(file->name, options->file, '\0');
2943 struct dirstat_file {
2944 const char *name;
2945 unsigned long changed;
2948 struct dirstat_dir {
2949 struct dirstat_file *files;
2950 int alloc, nr, permille, cumulative;
2953 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2954 unsigned long changed, const char *base, int baselen)
2956 unsigned long sum_changes = 0;
2957 unsigned int sources = 0;
2958 const char *line_prefix = diff_line_prefix(opt);
2960 while (dir->nr) {
2961 struct dirstat_file *f = dir->files;
2962 int namelen = strlen(f->name);
2963 unsigned long changes;
2964 char *slash;
2966 if (namelen < baselen)
2967 break;
2968 if (memcmp(f->name, base, baselen))
2969 break;
2970 slash = strchr(f->name + baselen, '/');
2971 if (slash) {
2972 int newbaselen = slash + 1 - f->name;
2973 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2974 sources++;
2975 } else {
2976 changes = f->changed;
2977 dir->files++;
2978 dir->nr--;
2979 sources += 2;
2981 sum_changes += changes;
2985 * We don't report dirstat's for
2986 * - the top level
2987 * - or cases where everything came from a single directory
2988 * under this directory (sources == 1).
2990 if (baselen && sources != 1) {
2991 if (sum_changes) {
2992 int permille = sum_changes * 1000 / changed;
2993 if (permille >= dir->permille) {
2994 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2995 permille / 10, permille % 10, baselen, base);
2996 if (!dir->cumulative)
2997 return 0;
3001 return sum_changes;
3004 static int dirstat_compare(const void *_a, const void *_b)
3006 const struct dirstat_file *a = _a;
3007 const struct dirstat_file *b = _b;
3008 return strcmp(a->name, b->name);
3011 static void conclude_dirstat(struct diff_options *options,
3012 struct dirstat_dir *dir,
3013 unsigned long changed)
3015 struct dirstat_file *to_free = dir->files;
3017 if (!changed) {
3018 /* This can happen even with many files, if everything was renames */
3020 } else {
3021 /* Show all directories with more than x% of the changes */
3022 QSORT(dir->files, dir->nr, dirstat_compare);
3023 gather_dirstat(options, dir, changed, "", 0);
3026 free(to_free);
3029 static void show_dirstat(struct diff_options *options)
3031 int i;
3032 unsigned long changed;
3033 struct dirstat_dir dir;
3034 struct diff_queue_struct *q = &diff_queued_diff;
3036 dir.files = NULL;
3037 dir.alloc = 0;
3038 dir.nr = 0;
3039 dir.permille = options->dirstat_permille;
3040 dir.cumulative = options->flags.dirstat_cumulative;
3042 changed = 0;
3043 for (i = 0; i < q->nr; i++) {
3044 struct diff_filepair *p = q->queue[i];
3045 const char *name;
3046 unsigned long copied, added, damage;
3047 struct diff_populate_filespec_options dpf_options = {
3048 .check_size_only = 1,
3051 name = p->two->path ? p->two->path : p->one->path;
3053 if (p->one->oid_valid && p->two->oid_valid &&
3054 oideq(&p->one->oid, &p->two->oid)) {
3056 * The SHA1 has not changed, so pre-/post-content is
3057 * identical. We can therefore skip looking at the
3058 * file contents altogether.
3060 damage = 0;
3061 goto found_damage;
3064 if (options->flags.dirstat_by_file) {
3066 * In --dirstat-by-file mode, we don't really need to
3067 * look at the actual file contents at all.
3068 * The fact that the SHA1 changed is enough for us to
3069 * add this file to the list of results
3070 * (with each file contributing equal damage).
3072 damage = 1;
3073 goto found_damage;
3076 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3077 diff_populate_filespec(options->repo, p->one, NULL);
3078 diff_populate_filespec(options->repo, p->two, NULL);
3079 diffcore_count_changes(options->repo,
3080 p->one, p->two, NULL, NULL,
3081 &copied, &added);
3082 diff_free_filespec_data(p->one);
3083 diff_free_filespec_data(p->two);
3084 } else if (DIFF_FILE_VALID(p->one)) {
3085 diff_populate_filespec(options->repo, p->one, &dpf_options);
3086 copied = added = 0;
3087 diff_free_filespec_data(p->one);
3088 } else if (DIFF_FILE_VALID(p->two)) {
3089 diff_populate_filespec(options->repo, p->two, &dpf_options);
3090 copied = 0;
3091 added = p->two->size;
3092 diff_free_filespec_data(p->two);
3093 } else
3094 continue;
3097 * Original minus copied is the removed material,
3098 * added is the new material. They are both damages
3099 * made to the preimage.
3100 * If the resulting damage is zero, we know that
3101 * diffcore_count_changes() considers the two entries to
3102 * be identical, but since the oid changed, we
3103 * know that there must have been _some_ kind of change,
3104 * so we force all entries to have damage > 0.
3106 damage = (p->one->size - copied) + added;
3107 if (!damage)
3108 damage = 1;
3110 found_damage:
3111 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3112 dir.files[dir.nr].name = name;
3113 dir.files[dir.nr].changed = damage;
3114 changed += damage;
3115 dir.nr++;
3118 conclude_dirstat(options, &dir, changed);
3121 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3123 int i;
3124 unsigned long changed;
3125 struct dirstat_dir dir;
3127 if (data->nr == 0)
3128 return;
3130 dir.files = NULL;
3131 dir.alloc = 0;
3132 dir.nr = 0;
3133 dir.permille = options->dirstat_permille;
3134 dir.cumulative = options->flags.dirstat_cumulative;
3136 changed = 0;
3137 for (i = 0; i < data->nr; i++) {
3138 struct diffstat_file *file = data->files[i];
3139 unsigned long damage = file->added + file->deleted;
3140 if (file->is_binary)
3142 * binary files counts bytes, not lines. Must find some
3143 * way to normalize binary bytes vs. textual lines.
3144 * The following heuristic assumes that there are 64
3145 * bytes per "line".
3146 * This is stupid and ugly, but very cheap...
3148 damage = DIV_ROUND_UP(damage, 64);
3149 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3150 dir.files[dir.nr].name = file->name;
3151 dir.files[dir.nr].changed = damage;
3152 changed += damage;
3153 dir.nr++;
3156 conclude_dirstat(options, &dir, changed);
3159 static void free_diffstat_file(struct diffstat_file *f)
3161 free(f->print_name);
3162 free(f->name);
3163 free(f->from_name);
3164 free(f);
3167 void free_diffstat_info(struct diffstat_t *diffstat)
3169 int i;
3170 for (i = 0; i < diffstat->nr; i++)
3171 free_diffstat_file(diffstat->files[i]);
3172 free(diffstat->files);
3175 struct checkdiff_t {
3176 const char *filename;
3177 int lineno;
3178 int conflict_marker_size;
3179 struct diff_options *o;
3180 unsigned ws_rule;
3181 unsigned status;
3184 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3186 char firstchar;
3187 int cnt;
3189 if (len < marker_size + 1)
3190 return 0;
3191 firstchar = line[0];
3192 switch (firstchar) {
3193 case '=': case '>': case '<': case '|':
3194 break;
3195 default:
3196 return 0;
3198 for (cnt = 1; cnt < marker_size; cnt++)
3199 if (line[cnt] != firstchar)
3200 return 0;
3201 /* line[1] through line[marker_size-1] are same as firstchar */
3202 if (len < marker_size + 1 || !isspace(line[marker_size]))
3203 return 0;
3204 return 1;
3207 static void checkdiff_consume_hunk(void *priv,
3208 long ob UNUSED, long on UNUSED,
3209 long nb, long nn UNUSED,
3210 const char *func UNUSED, long funclen UNUSED)
3213 struct checkdiff_t *data = priv;
3214 data->lineno = nb - 1;
3217 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3219 struct checkdiff_t *data = priv;
3220 int marker_size = data->conflict_marker_size;
3221 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3222 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3223 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3224 char *err;
3225 const char *line_prefix;
3227 assert(data->o);
3228 line_prefix = diff_line_prefix(data->o);
3230 if (line[0] == '+') {
3231 unsigned bad;
3232 data->lineno++;
3233 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3234 data->status |= 1;
3235 fprintf(data->o->file,
3236 "%s%s:%d: leftover conflict marker\n",
3237 line_prefix, data->filename, data->lineno);
3239 bad = ws_check(line + 1, len - 1, data->ws_rule);
3240 if (!bad)
3241 return 0;
3242 data->status |= bad;
3243 err = whitespace_error_string(bad);
3244 fprintf(data->o->file, "%s%s:%d: %s.\n",
3245 line_prefix, data->filename, data->lineno, err);
3246 free(err);
3247 emit_line(data->o, set, reset, line, 1);
3248 ws_check_emit(line + 1, len - 1, data->ws_rule,
3249 data->o->file, set, reset, ws);
3250 } else if (line[0] == ' ') {
3251 data->lineno++;
3253 return 0;
3256 static unsigned char *deflate_it(char *data,
3257 unsigned long size,
3258 unsigned long *result_size)
3260 int bound;
3261 unsigned char *deflated;
3262 git_zstream stream;
3264 git_deflate_init(&stream, zlib_compression_level);
3265 bound = git_deflate_bound(&stream, size);
3266 deflated = xmalloc(bound);
3267 stream.next_out = deflated;
3268 stream.avail_out = bound;
3270 stream.next_in = (unsigned char *)data;
3271 stream.avail_in = size;
3272 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3273 ; /* nothing */
3274 git_deflate_end(&stream);
3275 *result_size = stream.total_out;
3276 return deflated;
3279 static void emit_binary_diff_body(struct diff_options *o,
3280 mmfile_t *one, mmfile_t *two)
3282 void *cp;
3283 void *delta;
3284 void *deflated;
3285 void *data;
3286 unsigned long orig_size;
3287 unsigned long delta_size;
3288 unsigned long deflate_size;
3289 unsigned long data_size;
3291 /* We could do deflated delta, or we could do just deflated two,
3292 * whichever is smaller.
3294 delta = NULL;
3295 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3296 if (one->size && two->size) {
3297 delta = diff_delta(one->ptr, one->size,
3298 two->ptr, two->size,
3299 &delta_size, deflate_size);
3300 if (delta) {
3301 void *to_free = delta;
3302 orig_size = delta_size;
3303 delta = deflate_it(delta, delta_size, &delta_size);
3304 free(to_free);
3308 if (delta && delta_size < deflate_size) {
3309 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3310 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3311 s, strlen(s), 0);
3312 free(s);
3313 free(deflated);
3314 data = delta;
3315 data_size = delta_size;
3316 } else {
3317 char *s = xstrfmt("%lu", two->size);
3318 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3319 s, strlen(s), 0);
3320 free(s);
3321 free(delta);
3322 data = deflated;
3323 data_size = deflate_size;
3326 /* emit data encoded in base85 */
3327 cp = data;
3328 while (data_size) {
3329 int len;
3330 int bytes = (52 < data_size) ? 52 : data_size;
3331 char line[71];
3332 data_size -= bytes;
3333 if (bytes <= 26)
3334 line[0] = bytes + 'A' - 1;
3335 else
3336 line[0] = bytes - 26 + 'a' - 1;
3337 encode_85(line + 1, cp, bytes);
3338 cp = (char *) cp + bytes;
3340 len = strlen(line);
3341 line[len++] = '\n';
3342 line[len] = '\0';
3344 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3345 line, len, 0);
3347 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3348 free(data);
3351 static void emit_binary_diff(struct diff_options *o,
3352 mmfile_t *one, mmfile_t *two)
3354 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3355 emit_binary_diff_body(o, one, two);
3356 emit_binary_diff_body(o, two, one);
3359 int diff_filespec_is_binary(struct repository *r,
3360 struct diff_filespec *one)
3362 struct diff_populate_filespec_options dpf_options = {
3363 .check_binary = 1,
3366 if (one->is_binary == -1) {
3367 diff_filespec_load_driver(one, r->index);
3368 if (one->driver->binary != -1)
3369 one->is_binary = one->driver->binary;
3370 else {
3371 if (!one->data && DIFF_FILE_VALID(one))
3372 diff_populate_filespec(r, one, &dpf_options);
3373 if (one->is_binary == -1 && one->data)
3374 one->is_binary = buffer_is_binary(one->data,
3375 one->size);
3376 if (one->is_binary == -1)
3377 one->is_binary = 0;
3380 return one->is_binary;
3383 static const struct userdiff_funcname *
3384 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3386 diff_filespec_load_driver(one, o->repo->index);
3387 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3390 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3392 if (!options->a_prefix)
3393 options->a_prefix = a;
3394 if (!options->b_prefix)
3395 options->b_prefix = b;
3398 void diff_set_noprefix(struct diff_options *options)
3400 options->a_prefix = options->b_prefix = "";
3403 void diff_set_default_prefix(struct diff_options *options)
3405 options->a_prefix = "a/";
3406 options->b_prefix = "b/";
3409 struct userdiff_driver *get_textconv(struct repository *r,
3410 struct diff_filespec *one)
3412 if (!DIFF_FILE_VALID(one))
3413 return NULL;
3415 diff_filespec_load_driver(one, r->index);
3416 return userdiff_get_textconv(r, one->driver);
3419 static struct string_list *additional_headers(struct diff_options *o,
3420 const char *path)
3422 if (!o->additional_path_headers)
3423 return NULL;
3424 return strmap_get(o->additional_path_headers, path);
3427 static void add_formatted_header(struct strbuf *msg,
3428 const char *header,
3429 const char *line_prefix,
3430 const char *meta,
3431 const char *reset)
3433 const char *next, *newline;
3435 for (next = header; *next; next = newline) {
3436 newline = strchrnul(next, '\n');
3437 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3438 (int)(newline - next), next, reset);
3439 if (*newline)
3440 newline++;
3444 static void add_formatted_headers(struct strbuf *msg,
3445 struct string_list *more_headers,
3446 const char *line_prefix,
3447 const char *meta,
3448 const char *reset)
3450 int i;
3452 for (i = 0; i < more_headers->nr; i++)
3453 add_formatted_header(msg, more_headers->items[i].string,
3454 line_prefix, meta, reset);
3457 static int diff_filepair_is_phoney(struct diff_filespec *one,
3458 struct diff_filespec *two)
3461 * This function specifically looks for pairs injected by
3462 * create_filepairs_for_header_only_notifications(). Such
3463 * pairs are "phoney" in that they do not represent any
3464 * content or even mode difference, but were inserted because
3465 * diff_queued_diff previously had no pair associated with
3466 * that path but we needed some pair to avoid losing the
3467 * "remerge CONFLICT" header associated with the path.
3469 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3472 static int set_diff_algorithm(struct diff_options *opts,
3473 const char *alg)
3475 long value = parse_algorithm_value(alg);
3477 if (value < 0)
3478 return -1;
3480 /* clear out previous settings */
3481 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3482 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3483 opts->xdl_opts |= value;
3485 return 0;
3488 static void builtin_diff(const char *name_a,
3489 const char *name_b,
3490 struct diff_filespec *one,
3491 struct diff_filespec *two,
3492 const char *xfrm_msg,
3493 int must_show_header,
3494 struct diff_options *o,
3495 int complete_rewrite)
3497 mmfile_t mf1, mf2;
3498 const char *lbl[2];
3499 char *a_one, *b_two;
3500 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3501 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3502 const char *a_prefix, *b_prefix;
3503 struct userdiff_driver *textconv_one = NULL;
3504 struct userdiff_driver *textconv_two = NULL;
3505 struct strbuf header = STRBUF_INIT;
3506 const char *line_prefix = diff_line_prefix(o);
3508 diff_set_mnemonic_prefix(o, "a/", "b/");
3509 if (o->flags.reverse_diff) {
3510 a_prefix = o->b_prefix;
3511 b_prefix = o->a_prefix;
3512 } else {
3513 a_prefix = o->a_prefix;
3514 b_prefix = o->b_prefix;
3517 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3518 (!one->mode || S_ISGITLINK(one->mode)) &&
3519 (!two->mode || S_ISGITLINK(two->mode)) &&
3520 (!diff_filepair_is_phoney(one, two))) {
3521 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3522 &one->oid, &two->oid,
3523 two->dirty_submodule);
3524 return;
3525 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3526 (!one->mode || S_ISGITLINK(one->mode)) &&
3527 (!two->mode || S_ISGITLINK(two->mode)) &&
3528 (!diff_filepair_is_phoney(one, two))) {
3529 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3530 &one->oid, &two->oid,
3531 two->dirty_submodule);
3532 return;
3535 if (o->flags.allow_textconv) {
3536 textconv_one = get_textconv(o->repo, one);
3537 textconv_two = get_textconv(o->repo, two);
3540 /* Never use a non-valid filename anywhere if at all possible */
3541 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3542 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3544 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3545 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3546 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3547 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3548 if (diff_filepair_is_phoney(one, two)) {
3550 * We should only reach this point for pairs generated from
3551 * create_filepairs_for_header_only_notifications(). For
3552 * these, we want to avoid the "/dev/null" special casing
3553 * above, because we do not want such pairs shown as either
3554 * "new file" or "deleted file" below.
3556 lbl[0] = a_one;
3557 lbl[1] = b_two;
3559 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3560 if (lbl[0][0] == '/') {
3561 /* /dev/null */
3562 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3563 if (xfrm_msg)
3564 strbuf_addstr(&header, xfrm_msg);
3565 must_show_header = 1;
3567 else if (lbl[1][0] == '/') {
3568 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3569 if (xfrm_msg)
3570 strbuf_addstr(&header, xfrm_msg);
3571 must_show_header = 1;
3573 else {
3574 if (one->mode != two->mode) {
3575 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3576 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3577 must_show_header = 1;
3579 if (xfrm_msg)
3580 strbuf_addstr(&header, xfrm_msg);
3583 * we do not run diff between different kind
3584 * of objects.
3586 if ((one->mode ^ two->mode) & S_IFMT)
3587 goto free_ab_and_return;
3588 if (complete_rewrite &&
3589 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3590 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3591 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3592 header.buf, header.len, 0);
3593 strbuf_reset(&header);
3594 emit_rewrite_diff(name_a, name_b, one, two,
3595 textconv_one, textconv_two, o);
3596 o->found_changes = 1;
3597 goto free_ab_and_return;
3601 if (o->irreversible_delete && lbl[1][0] == '/') {
3602 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3603 header.len, 0);
3604 strbuf_reset(&header);
3605 goto free_ab_and_return;
3606 } else if (!o->flags.text &&
3607 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3608 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3609 struct strbuf sb = STRBUF_INIT;
3610 if (!one->data && !two->data &&
3611 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3612 !o->flags.binary) {
3613 if (oideq(&one->oid, &two->oid)) {
3614 if (must_show_header)
3615 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3616 header.buf, header.len,
3618 goto free_ab_and_return;
3620 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3621 header.buf, header.len, 0);
3622 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3623 diff_line_prefix(o), lbl[0], lbl[1]);
3624 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3625 sb.buf, sb.len, 0);
3626 strbuf_release(&sb);
3627 goto free_ab_and_return;
3629 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3630 fill_mmfile(o->repo, &mf2, two) < 0)
3631 die("unable to read files to diff");
3632 /* Quite common confusing case */
3633 if (mf1.size == mf2.size &&
3634 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3635 if (must_show_header)
3636 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3637 header.buf, header.len, 0);
3638 goto free_ab_and_return;
3640 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3641 strbuf_reset(&header);
3642 if (o->flags.binary)
3643 emit_binary_diff(o, &mf1, &mf2);
3644 else {
3645 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3646 diff_line_prefix(o), lbl[0], lbl[1]);
3647 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3648 sb.buf, sb.len, 0);
3649 strbuf_release(&sb);
3651 o->found_changes = 1;
3652 } else {
3653 /* Crazy xdl interfaces.. */
3654 const char *diffopts;
3655 const char *v;
3656 xpparam_t xpp;
3657 xdemitconf_t xecfg;
3658 struct emit_callback ecbdata;
3659 const struct userdiff_funcname *pe;
3661 if (must_show_header) {
3662 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3663 header.buf, header.len, 0);
3664 strbuf_reset(&header);
3667 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3668 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3670 pe = diff_funcname_pattern(o, one);
3671 if (!pe)
3672 pe = diff_funcname_pattern(o, two);
3674 memset(&xpp, 0, sizeof(xpp));
3675 memset(&xecfg, 0, sizeof(xecfg));
3676 memset(&ecbdata, 0, sizeof(ecbdata));
3677 if (o->flags.suppress_diff_headers)
3678 lbl[0] = NULL;
3679 ecbdata.label_path = lbl;
3680 ecbdata.color_diff = want_color(o->use_color);
3681 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3682 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3683 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3684 ecbdata.opt = o;
3685 if (header.len && !o->flags.suppress_diff_headers)
3686 ecbdata.header = &header;
3687 xpp.flags = o->xdl_opts;
3688 xpp.ignore_regex = o->ignore_regex;
3689 xpp.ignore_regex_nr = o->ignore_regex_nr;
3690 xpp.anchors = o->anchors;
3691 xpp.anchors_nr = o->anchors_nr;
3692 xecfg.ctxlen = o->context;
3693 xecfg.interhunkctxlen = o->interhunkcontext;
3694 xecfg.flags = XDL_EMIT_FUNCNAMES;
3695 if (o->flags.funccontext)
3696 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3697 if (pe)
3698 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3700 diffopts = getenv("GIT_DIFF_OPTS");
3701 if (!diffopts)
3703 else if (skip_prefix(diffopts, "--unified=", &v))
3704 xecfg.ctxlen = strtoul(v, NULL, 10);
3705 else if (skip_prefix(diffopts, "-u", &v))
3706 xecfg.ctxlen = strtoul(v, NULL, 10);
3708 if (o->word_diff)
3709 init_diff_words_data(&ecbdata, o, one, two);
3710 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3711 &ecbdata, &xpp, &xecfg))
3712 die("unable to generate diff for %s", one->path);
3713 if (o->word_diff)
3714 free_diff_words_data(&ecbdata);
3715 if (textconv_one)
3716 free(mf1.ptr);
3717 if (textconv_two)
3718 free(mf2.ptr);
3719 xdiff_clear_find_func(&xecfg);
3722 free_ab_and_return:
3723 strbuf_release(&header);
3724 diff_free_filespec_data(one);
3725 diff_free_filespec_data(two);
3726 free(a_one);
3727 free(b_two);
3728 return;
3731 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3733 if (!is_renamed) {
3734 if (p->status == DIFF_STATUS_ADDED) {
3735 if (S_ISLNK(p->two->mode))
3736 return "new +l";
3737 else if ((p->two->mode & 0777) == 0755)
3738 return "new +x";
3739 else
3740 return "new";
3741 } else if (p->status == DIFF_STATUS_DELETED)
3742 return "gone";
3744 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3745 return "mode -l";
3746 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3747 return "mode +l";
3748 else if ((p->one->mode & 0777) == 0644 &&
3749 (p->two->mode & 0777) == 0755)
3750 return "mode +x";
3751 else if ((p->one->mode & 0777) == 0755 &&
3752 (p->two->mode & 0777) == 0644)
3753 return "mode -x";
3754 return NULL;
3757 static void builtin_diffstat(const char *name_a, const char *name_b,
3758 struct diff_filespec *one,
3759 struct diff_filespec *two,
3760 struct diffstat_t *diffstat,
3761 struct diff_options *o,
3762 struct diff_filepair *p)
3764 mmfile_t mf1, mf2;
3765 struct diffstat_file *data;
3766 int may_differ;
3767 int complete_rewrite = 0;
3769 if (!DIFF_PAIR_UNMERGED(p)) {
3770 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3771 complete_rewrite = 1;
3774 data = diffstat_add(diffstat, name_a, name_b);
3775 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3776 if (o->flags.stat_with_summary)
3777 data->comments = get_compact_summary(p, data->is_renamed);
3779 if (!one || !two) {
3780 data->is_unmerged = 1;
3781 return;
3784 /* saves some reads if true, not a guarantee of diff outcome */
3785 may_differ = !(one->oid_valid && two->oid_valid &&
3786 oideq(&one->oid, &two->oid));
3788 if (diff_filespec_is_binary(o->repo, one) ||
3789 diff_filespec_is_binary(o->repo, two)) {
3790 data->is_binary = 1;
3791 if (!may_differ) {
3792 data->added = 0;
3793 data->deleted = 0;
3794 } else {
3795 data->added = diff_filespec_size(o->repo, two);
3796 data->deleted = diff_filespec_size(o->repo, one);
3800 else if (complete_rewrite) {
3801 diff_populate_filespec(o->repo, one, NULL);
3802 diff_populate_filespec(o->repo, two, NULL);
3803 data->deleted = count_lines(one->data, one->size);
3804 data->added = count_lines(two->data, two->size);
3807 else if (may_differ) {
3808 /* Crazy xdl interfaces.. */
3809 xpparam_t xpp;
3810 xdemitconf_t xecfg;
3812 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3813 fill_mmfile(o->repo, &mf2, two) < 0)
3814 die("unable to read files to diff");
3816 memset(&xpp, 0, sizeof(xpp));
3817 memset(&xecfg, 0, sizeof(xecfg));
3818 xpp.flags = o->xdl_opts;
3819 xpp.ignore_regex = o->ignore_regex;
3820 xpp.ignore_regex_nr = o->ignore_regex_nr;
3821 xpp.anchors = o->anchors;
3822 xpp.anchors_nr = o->anchors_nr;
3823 xecfg.ctxlen = o->context;
3824 xecfg.interhunkctxlen = o->interhunkcontext;
3825 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3826 if (xdi_diff_outf(&mf1, &mf2, NULL,
3827 diffstat_consume, diffstat, &xpp, &xecfg))
3828 die("unable to generate diffstat for %s", one->path);
3830 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3831 struct diffstat_file *file =
3832 diffstat->files[diffstat->nr - 1];
3834 * Omit diffstats of modified files where nothing changed.
3835 * Even if may_differ, this might be the case due to
3836 * ignoring whitespace changes, etc.
3838 * But note that we special-case additions, deletions,
3839 * renames, and mode changes as adding an empty file,
3840 * for example is still of interest.
3842 if ((p->status == DIFF_STATUS_MODIFIED)
3843 && !file->added
3844 && !file->deleted
3845 && one->mode == two->mode) {
3846 free_diffstat_file(file);
3847 diffstat->nr--;
3852 diff_free_filespec_data(one);
3853 diff_free_filespec_data(two);
3856 static void builtin_checkdiff(const char *name_a, const char *name_b,
3857 const char *attr_path,
3858 struct diff_filespec *one,
3859 struct diff_filespec *two,
3860 struct diff_options *o)
3862 mmfile_t mf1, mf2;
3863 struct checkdiff_t data;
3865 if (!two)
3866 return;
3868 memset(&data, 0, sizeof(data));
3869 data.filename = name_b ? name_b : name_a;
3870 data.lineno = 0;
3871 data.o = o;
3872 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3873 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3875 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3876 fill_mmfile(o->repo, &mf2, two) < 0)
3877 die("unable to read files to diff");
3880 * All the other codepaths check both sides, but not checking
3881 * the "old" side here is deliberate. We are checking the newly
3882 * introduced changes, and as long as the "new" side is text, we
3883 * can and should check what it introduces.
3885 if (diff_filespec_is_binary(o->repo, two))
3886 goto free_and_return;
3887 else {
3888 /* Crazy xdl interfaces.. */
3889 xpparam_t xpp;
3890 xdemitconf_t xecfg;
3892 memset(&xpp, 0, sizeof(xpp));
3893 memset(&xecfg, 0, sizeof(xecfg));
3894 xecfg.ctxlen = 1; /* at least one context line */
3895 xpp.flags = 0;
3896 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3897 checkdiff_consume, &data,
3898 &xpp, &xecfg))
3899 die("unable to generate checkdiff for %s", one->path);
3901 if (data.ws_rule & WS_BLANK_AT_EOF) {
3902 struct emit_callback ecbdata;
3903 int blank_at_eof;
3905 ecbdata.ws_rule = data.ws_rule;
3906 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3907 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3909 if (blank_at_eof) {
3910 static char *err;
3911 if (!err)
3912 err = whitespace_error_string(WS_BLANK_AT_EOF);
3913 fprintf(o->file, "%s:%d: %s.\n",
3914 data.filename, blank_at_eof, err);
3915 data.status = 1; /* report errors */
3919 free_and_return:
3920 diff_free_filespec_data(one);
3921 diff_free_filespec_data(two);
3922 if (data.status)
3923 o->flags.check_failed = 1;
3926 struct diff_filespec *alloc_filespec(const char *path)
3928 struct diff_filespec *spec;
3930 FLEXPTR_ALLOC_STR(spec, path, path);
3931 spec->count = 1;
3932 spec->is_binary = -1;
3933 return spec;
3936 void free_filespec(struct diff_filespec *spec)
3938 if (!--spec->count) {
3939 diff_free_filespec_data(spec);
3940 free(spec);
3944 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3945 int oid_valid, unsigned short mode)
3947 if (mode) {
3948 spec->mode = canon_mode(mode);
3949 oidcpy(&spec->oid, oid);
3950 spec->oid_valid = oid_valid;
3955 * Given a name and sha1 pair, if the index tells us the file in
3956 * the work tree has that object contents, return true, so that
3957 * prepare_temp_file() does not have to inflate and extract.
3959 static int reuse_worktree_file(struct index_state *istate,
3960 const char *name,
3961 const struct object_id *oid,
3962 int want_file)
3964 const struct cache_entry *ce;
3965 struct stat st;
3966 int pos, len;
3969 * We do not read the cache ourselves here, because the
3970 * benchmark with my previous version that always reads cache
3971 * shows that it makes things worse for diff-tree comparing
3972 * two linux-2.6 kernel trees in an already checked out work
3973 * tree. This is because most diff-tree comparisons deal with
3974 * only a small number of files, while reading the cache is
3975 * expensive for a large project, and its cost outweighs the
3976 * savings we get by not inflating the object to a temporary
3977 * file. Practically, this code only helps when we are used
3978 * by diff-cache --cached, which does read the cache before
3979 * calling us.
3981 if (!istate->cache)
3982 return 0;
3984 /* We want to avoid the working directory if our caller
3985 * doesn't need the data in a normal file, this system
3986 * is rather slow with its stat/open/mmap/close syscalls,
3987 * and the object is contained in a pack file. The pack
3988 * is probably already open and will be faster to obtain
3989 * the data through than the working directory. Loose
3990 * objects however would tend to be slower as they need
3991 * to be individually opened and inflated.
3993 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3994 return 0;
3997 * Similarly, if we'd have to convert the file contents anyway, that
3998 * makes the optimization not worthwhile.
4000 if (!want_file && would_convert_to_git(istate, name))
4001 return 0;
4004 * If this path does not match our sparse-checkout definition,
4005 * then the file will not be in the working directory.
4007 if (!path_in_sparse_checkout(name, istate))
4008 return 0;
4010 len = strlen(name);
4011 pos = index_name_pos(istate, name, len);
4012 if (pos < 0)
4013 return 0;
4014 ce = istate->cache[pos];
4017 * This is not the sha1 we are looking for, or
4018 * unreusable because it is not a regular file.
4020 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4021 return 0;
4024 * If ce is marked as "assume unchanged", there is no
4025 * guarantee that work tree matches what we are looking for.
4027 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4028 return 0;
4031 * If ce matches the file in the work tree, we can reuse it.
4033 if (ce_uptodate(ce) ||
4034 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4035 return 1;
4037 return 0;
4040 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4042 struct strbuf buf = STRBUF_INIT;
4043 char *dirty = "";
4045 /* Are we looking at the work tree? */
4046 if (s->dirty_submodule)
4047 dirty = "-dirty";
4049 strbuf_addf(&buf, "Subproject commit %s%s\n",
4050 oid_to_hex(&s->oid), dirty);
4051 s->size = buf.len;
4052 if (size_only) {
4053 s->data = NULL;
4054 strbuf_release(&buf);
4055 } else {
4056 s->data = strbuf_detach(&buf, NULL);
4057 s->should_free = 1;
4059 return 0;
4063 * While doing rename detection and pickaxe operation, we may need to
4064 * grab the data for the blob (or file) for our own in-core comparison.
4065 * diff_filespec has data and size fields for this purpose.
4067 int diff_populate_filespec(struct repository *r,
4068 struct diff_filespec *s,
4069 const struct diff_populate_filespec_options *options)
4071 int size_only = options ? options->check_size_only : 0;
4072 int check_binary = options ? options->check_binary : 0;
4073 int err = 0;
4074 int conv_flags = global_conv_flags_eol;
4076 * demote FAIL to WARN to allow inspecting the situation
4077 * instead of refusing.
4079 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4080 conv_flags = CONV_EOL_RNDTRP_WARN;
4082 if (!DIFF_FILE_VALID(s))
4083 die("internal error: asking to populate invalid file.");
4084 if (S_ISDIR(s->mode))
4085 return -1;
4087 if (s->data)
4088 return 0;
4090 if (size_only && 0 < s->size)
4091 return 0;
4093 if (S_ISGITLINK(s->mode))
4094 return diff_populate_gitlink(s, size_only);
4096 if (!s->oid_valid ||
4097 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4098 struct strbuf buf = STRBUF_INIT;
4099 struct stat st;
4100 int fd;
4102 if (lstat(s->path, &st) < 0) {
4103 err_empty:
4104 err = -1;
4105 empty:
4106 s->data = (char *)"";
4107 s->size = 0;
4108 return err;
4110 s->size = xsize_t(st.st_size);
4111 if (!s->size)
4112 goto empty;
4113 if (S_ISLNK(st.st_mode)) {
4114 struct strbuf sb = STRBUF_INIT;
4116 if (strbuf_readlink(&sb, s->path, s->size))
4117 goto err_empty;
4118 s->size = sb.len;
4119 s->data = strbuf_detach(&sb, NULL);
4120 s->should_free = 1;
4121 return 0;
4125 * Even if the caller would be happy with getting
4126 * only the size, we cannot return early at this
4127 * point if the path requires us to run the content
4128 * conversion.
4130 if (size_only && !would_convert_to_git(r->index, s->path))
4131 return 0;
4134 * Note: this check uses xsize_t(st.st_size) that may
4135 * not be the true size of the blob after it goes
4136 * through convert_to_git(). This may not strictly be
4137 * correct, but the whole point of big_file_threshold
4138 * and is_binary check being that we want to avoid
4139 * opening the file and inspecting the contents, this
4140 * is probably fine.
4142 if (check_binary &&
4143 s->size > big_file_threshold && s->is_binary == -1) {
4144 s->is_binary = 1;
4145 return 0;
4147 fd = open(s->path, O_RDONLY);
4148 if (fd < 0)
4149 goto err_empty;
4150 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4151 close(fd);
4152 s->should_munmap = 1;
4155 * Convert from working tree format to canonical git format
4157 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4158 size_t size = 0;
4159 munmap(s->data, s->size);
4160 s->should_munmap = 0;
4161 s->data = strbuf_detach(&buf, &size);
4162 s->size = size;
4163 s->should_free = 1;
4166 else {
4167 struct object_info info = {
4168 .sizep = &s->size
4171 if (!(size_only || check_binary))
4173 * Set contentp, since there is no chance that merely
4174 * the size is sufficient.
4176 info.contentp = &s->data;
4178 if (options && options->missing_object_cb) {
4179 if (!oid_object_info_extended(r, &s->oid, &info,
4180 OBJECT_INFO_LOOKUP_REPLACE |
4181 OBJECT_INFO_SKIP_FETCH_OBJECT))
4182 goto object_read;
4183 options->missing_object_cb(options->missing_object_data);
4185 if (oid_object_info_extended(r, &s->oid, &info,
4186 OBJECT_INFO_LOOKUP_REPLACE))
4187 die("unable to read %s", oid_to_hex(&s->oid));
4189 object_read:
4190 if (size_only || check_binary) {
4191 if (size_only)
4192 return 0;
4193 if (s->size > big_file_threshold && s->is_binary == -1) {
4194 s->is_binary = 1;
4195 return 0;
4198 if (!info.contentp) {
4199 info.contentp = &s->data;
4200 if (oid_object_info_extended(r, &s->oid, &info,
4201 OBJECT_INFO_LOOKUP_REPLACE))
4202 die("unable to read %s", oid_to_hex(&s->oid));
4204 s->should_free = 1;
4206 return 0;
4209 void diff_free_filespec_blob(struct diff_filespec *s)
4211 if (s->should_free)
4212 free(s->data);
4213 else if (s->should_munmap)
4214 munmap(s->data, s->size);
4216 if (s->should_free || s->should_munmap) {
4217 s->should_free = s->should_munmap = 0;
4218 s->data = NULL;
4222 void diff_free_filespec_data(struct diff_filespec *s)
4224 if (!s)
4225 return;
4227 diff_free_filespec_blob(s);
4228 FREE_AND_NULL(s->cnt_data);
4231 static void prep_temp_blob(struct index_state *istate,
4232 const char *path, struct diff_tempfile *temp,
4233 void *blob,
4234 unsigned long size,
4235 const struct object_id *oid,
4236 int mode)
4238 struct strbuf buf = STRBUF_INIT;
4239 char *path_dup = xstrdup(path);
4240 const char *base = basename(path_dup);
4241 struct checkout_metadata meta;
4243 init_checkout_metadata(&meta, NULL, NULL, oid);
4245 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4246 if (!temp->tempfile)
4247 die_errno("unable to create temp-file");
4248 if (convert_to_working_tree(istate, path,
4249 (const char *)blob, (size_t)size, &buf, &meta)) {
4250 blob = buf.buf;
4251 size = buf.len;
4253 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4254 close_tempfile_gently(temp->tempfile))
4255 die_errno("unable to write temp-file");
4256 temp->name = get_tempfile_path(temp->tempfile);
4257 oid_to_hex_r(temp->hex, oid);
4258 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4259 strbuf_release(&buf);
4260 free(path_dup);
4263 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4264 struct diff_filespec *one)
4266 struct diff_tempfile *temp = claim_diff_tempfile();
4268 if (!DIFF_FILE_VALID(one)) {
4269 not_a_valid_file:
4270 /* A '-' entry produces this for file-2, and
4271 * a '+' entry produces this for file-1.
4273 temp->name = "/dev/null";
4274 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4275 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4276 return temp;
4279 if (!S_ISGITLINK(one->mode) &&
4280 (!one->oid_valid ||
4281 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4282 struct stat st;
4283 if (lstat(one->path, &st) < 0) {
4284 if (errno == ENOENT)
4285 goto not_a_valid_file;
4286 die_errno("stat(%s)", one->path);
4288 if (S_ISLNK(st.st_mode)) {
4289 struct strbuf sb = STRBUF_INIT;
4290 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4291 die_errno("readlink(%s)", one->path);
4292 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4293 (one->oid_valid ?
4294 &one->oid : null_oid()),
4295 (one->oid_valid ?
4296 one->mode : S_IFLNK));
4297 strbuf_release(&sb);
4299 else {
4300 /* we can borrow from the file in the work tree */
4301 temp->name = one->path;
4302 if (!one->oid_valid)
4303 oid_to_hex_r(temp->hex, null_oid());
4304 else
4305 oid_to_hex_r(temp->hex, &one->oid);
4306 /* Even though we may sometimes borrow the
4307 * contents from the work tree, we always want
4308 * one->mode. mode is trustworthy even when
4309 * !(one->oid_valid), as long as
4310 * DIFF_FILE_VALID(one).
4312 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4314 return temp;
4316 else {
4317 if (diff_populate_filespec(r, one, NULL))
4318 die("cannot read data blob for %s", one->path);
4319 prep_temp_blob(r->index, one->path, temp,
4320 one->data, one->size,
4321 &one->oid, one->mode);
4323 return temp;
4326 static void add_external_diff_name(struct repository *r,
4327 struct strvec *argv,
4328 struct diff_filespec *df)
4330 struct diff_tempfile *temp = prepare_temp_file(r, df);
4331 strvec_push(argv, temp->name);
4332 strvec_push(argv, temp->hex);
4333 strvec_push(argv, temp->mode);
4336 /* An external diff command takes:
4338 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4339 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4342 static void run_external_diff(const char *pgm,
4343 const char *name,
4344 const char *other,
4345 struct diff_filespec *one,
4346 struct diff_filespec *two,
4347 const char *xfrm_msg,
4348 struct diff_options *o)
4350 struct child_process cmd = CHILD_PROCESS_INIT;
4351 struct diff_queue_struct *q = &diff_queued_diff;
4353 strvec_push(&cmd.args, pgm);
4354 strvec_push(&cmd.args, name);
4356 if (one && two) {
4357 add_external_diff_name(o->repo, &cmd.args, one);
4358 add_external_diff_name(o->repo, &cmd.args, two);
4359 if (other) {
4360 strvec_push(&cmd.args, other);
4361 strvec_push(&cmd.args, xfrm_msg);
4365 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4366 ++o->diff_path_counter);
4367 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4369 diff_free_filespec_data(one);
4370 diff_free_filespec_data(two);
4371 cmd.use_shell = 1;
4372 if (run_command(&cmd))
4373 die(_("external diff died, stopping at %s"), name);
4375 remove_tempfile();
4378 static int similarity_index(struct diff_filepair *p)
4380 return p->score * 100 / MAX_SCORE;
4383 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4385 if (startup_info->have_repository)
4386 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4387 else {
4388 char *hex = oid_to_hex(oid);
4389 if (abbrev < 0)
4390 abbrev = FALLBACK_DEFAULT_ABBREV;
4391 if (abbrev > the_hash_algo->hexsz)
4392 BUG("oid abbreviation out of range: %d", abbrev);
4393 if (abbrev)
4394 hex[abbrev] = '\0';
4395 return hex;
4399 static void fill_metainfo(struct strbuf *msg,
4400 const char *name,
4401 const char *other,
4402 struct diff_filespec *one,
4403 struct diff_filespec *two,
4404 struct diff_options *o,
4405 struct diff_filepair *p,
4406 int *must_show_header,
4407 int use_color)
4409 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4410 const char *reset = diff_get_color(use_color, DIFF_RESET);
4411 const char *line_prefix = diff_line_prefix(o);
4412 struct string_list *more_headers = NULL;
4414 *must_show_header = 1;
4415 strbuf_init(msg, PATH_MAX * 2 + 300);
4416 switch (p->status) {
4417 case DIFF_STATUS_COPIED:
4418 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4419 line_prefix, set, similarity_index(p));
4420 strbuf_addf(msg, "%s\n%s%scopy from ",
4421 reset, line_prefix, set);
4422 quote_c_style(name, msg, NULL, 0);
4423 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4424 quote_c_style(other, msg, NULL, 0);
4425 strbuf_addf(msg, "%s\n", reset);
4426 break;
4427 case DIFF_STATUS_RENAMED:
4428 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4429 line_prefix, set, similarity_index(p));
4430 strbuf_addf(msg, "%s\n%s%srename from ",
4431 reset, line_prefix, set);
4432 quote_c_style(name, msg, NULL, 0);
4433 strbuf_addf(msg, "%s\n%s%srename to ",
4434 reset, line_prefix, set);
4435 quote_c_style(other, msg, NULL, 0);
4436 strbuf_addf(msg, "%s\n", reset);
4437 break;
4438 case DIFF_STATUS_MODIFIED:
4439 if (p->score) {
4440 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4441 line_prefix,
4442 set, similarity_index(p), reset);
4443 break;
4445 /* fallthru */
4446 default:
4447 *must_show_header = 0;
4449 if ((more_headers = additional_headers(o, name))) {
4450 add_formatted_headers(msg, more_headers,
4451 line_prefix, set, reset);
4452 *must_show_header = 1;
4454 if (one && two && !oideq(&one->oid, &two->oid)) {
4455 const unsigned hexsz = the_hash_algo->hexsz;
4456 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4458 if (o->flags.full_index)
4459 abbrev = hexsz;
4461 if (o->flags.binary) {
4462 mmfile_t mf;
4463 if ((!fill_mmfile(o->repo, &mf, one) &&
4464 diff_filespec_is_binary(o->repo, one)) ||
4465 (!fill_mmfile(o->repo, &mf, two) &&
4466 diff_filespec_is_binary(o->repo, two)))
4467 abbrev = hexsz;
4469 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4470 diff_abbrev_oid(&one->oid, abbrev),
4471 diff_abbrev_oid(&two->oid, abbrev));
4472 if (one->mode == two->mode)
4473 strbuf_addf(msg, " %06o", one->mode);
4474 strbuf_addf(msg, "%s\n", reset);
4478 static void run_diff_cmd(const char *pgm,
4479 const char *name,
4480 const char *other,
4481 const char *attr_path,
4482 struct diff_filespec *one,
4483 struct diff_filespec *two,
4484 struct strbuf *msg,
4485 struct diff_options *o,
4486 struct diff_filepair *p)
4488 const char *xfrm_msg = NULL;
4489 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4490 int must_show_header = 0;
4491 struct userdiff_driver *drv = NULL;
4493 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4494 drv = userdiff_find_by_path(o->repo->index, attr_path);
4496 if (o->flags.allow_external && drv && drv->external)
4497 pgm = drv->external;
4499 if (msg) {
4501 * don't use colors when the header is intended for an
4502 * external diff driver
4504 fill_metainfo(msg, name, other, one, two, o, p,
4505 &must_show_header,
4506 want_color(o->use_color) && !pgm);
4507 xfrm_msg = msg->len ? msg->buf : NULL;
4510 if (pgm) {
4511 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4512 return;
4514 if (one && two) {
4515 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4516 set_diff_algorithm(o, drv->algorithm);
4518 builtin_diff(name, other ? other : name,
4519 one, two, xfrm_msg, must_show_header,
4520 o, complete_rewrite);
4521 } else {
4522 fprintf(o->file, "* Unmerged path %s\n", name);
4526 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4528 if (DIFF_FILE_VALID(one)) {
4529 if (!one->oid_valid) {
4530 struct stat st;
4531 if (one->is_stdin) {
4532 oidclr(&one->oid);
4533 return;
4535 if (lstat(one->path, &st) < 0)
4536 die_errno("stat '%s'", one->path);
4537 if (index_path(istate, &one->oid, one->path, &st, 0))
4538 die("cannot hash %s", one->path);
4541 else
4542 oidclr(&one->oid);
4545 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4547 /* Strip the prefix but do not molest /dev/null and absolute paths */
4548 if (*namep && !is_absolute_path(*namep)) {
4549 *namep += prefix_length;
4550 if (**namep == '/')
4551 ++*namep;
4553 if (*otherp && !is_absolute_path(*otherp)) {
4554 *otherp += prefix_length;
4555 if (**otherp == '/')
4556 ++*otherp;
4560 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4562 const char *pgm = external_diff();
4563 struct strbuf msg;
4564 struct diff_filespec *one = p->one;
4565 struct diff_filespec *two = p->two;
4566 const char *name;
4567 const char *other;
4568 const char *attr_path;
4570 name = one->path;
4571 other = (strcmp(name, two->path) ? two->path : NULL);
4572 attr_path = name;
4573 if (o->prefix_length)
4574 strip_prefix(o->prefix_length, &name, &other);
4576 if (!o->flags.allow_external)
4577 pgm = NULL;
4579 if (DIFF_PAIR_UNMERGED(p)) {
4580 run_diff_cmd(pgm, name, NULL, attr_path,
4581 NULL, NULL, NULL, o, p);
4582 return;
4585 diff_fill_oid_info(one, o->repo->index);
4586 diff_fill_oid_info(two, o->repo->index);
4588 if (!pgm &&
4589 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4590 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4592 * a filepair that changes between file and symlink
4593 * needs to be split into deletion and creation.
4595 struct diff_filespec *null = alloc_filespec(two->path);
4596 run_diff_cmd(NULL, name, other, attr_path,
4597 one, null, &msg,
4598 o, p);
4599 free(null);
4600 strbuf_release(&msg);
4602 null = alloc_filespec(one->path);
4603 run_diff_cmd(NULL, name, other, attr_path,
4604 null, two, &msg, o, p);
4605 free(null);
4607 else
4608 run_diff_cmd(pgm, name, other, attr_path,
4609 one, two, &msg, o, p);
4611 strbuf_release(&msg);
4614 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4615 struct diffstat_t *diffstat)
4617 const char *name;
4618 const char *other;
4620 if (!o->ignore_driver_algorithm) {
4621 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4622 p->one->path);
4624 if (drv && drv->algorithm)
4625 set_diff_algorithm(o, drv->algorithm);
4628 if (DIFF_PAIR_UNMERGED(p)) {
4629 /* unmerged */
4630 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4631 diffstat, o, p);
4632 return;
4635 name = p->one->path;
4636 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4638 if (o->prefix_length)
4639 strip_prefix(o->prefix_length, &name, &other);
4641 diff_fill_oid_info(p->one, o->repo->index);
4642 diff_fill_oid_info(p->two, o->repo->index);
4644 builtin_diffstat(name, other, p->one, p->two,
4645 diffstat, o, p);
4648 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4650 const char *name;
4651 const char *other;
4652 const char *attr_path;
4654 if (DIFF_PAIR_UNMERGED(p)) {
4655 /* unmerged */
4656 return;
4659 name = p->one->path;
4660 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4661 attr_path = other ? other : name;
4663 if (o->prefix_length)
4664 strip_prefix(o->prefix_length, &name, &other);
4666 diff_fill_oid_info(p->one, o->repo->index);
4667 diff_fill_oid_info(p->two, o->repo->index);
4669 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4672 void repo_diff_setup(struct repository *r, struct diff_options *options)
4674 memcpy(options, &default_diff_options, sizeof(*options));
4676 options->file = stdout;
4677 options->repo = r;
4679 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4680 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4681 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4682 options->abbrev = DEFAULT_ABBREV;
4683 options->line_termination = '\n';
4684 options->break_opt = -1;
4685 options->rename_limit = -1;
4686 options->dirstat_permille = diff_dirstat_permille_default;
4687 options->context = diff_context_default;
4688 options->interhunkcontext = diff_interhunk_context_default;
4689 options->ws_error_highlight = ws_error_highlight_default;
4690 options->flags.rename_empty = 1;
4691 options->flags.relative_name = diff_relative;
4692 options->objfind = NULL;
4694 /* pathchange left =NULL by default */
4695 options->change = diff_change;
4696 options->add_remove = diff_addremove;
4697 options->use_color = diff_use_color_default;
4698 options->detect_rename = diff_detect_rename_default;
4699 options->xdl_opts |= diff_algorithm;
4700 if (diff_indent_heuristic)
4701 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4703 options->orderfile = diff_order_file_cfg;
4705 if (!options->flags.ignore_submodule_set)
4706 options->flags.ignore_untracked_in_submodules = 1;
4708 if (diff_no_prefix) {
4709 diff_set_noprefix(options);
4710 } else if (!diff_mnemonic_prefix) {
4711 diff_set_default_prefix(options);
4714 options->color_moved = diff_color_moved_default;
4715 options->color_moved_ws_handling = diff_color_moved_ws_default;
4718 static const char diff_status_letters[] = {
4719 DIFF_STATUS_ADDED,
4720 DIFF_STATUS_COPIED,
4721 DIFF_STATUS_DELETED,
4722 DIFF_STATUS_MODIFIED,
4723 DIFF_STATUS_RENAMED,
4724 DIFF_STATUS_TYPE_CHANGED,
4725 DIFF_STATUS_UNKNOWN,
4726 DIFF_STATUS_UNMERGED,
4727 DIFF_STATUS_FILTER_AON,
4728 DIFF_STATUS_FILTER_BROKEN,
4729 '\0',
4732 static unsigned int filter_bit['Z' + 1];
4734 static void prepare_filter_bits(void)
4736 int i;
4738 if (!filter_bit[DIFF_STATUS_ADDED]) {
4739 for (i = 0; diff_status_letters[i]; i++)
4740 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4744 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4746 return opt->filter & filter_bit[(int) status];
4749 unsigned diff_filter_bit(char status)
4751 prepare_filter_bits();
4752 return filter_bit[(int) status];
4755 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4757 unsigned forbidden_magic;
4759 if (ps->nr != 1) {
4760 if (die_on_error)
4761 die(_("--follow requires exactly one pathspec"));
4762 return 0;
4765 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4766 PATHSPEC_LITERAL);
4767 if (forbidden_magic) {
4768 if (die_on_error) {
4769 struct strbuf sb = STRBUF_INIT;
4770 pathspec_magic_names(forbidden_magic, &sb);
4771 die(_("pathspec magic not supported by --follow: %s"),
4772 sb.buf);
4774 return 0;
4777 return 1;
4780 void diff_setup_done(struct diff_options *options)
4782 unsigned check_mask = DIFF_FORMAT_NAME |
4783 DIFF_FORMAT_NAME_STATUS |
4784 DIFF_FORMAT_CHECKDIFF |
4785 DIFF_FORMAT_NO_OUTPUT;
4787 * This must be signed because we're comparing against a potentially
4788 * negative value.
4790 const int hexsz = the_hash_algo->hexsz;
4792 if (options->set_default)
4793 options->set_default(options);
4795 if (HAS_MULTI_BITS(options->output_format & check_mask))
4796 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4797 "--name-only", "--name-status", "--check", "-s");
4799 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4800 die(_("options '%s', '%s', and '%s' cannot be used together"),
4801 "-G", "-S", "--find-object");
4803 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4804 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4805 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4807 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4808 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4809 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4812 * Most of the time we can say "there are changes"
4813 * only by checking if there are changed paths, but
4814 * --ignore-whitespace* options force us to look
4815 * inside contents.
4818 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4819 options->ignore_regex_nr)
4820 options->flags.diff_from_contents = 1;
4821 else
4822 options->flags.diff_from_contents = 0;
4824 if (options->flags.find_copies_harder)
4825 options->detect_rename = DIFF_DETECT_COPY;
4827 if (!options->flags.relative_name)
4828 options->prefix = NULL;
4829 if (options->prefix)
4830 options->prefix_length = strlen(options->prefix);
4831 else
4832 options->prefix_length = 0;
4834 if (options->output_format & (DIFF_FORMAT_NAME |
4835 DIFF_FORMAT_NAME_STATUS |
4836 DIFF_FORMAT_CHECKDIFF |
4837 DIFF_FORMAT_NO_OUTPUT))
4838 options->output_format &= ~(DIFF_FORMAT_RAW |
4839 DIFF_FORMAT_NUMSTAT |
4840 DIFF_FORMAT_DIFFSTAT |
4841 DIFF_FORMAT_SHORTSTAT |
4842 DIFF_FORMAT_DIRSTAT |
4843 DIFF_FORMAT_SUMMARY |
4844 DIFF_FORMAT_PATCH);
4847 * These cases always need recursive; we do not drop caller-supplied
4848 * recursive bits for other formats here.
4850 if (options->output_format & (DIFF_FORMAT_PATCH |
4851 DIFF_FORMAT_NUMSTAT |
4852 DIFF_FORMAT_DIFFSTAT |
4853 DIFF_FORMAT_SHORTSTAT |
4854 DIFF_FORMAT_DIRSTAT |
4855 DIFF_FORMAT_SUMMARY |
4856 DIFF_FORMAT_CHECKDIFF))
4857 options->flags.recursive = 1;
4859 * Also pickaxe would not work very well if you do not say recursive
4861 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4862 options->flags.recursive = 1;
4864 * When patches are generated, submodules diffed against the work tree
4865 * must be checked for dirtiness too so it can be shown in the output
4867 if (options->output_format & DIFF_FORMAT_PATCH)
4868 options->flags.dirty_submodules = 1;
4870 if (options->detect_rename && options->rename_limit < 0)
4871 options->rename_limit = diff_rename_limit_default;
4872 if (hexsz < options->abbrev)
4873 options->abbrev = hexsz; /* full */
4876 * It does not make sense to show the first hit we happened
4877 * to have found. It does not make sense not to return with
4878 * exit code in such a case either.
4880 if (options->flags.quick) {
4881 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4882 options->flags.exit_with_status = 1;
4885 options->diff_path_counter = 0;
4887 if (options->flags.follow_renames)
4888 diff_check_follow_pathspec(&options->pathspec, 1);
4890 if (!options->use_color || external_diff())
4891 options->color_moved = 0;
4893 if (options->filter_not) {
4894 if (!options->filter)
4895 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4896 options->filter &= ~options->filter_not;
4900 int parse_long_opt(const char *opt, const char **argv,
4901 const char **optarg)
4903 const char *arg = argv[0];
4904 if (!skip_prefix(arg, "--", &arg))
4905 return 0;
4906 if (!skip_prefix(arg, opt, &arg))
4907 return 0;
4908 if (*arg == '=') { /* stuck form: --option=value */
4909 *optarg = arg + 1;
4910 return 1;
4912 if (*arg != '\0')
4913 return 0;
4914 /* separate form: --option value */
4915 if (!argv[1])
4916 die("Option '--%s' requires a value", opt);
4917 *optarg = argv[1];
4918 return 2;
4921 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4923 struct diff_options *options = opt->value;
4924 int width = options->stat_width;
4925 int name_width = options->stat_name_width;
4926 int graph_width = options->stat_graph_width;
4927 int count = options->stat_count;
4928 char *end;
4930 BUG_ON_OPT_NEG(unset);
4932 if (!strcmp(opt->long_name, "stat")) {
4933 if (value) {
4934 width = strtoul(value, &end, 10);
4935 if (*end == ',')
4936 name_width = strtoul(end+1, &end, 10);
4937 if (*end == ',')
4938 count = strtoul(end+1, &end, 10);
4939 if (*end)
4940 return error(_("invalid --stat value: %s"), value);
4942 } else if (!strcmp(opt->long_name, "stat-width")) {
4943 width = strtoul(value, &end, 10);
4944 if (*end)
4945 return error(_("%s expects a numerical value"),
4946 opt->long_name);
4947 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4948 name_width = strtoul(value, &end, 10);
4949 if (*end)
4950 return error(_("%s expects a numerical value"),
4951 opt->long_name);
4952 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4953 graph_width = strtoul(value, &end, 10);
4954 if (*end)
4955 return error(_("%s expects a numerical value"),
4956 opt->long_name);
4957 } else if (!strcmp(opt->long_name, "stat-count")) {
4958 count = strtoul(value, &end, 10);
4959 if (*end)
4960 return error(_("%s expects a numerical value"),
4961 opt->long_name);
4962 } else
4963 BUG("%s should not get here", opt->long_name);
4965 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4966 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4967 options->stat_name_width = name_width;
4968 options->stat_graph_width = graph_width;
4969 options->stat_width = width;
4970 options->stat_count = count;
4971 return 0;
4974 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4976 struct strbuf errmsg = STRBUF_INIT;
4977 if (parse_dirstat_params(options, params, &errmsg))
4978 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4979 errmsg.buf);
4980 strbuf_release(&errmsg);
4982 * The caller knows a dirstat-related option is given from the command
4983 * line; allow it to say "return this_function();"
4985 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4986 options->output_format |= DIFF_FORMAT_DIRSTAT;
4987 return 1;
4990 static int diff_opt_diff_filter(const struct option *option,
4991 const char *optarg, int unset)
4993 struct diff_options *opt = option->value;
4994 int i, optch;
4996 BUG_ON_OPT_NEG(unset);
4997 prepare_filter_bits();
4999 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5000 unsigned int bit;
5001 int negate;
5003 if ('a' <= optch && optch <= 'z') {
5004 negate = 1;
5005 optch = toupper(optch);
5006 } else {
5007 negate = 0;
5010 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5011 if (!bit)
5012 return error(_("unknown change class '%c' in --diff-filter=%s"),
5013 optarg[i], optarg);
5014 if (negate)
5015 opt->filter_not |= bit;
5016 else
5017 opt->filter |= bit;
5019 return 0;
5022 static void enable_patch_output(int *fmt)
5024 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5025 *fmt |= DIFF_FORMAT_PATCH;
5028 static int diff_opt_ws_error_highlight(const struct option *option,
5029 const char *arg, int unset)
5031 struct diff_options *opt = option->value;
5032 int val = parse_ws_error_highlight(arg);
5034 BUG_ON_OPT_NEG(unset);
5035 if (val < 0)
5036 return error(_("unknown value after ws-error-highlight=%.*s"),
5037 -1 - val, arg);
5038 opt->ws_error_highlight = val;
5039 return 0;
5042 static int diff_opt_find_object(const struct option *option,
5043 const char *arg, int unset)
5045 struct diff_options *opt = option->value;
5046 struct object_id oid;
5048 BUG_ON_OPT_NEG(unset);
5049 if (repo_get_oid(the_repository, arg, &oid))
5050 return error(_("unable to resolve '%s'"), arg);
5052 if (!opt->objfind)
5053 CALLOC_ARRAY(opt->objfind, 1);
5055 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5056 opt->flags.recursive = 1;
5057 opt->flags.tree_in_recursive = 1;
5058 oidset_insert(opt->objfind, &oid);
5059 return 0;
5062 static int diff_opt_anchored(const struct option *opt,
5063 const char *arg, int unset)
5065 struct diff_options *options = opt->value;
5067 BUG_ON_OPT_NEG(unset);
5068 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5069 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5070 options->anchors_alloc);
5071 options->anchors[options->anchors_nr++] = xstrdup(arg);
5072 return 0;
5075 static int diff_opt_binary(const struct option *opt,
5076 const char *arg, int unset)
5078 struct diff_options *options = opt->value;
5080 BUG_ON_OPT_NEG(unset);
5081 BUG_ON_OPT_ARG(arg);
5082 enable_patch_output(&options->output_format);
5083 options->flags.binary = 1;
5084 return 0;
5087 static int diff_opt_break_rewrites(const struct option *opt,
5088 const char *arg, int unset)
5090 int *break_opt = opt->value;
5091 int opt1, opt2;
5093 BUG_ON_OPT_NEG(unset);
5094 if (!arg)
5095 arg = "";
5096 opt1 = parse_rename_score(&arg);
5097 if (*arg == 0)
5098 opt2 = 0;
5099 else if (*arg != '/')
5100 return error(_("%s expects <n>/<m> form"), opt->long_name);
5101 else {
5102 arg++;
5103 opt2 = parse_rename_score(&arg);
5105 if (*arg != 0)
5106 return error(_("%s expects <n>/<m> form"), opt->long_name);
5107 *break_opt = opt1 | (opt2 << 16);
5108 return 0;
5111 static int diff_opt_char(const struct option *opt,
5112 const char *arg, int unset)
5114 char *value = opt->value;
5116 BUG_ON_OPT_NEG(unset);
5117 if (arg[1])
5118 return error(_("%s expects a character, got '%s'"),
5119 opt->long_name, arg);
5120 *value = arg[0];
5121 return 0;
5124 static int diff_opt_color_moved(const struct option *opt,
5125 const char *arg, int unset)
5127 struct diff_options *options = opt->value;
5129 if (unset) {
5130 options->color_moved = COLOR_MOVED_NO;
5131 } else if (!arg) {
5132 if (diff_color_moved_default)
5133 options->color_moved = diff_color_moved_default;
5134 if (options->color_moved == COLOR_MOVED_NO)
5135 options->color_moved = COLOR_MOVED_DEFAULT;
5136 } else {
5137 int cm = parse_color_moved(arg);
5138 if (cm < 0)
5139 return error(_("bad --color-moved argument: %s"), arg);
5140 options->color_moved = cm;
5142 return 0;
5145 static int diff_opt_color_moved_ws(const struct option *opt,
5146 const char *arg, int unset)
5148 struct diff_options *options = opt->value;
5149 unsigned cm;
5151 if (unset) {
5152 options->color_moved_ws_handling = 0;
5153 return 0;
5156 cm = parse_color_moved_ws(arg);
5157 if (cm & COLOR_MOVED_WS_ERROR)
5158 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5159 options->color_moved_ws_handling = cm;
5160 return 0;
5163 static int diff_opt_color_words(const struct option *opt,
5164 const char *arg, int unset)
5166 struct diff_options *options = opt->value;
5168 BUG_ON_OPT_NEG(unset);
5169 options->use_color = 1;
5170 options->word_diff = DIFF_WORDS_COLOR;
5171 options->word_regex = arg;
5172 return 0;
5175 static int diff_opt_compact_summary(const struct option *opt,
5176 const char *arg, int unset)
5178 struct diff_options *options = opt->value;
5180 BUG_ON_OPT_ARG(arg);
5181 if (unset) {
5182 options->flags.stat_with_summary = 0;
5183 } else {
5184 options->flags.stat_with_summary = 1;
5185 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5186 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5188 return 0;
5191 static int diff_opt_diff_algorithm(const struct option *opt,
5192 const char *arg, int unset)
5194 struct diff_options *options = opt->value;
5196 BUG_ON_OPT_NEG(unset);
5198 if (set_diff_algorithm(options, arg))
5199 return error(_("option diff-algorithm accepts \"myers\", "
5200 "\"minimal\", \"patience\" and \"histogram\""));
5202 options->ignore_driver_algorithm = 1;
5204 return 0;
5207 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5208 const char *arg, int unset)
5210 struct diff_options *options = opt->value;
5212 BUG_ON_OPT_NEG(unset);
5213 BUG_ON_OPT_ARG(arg);
5215 if (set_diff_algorithm(options, opt->long_name))
5216 BUG("available diff algorithms include \"myers\", "
5217 "\"minimal\", \"patience\" and \"histogram\"");
5219 options->ignore_driver_algorithm = 1;
5221 return 0;
5224 static int diff_opt_dirstat(const struct option *opt,
5225 const char *arg, int unset)
5227 struct diff_options *options = opt->value;
5229 BUG_ON_OPT_NEG(unset);
5230 if (!strcmp(opt->long_name, "cumulative")) {
5231 if (arg)
5232 BUG("how come --cumulative take a value?");
5233 arg = "cumulative";
5234 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5235 parse_dirstat_opt(options, "files");
5236 parse_dirstat_opt(options, arg ? arg : "");
5237 return 0;
5240 static int diff_opt_find_copies(const struct option *opt,
5241 const char *arg, int unset)
5243 struct diff_options *options = opt->value;
5245 BUG_ON_OPT_NEG(unset);
5246 if (!arg)
5247 arg = "";
5248 options->rename_score = parse_rename_score(&arg);
5249 if (*arg != 0)
5250 return error(_("invalid argument to %s"), opt->long_name);
5252 if (options->detect_rename == DIFF_DETECT_COPY)
5253 options->flags.find_copies_harder = 1;
5254 else
5255 options->detect_rename = DIFF_DETECT_COPY;
5257 return 0;
5260 static int diff_opt_find_renames(const struct option *opt,
5261 const char *arg, int unset)
5263 struct diff_options *options = opt->value;
5265 BUG_ON_OPT_NEG(unset);
5266 if (!arg)
5267 arg = "";
5268 options->rename_score = parse_rename_score(&arg);
5269 if (*arg != 0)
5270 return error(_("invalid argument to %s"), opt->long_name);
5272 options->detect_rename = DIFF_DETECT_RENAME;
5273 return 0;
5276 static int diff_opt_follow(const struct option *opt,
5277 const char *arg, int unset)
5279 struct diff_options *options = opt->value;
5281 BUG_ON_OPT_ARG(arg);
5282 if (unset) {
5283 options->flags.follow_renames = 0;
5284 options->flags.default_follow_renames = 0;
5285 } else {
5286 options->flags.follow_renames = 1;
5288 return 0;
5291 static int diff_opt_ignore_submodules(const struct option *opt,
5292 const char *arg, int unset)
5294 struct diff_options *options = opt->value;
5296 BUG_ON_OPT_NEG(unset);
5297 if (!arg)
5298 arg = "all";
5299 options->flags.override_submodule_config = 1;
5300 handle_ignore_submodules_arg(options, arg);
5301 return 0;
5304 static int diff_opt_line_prefix(const struct option *opt,
5305 const char *optarg, int unset)
5307 struct diff_options *options = opt->value;
5309 BUG_ON_OPT_NEG(unset);
5310 options->line_prefix = optarg;
5311 options->line_prefix_length = strlen(options->line_prefix);
5312 graph_setup_line_prefix(options);
5313 return 0;
5316 static int diff_opt_no_prefix(const struct option *opt,
5317 const char *optarg, int unset)
5319 struct diff_options *options = opt->value;
5321 BUG_ON_OPT_NEG(unset);
5322 BUG_ON_OPT_ARG(optarg);
5323 diff_set_noprefix(options);
5324 return 0;
5327 static int diff_opt_default_prefix(const struct option *opt,
5328 const char *optarg, int unset)
5330 struct diff_options *options = opt->value;
5332 BUG_ON_OPT_NEG(unset);
5333 BUG_ON_OPT_ARG(optarg);
5334 diff_set_default_prefix(options);
5335 return 0;
5338 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5339 const struct option *opt,
5340 const char *arg, int unset)
5342 struct diff_options *options = opt->value;
5343 char *path;
5345 BUG_ON_OPT_NEG(unset);
5346 path = prefix_filename(ctx->prefix, arg);
5347 options->file = xfopen(path, "w");
5348 options->close_file = 1;
5349 if (options->use_color != GIT_COLOR_ALWAYS)
5350 options->use_color = GIT_COLOR_NEVER;
5351 free(path);
5352 return 0;
5355 static int diff_opt_patience(const struct option *opt,
5356 const char *arg, int unset)
5358 struct diff_options *options = opt->value;
5359 int i;
5361 BUG_ON_OPT_NEG(unset);
5362 BUG_ON_OPT_ARG(arg);
5364 * Both --patience and --anchored use PATIENCE_DIFF
5365 * internally, so remove any anchors previously
5366 * specified.
5368 for (i = 0; i < options->anchors_nr; i++)
5369 free(options->anchors[i]);
5370 options->anchors_nr = 0;
5371 options->ignore_driver_algorithm = 1;
5373 return set_diff_algorithm(options, "patience");
5376 static int diff_opt_ignore_regex(const struct option *opt,
5377 const char *arg, int unset)
5379 struct diff_options *options = opt->value;
5380 regex_t *regex;
5382 BUG_ON_OPT_NEG(unset);
5383 regex = xmalloc(sizeof(*regex));
5384 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5385 return error(_("invalid regex given to -I: '%s'"), arg);
5386 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5387 options->ignore_regex_alloc);
5388 options->ignore_regex[options->ignore_regex_nr++] = regex;
5389 return 0;
5392 static int diff_opt_pickaxe_regex(const struct option *opt,
5393 const char *arg, int unset)
5395 struct diff_options *options = opt->value;
5397 BUG_ON_OPT_NEG(unset);
5398 options->pickaxe = arg;
5399 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5400 return 0;
5403 static int diff_opt_pickaxe_string(const struct option *opt,
5404 const char *arg, int unset)
5406 struct diff_options *options = opt->value;
5408 BUG_ON_OPT_NEG(unset);
5409 options->pickaxe = arg;
5410 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5411 return 0;
5414 static int diff_opt_relative(const struct option *opt,
5415 const char *arg, int unset)
5417 struct diff_options *options = opt->value;
5419 options->flags.relative_name = !unset;
5420 if (arg)
5421 options->prefix = arg;
5422 return 0;
5425 static int diff_opt_submodule(const struct option *opt,
5426 const char *arg, int unset)
5428 struct diff_options *options = opt->value;
5430 BUG_ON_OPT_NEG(unset);
5431 if (!arg)
5432 arg = "log";
5433 if (parse_submodule_params(options, arg))
5434 return error(_("failed to parse --submodule option parameter: '%s'"),
5435 arg);
5436 return 0;
5439 static int diff_opt_textconv(const struct option *opt,
5440 const char *arg, int unset)
5442 struct diff_options *options = opt->value;
5444 BUG_ON_OPT_ARG(arg);
5445 if (unset) {
5446 options->flags.allow_textconv = 0;
5447 } else {
5448 options->flags.allow_textconv = 1;
5449 options->flags.textconv_set_via_cmdline = 1;
5451 return 0;
5454 static int diff_opt_unified(const struct option *opt,
5455 const char *arg, int unset)
5457 struct diff_options *options = opt->value;
5458 char *s;
5460 BUG_ON_OPT_NEG(unset);
5462 if (arg) {
5463 options->context = strtol(arg, &s, 10);
5464 if (*s)
5465 return error(_("%s expects a numerical value"), "--unified");
5467 enable_patch_output(&options->output_format);
5469 return 0;
5472 static int diff_opt_word_diff(const struct option *opt,
5473 const char *arg, int unset)
5475 struct diff_options *options = opt->value;
5477 BUG_ON_OPT_NEG(unset);
5478 if (arg) {
5479 if (!strcmp(arg, "plain"))
5480 options->word_diff = DIFF_WORDS_PLAIN;
5481 else if (!strcmp(arg, "color")) {
5482 options->use_color = 1;
5483 options->word_diff = DIFF_WORDS_COLOR;
5485 else if (!strcmp(arg, "porcelain"))
5486 options->word_diff = DIFF_WORDS_PORCELAIN;
5487 else if (!strcmp(arg, "none"))
5488 options->word_diff = DIFF_WORDS_NONE;
5489 else
5490 return error(_("bad --word-diff argument: %s"), arg);
5491 } else {
5492 if (options->word_diff == DIFF_WORDS_NONE)
5493 options->word_diff = DIFF_WORDS_PLAIN;
5495 return 0;
5498 static int diff_opt_word_diff_regex(const struct option *opt,
5499 const char *arg, int unset)
5501 struct diff_options *options = opt->value;
5503 BUG_ON_OPT_NEG(unset);
5504 if (options->word_diff == DIFF_WORDS_NONE)
5505 options->word_diff = DIFF_WORDS_PLAIN;
5506 options->word_regex = arg;
5507 return 0;
5510 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5512 struct diff_options *options = opt->value;
5514 BUG_ON_OPT_NEG(unset);
5515 if (!strcmp(opt->long_name, "skip-to"))
5516 options->skip_instead_of_rotate = 1;
5517 else
5518 options->skip_instead_of_rotate = 0;
5519 options->rotate_to = arg;
5520 return 0;
5524 * Consider adding new flags to __git_diff_common_options
5525 * in contrib/completion/git-completion.bash
5527 struct option *add_diff_options(const struct option *opts,
5528 struct diff_options *options)
5530 struct option parseopts[] = {
5531 OPT_GROUP(N_("Diff output format options")),
5532 OPT_BITOP('p', "patch", &options->output_format,
5533 N_("generate patch"),
5534 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5535 OPT_SET_INT('s', "no-patch", &options->output_format,
5536 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5537 OPT_BITOP('u', NULL, &options->output_format,
5538 N_("generate patch"),
5539 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5540 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5541 N_("generate diffs with <n> lines context"),
5542 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5543 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5544 N_("generate diffs with <n> lines context")),
5545 OPT_BITOP(0, "raw", &options->output_format,
5546 N_("generate the diff in raw format"),
5547 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5548 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5549 N_("synonym for '-p --raw'"),
5550 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5551 DIFF_FORMAT_NO_OUTPUT),
5552 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5553 N_("synonym for '-p --stat'"),
5554 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5555 DIFF_FORMAT_NO_OUTPUT),
5556 OPT_BITOP(0, "numstat", &options->output_format,
5557 N_("machine friendly --stat"),
5558 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5559 OPT_BITOP(0, "shortstat", &options->output_format,
5560 N_("output only the last line of --stat"),
5561 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5562 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5563 N_("output the distribution of relative amount of changes for each sub-directory"),
5564 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5565 diff_opt_dirstat),
5566 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5567 N_("synonym for --dirstat=cumulative"),
5568 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5569 diff_opt_dirstat),
5570 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5571 N_("synonym for --dirstat=files,param1,param2..."),
5572 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5573 diff_opt_dirstat),
5574 OPT_BIT_F(0, "check", &options->output_format,
5575 N_("warn if changes introduce conflict markers or whitespace errors"),
5576 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5577 OPT_BITOP(0, "summary", &options->output_format,
5578 N_("condensed summary such as creations, renames and mode changes"),
5579 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5580 OPT_BIT_F(0, "name-only", &options->output_format,
5581 N_("show only names of changed files"),
5582 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5583 OPT_BIT_F(0, "name-status", &options->output_format,
5584 N_("show only names and status of changed files"),
5585 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5586 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5587 N_("generate diffstat"),
5588 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5589 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5590 N_("generate diffstat with a given width"),
5591 PARSE_OPT_NONEG, diff_opt_stat),
5592 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5593 N_("generate diffstat with a given name width"),
5594 PARSE_OPT_NONEG, diff_opt_stat),
5595 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5596 N_("generate diffstat with a given graph width"),
5597 PARSE_OPT_NONEG, diff_opt_stat),
5598 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5599 N_("generate diffstat with limited lines"),
5600 PARSE_OPT_NONEG, diff_opt_stat),
5601 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5602 N_("generate compact summary in diffstat"),
5603 PARSE_OPT_NOARG, diff_opt_compact_summary),
5604 OPT_CALLBACK_F(0, "binary", options, NULL,
5605 N_("output a binary diff that can be applied"),
5606 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5607 OPT_BOOL(0, "full-index", &options->flags.full_index,
5608 N_("show full pre- and post-image object names on the \"index\" lines")),
5609 OPT_COLOR_FLAG(0, "color", &options->use_color,
5610 N_("show colored diff")),
5611 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5612 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5613 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5614 OPT_SET_INT('z', NULL, &options->line_termination,
5615 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5617 OPT__ABBREV(&options->abbrev),
5618 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5619 N_("show the given source prefix instead of \"a/\""),
5620 PARSE_OPT_NONEG),
5621 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5622 N_("show the given destination prefix instead of \"b/\""),
5623 PARSE_OPT_NONEG),
5624 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5625 N_("prepend an additional prefix to every line of output"),
5626 PARSE_OPT_NONEG, diff_opt_line_prefix),
5627 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5628 N_("do not show any source or destination prefix"),
5629 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5630 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5631 N_("use default prefixes a/ and b/"),
5632 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5633 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5634 N_("show context between diff hunks up to the specified number of lines"),
5635 PARSE_OPT_NONEG),
5636 OPT_CALLBACK_F(0, "output-indicator-new",
5637 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5638 N_("<char>"),
5639 N_("specify the character to indicate a new line instead of '+'"),
5640 PARSE_OPT_NONEG, diff_opt_char),
5641 OPT_CALLBACK_F(0, "output-indicator-old",
5642 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5643 N_("<char>"),
5644 N_("specify the character to indicate an old line instead of '-'"),
5645 PARSE_OPT_NONEG, diff_opt_char),
5646 OPT_CALLBACK_F(0, "output-indicator-context",
5647 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5648 N_("<char>"),
5649 N_("specify the character to indicate a context instead of ' '"),
5650 PARSE_OPT_NONEG, diff_opt_char),
5652 OPT_GROUP(N_("Diff rename options")),
5653 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5654 N_("break complete rewrite changes into pairs of delete and create"),
5655 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5656 diff_opt_break_rewrites),
5657 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5658 N_("detect renames"),
5659 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5660 diff_opt_find_renames),
5661 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5662 N_("omit the preimage for deletes"),
5663 1, PARSE_OPT_NONEG),
5664 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5665 N_("detect copies"),
5666 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5667 diff_opt_find_copies),
5668 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5669 N_("use unmodified files as source to find copies")),
5670 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5671 N_("disable rename detection"),
5672 0, PARSE_OPT_NONEG),
5673 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5674 N_("use empty blobs as rename source")),
5675 OPT_CALLBACK_F(0, "follow", options, NULL,
5676 N_("continue listing the history of a file beyond renames"),
5677 PARSE_OPT_NOARG, diff_opt_follow),
5678 OPT_INTEGER('l', NULL, &options->rename_limit,
5679 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5681 OPT_GROUP(N_("Diff algorithm options")),
5682 OPT_CALLBACK_F(0, "minimal", options, NULL,
5683 N_("produce the smallest possible diff"),
5684 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5685 diff_opt_diff_algorithm_no_arg),
5686 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5687 N_("ignore whitespace when comparing lines"),
5688 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5689 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5690 N_("ignore changes in amount of whitespace"),
5691 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5692 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5693 N_("ignore changes in whitespace at EOL"),
5694 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5695 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5696 N_("ignore carrier-return at the end of line"),
5697 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5698 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5699 N_("ignore changes whose lines are all blank"),
5700 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5701 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5702 N_("ignore changes whose all lines match <regex>"),
5703 0, diff_opt_ignore_regex),
5704 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5705 N_("heuristic to shift diff hunk boundaries for easy reading"),
5706 XDF_INDENT_HEURISTIC),
5707 OPT_CALLBACK_F(0, "patience", options, NULL,
5708 N_("generate diff using the \"patience diff\" algorithm"),
5709 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5710 diff_opt_patience),
5711 OPT_CALLBACK_F(0, "histogram", options, NULL,
5712 N_("generate diff using the \"histogram diff\" algorithm"),
5713 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5714 diff_opt_diff_algorithm_no_arg),
5715 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5716 N_("choose a diff algorithm"),
5717 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5718 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5719 N_("generate diff using the \"anchored diff\" algorithm"),
5720 PARSE_OPT_NONEG, diff_opt_anchored),
5721 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5722 N_("show word diff, using <mode> to delimit changed words"),
5723 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5724 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5725 N_("use <regex> to decide what a word is"),
5726 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5727 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5728 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5729 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5730 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5731 N_("moved lines of code are colored differently"),
5732 PARSE_OPT_OPTARG, diff_opt_color_moved),
5733 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5734 N_("how white spaces are ignored in --color-moved"),
5735 0, diff_opt_color_moved_ws),
5737 OPT_GROUP(N_("Other diff options")),
5738 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5739 N_("when run from subdir, exclude changes outside and show relative paths"),
5740 PARSE_OPT_OPTARG,
5741 diff_opt_relative),
5742 OPT_BOOL('a', "text", &options->flags.text,
5743 N_("treat all files as text")),
5744 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5745 N_("swap two inputs, reverse the diff")),
5746 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5747 N_("exit with 1 if there were differences, 0 otherwise")),
5748 OPT_BOOL(0, "quiet", &options->flags.quick,
5749 N_("disable all output of the program")),
5750 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5751 N_("allow an external diff helper to be executed")),
5752 OPT_CALLBACK_F(0, "textconv", options, NULL,
5753 N_("run external text conversion filters when comparing binary files"),
5754 PARSE_OPT_NOARG, diff_opt_textconv),
5755 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5756 N_("ignore changes to submodules in the diff generation"),
5757 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5758 diff_opt_ignore_submodules),
5759 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5760 N_("specify how differences in submodules are shown"),
5761 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5762 diff_opt_submodule),
5763 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5764 N_("hide 'git add -N' entries from the index"),
5765 1, PARSE_OPT_NONEG),
5766 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5767 N_("treat 'git add -N' entries as real in the index"),
5768 0, PARSE_OPT_NONEG),
5769 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5770 N_("look for differences that change the number of occurrences of the specified string"),
5771 0, diff_opt_pickaxe_string),
5772 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5773 N_("look for differences that change the number of occurrences of the specified regex"),
5774 0, diff_opt_pickaxe_regex),
5775 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5776 N_("show all changes in the changeset with -S or -G"),
5777 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5778 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5779 N_("treat <string> in -S as extended POSIX regular expression"),
5780 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5781 OPT_FILENAME('O', NULL, &options->orderfile,
5782 N_("control the order in which files appear in the output")),
5783 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5784 N_("show the change in the specified path first"),
5785 PARSE_OPT_NONEG, diff_opt_rotate_to),
5786 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5787 N_("skip the output to the specified path"),
5788 PARSE_OPT_NONEG, diff_opt_rotate_to),
5789 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5790 N_("look for differences that change the number of occurrences of the specified object"),
5791 PARSE_OPT_NONEG, diff_opt_find_object),
5792 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5793 N_("select files by diff type"),
5794 PARSE_OPT_NONEG, diff_opt_diff_filter),
5795 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5796 N_("output to a specific file"),
5797 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5799 OPT_END()
5802 return parse_options_concat(opts, parseopts);
5805 int diff_opt_parse(struct diff_options *options,
5806 const char **av, int ac, const char *prefix)
5808 struct option no_options[] = { OPT_END() };
5809 struct option *parseopts = add_diff_options(no_options, options);
5811 if (!prefix)
5812 prefix = "";
5814 ac = parse_options(ac, av, prefix, parseopts, NULL,
5815 PARSE_OPT_KEEP_DASHDASH |
5816 PARSE_OPT_KEEP_UNKNOWN_OPT |
5817 PARSE_OPT_NO_INTERNAL_HELP |
5818 PARSE_OPT_ONE_SHOT |
5819 PARSE_OPT_STOP_AT_NON_OPTION);
5820 free(parseopts);
5822 return ac;
5825 int parse_rename_score(const char **cp_p)
5827 unsigned long num, scale;
5828 int ch, dot;
5829 const char *cp = *cp_p;
5831 num = 0;
5832 scale = 1;
5833 dot = 0;
5834 for (;;) {
5835 ch = *cp;
5836 if ( !dot && ch == '.' ) {
5837 scale = 1;
5838 dot = 1;
5839 } else if ( ch == '%' ) {
5840 scale = dot ? scale*100 : 100;
5841 cp++; /* % is always at the end */
5842 break;
5843 } else if ( ch >= '0' && ch <= '9' ) {
5844 if ( scale < 100000 ) {
5845 scale *= 10;
5846 num = (num*10) + (ch-'0');
5848 } else {
5849 break;
5851 cp++;
5853 *cp_p = cp;
5855 /* user says num divided by scale and we say internally that
5856 * is MAX_SCORE * num / scale.
5858 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5861 struct diff_queue_struct diff_queued_diff;
5863 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5865 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5866 queue->queue[queue->nr++] = dp;
5869 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5870 struct diff_filespec *one,
5871 struct diff_filespec *two)
5873 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5874 dp->one = one;
5875 dp->two = two;
5876 if (queue)
5877 diff_q(queue, dp);
5878 return dp;
5881 void diff_free_filepair(struct diff_filepair *p)
5883 free_filespec(p->one);
5884 free_filespec(p->two);
5885 free(p);
5888 void diff_free_queue(struct diff_queue_struct *q)
5890 for (int i = 0; i < q->nr; i++)
5891 diff_free_filepair(q->queue[i]);
5892 free(q->queue);
5895 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5897 int abblen;
5898 const char *abbrev;
5900 /* Do we want all 40 hex characters? */
5901 if (len == the_hash_algo->hexsz)
5902 return oid_to_hex(oid);
5904 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5905 abbrev = diff_abbrev_oid(oid, len);
5907 if (!print_sha1_ellipsis())
5908 return abbrev;
5910 abblen = strlen(abbrev);
5913 * In well-behaved cases, where the abbreviated result is the
5914 * same as the requested length, append three dots after the
5915 * abbreviation (hence the whole logic is limited to the case
5916 * where abblen < 37); when the actual abbreviated result is a
5917 * bit longer than the requested length, we reduce the number
5918 * of dots so that they match the well-behaved ones. However,
5919 * if the actual abbreviation is longer than the requested
5920 * length by more than three, we give up on aligning, and add
5921 * three dots anyway, to indicate that the output is not the
5922 * full object name. Yes, this may be suboptimal, but this
5923 * appears only in "diff --raw --abbrev" output and it is not
5924 * worth the effort to change it now. Note that this would
5925 * likely to work fine when the automatic sizing of default
5926 * abbreviation length is used--we would be fed -1 in "len" in
5927 * that case, and will end up always appending three-dots, but
5928 * the automatic sizing is supposed to give abblen that ensures
5929 * uniqueness across all objects (statistically speaking).
5931 if (abblen < the_hash_algo->hexsz - 3) {
5932 static char hex[GIT_MAX_HEXSZ + 1];
5933 if (len < abblen && abblen <= len + 2)
5934 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5935 else
5936 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5937 return hex;
5940 return oid_to_hex(oid);
5943 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5945 int line_termination = opt->line_termination;
5946 int inter_name_termination = line_termination ? '\t' : '\0';
5948 fprintf(opt->file, "%s", diff_line_prefix(opt));
5949 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5950 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5951 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5952 fprintf(opt->file, "%s ",
5953 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5955 if (p->score) {
5956 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5957 inter_name_termination);
5958 } else {
5959 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5962 if (p->status == DIFF_STATUS_COPIED ||
5963 p->status == DIFF_STATUS_RENAMED) {
5964 const char *name_a, *name_b;
5965 name_a = p->one->path;
5966 name_b = p->two->path;
5967 strip_prefix(opt->prefix_length, &name_a, &name_b);
5968 write_name_quoted(name_a, opt->file, inter_name_termination);
5969 write_name_quoted(name_b, opt->file, line_termination);
5970 } else {
5971 const char *name_a, *name_b;
5972 name_a = p->one->mode ? p->one->path : p->two->path;
5973 name_b = NULL;
5974 strip_prefix(opt->prefix_length, &name_a, &name_b);
5975 write_name_quoted(name_a, opt->file, line_termination);
5979 int diff_unmodified_pair(struct diff_filepair *p)
5981 /* This function is written stricter than necessary to support
5982 * the currently implemented transformers, but the idea is to
5983 * let transformers to produce diff_filepairs any way they want,
5984 * and filter and clean them up here before producing the output.
5986 struct diff_filespec *one = p->one, *two = p->two;
5988 if (DIFF_PAIR_UNMERGED(p))
5989 return 0; /* unmerged is interesting */
5991 /* deletion, addition, mode or type change
5992 * and rename are all interesting.
5994 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5995 DIFF_PAIR_MODE_CHANGED(p) ||
5996 strcmp(one->path, two->path))
5997 return 0;
5999 /* both are valid and point at the same path. that is, we are
6000 * dealing with a change.
6002 if (one->oid_valid && two->oid_valid &&
6003 oideq(&one->oid, &two->oid) &&
6004 !one->dirty_submodule && !two->dirty_submodule)
6005 return 1; /* no change */
6006 if (!one->oid_valid && !two->oid_valid)
6007 return 1; /* both look at the same file on the filesystem. */
6008 return 0;
6011 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6013 int include_conflict_headers =
6014 (additional_headers(o, p->one->path) &&
6015 !o->pickaxe_opts &&
6016 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6019 * Check if we can return early without showing a diff. Note that
6020 * diff_filepair only stores {oid, path, mode, is_valid}
6021 * information for each path, and thus diff_unmodified_pair() only
6022 * considers those bits of info. However, we do not want pairs
6023 * created by create_filepairs_for_header_only_notifications()
6024 * (which always look like unmodified pairs) to be ignored, so
6025 * return early if both p is unmodified AND we don't want to
6026 * include_conflict_headers.
6028 if (diff_unmodified_pair(p) && !include_conflict_headers)
6029 return;
6031 /* Actually, we can also return early to avoid showing tree diffs */
6032 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6033 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6034 return;
6036 run_diff(p, o);
6039 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6040 struct diffstat_t *diffstat)
6042 if (diff_unmodified_pair(p))
6043 return;
6045 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6046 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6047 return; /* no useful stat for tree diffs */
6049 run_diffstat(p, o, diffstat);
6052 static void diff_flush_checkdiff(struct diff_filepair *p,
6053 struct diff_options *o)
6055 if (diff_unmodified_pair(p))
6056 return;
6058 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6059 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6060 return; /* nothing to check in tree diffs */
6062 run_checkdiff(p, o);
6065 int diff_queue_is_empty(struct diff_options *o)
6067 struct diff_queue_struct *q = &diff_queued_diff;
6068 int i;
6069 int include_conflict_headers =
6070 (o->additional_path_headers &&
6071 strmap_get_size(o->additional_path_headers) &&
6072 !o->pickaxe_opts &&
6073 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6075 if (include_conflict_headers)
6076 return 0;
6078 for (i = 0; i < q->nr; i++)
6079 if (!diff_unmodified_pair(q->queue[i]))
6080 return 0;
6081 return 1;
6084 #if DIFF_DEBUG
6085 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6087 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6088 x, one ? one : "",
6089 s->path,
6090 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6091 s->mode,
6092 s->oid_valid ? oid_to_hex(&s->oid) : "");
6093 fprintf(stderr, "queue[%d] %s size %lu\n",
6094 x, one ? one : "",
6095 s->size);
6098 void diff_debug_filepair(const struct diff_filepair *p, int i)
6100 diff_debug_filespec(p->one, i, "one");
6101 diff_debug_filespec(p->two, i, "two");
6102 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6103 p->score, p->status ? p->status : '?',
6104 p->one->rename_used, p->broken_pair);
6107 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6109 int i;
6110 if (msg)
6111 fprintf(stderr, "%s\n", msg);
6112 fprintf(stderr, "q->nr = %d\n", q->nr);
6113 for (i = 0; i < q->nr; i++) {
6114 struct diff_filepair *p = q->queue[i];
6115 diff_debug_filepair(p, i);
6118 #endif
6120 static void diff_resolve_rename_copy(void)
6122 int i;
6123 struct diff_filepair *p;
6124 struct diff_queue_struct *q = &diff_queued_diff;
6126 diff_debug_queue("resolve-rename-copy", q);
6128 for (i = 0; i < q->nr; i++) {
6129 p = q->queue[i];
6130 p->status = 0; /* undecided */
6131 if (DIFF_PAIR_UNMERGED(p))
6132 p->status = DIFF_STATUS_UNMERGED;
6133 else if (!DIFF_FILE_VALID(p->one))
6134 p->status = DIFF_STATUS_ADDED;
6135 else if (!DIFF_FILE_VALID(p->two))
6136 p->status = DIFF_STATUS_DELETED;
6137 else if (DIFF_PAIR_TYPE_CHANGED(p))
6138 p->status = DIFF_STATUS_TYPE_CHANGED;
6140 /* from this point on, we are dealing with a pair
6141 * whose both sides are valid and of the same type, i.e.
6142 * either in-place edit or rename/copy edit.
6144 else if (DIFF_PAIR_RENAME(p)) {
6146 * A rename might have re-connected a broken
6147 * pair up, causing the pathnames to be the
6148 * same again. If so, that's not a rename at
6149 * all, just a modification..
6151 * Otherwise, see if this source was used for
6152 * multiple renames, in which case we decrement
6153 * the count, and call it a copy.
6155 if (!strcmp(p->one->path, p->two->path))
6156 p->status = DIFF_STATUS_MODIFIED;
6157 else if (--p->one->rename_used > 0)
6158 p->status = DIFF_STATUS_COPIED;
6159 else
6160 p->status = DIFF_STATUS_RENAMED;
6162 else if (!oideq(&p->one->oid, &p->two->oid) ||
6163 p->one->mode != p->two->mode ||
6164 p->one->dirty_submodule ||
6165 p->two->dirty_submodule ||
6166 is_null_oid(&p->one->oid))
6167 p->status = DIFF_STATUS_MODIFIED;
6168 else {
6169 /* This is a "no-change" entry and should not
6170 * happen anymore, but prepare for broken callers.
6172 error("feeding unmodified %s to diffcore",
6173 p->one->path);
6174 p->status = DIFF_STATUS_UNKNOWN;
6177 diff_debug_queue("resolve-rename-copy done", q);
6180 static int check_pair_status(struct diff_filepair *p)
6182 switch (p->status) {
6183 case DIFF_STATUS_UNKNOWN:
6184 return 0;
6185 case 0:
6186 die("internal error in diff-resolve-rename-copy");
6187 default:
6188 return 1;
6192 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6194 int fmt = opt->output_format;
6196 if (fmt & DIFF_FORMAT_CHECKDIFF)
6197 diff_flush_checkdiff(p, opt);
6198 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6199 diff_flush_raw(p, opt);
6200 else if (fmt & DIFF_FORMAT_NAME) {
6201 const char *name_a, *name_b;
6202 name_a = p->two->path;
6203 name_b = NULL;
6204 strip_prefix(opt->prefix_length, &name_a, &name_b);
6205 fprintf(opt->file, "%s", diff_line_prefix(opt));
6206 write_name_quoted(name_a, opt->file, opt->line_termination);
6210 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6212 struct strbuf sb = STRBUF_INIT;
6213 if (fs->mode)
6214 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6215 else
6216 strbuf_addf(&sb, " %s ", newdelete);
6218 quote_c_style(fs->path, &sb, NULL, 0);
6219 strbuf_addch(&sb, '\n');
6220 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6221 sb.buf, sb.len, 0);
6222 strbuf_release(&sb);
6225 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6226 int show_name)
6228 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6229 struct strbuf sb = STRBUF_INIT;
6230 strbuf_addf(&sb, " mode change %06o => %06o",
6231 p->one->mode, p->two->mode);
6232 if (show_name) {
6233 strbuf_addch(&sb, ' ');
6234 quote_c_style(p->two->path, &sb, NULL, 0);
6236 strbuf_addch(&sb, '\n');
6237 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6238 sb.buf, sb.len, 0);
6239 strbuf_release(&sb);
6243 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6244 struct diff_filepair *p)
6246 struct strbuf sb = STRBUF_INIT;
6247 struct strbuf names = STRBUF_INIT;
6249 pprint_rename(&names, p->one->path, p->two->path);
6250 strbuf_addf(&sb, " %s %s (%d%%)\n",
6251 renamecopy, names.buf, similarity_index(p));
6252 strbuf_release(&names);
6253 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6254 sb.buf, sb.len, 0);
6255 show_mode_change(opt, p, 0);
6256 strbuf_release(&sb);
6259 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6261 switch(p->status) {
6262 case DIFF_STATUS_DELETED:
6263 show_file_mode_name(opt, "delete", p->one);
6264 break;
6265 case DIFF_STATUS_ADDED:
6266 show_file_mode_name(opt, "create", p->two);
6267 break;
6268 case DIFF_STATUS_COPIED:
6269 show_rename_copy(opt, "copy", p);
6270 break;
6271 case DIFF_STATUS_RENAMED:
6272 show_rename_copy(opt, "rename", p);
6273 break;
6274 default:
6275 if (p->score) {
6276 struct strbuf sb = STRBUF_INIT;
6277 strbuf_addstr(&sb, " rewrite ");
6278 quote_c_style(p->two->path, &sb, NULL, 0);
6279 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6280 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6281 sb.buf, sb.len, 0);
6282 strbuf_release(&sb);
6284 show_mode_change(opt, p, !p->score);
6285 break;
6289 struct patch_id_t {
6290 git_hash_ctx *ctx;
6291 int patchlen;
6294 static int remove_space(char *line, int len)
6296 int i;
6297 char *dst = line;
6298 unsigned char c;
6300 for (i = 0; i < len; i++)
6301 if (!isspace((c = line[i])))
6302 *dst++ = c;
6304 return dst - line;
6307 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6309 unsigned char hash[GIT_MAX_RAWSZ];
6310 unsigned short carry = 0;
6311 int i;
6313 the_hash_algo->final_fn(hash, ctx);
6314 the_hash_algo->init_fn(ctx);
6315 /* 20-byte sum, with carry */
6316 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6317 carry += result->hash[i] + hash[i];
6318 result->hash[i] = carry;
6319 carry >>= 8;
6323 static int patch_id_consume(void *priv, char *line, unsigned long len)
6325 struct patch_id_t *data = priv;
6326 int new_len;
6328 if (len > 12 && starts_with(line, "\\ "))
6329 return 0;
6330 new_len = remove_space(line, len);
6332 the_hash_algo->update_fn(data->ctx, line, new_len);
6333 data->patchlen += new_len;
6334 return 0;
6337 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6339 the_hash_algo->update_fn(ctx, str, strlen(str));
6342 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6344 /* large enough for 2^32 in octal */
6345 char buf[12];
6346 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6347 the_hash_algo->update_fn(ctx, buf, len);
6350 /* returns 0 upon success, and writes result into oid */
6351 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6353 struct diff_queue_struct *q = &diff_queued_diff;
6354 int i;
6355 git_hash_ctx ctx;
6356 struct patch_id_t data;
6358 the_hash_algo->init_fn(&ctx);
6359 memset(&data, 0, sizeof(struct patch_id_t));
6360 data.ctx = &ctx;
6361 oidclr(oid);
6363 for (i = 0; i < q->nr; i++) {
6364 xpparam_t xpp;
6365 xdemitconf_t xecfg;
6366 mmfile_t mf1, mf2;
6367 struct diff_filepair *p = q->queue[i];
6368 int len1, len2;
6370 memset(&xpp, 0, sizeof(xpp));
6371 memset(&xecfg, 0, sizeof(xecfg));
6372 if (p->status == 0)
6373 return error("internal diff status error");
6374 if (p->status == DIFF_STATUS_UNKNOWN)
6375 continue;
6376 if (diff_unmodified_pair(p))
6377 continue;
6378 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6379 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6380 continue;
6381 if (DIFF_PAIR_UNMERGED(p))
6382 continue;
6384 diff_fill_oid_info(p->one, options->repo->index);
6385 diff_fill_oid_info(p->two, options->repo->index);
6387 len1 = remove_space(p->one->path, strlen(p->one->path));
6388 len2 = remove_space(p->two->path, strlen(p->two->path));
6389 patch_id_add_string(&ctx, "diff--git");
6390 patch_id_add_string(&ctx, "a/");
6391 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6392 patch_id_add_string(&ctx, "b/");
6393 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6395 if (p->one->mode == 0) {
6396 patch_id_add_string(&ctx, "newfilemode");
6397 patch_id_add_mode(&ctx, p->two->mode);
6398 } else if (p->two->mode == 0) {
6399 patch_id_add_string(&ctx, "deletedfilemode");
6400 patch_id_add_mode(&ctx, p->one->mode);
6401 } else if (p->one->mode != p->two->mode) {
6402 patch_id_add_string(&ctx, "oldmode");
6403 patch_id_add_mode(&ctx, p->one->mode);
6404 patch_id_add_string(&ctx, "newmode");
6405 patch_id_add_mode(&ctx, p->two->mode);
6408 if (diff_header_only) {
6409 /* don't do anything since we're only populating header info */
6410 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6411 diff_filespec_is_binary(options->repo, p->two)) {
6412 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6413 the_hash_algo->hexsz);
6414 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6415 the_hash_algo->hexsz);
6416 } else {
6417 if (p->one->mode == 0) {
6418 patch_id_add_string(&ctx, "---/dev/null");
6419 patch_id_add_string(&ctx, "+++b/");
6420 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6421 } else if (p->two->mode == 0) {
6422 patch_id_add_string(&ctx, "---a/");
6423 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6424 patch_id_add_string(&ctx, "+++/dev/null");
6425 } else {
6426 patch_id_add_string(&ctx, "---a/");
6427 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6428 patch_id_add_string(&ctx, "+++b/");
6429 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6432 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6433 fill_mmfile(options->repo, &mf2, p->two) < 0)
6434 return error("unable to read files to diff");
6435 xpp.flags = 0;
6436 xecfg.ctxlen = 3;
6437 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6438 if (xdi_diff_outf(&mf1, &mf2, NULL,
6439 patch_id_consume, &data, &xpp, &xecfg))
6440 return error("unable to generate patch-id diff for %s",
6441 p->one->path);
6443 flush_one_hunk(oid, &ctx);
6446 return 0;
6449 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6451 struct diff_queue_struct *q = &diff_queued_diff;
6452 int result = diff_get_patch_id(options, oid, diff_header_only);
6454 diff_free_queue(q);
6455 DIFF_QUEUE_CLEAR(q);
6457 return result;
6460 static int is_summary_empty(const struct diff_queue_struct *q)
6462 int i;
6464 for (i = 0; i < q->nr; i++) {
6465 const struct diff_filepair *p = q->queue[i];
6467 switch (p->status) {
6468 case DIFF_STATUS_DELETED:
6469 case DIFF_STATUS_ADDED:
6470 case DIFF_STATUS_COPIED:
6471 case DIFF_STATUS_RENAMED:
6472 return 0;
6473 default:
6474 if (p->score)
6475 return 0;
6476 if (p->one->mode && p->two->mode &&
6477 p->one->mode != p->two->mode)
6478 return 0;
6479 break;
6482 return 1;
6485 static const char rename_limit_warning[] =
6486 N_("exhaustive rename detection was skipped due to too many files.");
6488 static const char degrade_cc_to_c_warning[] =
6489 N_("only found copies from modified paths due to too many files.");
6491 static const char rename_limit_advice[] =
6492 N_("you may want to set your %s variable to at least "
6493 "%d and retry the command.");
6495 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6497 fflush(stdout);
6498 if (degraded_cc)
6499 warning(_(degrade_cc_to_c_warning));
6500 else if (needed)
6501 warning(_(rename_limit_warning));
6502 else
6503 return;
6504 if (0 < needed)
6505 warning(_(rename_limit_advice), varname, needed);
6508 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6510 struct strset present;
6511 struct diff_queue_struct *q = &diff_queued_diff;
6512 struct hashmap_iter iter;
6513 struct strmap_entry *e;
6514 int i;
6516 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6519 * Find out which paths exist in diff_queued_diff, preferring
6520 * one->path for any pair that has multiple paths.
6522 for (i = 0; i < q->nr; i++) {
6523 struct diff_filepair *p = q->queue[i];
6524 char *path = p->one->path ? p->one->path : p->two->path;
6526 if (strmap_contains(o->additional_path_headers, path))
6527 strset_add(&present, path);
6531 * Loop over paths in additional_path_headers; for each NOT already
6532 * in diff_queued_diff, create a synthetic filepair and insert that
6533 * into diff_queued_diff.
6535 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6536 if (!strset_contains(&present, e->key)) {
6537 struct diff_filespec *one, *two;
6538 struct diff_filepair *p;
6540 one = alloc_filespec(e->key);
6541 two = alloc_filespec(e->key);
6542 fill_filespec(one, null_oid(), 0, 0);
6543 fill_filespec(two, null_oid(), 0, 0);
6544 p = diff_queue(q, one, two);
6545 p->status = DIFF_STATUS_MODIFIED;
6549 /* Re-sort the filepairs */
6550 diffcore_fix_diff_index();
6552 /* Cleanup */
6553 strset_clear(&present);
6556 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6558 int i;
6559 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6560 struct diff_queue_struct *q = &diff_queued_diff;
6562 if (WSEH_NEW & WS_RULE_MASK)
6563 BUG("WS rules bit mask overlaps with diff symbol flags");
6565 if (o->color_moved)
6566 o->emitted_symbols = &esm;
6568 if (o->additional_path_headers)
6569 create_filepairs_for_header_only_notifications(o);
6571 for (i = 0; i < q->nr; i++) {
6572 struct diff_filepair *p = q->queue[i];
6573 if (check_pair_status(p))
6574 diff_flush_patch(p, o);
6577 if (o->emitted_symbols) {
6578 if (o->color_moved) {
6579 struct mem_pool entry_pool;
6580 struct moved_entry_list *entry_list;
6582 mem_pool_init(&entry_pool, 1024 * 1024);
6583 entry_list = add_lines_to_move_detection(o,
6584 &entry_pool);
6585 mark_color_as_moved(o, entry_list);
6586 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6587 dim_moved_lines(o);
6589 mem_pool_discard(&entry_pool, 0);
6590 free(entry_list);
6593 for (i = 0; i < esm.nr; i++)
6594 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6596 for (i = 0; i < esm.nr; i++)
6597 free((void *)esm.buf[i].line);
6598 esm.nr = 0;
6600 o->emitted_symbols = NULL;
6604 static void diff_free_file(struct diff_options *options)
6606 if (options->close_file)
6607 fclose(options->file);
6610 static void diff_free_ignore_regex(struct diff_options *options)
6612 int i;
6614 for (i = 0; i < options->ignore_regex_nr; i++) {
6615 regfree(options->ignore_regex[i]);
6616 free(options->ignore_regex[i]);
6618 free(options->ignore_regex);
6621 void diff_free(struct diff_options *options)
6623 if (options->no_free)
6624 return;
6626 diff_free_file(options);
6627 diff_free_ignore_regex(options);
6628 clear_pathspec(&options->pathspec);
6631 void diff_flush(struct diff_options *options)
6633 struct diff_queue_struct *q = &diff_queued_diff;
6634 int i, output_format = options->output_format;
6635 int separator = 0;
6636 int dirstat_by_line = 0;
6639 * Order: raw, stat, summary, patch
6640 * or: name/name-status/checkdiff (other bits clear)
6642 if (!q->nr && !options->additional_path_headers)
6643 goto free_queue;
6645 if (output_format & (DIFF_FORMAT_RAW |
6646 DIFF_FORMAT_NAME |
6647 DIFF_FORMAT_NAME_STATUS |
6648 DIFF_FORMAT_CHECKDIFF)) {
6649 for (i = 0; i < q->nr; i++) {
6650 struct diff_filepair *p = q->queue[i];
6651 if (check_pair_status(p))
6652 flush_one_pair(p, options);
6654 separator++;
6657 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6658 dirstat_by_line = 1;
6660 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6661 dirstat_by_line) {
6662 struct diffstat_t diffstat;
6664 compute_diffstat(options, &diffstat, q);
6665 if (output_format & DIFF_FORMAT_NUMSTAT)
6666 show_numstat(&diffstat, options);
6667 if (output_format & DIFF_FORMAT_DIFFSTAT)
6668 show_stats(&diffstat, options);
6669 if (output_format & DIFF_FORMAT_SHORTSTAT)
6670 show_shortstats(&diffstat, options);
6671 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6672 show_dirstat_by_line(&diffstat, options);
6673 free_diffstat_info(&diffstat);
6674 separator++;
6676 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6677 show_dirstat(options);
6679 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6680 for (i = 0; i < q->nr; i++) {
6681 diff_summary(options, q->queue[i]);
6683 separator++;
6686 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6687 options->flags.exit_with_status &&
6688 options->flags.diff_from_contents) {
6690 * run diff_flush_patch for the exit status. setting
6691 * options->file to /dev/null should be safe, because we
6692 * aren't supposed to produce any output anyway.
6694 diff_free_file(options);
6695 options->file = xfopen("/dev/null", "w");
6696 options->close_file = 1;
6697 options->color_moved = 0;
6698 for (i = 0; i < q->nr; i++) {
6699 struct diff_filepair *p = q->queue[i];
6700 if (check_pair_status(p))
6701 diff_flush_patch(p, options);
6702 if (options->found_changes)
6703 break;
6707 if (output_format & DIFF_FORMAT_PATCH) {
6708 if (separator) {
6709 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6710 if (options->stat_sep)
6711 /* attach patch instead of inline */
6712 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6713 NULL, 0, 0);
6716 diff_flush_patch_all_file_pairs(options);
6719 if (output_format & DIFF_FORMAT_CALLBACK)
6720 options->format_callback(q, options, options->format_callback_data);
6722 free_queue:
6723 diff_free_queue(q);
6724 DIFF_QUEUE_CLEAR(q);
6725 diff_free(options);
6728 * Report the content-level differences with HAS_CHANGES;
6729 * diff_addremove/diff_change does not set the bit when
6730 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6732 if (options->flags.diff_from_contents) {
6733 if (options->found_changes)
6734 options->flags.has_changes = 1;
6735 else
6736 options->flags.has_changes = 0;
6740 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6742 return (((p->status == DIFF_STATUS_MODIFIED) &&
6743 ((p->score &&
6744 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6745 (!p->score &&
6746 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6747 ((p->status != DIFF_STATUS_MODIFIED) &&
6748 filter_bit_tst(p->status, options)));
6751 static void diffcore_apply_filter(struct diff_options *options)
6753 int i;
6754 struct diff_queue_struct *q = &diff_queued_diff;
6755 struct diff_queue_struct outq;
6757 DIFF_QUEUE_CLEAR(&outq);
6759 if (!options->filter)
6760 return;
6762 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6763 int found;
6764 for (i = found = 0; !found && i < q->nr; i++) {
6765 if (match_filter(options, q->queue[i]))
6766 found++;
6768 if (found)
6769 return;
6771 /* otherwise we will clear the whole queue
6772 * by copying the empty outq at the end of this
6773 * function, but first clear the current entries
6774 * in the queue.
6776 for (i = 0; i < q->nr; i++)
6777 diff_free_filepair(q->queue[i]);
6779 else {
6780 /* Only the matching ones */
6781 for (i = 0; i < q->nr; i++) {
6782 struct diff_filepair *p = q->queue[i];
6783 if (match_filter(options, p))
6784 diff_q(&outq, p);
6785 else
6786 diff_free_filepair(p);
6789 free(q->queue);
6790 *q = outq;
6793 /* Check whether two filespecs with the same mode and size are identical */
6794 static int diff_filespec_is_identical(struct repository *r,
6795 struct diff_filespec *one,
6796 struct diff_filespec *two)
6798 if (S_ISGITLINK(one->mode))
6799 return 0;
6800 if (diff_populate_filespec(r, one, NULL))
6801 return 0;
6802 if (diff_populate_filespec(r, two, NULL))
6803 return 0;
6804 return !memcmp(one->data, two->data, one->size);
6807 static int diff_filespec_check_stat_unmatch(struct repository *r,
6808 struct diff_filepair *p)
6810 struct diff_populate_filespec_options dpf_options = {
6811 .check_size_only = 1,
6812 .missing_object_cb = diff_queued_diff_prefetch,
6813 .missing_object_data = r,
6816 if (p->done_skip_stat_unmatch)
6817 return p->skip_stat_unmatch_result;
6819 p->done_skip_stat_unmatch = 1;
6820 p->skip_stat_unmatch_result = 0;
6822 * 1. Entries that come from stat info dirtiness
6823 * always have both sides (iow, not create/delete),
6824 * one side of the object name is unknown, with
6825 * the same mode and size. Keep the ones that
6826 * do not match these criteria. They have real
6827 * differences.
6829 * 2. At this point, the file is known to be modified,
6830 * with the same mode and size, and the object
6831 * name of one side is unknown. Need to inspect
6832 * the identical contents.
6834 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6835 !DIFF_FILE_VALID(p->two) ||
6836 (p->one->oid_valid && p->two->oid_valid) ||
6837 (p->one->mode != p->two->mode) ||
6838 diff_populate_filespec(r, p->one, &dpf_options) ||
6839 diff_populate_filespec(r, p->two, &dpf_options) ||
6840 (p->one->size != p->two->size) ||
6841 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6842 p->skip_stat_unmatch_result = 1;
6843 return p->skip_stat_unmatch_result;
6846 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6848 int i;
6849 struct diff_queue_struct *q = &diff_queued_diff;
6850 struct diff_queue_struct outq;
6851 DIFF_QUEUE_CLEAR(&outq);
6853 for (i = 0; i < q->nr; i++) {
6854 struct diff_filepair *p = q->queue[i];
6856 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6857 diff_q(&outq, p);
6858 else {
6860 * The caller can subtract 1 from skip_stat_unmatch
6861 * to determine how many paths were dirty only
6862 * due to stat info mismatch.
6864 if (!diffopt->flags.no_index)
6865 diffopt->skip_stat_unmatch++;
6866 diff_free_filepair(p);
6869 free(q->queue);
6870 *q = outq;
6873 static int diffnamecmp(const void *a_, const void *b_)
6875 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6876 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6877 const char *name_a, *name_b;
6879 name_a = a->one ? a->one->path : a->two->path;
6880 name_b = b->one ? b->one->path : b->two->path;
6881 return strcmp(name_a, name_b);
6884 void diffcore_fix_diff_index(void)
6886 struct diff_queue_struct *q = &diff_queued_diff;
6887 QSORT(q->queue, q->nr, diffnamecmp);
6890 void diff_add_if_missing(struct repository *r,
6891 struct oid_array *to_fetch,
6892 const struct diff_filespec *filespec)
6894 if (filespec && filespec->oid_valid &&
6895 !S_ISGITLINK(filespec->mode) &&
6896 oid_object_info_extended(r, &filespec->oid, NULL,
6897 OBJECT_INFO_FOR_PREFETCH))
6898 oid_array_append(to_fetch, &filespec->oid);
6901 void diff_queued_diff_prefetch(void *repository)
6903 struct repository *repo = repository;
6904 int i;
6905 struct diff_queue_struct *q = &diff_queued_diff;
6906 struct oid_array to_fetch = OID_ARRAY_INIT;
6908 for (i = 0; i < q->nr; i++) {
6909 struct diff_filepair *p = q->queue[i];
6910 diff_add_if_missing(repo, &to_fetch, p->one);
6911 diff_add_if_missing(repo, &to_fetch, p->two);
6915 * NEEDSWORK: Consider deduplicating the OIDs sent.
6917 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6919 oid_array_clear(&to_fetch);
6922 void diffcore_std(struct diff_options *options)
6924 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6925 DIFF_FORMAT_NUMSTAT |
6926 DIFF_FORMAT_PATCH |
6927 DIFF_FORMAT_SHORTSTAT |
6928 DIFF_FORMAT_DIRSTAT;
6931 * Check if the user requested a blob-data-requiring diff output and/or
6932 * break-rewrite detection (which requires blob data). If yes, prefetch
6933 * the diff pairs.
6935 * If no prefetching occurs, diffcore_rename() will prefetch if it
6936 * decides that it needs inexact rename detection.
6938 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6939 (options->output_format & output_formats_to_prefetch ||
6940 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6941 diff_queued_diff_prefetch(options->repo);
6943 /* NOTE please keep the following in sync with diff_tree_combined() */
6944 if (options->skip_stat_unmatch)
6945 diffcore_skip_stat_unmatch(options);
6946 if (!options->found_follow) {
6947 /* See try_to_follow_renames() in tree-diff.c */
6948 if (options->break_opt != -1)
6949 diffcore_break(options->repo,
6950 options->break_opt);
6951 if (options->detect_rename)
6952 diffcore_rename(options);
6953 if (options->break_opt != -1)
6954 diffcore_merge_broken();
6956 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6957 diffcore_pickaxe(options);
6958 if (options->orderfile)
6959 diffcore_order(options->orderfile);
6960 if (options->rotate_to)
6961 diffcore_rotate(options);
6962 if (!options->found_follow)
6963 /* See try_to_follow_renames() in tree-diff.c */
6964 diff_resolve_rename_copy();
6965 diffcore_apply_filter(options);
6967 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6968 options->flags.has_changes = 1;
6969 else
6970 options->flags.has_changes = 0;
6972 options->found_follow = 0;
6975 int diff_result_code(struct diff_options *opt, int status)
6977 int result = 0;
6979 diff_warn_rename_limit("diff.renameLimit",
6980 opt->needed_rename_limit,
6981 opt->degraded_cc_to_c);
6982 if (!opt->flags.exit_with_status &&
6983 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6984 return status;
6985 if (opt->flags.exit_with_status &&
6986 opt->flags.has_changes)
6987 result |= 01;
6988 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6989 opt->flags.check_failed)
6990 result |= 02;
6991 return result;
6994 int diff_can_quit_early(struct diff_options *opt)
6996 return (opt->flags.quick &&
6997 !opt->filter &&
6998 opt->flags.has_changes);
7002 * Shall changes to this submodule be ignored?
7004 * Submodule changes can be configured to be ignored separately for each path,
7005 * but that configuration can be overridden from the command line.
7007 static int is_submodule_ignored(const char *path, struct diff_options *options)
7009 int ignored = 0;
7010 struct diff_flags orig_flags = options->flags;
7011 if (!options->flags.override_submodule_config)
7012 set_diffopt_flags_from_submodule_config(options, path);
7013 if (options->flags.ignore_submodules)
7014 ignored = 1;
7015 options->flags = orig_flags;
7016 return ignored;
7019 void compute_diffstat(struct diff_options *options,
7020 struct diffstat_t *diffstat,
7021 struct diff_queue_struct *q)
7023 int i;
7025 memset(diffstat, 0, sizeof(struct diffstat_t));
7026 for (i = 0; i < q->nr; i++) {
7027 struct diff_filepair *p = q->queue[i];
7028 if (check_pair_status(p))
7029 diff_flush_stat(p, options, diffstat);
7033 void diff_addremove(struct diff_options *options,
7034 int addremove, unsigned mode,
7035 const struct object_id *oid,
7036 int oid_valid,
7037 const char *concatpath, unsigned dirty_submodule)
7039 struct diff_filespec *one, *two;
7041 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7042 return;
7044 /* This may look odd, but it is a preparation for
7045 * feeding "there are unchanged files which should
7046 * not produce diffs, but when you are doing copy
7047 * detection you would need them, so here they are"
7048 * entries to the diff-core. They will be prefixed
7049 * with something like '=' or '*' (I haven't decided
7050 * which but should not make any difference).
7051 * Feeding the same new and old to diff_change()
7052 * also has the same effect.
7053 * Before the final output happens, they are pruned after
7054 * merged into rename/copy pairs as appropriate.
7056 if (options->flags.reverse_diff)
7057 addremove = (addremove == '+' ? '-' :
7058 addremove == '-' ? '+' : addremove);
7060 if (options->prefix &&
7061 strncmp(concatpath, options->prefix, options->prefix_length))
7062 return;
7064 one = alloc_filespec(concatpath);
7065 two = alloc_filespec(concatpath);
7067 if (addremove != '+')
7068 fill_filespec(one, oid, oid_valid, mode);
7069 if (addremove != '-') {
7070 fill_filespec(two, oid, oid_valid, mode);
7071 two->dirty_submodule = dirty_submodule;
7074 diff_queue(&diff_queued_diff, one, two);
7075 if (!options->flags.diff_from_contents)
7076 options->flags.has_changes = 1;
7079 void diff_change(struct diff_options *options,
7080 unsigned old_mode, unsigned new_mode,
7081 const struct object_id *old_oid,
7082 const struct object_id *new_oid,
7083 int old_oid_valid, int new_oid_valid,
7084 const char *concatpath,
7085 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7087 struct diff_filespec *one, *two;
7088 struct diff_filepair *p;
7090 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7091 is_submodule_ignored(concatpath, options))
7092 return;
7094 if (options->flags.reverse_diff) {
7095 SWAP(old_mode, new_mode);
7096 SWAP(old_oid, new_oid);
7097 SWAP(old_oid_valid, new_oid_valid);
7098 SWAP(old_dirty_submodule, new_dirty_submodule);
7101 if (options->prefix &&
7102 strncmp(concatpath, options->prefix, options->prefix_length))
7103 return;
7105 one = alloc_filespec(concatpath);
7106 two = alloc_filespec(concatpath);
7107 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7108 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7109 one->dirty_submodule = old_dirty_submodule;
7110 two->dirty_submodule = new_dirty_submodule;
7111 p = diff_queue(&diff_queued_diff, one, two);
7113 if (options->flags.diff_from_contents)
7114 return;
7116 if (options->flags.quick && options->skip_stat_unmatch &&
7117 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7118 diff_free_filespec_data(p->one);
7119 diff_free_filespec_data(p->two);
7120 return;
7123 options->flags.has_changes = 1;
7126 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7128 struct diff_filepair *pair;
7129 struct diff_filespec *one, *two;
7131 if (options->prefix &&
7132 strncmp(path, options->prefix, options->prefix_length))
7133 return NULL;
7135 one = alloc_filespec(path);
7136 two = alloc_filespec(path);
7137 pair = diff_queue(&diff_queued_diff, one, two);
7138 pair->is_unmerged = 1;
7139 return pair;
7142 static char *run_textconv(struct repository *r,
7143 const char *pgm,
7144 struct diff_filespec *spec,
7145 size_t *outsize)
7147 struct diff_tempfile *temp;
7148 struct child_process child = CHILD_PROCESS_INIT;
7149 struct strbuf buf = STRBUF_INIT;
7150 int err = 0;
7152 temp = prepare_temp_file(r, spec);
7153 strvec_push(&child.args, pgm);
7154 strvec_push(&child.args, temp->name);
7156 child.use_shell = 1;
7157 child.out = -1;
7158 if (start_command(&child)) {
7159 remove_tempfile();
7160 return NULL;
7163 if (strbuf_read(&buf, child.out, 0) < 0)
7164 err = error("error reading from textconv command '%s'", pgm);
7165 close(child.out);
7167 if (finish_command(&child) || err) {
7168 strbuf_release(&buf);
7169 remove_tempfile();
7170 return NULL;
7172 remove_tempfile();
7174 return strbuf_detach(&buf, outsize);
7177 size_t fill_textconv(struct repository *r,
7178 struct userdiff_driver *driver,
7179 struct diff_filespec *df,
7180 char **outbuf)
7182 size_t size;
7184 if (!driver) {
7185 if (!DIFF_FILE_VALID(df)) {
7186 *outbuf = "";
7187 return 0;
7189 if (diff_populate_filespec(r, df, NULL))
7190 die("unable to read files to diff");
7191 *outbuf = df->data;
7192 return df->size;
7195 if (!driver->textconv)
7196 BUG("fill_textconv called with non-textconv driver");
7198 if (driver->textconv_cache && df->oid_valid) {
7199 *outbuf = notes_cache_get(driver->textconv_cache,
7200 &df->oid,
7201 &size);
7202 if (*outbuf)
7203 return size;
7206 *outbuf = run_textconv(r, driver->textconv, df, &size);
7207 if (!*outbuf)
7208 die("unable to read files to diff");
7210 if (driver->textconv_cache && df->oid_valid) {
7211 /* ignore errors, as we might be in a readonly repository */
7212 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7213 size);
7215 * we could save up changes and flush them all at the end,
7216 * but we would need an extra call after all diffing is done.
7217 * Since generating a cache entry is the slow path anyway,
7218 * this extra overhead probably isn't a big deal.
7220 notes_cache_write(driver->textconv_cache);
7223 return size;
7226 int textconv_object(struct repository *r,
7227 const char *path,
7228 unsigned mode,
7229 const struct object_id *oid,
7230 int oid_valid,
7231 char **buf,
7232 unsigned long *buf_size)
7234 struct diff_filespec *df;
7235 struct userdiff_driver *textconv;
7237 df = alloc_filespec(path);
7238 fill_filespec(df, oid, oid_valid, mode);
7239 textconv = get_textconv(r, df);
7240 if (!textconv) {
7241 free_filespec(df);
7242 return 0;
7245 *buf_size = fill_textconv(r, textconv, df, buf);
7246 free_filespec(df);
7247 return 1;
7250 void setup_diff_pager(struct diff_options *opt)
7253 * If the user asked for our exit code, then either they want --quiet
7254 * or --exit-code. We should definitely not bother with a pager in the
7255 * former case, as we will generate no output. Since we still properly
7256 * report our exit code even when a pager is run, we _could_ run a
7257 * pager with --exit-code. But since we have not done so historically,
7258 * and because it is easy to find people oneline advising "git diff
7259 * --exit-code" in hooks and other scripts, we do not do so.
7261 if (!opt->flags.exit_with_status &&
7262 check_pager_config("diff") != 0)
7263 setup_pager();