Merge branch 'bc/more-git-var'
[git/debian.git] / diff.c
blob6fb2946a6413f8d8546fe1b04b35c6aaf69f0ae9
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;
5523 struct option *add_diff_options(const struct option *opts,
5524 struct diff_options *options)
5526 struct option parseopts[] = {
5527 OPT_GROUP(N_("Diff output format options")),
5528 OPT_BITOP('p', "patch", &options->output_format,
5529 N_("generate patch"),
5530 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5531 OPT_SET_INT('s', "no-patch", &options->output_format,
5532 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5533 OPT_BITOP('u', NULL, &options->output_format,
5534 N_("generate patch"),
5535 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5536 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5537 N_("generate diffs with <n> lines context"),
5538 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5539 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5540 N_("generate diffs with <n> lines context")),
5541 OPT_BITOP(0, "raw", &options->output_format,
5542 N_("generate the diff in raw format"),
5543 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5544 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5545 N_("synonym for '-p --raw'"),
5546 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5547 DIFF_FORMAT_NO_OUTPUT),
5548 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5549 N_("synonym for '-p --stat'"),
5550 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5551 DIFF_FORMAT_NO_OUTPUT),
5552 OPT_BITOP(0, "numstat", &options->output_format,
5553 N_("machine friendly --stat"),
5554 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5555 OPT_BITOP(0, "shortstat", &options->output_format,
5556 N_("output only the last line of --stat"),
5557 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5558 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5559 N_("output the distribution of relative amount of changes for each sub-directory"),
5560 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5561 diff_opt_dirstat),
5562 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5563 N_("synonym for --dirstat=cumulative"),
5564 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5565 diff_opt_dirstat),
5566 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5567 N_("synonym for --dirstat=files,param1,param2..."),
5568 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5569 diff_opt_dirstat),
5570 OPT_BIT_F(0, "check", &options->output_format,
5571 N_("warn if changes introduce conflict markers or whitespace errors"),
5572 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5573 OPT_BITOP(0, "summary", &options->output_format,
5574 N_("condensed summary such as creations, renames and mode changes"),
5575 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5576 OPT_BIT_F(0, "name-only", &options->output_format,
5577 N_("show only names of changed files"),
5578 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5579 OPT_BIT_F(0, "name-status", &options->output_format,
5580 N_("show only names and status of changed files"),
5581 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5582 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5583 N_("generate diffstat"),
5584 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5585 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5586 N_("generate diffstat with a given width"),
5587 PARSE_OPT_NONEG, diff_opt_stat),
5588 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5589 N_("generate diffstat with a given name width"),
5590 PARSE_OPT_NONEG, diff_opt_stat),
5591 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5592 N_("generate diffstat with a given graph width"),
5593 PARSE_OPT_NONEG, diff_opt_stat),
5594 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5595 N_("generate diffstat with limited lines"),
5596 PARSE_OPT_NONEG, diff_opt_stat),
5597 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5598 N_("generate compact summary in diffstat"),
5599 PARSE_OPT_NOARG, diff_opt_compact_summary),
5600 OPT_CALLBACK_F(0, "binary", options, NULL,
5601 N_("output a binary diff that can be applied"),
5602 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5603 OPT_BOOL(0, "full-index", &options->flags.full_index,
5604 N_("show full pre- and post-image object names on the \"index\" lines")),
5605 OPT_COLOR_FLAG(0, "color", &options->use_color,
5606 N_("show colored diff")),
5607 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5608 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5609 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5610 OPT_SET_INT('z', NULL, &options->line_termination,
5611 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5613 OPT__ABBREV(&options->abbrev),
5614 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5615 N_("show the given source prefix instead of \"a/\""),
5616 PARSE_OPT_NONEG),
5617 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5618 N_("show the given destination prefix instead of \"b/\""),
5619 PARSE_OPT_NONEG),
5620 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5621 N_("prepend an additional prefix to every line of output"),
5622 PARSE_OPT_NONEG, diff_opt_line_prefix),
5623 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5624 N_("do not show any source or destination prefix"),
5625 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5626 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5627 N_("use default prefixes a/ and b/"),
5628 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5629 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5630 N_("show context between diff hunks up to the specified number of lines"),
5631 PARSE_OPT_NONEG),
5632 OPT_CALLBACK_F(0, "output-indicator-new",
5633 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5634 N_("<char>"),
5635 N_("specify the character to indicate a new line instead of '+'"),
5636 PARSE_OPT_NONEG, diff_opt_char),
5637 OPT_CALLBACK_F(0, "output-indicator-old",
5638 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5639 N_("<char>"),
5640 N_("specify the character to indicate an old line instead of '-'"),
5641 PARSE_OPT_NONEG, diff_opt_char),
5642 OPT_CALLBACK_F(0, "output-indicator-context",
5643 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5644 N_("<char>"),
5645 N_("specify the character to indicate a context instead of ' '"),
5646 PARSE_OPT_NONEG, diff_opt_char),
5648 OPT_GROUP(N_("Diff rename options")),
5649 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5650 N_("break complete rewrite changes into pairs of delete and create"),
5651 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5652 diff_opt_break_rewrites),
5653 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5654 N_("detect renames"),
5655 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5656 diff_opt_find_renames),
5657 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5658 N_("omit the preimage for deletes"),
5659 1, PARSE_OPT_NONEG),
5660 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5661 N_("detect copies"),
5662 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5663 diff_opt_find_copies),
5664 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5665 N_("use unmodified files as source to find copies")),
5666 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5667 N_("disable rename detection"),
5668 0, PARSE_OPT_NONEG),
5669 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5670 N_("use empty blobs as rename source")),
5671 OPT_CALLBACK_F(0, "follow", options, NULL,
5672 N_("continue listing the history of a file beyond renames"),
5673 PARSE_OPT_NOARG, diff_opt_follow),
5674 OPT_INTEGER('l', NULL, &options->rename_limit,
5675 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5677 OPT_GROUP(N_("Diff algorithm options")),
5678 OPT_CALLBACK_F(0, "minimal", options, NULL,
5679 N_("produce the smallest possible diff"),
5680 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5681 diff_opt_diff_algorithm_no_arg),
5682 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5683 N_("ignore whitespace when comparing lines"),
5684 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5685 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5686 N_("ignore changes in amount of whitespace"),
5687 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5688 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5689 N_("ignore changes in whitespace at EOL"),
5690 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5691 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5692 N_("ignore carrier-return at the end of line"),
5693 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5694 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5695 N_("ignore changes whose lines are all blank"),
5696 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5697 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5698 N_("ignore changes whose all lines match <regex>"),
5699 0, diff_opt_ignore_regex),
5700 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5701 N_("heuristic to shift diff hunk boundaries for easy reading"),
5702 XDF_INDENT_HEURISTIC),
5703 OPT_CALLBACK_F(0, "patience", options, NULL,
5704 N_("generate diff using the \"patience diff\" algorithm"),
5705 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5706 diff_opt_patience),
5707 OPT_CALLBACK_F(0, "histogram", options, NULL,
5708 N_("generate diff using the \"histogram diff\" algorithm"),
5709 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5710 diff_opt_diff_algorithm_no_arg),
5711 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5712 N_("choose a diff algorithm"),
5713 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5714 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5715 N_("generate diff using the \"anchored diff\" algorithm"),
5716 PARSE_OPT_NONEG, diff_opt_anchored),
5717 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5718 N_("show word diff, using <mode> to delimit changed words"),
5719 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5720 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5721 N_("use <regex> to decide what a word is"),
5722 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5723 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5724 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5725 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5726 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5727 N_("moved lines of code are colored differently"),
5728 PARSE_OPT_OPTARG, diff_opt_color_moved),
5729 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5730 N_("how white spaces are ignored in --color-moved"),
5731 0, diff_opt_color_moved_ws),
5733 OPT_GROUP(N_("Other diff options")),
5734 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5735 N_("when run from subdir, exclude changes outside and show relative paths"),
5736 PARSE_OPT_OPTARG,
5737 diff_opt_relative),
5738 OPT_BOOL('a', "text", &options->flags.text,
5739 N_("treat all files as text")),
5740 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5741 N_("swap two inputs, reverse the diff")),
5742 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5743 N_("exit with 1 if there were differences, 0 otherwise")),
5744 OPT_BOOL(0, "quiet", &options->flags.quick,
5745 N_("disable all output of the program")),
5746 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5747 N_("allow an external diff helper to be executed")),
5748 OPT_CALLBACK_F(0, "textconv", options, NULL,
5749 N_("run external text conversion filters when comparing binary files"),
5750 PARSE_OPT_NOARG, diff_opt_textconv),
5751 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5752 N_("ignore changes to submodules in the diff generation"),
5753 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5754 diff_opt_ignore_submodules),
5755 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5756 N_("specify how differences in submodules are shown"),
5757 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5758 diff_opt_submodule),
5759 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5760 N_("hide 'git add -N' entries from the index"),
5761 1, PARSE_OPT_NONEG),
5762 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5763 N_("treat 'git add -N' entries as real in the index"),
5764 0, PARSE_OPT_NONEG),
5765 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5766 N_("look for differences that change the number of occurrences of the specified string"),
5767 0, diff_opt_pickaxe_string),
5768 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5769 N_("look for differences that change the number of occurrences of the specified regex"),
5770 0, diff_opt_pickaxe_regex),
5771 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5772 N_("show all changes in the changeset with -S or -G"),
5773 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5774 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5775 N_("treat <string> in -S as extended POSIX regular expression"),
5776 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5777 OPT_FILENAME('O', NULL, &options->orderfile,
5778 N_("control the order in which files appear in the output")),
5779 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5780 N_("show the change in the specified path first"),
5781 PARSE_OPT_NONEG, diff_opt_rotate_to),
5782 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5783 N_("skip the output to the specified path"),
5784 PARSE_OPT_NONEG, diff_opt_rotate_to),
5785 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5786 N_("look for differences that change the number of occurrences of the specified object"),
5787 PARSE_OPT_NONEG, diff_opt_find_object),
5788 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5789 N_("select files by diff type"),
5790 PARSE_OPT_NONEG, diff_opt_diff_filter),
5791 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5792 N_("output to a specific file"),
5793 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5795 OPT_END()
5798 return parse_options_concat(opts, parseopts);
5801 int diff_opt_parse(struct diff_options *options,
5802 const char **av, int ac, const char *prefix)
5804 struct option no_options[] = { OPT_END() };
5805 struct option *parseopts = add_diff_options(no_options, options);
5807 if (!prefix)
5808 prefix = "";
5810 ac = parse_options(ac, av, prefix, parseopts, NULL,
5811 PARSE_OPT_KEEP_DASHDASH |
5812 PARSE_OPT_KEEP_UNKNOWN_OPT |
5813 PARSE_OPT_NO_INTERNAL_HELP |
5814 PARSE_OPT_ONE_SHOT |
5815 PARSE_OPT_STOP_AT_NON_OPTION);
5816 free(parseopts);
5818 return ac;
5821 int parse_rename_score(const char **cp_p)
5823 unsigned long num, scale;
5824 int ch, dot;
5825 const char *cp = *cp_p;
5827 num = 0;
5828 scale = 1;
5829 dot = 0;
5830 for (;;) {
5831 ch = *cp;
5832 if ( !dot && ch == '.' ) {
5833 scale = 1;
5834 dot = 1;
5835 } else if ( ch == '%' ) {
5836 scale = dot ? scale*100 : 100;
5837 cp++; /* % is always at the end */
5838 break;
5839 } else if ( ch >= '0' && ch <= '9' ) {
5840 if ( scale < 100000 ) {
5841 scale *= 10;
5842 num = (num*10) + (ch-'0');
5844 } else {
5845 break;
5847 cp++;
5849 *cp_p = cp;
5851 /* user says num divided by scale and we say internally that
5852 * is MAX_SCORE * num / scale.
5854 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5857 struct diff_queue_struct diff_queued_diff;
5859 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5861 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5862 queue->queue[queue->nr++] = dp;
5865 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5866 struct diff_filespec *one,
5867 struct diff_filespec *two)
5869 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5870 dp->one = one;
5871 dp->two = two;
5872 if (queue)
5873 diff_q(queue, dp);
5874 return dp;
5877 void diff_free_filepair(struct diff_filepair *p)
5879 free_filespec(p->one);
5880 free_filespec(p->two);
5881 free(p);
5884 void diff_free_queue(struct diff_queue_struct *q)
5886 for (int i = 0; i < q->nr; i++)
5887 diff_free_filepair(q->queue[i]);
5888 free(q->queue);
5891 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5893 int abblen;
5894 const char *abbrev;
5896 /* Do we want all 40 hex characters? */
5897 if (len == the_hash_algo->hexsz)
5898 return oid_to_hex(oid);
5900 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5901 abbrev = diff_abbrev_oid(oid, len);
5903 if (!print_sha1_ellipsis())
5904 return abbrev;
5906 abblen = strlen(abbrev);
5909 * In well-behaved cases, where the abbreviated result is the
5910 * same as the requested length, append three dots after the
5911 * abbreviation (hence the whole logic is limited to the case
5912 * where abblen < 37); when the actual abbreviated result is a
5913 * bit longer than the requested length, we reduce the number
5914 * of dots so that they match the well-behaved ones. However,
5915 * if the actual abbreviation is longer than the requested
5916 * length by more than three, we give up on aligning, and add
5917 * three dots anyway, to indicate that the output is not the
5918 * full object name. Yes, this may be suboptimal, but this
5919 * appears only in "diff --raw --abbrev" output and it is not
5920 * worth the effort to change it now. Note that this would
5921 * likely to work fine when the automatic sizing of default
5922 * abbreviation length is used--we would be fed -1 in "len" in
5923 * that case, and will end up always appending three-dots, but
5924 * the automatic sizing is supposed to give abblen that ensures
5925 * uniqueness across all objects (statistically speaking).
5927 if (abblen < the_hash_algo->hexsz - 3) {
5928 static char hex[GIT_MAX_HEXSZ + 1];
5929 if (len < abblen && abblen <= len + 2)
5930 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5931 else
5932 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5933 return hex;
5936 return oid_to_hex(oid);
5939 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5941 int line_termination = opt->line_termination;
5942 int inter_name_termination = line_termination ? '\t' : '\0';
5944 fprintf(opt->file, "%s", diff_line_prefix(opt));
5945 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5946 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5947 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5948 fprintf(opt->file, "%s ",
5949 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5951 if (p->score) {
5952 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5953 inter_name_termination);
5954 } else {
5955 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5958 if (p->status == DIFF_STATUS_COPIED ||
5959 p->status == DIFF_STATUS_RENAMED) {
5960 const char *name_a, *name_b;
5961 name_a = p->one->path;
5962 name_b = p->two->path;
5963 strip_prefix(opt->prefix_length, &name_a, &name_b);
5964 write_name_quoted(name_a, opt->file, inter_name_termination);
5965 write_name_quoted(name_b, opt->file, line_termination);
5966 } else {
5967 const char *name_a, *name_b;
5968 name_a = p->one->mode ? p->one->path : p->two->path;
5969 name_b = NULL;
5970 strip_prefix(opt->prefix_length, &name_a, &name_b);
5971 write_name_quoted(name_a, opt->file, line_termination);
5975 int diff_unmodified_pair(struct diff_filepair *p)
5977 /* This function is written stricter than necessary to support
5978 * the currently implemented transformers, but the idea is to
5979 * let transformers to produce diff_filepairs any way they want,
5980 * and filter and clean them up here before producing the output.
5982 struct diff_filespec *one = p->one, *two = p->two;
5984 if (DIFF_PAIR_UNMERGED(p))
5985 return 0; /* unmerged is interesting */
5987 /* deletion, addition, mode or type change
5988 * and rename are all interesting.
5990 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5991 DIFF_PAIR_MODE_CHANGED(p) ||
5992 strcmp(one->path, two->path))
5993 return 0;
5995 /* both are valid and point at the same path. that is, we are
5996 * dealing with a change.
5998 if (one->oid_valid && two->oid_valid &&
5999 oideq(&one->oid, &two->oid) &&
6000 !one->dirty_submodule && !two->dirty_submodule)
6001 return 1; /* no change */
6002 if (!one->oid_valid && !two->oid_valid)
6003 return 1; /* both look at the same file on the filesystem. */
6004 return 0;
6007 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6009 int include_conflict_headers =
6010 (additional_headers(o, p->one->path) &&
6011 !o->pickaxe_opts &&
6012 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6015 * Check if we can return early without showing a diff. Note that
6016 * diff_filepair only stores {oid, path, mode, is_valid}
6017 * information for each path, and thus diff_unmodified_pair() only
6018 * considers those bits of info. However, we do not want pairs
6019 * created by create_filepairs_for_header_only_notifications()
6020 * (which always look like unmodified pairs) to be ignored, so
6021 * return early if both p is unmodified AND we don't want to
6022 * include_conflict_headers.
6024 if (diff_unmodified_pair(p) && !include_conflict_headers)
6025 return;
6027 /* Actually, we can also return early to avoid showing tree diffs */
6028 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6029 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6030 return;
6032 run_diff(p, o);
6035 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6036 struct diffstat_t *diffstat)
6038 if (diff_unmodified_pair(p))
6039 return;
6041 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6042 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6043 return; /* no useful stat for tree diffs */
6045 run_diffstat(p, o, diffstat);
6048 static void diff_flush_checkdiff(struct diff_filepair *p,
6049 struct diff_options *o)
6051 if (diff_unmodified_pair(p))
6052 return;
6054 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6055 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6056 return; /* nothing to check in tree diffs */
6058 run_checkdiff(p, o);
6061 int diff_queue_is_empty(struct diff_options *o)
6063 struct diff_queue_struct *q = &diff_queued_diff;
6064 int i;
6065 int include_conflict_headers =
6066 (o->additional_path_headers &&
6067 strmap_get_size(o->additional_path_headers) &&
6068 !o->pickaxe_opts &&
6069 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6071 if (include_conflict_headers)
6072 return 0;
6074 for (i = 0; i < q->nr; i++)
6075 if (!diff_unmodified_pair(q->queue[i]))
6076 return 0;
6077 return 1;
6080 #if DIFF_DEBUG
6081 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6083 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6084 x, one ? one : "",
6085 s->path,
6086 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6087 s->mode,
6088 s->oid_valid ? oid_to_hex(&s->oid) : "");
6089 fprintf(stderr, "queue[%d] %s size %lu\n",
6090 x, one ? one : "",
6091 s->size);
6094 void diff_debug_filepair(const struct diff_filepair *p, int i)
6096 diff_debug_filespec(p->one, i, "one");
6097 diff_debug_filespec(p->two, i, "two");
6098 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6099 p->score, p->status ? p->status : '?',
6100 p->one->rename_used, p->broken_pair);
6103 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6105 int i;
6106 if (msg)
6107 fprintf(stderr, "%s\n", msg);
6108 fprintf(stderr, "q->nr = %d\n", q->nr);
6109 for (i = 0; i < q->nr; i++) {
6110 struct diff_filepair *p = q->queue[i];
6111 diff_debug_filepair(p, i);
6114 #endif
6116 static void diff_resolve_rename_copy(void)
6118 int i;
6119 struct diff_filepair *p;
6120 struct diff_queue_struct *q = &diff_queued_diff;
6122 diff_debug_queue("resolve-rename-copy", q);
6124 for (i = 0; i < q->nr; i++) {
6125 p = q->queue[i];
6126 p->status = 0; /* undecided */
6127 if (DIFF_PAIR_UNMERGED(p))
6128 p->status = DIFF_STATUS_UNMERGED;
6129 else if (!DIFF_FILE_VALID(p->one))
6130 p->status = DIFF_STATUS_ADDED;
6131 else if (!DIFF_FILE_VALID(p->two))
6132 p->status = DIFF_STATUS_DELETED;
6133 else if (DIFF_PAIR_TYPE_CHANGED(p))
6134 p->status = DIFF_STATUS_TYPE_CHANGED;
6136 /* from this point on, we are dealing with a pair
6137 * whose both sides are valid and of the same type, i.e.
6138 * either in-place edit or rename/copy edit.
6140 else if (DIFF_PAIR_RENAME(p)) {
6142 * A rename might have re-connected a broken
6143 * pair up, causing the pathnames to be the
6144 * same again. If so, that's not a rename at
6145 * all, just a modification..
6147 * Otherwise, see if this source was used for
6148 * multiple renames, in which case we decrement
6149 * the count, and call it a copy.
6151 if (!strcmp(p->one->path, p->two->path))
6152 p->status = DIFF_STATUS_MODIFIED;
6153 else if (--p->one->rename_used > 0)
6154 p->status = DIFF_STATUS_COPIED;
6155 else
6156 p->status = DIFF_STATUS_RENAMED;
6158 else if (!oideq(&p->one->oid, &p->two->oid) ||
6159 p->one->mode != p->two->mode ||
6160 p->one->dirty_submodule ||
6161 p->two->dirty_submodule ||
6162 is_null_oid(&p->one->oid))
6163 p->status = DIFF_STATUS_MODIFIED;
6164 else {
6165 /* This is a "no-change" entry and should not
6166 * happen anymore, but prepare for broken callers.
6168 error("feeding unmodified %s to diffcore",
6169 p->one->path);
6170 p->status = DIFF_STATUS_UNKNOWN;
6173 diff_debug_queue("resolve-rename-copy done", q);
6176 static int check_pair_status(struct diff_filepair *p)
6178 switch (p->status) {
6179 case DIFF_STATUS_UNKNOWN:
6180 return 0;
6181 case 0:
6182 die("internal error in diff-resolve-rename-copy");
6183 default:
6184 return 1;
6188 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6190 int fmt = opt->output_format;
6192 if (fmt & DIFF_FORMAT_CHECKDIFF)
6193 diff_flush_checkdiff(p, opt);
6194 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6195 diff_flush_raw(p, opt);
6196 else if (fmt & DIFF_FORMAT_NAME) {
6197 const char *name_a, *name_b;
6198 name_a = p->two->path;
6199 name_b = NULL;
6200 strip_prefix(opt->prefix_length, &name_a, &name_b);
6201 fprintf(opt->file, "%s", diff_line_prefix(opt));
6202 write_name_quoted(name_a, opt->file, opt->line_termination);
6206 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6208 struct strbuf sb = STRBUF_INIT;
6209 if (fs->mode)
6210 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6211 else
6212 strbuf_addf(&sb, " %s ", newdelete);
6214 quote_c_style(fs->path, &sb, NULL, 0);
6215 strbuf_addch(&sb, '\n');
6216 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6217 sb.buf, sb.len, 0);
6218 strbuf_release(&sb);
6221 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6222 int show_name)
6224 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6225 struct strbuf sb = STRBUF_INIT;
6226 strbuf_addf(&sb, " mode change %06o => %06o",
6227 p->one->mode, p->two->mode);
6228 if (show_name) {
6229 strbuf_addch(&sb, ' ');
6230 quote_c_style(p->two->path, &sb, NULL, 0);
6232 strbuf_addch(&sb, '\n');
6233 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6234 sb.buf, sb.len, 0);
6235 strbuf_release(&sb);
6239 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6240 struct diff_filepair *p)
6242 struct strbuf sb = STRBUF_INIT;
6243 struct strbuf names = STRBUF_INIT;
6245 pprint_rename(&names, p->one->path, p->two->path);
6246 strbuf_addf(&sb, " %s %s (%d%%)\n",
6247 renamecopy, names.buf, similarity_index(p));
6248 strbuf_release(&names);
6249 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6250 sb.buf, sb.len, 0);
6251 show_mode_change(opt, p, 0);
6252 strbuf_release(&sb);
6255 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6257 switch(p->status) {
6258 case DIFF_STATUS_DELETED:
6259 show_file_mode_name(opt, "delete", p->one);
6260 break;
6261 case DIFF_STATUS_ADDED:
6262 show_file_mode_name(opt, "create", p->two);
6263 break;
6264 case DIFF_STATUS_COPIED:
6265 show_rename_copy(opt, "copy", p);
6266 break;
6267 case DIFF_STATUS_RENAMED:
6268 show_rename_copy(opt, "rename", p);
6269 break;
6270 default:
6271 if (p->score) {
6272 struct strbuf sb = STRBUF_INIT;
6273 strbuf_addstr(&sb, " rewrite ");
6274 quote_c_style(p->two->path, &sb, NULL, 0);
6275 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6276 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6277 sb.buf, sb.len, 0);
6278 strbuf_release(&sb);
6280 show_mode_change(opt, p, !p->score);
6281 break;
6285 struct patch_id_t {
6286 git_hash_ctx *ctx;
6287 int patchlen;
6290 static int remove_space(char *line, int len)
6292 int i;
6293 char *dst = line;
6294 unsigned char c;
6296 for (i = 0; i < len; i++)
6297 if (!isspace((c = line[i])))
6298 *dst++ = c;
6300 return dst - line;
6303 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6305 unsigned char hash[GIT_MAX_RAWSZ];
6306 unsigned short carry = 0;
6307 int i;
6309 the_hash_algo->final_fn(hash, ctx);
6310 the_hash_algo->init_fn(ctx);
6311 /* 20-byte sum, with carry */
6312 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6313 carry += result->hash[i] + hash[i];
6314 result->hash[i] = carry;
6315 carry >>= 8;
6319 static int patch_id_consume(void *priv, char *line, unsigned long len)
6321 struct patch_id_t *data = priv;
6322 int new_len;
6324 if (len > 12 && starts_with(line, "\\ "))
6325 return 0;
6326 new_len = remove_space(line, len);
6328 the_hash_algo->update_fn(data->ctx, line, new_len);
6329 data->patchlen += new_len;
6330 return 0;
6333 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6335 the_hash_algo->update_fn(ctx, str, strlen(str));
6338 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6340 /* large enough for 2^32 in octal */
6341 char buf[12];
6342 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6343 the_hash_algo->update_fn(ctx, buf, len);
6346 /* returns 0 upon success, and writes result into oid */
6347 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6349 struct diff_queue_struct *q = &diff_queued_diff;
6350 int i;
6351 git_hash_ctx ctx;
6352 struct patch_id_t data;
6354 the_hash_algo->init_fn(&ctx);
6355 memset(&data, 0, sizeof(struct patch_id_t));
6356 data.ctx = &ctx;
6357 oidclr(oid);
6359 for (i = 0; i < q->nr; i++) {
6360 xpparam_t xpp;
6361 xdemitconf_t xecfg;
6362 mmfile_t mf1, mf2;
6363 struct diff_filepair *p = q->queue[i];
6364 int len1, len2;
6366 memset(&xpp, 0, sizeof(xpp));
6367 memset(&xecfg, 0, sizeof(xecfg));
6368 if (p->status == 0)
6369 return error("internal diff status error");
6370 if (p->status == DIFF_STATUS_UNKNOWN)
6371 continue;
6372 if (diff_unmodified_pair(p))
6373 continue;
6374 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6375 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6376 continue;
6377 if (DIFF_PAIR_UNMERGED(p))
6378 continue;
6380 diff_fill_oid_info(p->one, options->repo->index);
6381 diff_fill_oid_info(p->two, options->repo->index);
6383 len1 = remove_space(p->one->path, strlen(p->one->path));
6384 len2 = remove_space(p->two->path, strlen(p->two->path));
6385 patch_id_add_string(&ctx, "diff--git");
6386 patch_id_add_string(&ctx, "a/");
6387 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6388 patch_id_add_string(&ctx, "b/");
6389 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6391 if (p->one->mode == 0) {
6392 patch_id_add_string(&ctx, "newfilemode");
6393 patch_id_add_mode(&ctx, p->two->mode);
6394 } else if (p->two->mode == 0) {
6395 patch_id_add_string(&ctx, "deletedfilemode");
6396 patch_id_add_mode(&ctx, p->one->mode);
6397 } else if (p->one->mode != p->two->mode) {
6398 patch_id_add_string(&ctx, "oldmode");
6399 patch_id_add_mode(&ctx, p->one->mode);
6400 patch_id_add_string(&ctx, "newmode");
6401 patch_id_add_mode(&ctx, p->two->mode);
6404 if (diff_header_only) {
6405 /* don't do anything since we're only populating header info */
6406 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6407 diff_filespec_is_binary(options->repo, p->two)) {
6408 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6409 the_hash_algo->hexsz);
6410 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6411 the_hash_algo->hexsz);
6412 } else {
6413 if (p->one->mode == 0) {
6414 patch_id_add_string(&ctx, "---/dev/null");
6415 patch_id_add_string(&ctx, "+++b/");
6416 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6417 } else if (p->two->mode == 0) {
6418 patch_id_add_string(&ctx, "---a/");
6419 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6420 patch_id_add_string(&ctx, "+++/dev/null");
6421 } else {
6422 patch_id_add_string(&ctx, "---a/");
6423 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6424 patch_id_add_string(&ctx, "+++b/");
6425 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6428 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6429 fill_mmfile(options->repo, &mf2, p->two) < 0)
6430 return error("unable to read files to diff");
6431 xpp.flags = 0;
6432 xecfg.ctxlen = 3;
6433 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6434 if (xdi_diff_outf(&mf1, &mf2, NULL,
6435 patch_id_consume, &data, &xpp, &xecfg))
6436 return error("unable to generate patch-id diff for %s",
6437 p->one->path);
6439 flush_one_hunk(oid, &ctx);
6442 return 0;
6445 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6447 struct diff_queue_struct *q = &diff_queued_diff;
6448 int result = diff_get_patch_id(options, oid, diff_header_only);
6450 diff_free_queue(q);
6451 DIFF_QUEUE_CLEAR(q);
6453 return result;
6456 static int is_summary_empty(const struct diff_queue_struct *q)
6458 int i;
6460 for (i = 0; i < q->nr; i++) {
6461 const struct diff_filepair *p = q->queue[i];
6463 switch (p->status) {
6464 case DIFF_STATUS_DELETED:
6465 case DIFF_STATUS_ADDED:
6466 case DIFF_STATUS_COPIED:
6467 case DIFF_STATUS_RENAMED:
6468 return 0;
6469 default:
6470 if (p->score)
6471 return 0;
6472 if (p->one->mode && p->two->mode &&
6473 p->one->mode != p->two->mode)
6474 return 0;
6475 break;
6478 return 1;
6481 static const char rename_limit_warning[] =
6482 N_("exhaustive rename detection was skipped due to too many files.");
6484 static const char degrade_cc_to_c_warning[] =
6485 N_("only found copies from modified paths due to too many files.");
6487 static const char rename_limit_advice[] =
6488 N_("you may want to set your %s variable to at least "
6489 "%d and retry the command.");
6491 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6493 fflush(stdout);
6494 if (degraded_cc)
6495 warning(_(degrade_cc_to_c_warning));
6496 else if (needed)
6497 warning(_(rename_limit_warning));
6498 else
6499 return;
6500 if (0 < needed)
6501 warning(_(rename_limit_advice), varname, needed);
6504 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6506 struct strset present;
6507 struct diff_queue_struct *q = &diff_queued_diff;
6508 struct hashmap_iter iter;
6509 struct strmap_entry *e;
6510 int i;
6512 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6515 * Find out which paths exist in diff_queued_diff, preferring
6516 * one->path for any pair that has multiple paths.
6518 for (i = 0; i < q->nr; i++) {
6519 struct diff_filepair *p = q->queue[i];
6520 char *path = p->one->path ? p->one->path : p->two->path;
6522 if (strmap_contains(o->additional_path_headers, path))
6523 strset_add(&present, path);
6527 * Loop over paths in additional_path_headers; for each NOT already
6528 * in diff_queued_diff, create a synthetic filepair and insert that
6529 * into diff_queued_diff.
6531 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6532 if (!strset_contains(&present, e->key)) {
6533 struct diff_filespec *one, *two;
6534 struct diff_filepair *p;
6536 one = alloc_filespec(e->key);
6537 two = alloc_filespec(e->key);
6538 fill_filespec(one, null_oid(), 0, 0);
6539 fill_filespec(two, null_oid(), 0, 0);
6540 p = diff_queue(q, one, two);
6541 p->status = DIFF_STATUS_MODIFIED;
6545 /* Re-sort the filepairs */
6546 diffcore_fix_diff_index();
6548 /* Cleanup */
6549 strset_clear(&present);
6552 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6554 int i;
6555 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6556 struct diff_queue_struct *q = &diff_queued_diff;
6558 if (WSEH_NEW & WS_RULE_MASK)
6559 BUG("WS rules bit mask overlaps with diff symbol flags");
6561 if (o->color_moved)
6562 o->emitted_symbols = &esm;
6564 if (o->additional_path_headers)
6565 create_filepairs_for_header_only_notifications(o);
6567 for (i = 0; i < q->nr; i++) {
6568 struct diff_filepair *p = q->queue[i];
6569 if (check_pair_status(p))
6570 diff_flush_patch(p, o);
6573 if (o->emitted_symbols) {
6574 if (o->color_moved) {
6575 struct mem_pool entry_pool;
6576 struct moved_entry_list *entry_list;
6578 mem_pool_init(&entry_pool, 1024 * 1024);
6579 entry_list = add_lines_to_move_detection(o,
6580 &entry_pool);
6581 mark_color_as_moved(o, entry_list);
6582 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6583 dim_moved_lines(o);
6585 mem_pool_discard(&entry_pool, 0);
6586 free(entry_list);
6589 for (i = 0; i < esm.nr; i++)
6590 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6592 for (i = 0; i < esm.nr; i++)
6593 free((void *)esm.buf[i].line);
6594 esm.nr = 0;
6596 o->emitted_symbols = NULL;
6600 static void diff_free_file(struct diff_options *options)
6602 if (options->close_file)
6603 fclose(options->file);
6606 static void diff_free_ignore_regex(struct diff_options *options)
6608 int i;
6610 for (i = 0; i < options->ignore_regex_nr; i++) {
6611 regfree(options->ignore_regex[i]);
6612 free(options->ignore_regex[i]);
6614 free(options->ignore_regex);
6617 void diff_free(struct diff_options *options)
6619 if (options->no_free)
6620 return;
6622 diff_free_file(options);
6623 diff_free_ignore_regex(options);
6624 clear_pathspec(&options->pathspec);
6627 void diff_flush(struct diff_options *options)
6629 struct diff_queue_struct *q = &diff_queued_diff;
6630 int i, output_format = options->output_format;
6631 int separator = 0;
6632 int dirstat_by_line = 0;
6635 * Order: raw, stat, summary, patch
6636 * or: name/name-status/checkdiff (other bits clear)
6638 if (!q->nr && !options->additional_path_headers)
6639 goto free_queue;
6641 if (output_format & (DIFF_FORMAT_RAW |
6642 DIFF_FORMAT_NAME |
6643 DIFF_FORMAT_NAME_STATUS |
6644 DIFF_FORMAT_CHECKDIFF)) {
6645 for (i = 0; i < q->nr; i++) {
6646 struct diff_filepair *p = q->queue[i];
6647 if (check_pair_status(p))
6648 flush_one_pair(p, options);
6650 separator++;
6653 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6654 dirstat_by_line = 1;
6656 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6657 dirstat_by_line) {
6658 struct diffstat_t diffstat;
6660 compute_diffstat(options, &diffstat, q);
6661 if (output_format & DIFF_FORMAT_NUMSTAT)
6662 show_numstat(&diffstat, options);
6663 if (output_format & DIFF_FORMAT_DIFFSTAT)
6664 show_stats(&diffstat, options);
6665 if (output_format & DIFF_FORMAT_SHORTSTAT)
6666 show_shortstats(&diffstat, options);
6667 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6668 show_dirstat_by_line(&diffstat, options);
6669 free_diffstat_info(&diffstat);
6670 separator++;
6672 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6673 show_dirstat(options);
6675 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6676 for (i = 0; i < q->nr; i++) {
6677 diff_summary(options, q->queue[i]);
6679 separator++;
6682 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6683 options->flags.exit_with_status &&
6684 options->flags.diff_from_contents) {
6686 * run diff_flush_patch for the exit status. setting
6687 * options->file to /dev/null should be safe, because we
6688 * aren't supposed to produce any output anyway.
6690 diff_free_file(options);
6691 options->file = xfopen("/dev/null", "w");
6692 options->close_file = 1;
6693 options->color_moved = 0;
6694 for (i = 0; i < q->nr; i++) {
6695 struct diff_filepair *p = q->queue[i];
6696 if (check_pair_status(p))
6697 diff_flush_patch(p, options);
6698 if (options->found_changes)
6699 break;
6703 if (output_format & DIFF_FORMAT_PATCH) {
6704 if (separator) {
6705 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6706 if (options->stat_sep)
6707 /* attach patch instead of inline */
6708 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6709 NULL, 0, 0);
6712 diff_flush_patch_all_file_pairs(options);
6715 if (output_format & DIFF_FORMAT_CALLBACK)
6716 options->format_callback(q, options, options->format_callback_data);
6718 free_queue:
6719 diff_free_queue(q);
6720 DIFF_QUEUE_CLEAR(q);
6721 diff_free(options);
6724 * Report the content-level differences with HAS_CHANGES;
6725 * diff_addremove/diff_change does not set the bit when
6726 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6728 if (options->flags.diff_from_contents) {
6729 if (options->found_changes)
6730 options->flags.has_changes = 1;
6731 else
6732 options->flags.has_changes = 0;
6736 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6738 return (((p->status == DIFF_STATUS_MODIFIED) &&
6739 ((p->score &&
6740 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6741 (!p->score &&
6742 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6743 ((p->status != DIFF_STATUS_MODIFIED) &&
6744 filter_bit_tst(p->status, options)));
6747 static void diffcore_apply_filter(struct diff_options *options)
6749 int i;
6750 struct diff_queue_struct *q = &diff_queued_diff;
6751 struct diff_queue_struct outq;
6753 DIFF_QUEUE_CLEAR(&outq);
6755 if (!options->filter)
6756 return;
6758 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6759 int found;
6760 for (i = found = 0; !found && i < q->nr; i++) {
6761 if (match_filter(options, q->queue[i]))
6762 found++;
6764 if (found)
6765 return;
6767 /* otherwise we will clear the whole queue
6768 * by copying the empty outq at the end of this
6769 * function, but first clear the current entries
6770 * in the queue.
6772 for (i = 0; i < q->nr; i++)
6773 diff_free_filepair(q->queue[i]);
6775 else {
6776 /* Only the matching ones */
6777 for (i = 0; i < q->nr; i++) {
6778 struct diff_filepair *p = q->queue[i];
6779 if (match_filter(options, p))
6780 diff_q(&outq, p);
6781 else
6782 diff_free_filepair(p);
6785 free(q->queue);
6786 *q = outq;
6789 /* Check whether two filespecs with the same mode and size are identical */
6790 static int diff_filespec_is_identical(struct repository *r,
6791 struct diff_filespec *one,
6792 struct diff_filespec *two)
6794 if (S_ISGITLINK(one->mode))
6795 return 0;
6796 if (diff_populate_filespec(r, one, NULL))
6797 return 0;
6798 if (diff_populate_filespec(r, two, NULL))
6799 return 0;
6800 return !memcmp(one->data, two->data, one->size);
6803 static int diff_filespec_check_stat_unmatch(struct repository *r,
6804 struct diff_filepair *p)
6806 struct diff_populate_filespec_options dpf_options = {
6807 .check_size_only = 1,
6808 .missing_object_cb = diff_queued_diff_prefetch,
6809 .missing_object_data = r,
6812 if (p->done_skip_stat_unmatch)
6813 return p->skip_stat_unmatch_result;
6815 p->done_skip_stat_unmatch = 1;
6816 p->skip_stat_unmatch_result = 0;
6818 * 1. Entries that come from stat info dirtiness
6819 * always have both sides (iow, not create/delete),
6820 * one side of the object name is unknown, with
6821 * the same mode and size. Keep the ones that
6822 * do not match these criteria. They have real
6823 * differences.
6825 * 2. At this point, the file is known to be modified,
6826 * with the same mode and size, and the object
6827 * name of one side is unknown. Need to inspect
6828 * the identical contents.
6830 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6831 !DIFF_FILE_VALID(p->two) ||
6832 (p->one->oid_valid && p->two->oid_valid) ||
6833 (p->one->mode != p->two->mode) ||
6834 diff_populate_filespec(r, p->one, &dpf_options) ||
6835 diff_populate_filespec(r, p->two, &dpf_options) ||
6836 (p->one->size != p->two->size) ||
6837 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6838 p->skip_stat_unmatch_result = 1;
6839 return p->skip_stat_unmatch_result;
6842 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6844 int i;
6845 struct diff_queue_struct *q = &diff_queued_diff;
6846 struct diff_queue_struct outq;
6847 DIFF_QUEUE_CLEAR(&outq);
6849 for (i = 0; i < q->nr; i++) {
6850 struct diff_filepair *p = q->queue[i];
6852 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6853 diff_q(&outq, p);
6854 else {
6856 * The caller can subtract 1 from skip_stat_unmatch
6857 * to determine how many paths were dirty only
6858 * due to stat info mismatch.
6860 if (!diffopt->flags.no_index)
6861 diffopt->skip_stat_unmatch++;
6862 diff_free_filepair(p);
6865 free(q->queue);
6866 *q = outq;
6869 static int diffnamecmp(const void *a_, const void *b_)
6871 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6872 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6873 const char *name_a, *name_b;
6875 name_a = a->one ? a->one->path : a->two->path;
6876 name_b = b->one ? b->one->path : b->two->path;
6877 return strcmp(name_a, name_b);
6880 void diffcore_fix_diff_index(void)
6882 struct diff_queue_struct *q = &diff_queued_diff;
6883 QSORT(q->queue, q->nr, diffnamecmp);
6886 void diff_add_if_missing(struct repository *r,
6887 struct oid_array *to_fetch,
6888 const struct diff_filespec *filespec)
6890 if (filespec && filespec->oid_valid &&
6891 !S_ISGITLINK(filespec->mode) &&
6892 oid_object_info_extended(r, &filespec->oid, NULL,
6893 OBJECT_INFO_FOR_PREFETCH))
6894 oid_array_append(to_fetch, &filespec->oid);
6897 void diff_queued_diff_prefetch(void *repository)
6899 struct repository *repo = repository;
6900 int i;
6901 struct diff_queue_struct *q = &diff_queued_diff;
6902 struct oid_array to_fetch = OID_ARRAY_INIT;
6904 for (i = 0; i < q->nr; i++) {
6905 struct diff_filepair *p = q->queue[i];
6906 diff_add_if_missing(repo, &to_fetch, p->one);
6907 diff_add_if_missing(repo, &to_fetch, p->two);
6911 * NEEDSWORK: Consider deduplicating the OIDs sent.
6913 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6915 oid_array_clear(&to_fetch);
6918 void diffcore_std(struct diff_options *options)
6920 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6921 DIFF_FORMAT_NUMSTAT |
6922 DIFF_FORMAT_PATCH |
6923 DIFF_FORMAT_SHORTSTAT |
6924 DIFF_FORMAT_DIRSTAT;
6927 * Check if the user requested a blob-data-requiring diff output and/or
6928 * break-rewrite detection (which requires blob data). If yes, prefetch
6929 * the diff pairs.
6931 * If no prefetching occurs, diffcore_rename() will prefetch if it
6932 * decides that it needs inexact rename detection.
6934 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6935 (options->output_format & output_formats_to_prefetch ||
6936 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6937 diff_queued_diff_prefetch(options->repo);
6939 /* NOTE please keep the following in sync with diff_tree_combined() */
6940 if (options->skip_stat_unmatch)
6941 diffcore_skip_stat_unmatch(options);
6942 if (!options->found_follow) {
6943 /* See try_to_follow_renames() in tree-diff.c */
6944 if (options->break_opt != -1)
6945 diffcore_break(options->repo,
6946 options->break_opt);
6947 if (options->detect_rename)
6948 diffcore_rename(options);
6949 if (options->break_opt != -1)
6950 diffcore_merge_broken();
6952 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6953 diffcore_pickaxe(options);
6954 if (options->orderfile)
6955 diffcore_order(options->orderfile);
6956 if (options->rotate_to)
6957 diffcore_rotate(options);
6958 if (!options->found_follow)
6959 /* See try_to_follow_renames() in tree-diff.c */
6960 diff_resolve_rename_copy();
6961 diffcore_apply_filter(options);
6963 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6964 options->flags.has_changes = 1;
6965 else
6966 options->flags.has_changes = 0;
6968 options->found_follow = 0;
6971 int diff_result_code(struct diff_options *opt, int status)
6973 int result = 0;
6975 diff_warn_rename_limit("diff.renameLimit",
6976 opt->needed_rename_limit,
6977 opt->degraded_cc_to_c);
6978 if (!opt->flags.exit_with_status &&
6979 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6980 return status;
6981 if (opt->flags.exit_with_status &&
6982 opt->flags.has_changes)
6983 result |= 01;
6984 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6985 opt->flags.check_failed)
6986 result |= 02;
6987 return result;
6990 int diff_can_quit_early(struct diff_options *opt)
6992 return (opt->flags.quick &&
6993 !opt->filter &&
6994 opt->flags.has_changes);
6998 * Shall changes to this submodule be ignored?
7000 * Submodule changes can be configured to be ignored separately for each path,
7001 * but that configuration can be overridden from the command line.
7003 static int is_submodule_ignored(const char *path, struct diff_options *options)
7005 int ignored = 0;
7006 struct diff_flags orig_flags = options->flags;
7007 if (!options->flags.override_submodule_config)
7008 set_diffopt_flags_from_submodule_config(options, path);
7009 if (options->flags.ignore_submodules)
7010 ignored = 1;
7011 options->flags = orig_flags;
7012 return ignored;
7015 void compute_diffstat(struct diff_options *options,
7016 struct diffstat_t *diffstat,
7017 struct diff_queue_struct *q)
7019 int i;
7021 memset(diffstat, 0, sizeof(struct diffstat_t));
7022 for (i = 0; i < q->nr; i++) {
7023 struct diff_filepair *p = q->queue[i];
7024 if (check_pair_status(p))
7025 diff_flush_stat(p, options, diffstat);
7029 void diff_addremove(struct diff_options *options,
7030 int addremove, unsigned mode,
7031 const struct object_id *oid,
7032 int oid_valid,
7033 const char *concatpath, unsigned dirty_submodule)
7035 struct diff_filespec *one, *two;
7037 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7038 return;
7040 /* This may look odd, but it is a preparation for
7041 * feeding "there are unchanged files which should
7042 * not produce diffs, but when you are doing copy
7043 * detection you would need them, so here they are"
7044 * entries to the diff-core. They will be prefixed
7045 * with something like '=' or '*' (I haven't decided
7046 * which but should not make any difference).
7047 * Feeding the same new and old to diff_change()
7048 * also has the same effect.
7049 * Before the final output happens, they are pruned after
7050 * merged into rename/copy pairs as appropriate.
7052 if (options->flags.reverse_diff)
7053 addremove = (addremove == '+' ? '-' :
7054 addremove == '-' ? '+' : addremove);
7056 if (options->prefix &&
7057 strncmp(concatpath, options->prefix, options->prefix_length))
7058 return;
7060 one = alloc_filespec(concatpath);
7061 two = alloc_filespec(concatpath);
7063 if (addremove != '+')
7064 fill_filespec(one, oid, oid_valid, mode);
7065 if (addremove != '-') {
7066 fill_filespec(two, oid, oid_valid, mode);
7067 two->dirty_submodule = dirty_submodule;
7070 diff_queue(&diff_queued_diff, one, two);
7071 if (!options->flags.diff_from_contents)
7072 options->flags.has_changes = 1;
7075 void diff_change(struct diff_options *options,
7076 unsigned old_mode, unsigned new_mode,
7077 const struct object_id *old_oid,
7078 const struct object_id *new_oid,
7079 int old_oid_valid, int new_oid_valid,
7080 const char *concatpath,
7081 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7083 struct diff_filespec *one, *two;
7084 struct diff_filepair *p;
7086 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7087 is_submodule_ignored(concatpath, options))
7088 return;
7090 if (options->flags.reverse_diff) {
7091 SWAP(old_mode, new_mode);
7092 SWAP(old_oid, new_oid);
7093 SWAP(old_oid_valid, new_oid_valid);
7094 SWAP(old_dirty_submodule, new_dirty_submodule);
7097 if (options->prefix &&
7098 strncmp(concatpath, options->prefix, options->prefix_length))
7099 return;
7101 one = alloc_filespec(concatpath);
7102 two = alloc_filespec(concatpath);
7103 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7104 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7105 one->dirty_submodule = old_dirty_submodule;
7106 two->dirty_submodule = new_dirty_submodule;
7107 p = diff_queue(&diff_queued_diff, one, two);
7109 if (options->flags.diff_from_contents)
7110 return;
7112 if (options->flags.quick && options->skip_stat_unmatch &&
7113 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7114 diff_free_filespec_data(p->one);
7115 diff_free_filespec_data(p->two);
7116 return;
7119 options->flags.has_changes = 1;
7122 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7124 struct diff_filepair *pair;
7125 struct diff_filespec *one, *two;
7127 if (options->prefix &&
7128 strncmp(path, options->prefix, options->prefix_length))
7129 return NULL;
7131 one = alloc_filespec(path);
7132 two = alloc_filespec(path);
7133 pair = diff_queue(&diff_queued_diff, one, two);
7134 pair->is_unmerged = 1;
7135 return pair;
7138 static char *run_textconv(struct repository *r,
7139 const char *pgm,
7140 struct diff_filespec *spec,
7141 size_t *outsize)
7143 struct diff_tempfile *temp;
7144 struct child_process child = CHILD_PROCESS_INIT;
7145 struct strbuf buf = STRBUF_INIT;
7146 int err = 0;
7148 temp = prepare_temp_file(r, spec);
7149 strvec_push(&child.args, pgm);
7150 strvec_push(&child.args, temp->name);
7152 child.use_shell = 1;
7153 child.out = -1;
7154 if (start_command(&child)) {
7155 remove_tempfile();
7156 return NULL;
7159 if (strbuf_read(&buf, child.out, 0) < 0)
7160 err = error("error reading from textconv command '%s'", pgm);
7161 close(child.out);
7163 if (finish_command(&child) || err) {
7164 strbuf_release(&buf);
7165 remove_tempfile();
7166 return NULL;
7168 remove_tempfile();
7170 return strbuf_detach(&buf, outsize);
7173 size_t fill_textconv(struct repository *r,
7174 struct userdiff_driver *driver,
7175 struct diff_filespec *df,
7176 char **outbuf)
7178 size_t size;
7180 if (!driver) {
7181 if (!DIFF_FILE_VALID(df)) {
7182 *outbuf = "";
7183 return 0;
7185 if (diff_populate_filespec(r, df, NULL))
7186 die("unable to read files to diff");
7187 *outbuf = df->data;
7188 return df->size;
7191 if (!driver->textconv)
7192 BUG("fill_textconv called with non-textconv driver");
7194 if (driver->textconv_cache && df->oid_valid) {
7195 *outbuf = notes_cache_get(driver->textconv_cache,
7196 &df->oid,
7197 &size);
7198 if (*outbuf)
7199 return size;
7202 *outbuf = run_textconv(r, driver->textconv, df, &size);
7203 if (!*outbuf)
7204 die("unable to read files to diff");
7206 if (driver->textconv_cache && df->oid_valid) {
7207 /* ignore errors, as we might be in a readonly repository */
7208 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7209 size);
7211 * we could save up changes and flush them all at the end,
7212 * but we would need an extra call after all diffing is done.
7213 * Since generating a cache entry is the slow path anyway,
7214 * this extra overhead probably isn't a big deal.
7216 notes_cache_write(driver->textconv_cache);
7219 return size;
7222 int textconv_object(struct repository *r,
7223 const char *path,
7224 unsigned mode,
7225 const struct object_id *oid,
7226 int oid_valid,
7227 char **buf,
7228 unsigned long *buf_size)
7230 struct diff_filespec *df;
7231 struct userdiff_driver *textconv;
7233 df = alloc_filespec(path);
7234 fill_filespec(df, oid, oid_valid, mode);
7235 textconv = get_textconv(r, df);
7236 if (!textconv) {
7237 free_filespec(df);
7238 return 0;
7241 *buf_size = fill_textconv(r, textconv, df, buf);
7242 free_filespec(df);
7243 return 1;
7246 void setup_diff_pager(struct diff_options *opt)
7249 * If the user asked for our exit code, then either they want --quiet
7250 * or --exit-code. We should definitely not bother with a pager in the
7251 * former case, as we will generate no output. Since we still properly
7252 * report our exit code even when a pager is run, we _could_ run a
7253 * pager with --exit-code. But since we have not done so historically,
7254 * and because it is easy to find people oneline advising "git diff
7255 * --exit-code" in hooks and other scripts, we do not do so.
7257 if (!opt->flags.exit_with_status &&
7258 check_pager_config("diff") != 0)
7259 setup_pager();