common-main.c: move non-trace2 exit() behavior out of trace2.c
[git/debian.git] / diff.c
blobe71cf758861bd7596ce122611a4c92fe6b27d8c5
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "tempfile.h"
7 #include "quote.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "delta.h"
11 #include "xdiff-interface.h"
12 #include "color.h"
13 #include "attr.h"
14 #include "run-command.h"
15 #include "utf8.h"
16 #include "object-store.h"
17 #include "userdiff.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
20 #include "hashmap.h"
21 #include "mem-pool.h"
22 #include "ll-merge.h"
23 #include "string-list.h"
24 #include "strvec.h"
25 #include "graph.h"
26 #include "packfile.h"
27 #include "parse-options.h"
28 #include "help.h"
29 #include "promisor-remote.h"
30 #include "dir.h"
31 #include "strmap.h"
33 #ifdef NO_FAST_WORKING_DIRECTORY
34 #define FAST_WORKING_DIRECTORY 0
35 #else
36 #define FAST_WORKING_DIRECTORY 1
37 #endif
39 static int diff_detect_rename_default;
40 static int diff_indent_heuristic = 1;
41 static int diff_rename_limit_default = 1000;
42 static int diff_suppress_blank_empty;
43 static int diff_use_color_default = -1;
44 static int diff_color_moved_default;
45 static int diff_color_moved_ws_default;
46 static int diff_context_default = 3;
47 static int diff_interhunk_context_default;
48 static const char *diff_word_regex_cfg;
49 static const char *external_diff_cmd_cfg;
50 static const char *diff_order_file_cfg;
51 int diff_auto_refresh_index = 1;
52 static int diff_mnemonic_prefix;
53 static int diff_no_prefix;
54 static int diff_relative;
55 static int diff_stat_graph_width;
56 static int diff_dirstat_permille_default = 30;
57 static struct diff_options default_diff_options;
58 static long diff_algorithm;
59 static unsigned ws_error_highlight_default = WSEH_NEW;
61 static char diff_colors[][COLOR_MAXLEN] = {
62 GIT_COLOR_RESET,
63 GIT_COLOR_NORMAL, /* CONTEXT */
64 GIT_COLOR_BOLD, /* METAINFO */
65 GIT_COLOR_CYAN, /* FRAGINFO */
66 GIT_COLOR_RED, /* OLD */
67 GIT_COLOR_GREEN, /* NEW */
68 GIT_COLOR_YELLOW, /* COMMIT */
69 GIT_COLOR_BG_RED, /* WHITESPACE */
70 GIT_COLOR_NORMAL, /* FUNCINFO */
71 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
72 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
73 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
74 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
75 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
76 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
77 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
78 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
79 GIT_COLOR_FAINT, /* CONTEXT_DIM */
80 GIT_COLOR_FAINT_RED, /* OLD_DIM */
81 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
82 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
83 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
84 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
87 static const char *color_diff_slots[] = {
88 [DIFF_CONTEXT] = "context",
89 [DIFF_METAINFO] = "meta",
90 [DIFF_FRAGINFO] = "frag",
91 [DIFF_FILE_OLD] = "old",
92 [DIFF_FILE_NEW] = "new",
93 [DIFF_COMMIT] = "commit",
94 [DIFF_WHITESPACE] = "whitespace",
95 [DIFF_FUNCINFO] = "func",
96 [DIFF_FILE_OLD_MOVED] = "oldMoved",
97 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
98 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
99 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
100 [DIFF_FILE_NEW_MOVED] = "newMoved",
101 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
102 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
103 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
104 [DIFF_CONTEXT_DIM] = "contextDimmed",
105 [DIFF_FILE_OLD_DIM] = "oldDimmed",
106 [DIFF_FILE_NEW_DIM] = "newDimmed",
107 [DIFF_CONTEXT_BOLD] = "contextBold",
108 [DIFF_FILE_OLD_BOLD] = "oldBold",
109 [DIFF_FILE_NEW_BOLD] = "newBold",
112 define_list_config_array_extra(color_diff_slots, {"plain"});
114 static int parse_diff_color_slot(const char *var)
116 if (!strcasecmp(var, "plain"))
117 return DIFF_CONTEXT;
118 return LOOKUP_CONFIG(color_diff_slots, var);
121 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
122 struct strbuf *errmsg)
124 char *params_copy = xstrdup(params_string);
125 struct string_list params = STRING_LIST_INIT_NODUP;
126 int ret = 0;
127 int i;
129 if (*params_copy)
130 string_list_split_in_place(&params, params_copy, ',', -1);
131 for (i = 0; i < params.nr; i++) {
132 const char *p = params.items[i].string;
133 if (!strcmp(p, "changes")) {
134 options->flags.dirstat_by_line = 0;
135 options->flags.dirstat_by_file = 0;
136 } else if (!strcmp(p, "lines")) {
137 options->flags.dirstat_by_line = 1;
138 options->flags.dirstat_by_file = 0;
139 } else if (!strcmp(p, "files")) {
140 options->flags.dirstat_by_line = 0;
141 options->flags.dirstat_by_file = 1;
142 } else if (!strcmp(p, "noncumulative")) {
143 options->flags.dirstat_cumulative = 0;
144 } else if (!strcmp(p, "cumulative")) {
145 options->flags.dirstat_cumulative = 1;
146 } else if (isdigit(*p)) {
147 char *end;
148 int permille = strtoul(p, &end, 10) * 10;
149 if (*end == '.' && isdigit(*++end)) {
150 /* only use first digit */
151 permille += *end - '0';
152 /* .. and ignore any further digits */
153 while (isdigit(*++end))
154 ; /* nothing */
156 if (!*end)
157 options->dirstat_permille = permille;
158 else {
159 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
161 ret++;
163 } else {
164 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
165 ret++;
169 string_list_clear(&params, 0);
170 free(params_copy);
171 return ret;
174 static int parse_submodule_params(struct diff_options *options, const char *value)
176 if (!strcmp(value, "log"))
177 options->submodule_format = DIFF_SUBMODULE_LOG;
178 else if (!strcmp(value, "short"))
179 options->submodule_format = DIFF_SUBMODULE_SHORT;
180 else if (!strcmp(value, "diff"))
181 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
183 * Please update $__git_diff_submodule_formats in
184 * git-completion.bash when you add new formats.
186 else
187 return -1;
188 return 0;
191 int git_config_rename(const char *var, const char *value)
193 if (!value)
194 return DIFF_DETECT_RENAME;
195 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
196 return DIFF_DETECT_COPY;
197 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
200 long parse_algorithm_value(const char *value)
202 if (!value)
203 return -1;
204 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
205 return 0;
206 else if (!strcasecmp(value, "minimal"))
207 return XDF_NEED_MINIMAL;
208 else if (!strcasecmp(value, "patience"))
209 return XDF_PATIENCE_DIFF;
210 else if (!strcasecmp(value, "histogram"))
211 return XDF_HISTOGRAM_DIFF;
213 * Please update $__git_diff_algorithms in git-completion.bash
214 * when you add new algorithms.
216 return -1;
219 static int parse_one_token(const char **arg, const char *token)
221 const char *rest;
222 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
223 *arg = rest;
224 return 1;
226 return 0;
229 static int parse_ws_error_highlight(const char *arg)
231 const char *orig_arg = arg;
232 unsigned val = 0;
234 while (*arg) {
235 if (parse_one_token(&arg, "none"))
236 val = 0;
237 else if (parse_one_token(&arg, "default"))
238 val = WSEH_NEW;
239 else if (parse_one_token(&arg, "all"))
240 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
241 else if (parse_one_token(&arg, "new"))
242 val |= WSEH_NEW;
243 else if (parse_one_token(&arg, "old"))
244 val |= WSEH_OLD;
245 else if (parse_one_token(&arg, "context"))
246 val |= WSEH_CONTEXT;
247 else {
248 return -1 - (int)(arg - orig_arg);
250 if (*arg)
251 arg++;
253 return val;
257 * These are to give UI layer defaults.
258 * The core-level commands such as git-diff-files should
259 * never be affected by the setting of diff.renames
260 * the user happens to have in the configuration file.
262 void init_diff_ui_defaults(void)
264 diff_detect_rename_default = DIFF_DETECT_RENAME;
267 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
269 if (!strcmp(var, "diff.indentheuristic"))
270 diff_indent_heuristic = git_config_bool(var, value);
271 return 0;
274 static int parse_color_moved(const char *arg)
276 switch (git_parse_maybe_bool(arg)) {
277 case 0:
278 return COLOR_MOVED_NO;
279 case 1:
280 return COLOR_MOVED_DEFAULT;
281 default:
282 break;
285 if (!strcmp(arg, "no"))
286 return COLOR_MOVED_NO;
287 else if (!strcmp(arg, "plain"))
288 return COLOR_MOVED_PLAIN;
289 else if (!strcmp(arg, "blocks"))
290 return COLOR_MOVED_BLOCKS;
291 else if (!strcmp(arg, "zebra"))
292 return COLOR_MOVED_ZEBRA;
293 else if (!strcmp(arg, "default"))
294 return COLOR_MOVED_DEFAULT;
295 else if (!strcmp(arg, "dimmed-zebra"))
296 return COLOR_MOVED_ZEBRA_DIM;
297 else if (!strcmp(arg, "dimmed_zebra"))
298 return COLOR_MOVED_ZEBRA_DIM;
299 else
300 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
303 static unsigned parse_color_moved_ws(const char *arg)
305 int ret = 0;
306 struct string_list l = STRING_LIST_INIT_DUP;
307 struct string_list_item *i;
309 string_list_split(&l, arg, ',', -1);
311 for_each_string_list_item(i, &l) {
312 struct strbuf sb = STRBUF_INIT;
313 strbuf_addstr(&sb, i->string);
314 strbuf_trim(&sb);
316 if (!strcmp(sb.buf, "no"))
317 ret = 0;
318 else if (!strcmp(sb.buf, "ignore-space-change"))
319 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
320 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
321 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
322 else if (!strcmp(sb.buf, "ignore-all-space"))
323 ret |= XDF_IGNORE_WHITESPACE;
324 else if (!strcmp(sb.buf, "allow-indentation-change"))
325 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
326 else {
327 ret |= COLOR_MOVED_WS_ERROR;
328 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);
331 strbuf_release(&sb);
334 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
335 (ret & XDF_WHITESPACE_FLAGS)) {
336 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
337 ret |= COLOR_MOVED_WS_ERROR;
340 string_list_clear(&l, 0);
342 return ret;
345 int git_diff_ui_config(const char *var, const char *value, void *cb)
347 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
348 diff_use_color_default = git_config_colorbool(var, value);
349 return 0;
351 if (!strcmp(var, "diff.colormoved")) {
352 int cm = parse_color_moved(value);
353 if (cm < 0)
354 return -1;
355 diff_color_moved_default = cm;
356 return 0;
358 if (!strcmp(var, "diff.colormovedws")) {
359 unsigned cm = parse_color_moved_ws(value);
360 if (cm & COLOR_MOVED_WS_ERROR)
361 return -1;
362 diff_color_moved_ws_default = cm;
363 return 0;
365 if (!strcmp(var, "diff.context")) {
366 diff_context_default = git_config_int(var, value);
367 if (diff_context_default < 0)
368 return -1;
369 return 0;
371 if (!strcmp(var, "diff.interhunkcontext")) {
372 diff_interhunk_context_default = git_config_int(var, value);
373 if (diff_interhunk_context_default < 0)
374 return -1;
375 return 0;
377 if (!strcmp(var, "diff.renames")) {
378 diff_detect_rename_default = git_config_rename(var, value);
379 return 0;
381 if (!strcmp(var, "diff.autorefreshindex")) {
382 diff_auto_refresh_index = git_config_bool(var, value);
383 return 0;
385 if (!strcmp(var, "diff.mnemonicprefix")) {
386 diff_mnemonic_prefix = git_config_bool(var, value);
387 return 0;
389 if (!strcmp(var, "diff.noprefix")) {
390 diff_no_prefix = git_config_bool(var, value);
391 return 0;
393 if (!strcmp(var, "diff.relative")) {
394 diff_relative = git_config_bool(var, value);
395 return 0;
397 if (!strcmp(var, "diff.statgraphwidth")) {
398 diff_stat_graph_width = git_config_int(var, value);
399 return 0;
401 if (!strcmp(var, "diff.external"))
402 return git_config_string(&external_diff_cmd_cfg, var, value);
403 if (!strcmp(var, "diff.wordregex"))
404 return git_config_string(&diff_word_regex_cfg, var, value);
405 if (!strcmp(var, "diff.orderfile"))
406 return git_config_pathname(&diff_order_file_cfg, var, value);
408 if (!strcmp(var, "diff.ignoresubmodules"))
409 handle_ignore_submodules_arg(&default_diff_options, value);
411 if (!strcmp(var, "diff.submodule")) {
412 if (parse_submodule_params(&default_diff_options, value))
413 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
414 value);
415 return 0;
418 if (!strcmp(var, "diff.algorithm")) {
419 diff_algorithm = parse_algorithm_value(value);
420 if (diff_algorithm < 0)
421 return -1;
422 return 0;
425 if (git_color_config(var, value, cb) < 0)
426 return -1;
428 return git_diff_basic_config(var, value, cb);
431 int git_diff_basic_config(const char *var, const char *value, void *cb)
433 const char *name;
435 if (!strcmp(var, "diff.renamelimit")) {
436 diff_rename_limit_default = git_config_int(var, value);
437 return 0;
440 if (userdiff_config(var, value) < 0)
441 return -1;
443 if (skip_prefix(var, "diff.color.", &name) ||
444 skip_prefix(var, "color.diff.", &name)) {
445 int slot = parse_diff_color_slot(name);
446 if (slot < 0)
447 return 0;
448 if (!value)
449 return config_error_nonbool(var);
450 return color_parse(value, diff_colors[slot]);
453 if (!strcmp(var, "diff.wserrorhighlight")) {
454 int val = parse_ws_error_highlight(value);
455 if (val < 0)
456 return -1;
457 ws_error_highlight_default = val;
458 return 0;
461 /* like GNU diff's --suppress-blank-empty option */
462 if (!strcmp(var, "diff.suppressblankempty") ||
463 /* for backwards compatibility */
464 !strcmp(var, "diff.suppress-blank-empty")) {
465 diff_suppress_blank_empty = git_config_bool(var, value);
466 return 0;
469 if (!strcmp(var, "diff.dirstat")) {
470 struct strbuf errmsg = STRBUF_INIT;
471 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
472 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
473 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
474 errmsg.buf);
475 strbuf_release(&errmsg);
476 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
477 return 0;
480 if (git_diff_heuristic_config(var, value, cb) < 0)
481 return -1;
483 return git_default_config(var, value, cb);
486 static char *quote_two(const char *one, const char *two)
488 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
489 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
490 struct strbuf res = STRBUF_INIT;
492 if (need_one + need_two) {
493 strbuf_addch(&res, '"');
494 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
495 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
496 strbuf_addch(&res, '"');
497 } else {
498 strbuf_addstr(&res, one);
499 strbuf_addstr(&res, two);
501 return strbuf_detach(&res, NULL);
504 static const char *external_diff(void)
506 static const char *external_diff_cmd = NULL;
507 static int done_preparing = 0;
509 if (done_preparing)
510 return external_diff_cmd;
511 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
512 if (!external_diff_cmd)
513 external_diff_cmd = external_diff_cmd_cfg;
514 done_preparing = 1;
515 return external_diff_cmd;
519 * Keep track of files used for diffing. Sometimes such an entry
520 * refers to a temporary file, sometimes to an existing file, and
521 * sometimes to "/dev/null".
523 static struct diff_tempfile {
525 * filename external diff should read from, or NULL if this
526 * entry is currently not in use:
528 const char *name;
530 char hex[GIT_MAX_HEXSZ + 1];
531 char mode[10];
534 * If this diff_tempfile instance refers to a temporary file,
535 * this tempfile object is used to manage its lifetime.
537 struct tempfile *tempfile;
538 } diff_temp[2];
540 struct emit_callback {
541 int color_diff;
542 unsigned ws_rule;
543 int blank_at_eof_in_preimage;
544 int blank_at_eof_in_postimage;
545 int lno_in_preimage;
546 int lno_in_postimage;
547 const char **label_path;
548 struct diff_words_data *diff_words;
549 struct diff_options *opt;
550 struct strbuf *header;
553 static int count_lines(const char *data, int size)
555 int count, ch, completely_empty = 1, nl_just_seen = 0;
556 count = 0;
557 while (0 < size--) {
558 ch = *data++;
559 if (ch == '\n') {
560 count++;
561 nl_just_seen = 1;
562 completely_empty = 0;
564 else {
565 nl_just_seen = 0;
566 completely_empty = 0;
569 if (completely_empty)
570 return 0;
571 if (!nl_just_seen)
572 count++; /* no trailing newline */
573 return count;
576 static int fill_mmfile(struct repository *r, mmfile_t *mf,
577 struct diff_filespec *one)
579 if (!DIFF_FILE_VALID(one)) {
580 mf->ptr = (char *)""; /* does not matter */
581 mf->size = 0;
582 return 0;
584 else if (diff_populate_filespec(r, one, NULL))
585 return -1;
587 mf->ptr = one->data;
588 mf->size = one->size;
589 return 0;
592 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
593 static unsigned long diff_filespec_size(struct repository *r,
594 struct diff_filespec *one)
596 struct diff_populate_filespec_options dpf_options = {
597 .check_size_only = 1,
600 if (!DIFF_FILE_VALID(one))
601 return 0;
602 diff_populate_filespec(r, one, &dpf_options);
603 return one->size;
606 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
608 char *ptr = mf->ptr;
609 long size = mf->size;
610 int cnt = 0;
612 if (!size)
613 return cnt;
614 ptr += size - 1; /* pointing at the very end */
615 if (*ptr != '\n')
616 ; /* incomplete line */
617 else
618 ptr--; /* skip the last LF */
619 while (mf->ptr < ptr) {
620 char *prev_eol;
621 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
622 if (*prev_eol == '\n')
623 break;
624 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
625 break;
626 cnt++;
627 ptr = prev_eol - 1;
629 return cnt;
632 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
633 struct emit_callback *ecbdata)
635 int l1, l2, at;
636 unsigned ws_rule = ecbdata->ws_rule;
637 l1 = count_trailing_blank(mf1, ws_rule);
638 l2 = count_trailing_blank(mf2, ws_rule);
639 if (l2 <= l1) {
640 ecbdata->blank_at_eof_in_preimage = 0;
641 ecbdata->blank_at_eof_in_postimage = 0;
642 return;
644 at = count_lines(mf1->ptr, mf1->size);
645 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
647 at = count_lines(mf2->ptr, mf2->size);
648 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
651 static void emit_line_0(struct diff_options *o,
652 const char *set_sign, const char *set, unsigned reverse, const char *reset,
653 int first, const char *line, int len)
655 int has_trailing_newline, has_trailing_carriage_return;
656 int needs_reset = 0; /* at the end of the line */
657 FILE *file = o->file;
659 fputs(diff_line_prefix(o), file);
661 has_trailing_newline = (len > 0 && line[len-1] == '\n');
662 if (has_trailing_newline)
663 len--;
665 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
666 if (has_trailing_carriage_return)
667 len--;
669 if (!len && !first)
670 goto end_of_line;
672 if (reverse && want_color(o->use_color)) {
673 fputs(GIT_COLOR_REVERSE, file);
674 needs_reset = 1;
677 if (set_sign) {
678 fputs(set_sign, file);
679 needs_reset = 1;
682 if (first)
683 fputc(first, file);
685 if (!len)
686 goto end_of_line;
688 if (set) {
689 if (set_sign && set != set_sign)
690 fputs(reset, file);
691 fputs(set, file);
692 needs_reset = 1;
694 fwrite(line, len, 1, file);
695 needs_reset = 1; /* 'line' may contain color codes. */
697 end_of_line:
698 if (needs_reset)
699 fputs(reset, file);
700 if (has_trailing_carriage_return)
701 fputc('\r', file);
702 if (has_trailing_newline)
703 fputc('\n', file);
706 static void emit_line(struct diff_options *o, const char *set, const char *reset,
707 const char *line, int len)
709 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
712 enum diff_symbol {
713 DIFF_SYMBOL_BINARY_DIFF_HEADER,
714 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
715 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
716 DIFF_SYMBOL_BINARY_DIFF_BODY,
717 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
718 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
719 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
720 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
721 DIFF_SYMBOL_STATS_LINE,
722 DIFF_SYMBOL_WORD_DIFF,
723 DIFF_SYMBOL_STAT_SEP,
724 DIFF_SYMBOL_SUMMARY,
725 DIFF_SYMBOL_SUBMODULE_ADD,
726 DIFF_SYMBOL_SUBMODULE_DEL,
727 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
728 DIFF_SYMBOL_SUBMODULE_MODIFIED,
729 DIFF_SYMBOL_SUBMODULE_HEADER,
730 DIFF_SYMBOL_SUBMODULE_ERROR,
731 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
732 DIFF_SYMBOL_REWRITE_DIFF,
733 DIFF_SYMBOL_BINARY_FILES,
734 DIFF_SYMBOL_HEADER,
735 DIFF_SYMBOL_FILEPAIR_PLUS,
736 DIFF_SYMBOL_FILEPAIR_MINUS,
737 DIFF_SYMBOL_WORDS_PORCELAIN,
738 DIFF_SYMBOL_WORDS,
739 DIFF_SYMBOL_CONTEXT,
740 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
741 DIFF_SYMBOL_PLUS,
742 DIFF_SYMBOL_MINUS,
743 DIFF_SYMBOL_NO_LF_EOF,
744 DIFF_SYMBOL_CONTEXT_FRAGINFO,
745 DIFF_SYMBOL_CONTEXT_MARKER,
746 DIFF_SYMBOL_SEPARATOR
749 * Flags for content lines:
750 * 0..12 are whitespace rules
751 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
752 * 16 is marking if the line is blank at EOF
754 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
755 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
756 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
757 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
758 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
761 * This struct is used when we need to buffer the output of the diff output.
763 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
764 * into the pre/post image file. This pointer could be a union with the
765 * line pointer. By storing an offset into the file instead of the literal line,
766 * we can decrease the memory footprint for the buffered output. At first we
767 * may want to only have indirection for the content lines, but we could also
768 * enhance the state for emitting prefabricated lines, e.g. the similarity
769 * score line or hunk/file headers would only need to store a number or path
770 * and then the output can be constructed later on depending on state.
772 struct emitted_diff_symbol {
773 const char *line;
774 int len;
775 int flags;
776 int indent_off; /* Offset to first non-whitespace character */
777 int indent_width; /* The visual width of the indentation */
778 unsigned id;
779 enum diff_symbol s;
781 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
783 struct emitted_diff_symbols {
784 struct emitted_diff_symbol *buf;
785 int nr, alloc;
787 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
789 static void append_emitted_diff_symbol(struct diff_options *o,
790 struct emitted_diff_symbol *e)
792 struct emitted_diff_symbol *f;
794 ALLOC_GROW(o->emitted_symbols->buf,
795 o->emitted_symbols->nr + 1,
796 o->emitted_symbols->alloc);
797 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
799 memcpy(f, e, sizeof(struct emitted_diff_symbol));
800 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
803 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
805 if (!e)
806 return;
807 free(e->buf);
808 free(e);
811 struct moved_entry {
812 const struct emitted_diff_symbol *es;
813 struct moved_entry *next_line;
814 struct moved_entry *next_match;
817 struct moved_block {
818 struct moved_entry *match;
819 int wsd; /* The whitespace delta of this block */
822 #define INDENT_BLANKLINE INT_MIN
824 static void fill_es_indent_data(struct emitted_diff_symbol *es)
826 unsigned int off = 0, i;
827 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
828 const char *s = es->line;
829 const int len = es->len;
831 /* skip any \v \f \r at start of indentation */
832 while (s[off] == '\f' || s[off] == '\v' ||
833 (s[off] == '\r' && off < len - 1))
834 off++;
836 /* calculate the visual width of indentation */
837 while(1) {
838 if (s[off] == ' ') {
839 width++;
840 off++;
841 } else if (s[off] == '\t') {
842 width += tab_width - (width % tab_width);
843 while (s[++off] == '\t')
844 width += tab_width;
845 } else {
846 break;
850 /* check if this line is blank */
851 for (i = off; i < len; i++)
852 if (!isspace(s[i]))
853 break;
855 if (i == len) {
856 es->indent_width = INDENT_BLANKLINE;
857 es->indent_off = len;
858 } else {
859 es->indent_off = off;
860 es->indent_width = width;
864 static int compute_ws_delta(const struct emitted_diff_symbol *a,
865 const struct emitted_diff_symbol *b)
867 int a_width = a->indent_width,
868 b_width = b->indent_width;
870 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
871 return INDENT_BLANKLINE;
873 return a_width - b_width;
876 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
877 const struct emitted_diff_symbol *l,
878 struct moved_block *pmb)
880 int a_width = cur->es->indent_width, b_width = l->indent_width;
881 int delta;
883 /* The text of each line must match */
884 if (cur->es->id != l->id)
885 return 1;
888 * If 'l' and 'cur' are both blank then we don't need to check the
889 * indent. We only need to check cur as we know the strings match.
890 * */
891 if (a_width == INDENT_BLANKLINE)
892 return 0;
895 * The indent changes of the block are known and stored in pmb->wsd;
896 * however we need to check if the indent changes of the current line
897 * match those of the current block.
899 delta = b_width - a_width;
902 * If the previous lines of this block were all blank then set its
903 * whitespace delta.
905 if (pmb->wsd == INDENT_BLANKLINE)
906 pmb->wsd = delta;
908 return delta != pmb->wsd;
911 struct interned_diff_symbol {
912 struct hashmap_entry ent;
913 struct emitted_diff_symbol *es;
916 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
917 const struct hashmap_entry *eptr,
918 const struct hashmap_entry *entry_or_key,
919 const void *keydata)
921 const struct diff_options *diffopt = hashmap_cmp_fn_data;
922 const struct emitted_diff_symbol *a, *b;
923 unsigned flags = diffopt->color_moved_ws_handling
924 & XDF_WHITESPACE_FLAGS;
926 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
927 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
929 return !xdiff_compare_lines(a->line + a->indent_off,
930 a->len - a->indent_off,
931 b->line + b->indent_off,
932 b->len - b->indent_off, flags);
935 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
936 struct interned_diff_symbol *s)
938 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
939 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
940 l->len - l->indent_off, flags);
942 hashmap_entry_init(&s->ent, hash);
943 s->es = l;
946 struct moved_entry_list {
947 struct moved_entry *add, *del;
950 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
951 struct mem_pool *entry_mem_pool)
953 struct moved_entry *prev_line = NULL;
954 struct mem_pool interned_pool;
955 struct hashmap interned_map;
956 struct moved_entry_list *entry_list = NULL;
957 size_t entry_list_alloc = 0;
958 unsigned id = 0;
959 int n;
961 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
962 mem_pool_init(&interned_pool, 1024 * 1024);
964 for (n = 0; n < o->emitted_symbols->nr; n++) {
965 struct interned_diff_symbol key;
966 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
967 struct interned_diff_symbol *s;
968 struct moved_entry *entry;
970 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
971 prev_line = NULL;
972 continue;
975 if (o->color_moved_ws_handling &
976 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
977 fill_es_indent_data(l);
979 prepare_entry(o, l, &key);
980 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
981 if (s) {
982 l->id = s->es->id;
983 } else {
984 l->id = id;
985 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
986 hashmap_add(&interned_map,
987 memcpy(mem_pool_alloc(&interned_pool,
988 sizeof(key)),
989 &key, sizeof(key)));
991 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
992 entry->es = l;
993 entry->next_line = NULL;
994 if (prev_line && prev_line->es->s == l->s)
995 prev_line->next_line = entry;
996 prev_line = entry;
997 if (l->s == DIFF_SYMBOL_PLUS) {
998 entry->next_match = entry_list[l->id].add;
999 entry_list[l->id].add = entry;
1000 } else {
1001 entry->next_match = entry_list[l->id].del;
1002 entry_list[l->id].del = entry;
1006 hashmap_clear(&interned_map);
1007 mem_pool_discard(&interned_pool, 0);
1009 return entry_list;
1012 static void pmb_advance_or_null(struct diff_options *o,
1013 struct emitted_diff_symbol *l,
1014 struct moved_block *pmb,
1015 int *pmb_nr)
1017 int i, j;
1019 for (i = 0, j = 0; i < *pmb_nr; i++) {
1020 int match;
1021 struct moved_entry *prev = pmb[i].match;
1022 struct moved_entry *cur = (prev && prev->next_line) ?
1023 prev->next_line : NULL;
1025 if (o->color_moved_ws_handling &
1026 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1027 match = cur &&
1028 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1029 else
1030 match = cur && cur->es->id == l->id;
1032 if (match) {
1033 pmb[j] = pmb[i];
1034 pmb[j++].match = cur;
1037 *pmb_nr = j;
1040 static void fill_potential_moved_blocks(struct diff_options *o,
1041 struct moved_entry *match,
1042 struct emitted_diff_symbol *l,
1043 struct moved_block **pmb_p,
1044 int *pmb_alloc_p, int *pmb_nr_p)
1047 struct moved_block *pmb = *pmb_p;
1048 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1051 * The current line is the start of a new block.
1052 * Setup the set of potential blocks.
1054 for (; match; match = match->next_match) {
1055 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1056 if (o->color_moved_ws_handling &
1057 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1058 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1059 else
1060 pmb[pmb_nr].wsd = 0;
1061 pmb[pmb_nr++].match = match;
1064 *pmb_p = pmb;
1065 *pmb_alloc_p = pmb_alloc;
1066 *pmb_nr_p = pmb_nr;
1070 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1072 * Otherwise, if the last block has fewer alphanumeric characters than
1073 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1074 * that block.
1076 * The last block consists of the (n - block_length)'th line up to but not
1077 * including the nth line.
1079 * Returns 0 if the last block is empty or is unset by this function, non zero
1080 * otherwise.
1082 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1083 * Think of a way to unify them.
1085 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1086 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1087 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1089 int i, alnum_count = 0;
1090 if (o->color_moved == COLOR_MOVED_PLAIN)
1091 return block_length;
1092 for (i = 1; i < block_length + 1; i++) {
1093 const char *c = o->emitted_symbols->buf[n - i].line;
1094 for (; *c; c++) {
1095 if (!isalnum(*c))
1096 continue;
1097 alnum_count++;
1098 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1099 return 1;
1102 for (i = 1; i < block_length + 1; i++)
1103 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1104 return 0;
1107 /* Find blocks of moved code, delegate actual coloring decision to helper */
1108 static void mark_color_as_moved(struct diff_options *o,
1109 struct moved_entry_list *entry_list)
1111 struct moved_block *pmb = NULL; /* potentially moved blocks */
1112 int pmb_nr = 0, pmb_alloc = 0;
1113 int n, flipped_block = 0, block_length = 0;
1114 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1117 for (n = 0; n < o->emitted_symbols->nr; n++) {
1118 struct moved_entry *match = NULL;
1119 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1121 switch (l->s) {
1122 case DIFF_SYMBOL_PLUS:
1123 match = entry_list[l->id].del;
1124 break;
1125 case DIFF_SYMBOL_MINUS:
1126 match = entry_list[l->id].add;
1127 break;
1128 default:
1129 flipped_block = 0;
1132 if (pmb_nr && (!match || l->s != moved_symbol)) {
1133 if (!adjust_last_block(o, n, block_length) &&
1134 block_length > 1) {
1136 * Rewind in case there is another match
1137 * starting at the second line of the block
1139 match = NULL;
1140 n -= block_length;
1142 pmb_nr = 0;
1143 block_length = 0;
1144 flipped_block = 0;
1146 if (!match) {
1147 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1148 continue;
1151 if (o->color_moved == COLOR_MOVED_PLAIN) {
1152 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1153 continue;
1156 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1158 if (pmb_nr == 0) {
1159 int contiguous = adjust_last_block(o, n, block_length);
1161 if (!contiguous && block_length > 1)
1163 * Rewind in case there is another match
1164 * starting at the second line of the block
1166 n -= block_length;
1167 else
1168 fill_potential_moved_blocks(o, match, l,
1169 &pmb, &pmb_alloc,
1170 &pmb_nr);
1172 if (contiguous && pmb_nr && moved_symbol == l->s)
1173 flipped_block = (flipped_block + 1) % 2;
1174 else
1175 flipped_block = 0;
1177 if (pmb_nr)
1178 moved_symbol = l->s;
1179 else
1180 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1182 block_length = 0;
1185 if (pmb_nr) {
1186 block_length++;
1187 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1188 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1189 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1192 adjust_last_block(o, n, block_length);
1194 free(pmb);
1197 static void dim_moved_lines(struct diff_options *o)
1199 int n;
1200 for (n = 0; n < o->emitted_symbols->nr; n++) {
1201 struct emitted_diff_symbol *prev = (n != 0) ?
1202 &o->emitted_symbols->buf[n - 1] : NULL;
1203 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1204 struct emitted_diff_symbol *next =
1205 (n < o->emitted_symbols->nr - 1) ?
1206 &o->emitted_symbols->buf[n + 1] : NULL;
1208 /* Not a plus or minus line? */
1209 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1210 continue;
1212 /* Not a moved line? */
1213 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1214 continue;
1217 * If prev or next are not a plus or minus line,
1218 * pretend they don't exist
1220 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1221 prev->s != DIFF_SYMBOL_MINUS)
1222 prev = NULL;
1223 if (next && next->s != DIFF_SYMBOL_PLUS &&
1224 next->s != DIFF_SYMBOL_MINUS)
1225 next = NULL;
1227 /* Inside a block? */
1228 if ((prev &&
1229 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1230 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1231 (next &&
1232 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1233 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1234 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1235 continue;
1238 /* Check if we are at an interesting bound: */
1239 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1240 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1241 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1242 continue;
1243 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1244 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1245 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1246 continue;
1249 * The boundary to prev and next are not interesting,
1250 * so this line is not interesting as a whole
1252 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1256 static void emit_line_ws_markup(struct diff_options *o,
1257 const char *set_sign, const char *set,
1258 const char *reset,
1259 int sign_index, const char *line, int len,
1260 unsigned ws_rule, int blank_at_eof)
1262 const char *ws = NULL;
1263 int sign = o->output_indicators[sign_index];
1265 if (o->ws_error_highlight & ws_rule) {
1266 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1267 if (!*ws)
1268 ws = NULL;
1271 if (!ws && !set_sign)
1272 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1273 else if (!ws) {
1274 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1275 } else if (blank_at_eof)
1276 /* Blank line at EOF - paint '+' as well */
1277 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1278 else {
1279 /* Emit just the prefix, then the rest. */
1280 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1281 sign, "", 0);
1282 ws_check_emit(line, len, ws_rule,
1283 o->file, set, reset, ws);
1287 static void emit_diff_symbol_from_struct(struct diff_options *o,
1288 struct emitted_diff_symbol *eds)
1290 static const char *nneof = " No newline at end of file\n";
1291 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1292 struct strbuf sb = STRBUF_INIT;
1294 enum diff_symbol s = eds->s;
1295 const char *line = eds->line;
1296 int len = eds->len;
1297 unsigned flags = eds->flags;
1299 switch (s) {
1300 case DIFF_SYMBOL_NO_LF_EOF:
1301 context = diff_get_color_opt(o, DIFF_CONTEXT);
1302 reset = diff_get_color_opt(o, DIFF_RESET);
1303 putc('\n', o->file);
1304 emit_line_0(o, context, NULL, 0, reset, '\\',
1305 nneof, strlen(nneof));
1306 break;
1307 case DIFF_SYMBOL_SUBMODULE_HEADER:
1308 case DIFF_SYMBOL_SUBMODULE_ERROR:
1309 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1310 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1311 case DIFF_SYMBOL_SUMMARY:
1312 case DIFF_SYMBOL_STATS_LINE:
1313 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1314 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1315 emit_line(o, "", "", line, len);
1316 break;
1317 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1318 case DIFF_SYMBOL_CONTEXT_MARKER:
1319 context = diff_get_color_opt(o, DIFF_CONTEXT);
1320 reset = diff_get_color_opt(o, DIFF_RESET);
1321 emit_line(o, context, reset, line, len);
1322 break;
1323 case DIFF_SYMBOL_SEPARATOR:
1324 fprintf(o->file, "%s%c",
1325 diff_line_prefix(o),
1326 o->line_termination);
1327 break;
1328 case DIFF_SYMBOL_CONTEXT:
1329 set = diff_get_color_opt(o, DIFF_CONTEXT);
1330 reset = diff_get_color_opt(o, DIFF_RESET);
1331 set_sign = NULL;
1332 if (o->flags.dual_color_diffed_diffs) {
1333 char c = !len ? 0 : line[0];
1335 if (c == '+')
1336 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1337 else if (c == '@')
1338 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1339 else if (c == '-')
1340 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1342 emit_line_ws_markup(o, set_sign, set, reset,
1343 OUTPUT_INDICATOR_CONTEXT, line, len,
1344 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1345 break;
1346 case DIFF_SYMBOL_PLUS:
1347 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1348 DIFF_SYMBOL_MOVED_LINE_ALT |
1349 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1350 case DIFF_SYMBOL_MOVED_LINE |
1351 DIFF_SYMBOL_MOVED_LINE_ALT |
1352 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1353 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1354 break;
1355 case DIFF_SYMBOL_MOVED_LINE |
1356 DIFF_SYMBOL_MOVED_LINE_ALT:
1357 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1358 break;
1359 case DIFF_SYMBOL_MOVED_LINE |
1360 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1361 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1362 break;
1363 case DIFF_SYMBOL_MOVED_LINE:
1364 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1365 break;
1366 default:
1367 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1369 reset = diff_get_color_opt(o, DIFF_RESET);
1370 if (!o->flags.dual_color_diffed_diffs)
1371 set_sign = NULL;
1372 else {
1373 char c = !len ? 0 : line[0];
1375 set_sign = set;
1376 if (c == '-')
1377 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1378 else if (c == '@')
1379 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1380 else if (c == '+')
1381 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1382 else
1383 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1384 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1386 emit_line_ws_markup(o, set_sign, set, reset,
1387 OUTPUT_INDICATOR_NEW, line, len,
1388 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1389 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1390 break;
1391 case DIFF_SYMBOL_MINUS:
1392 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1393 DIFF_SYMBOL_MOVED_LINE_ALT |
1394 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1395 case DIFF_SYMBOL_MOVED_LINE |
1396 DIFF_SYMBOL_MOVED_LINE_ALT |
1397 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1398 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1399 break;
1400 case DIFF_SYMBOL_MOVED_LINE |
1401 DIFF_SYMBOL_MOVED_LINE_ALT:
1402 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1403 break;
1404 case DIFF_SYMBOL_MOVED_LINE |
1405 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1406 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1407 break;
1408 case DIFF_SYMBOL_MOVED_LINE:
1409 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1410 break;
1411 default:
1412 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1414 reset = diff_get_color_opt(o, DIFF_RESET);
1415 if (!o->flags.dual_color_diffed_diffs)
1416 set_sign = NULL;
1417 else {
1418 char c = !len ? 0 : line[0];
1420 set_sign = set;
1421 if (c == '+')
1422 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1423 else if (c == '@')
1424 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1425 else if (c == '-')
1426 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1427 else
1428 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1430 emit_line_ws_markup(o, set_sign, set, reset,
1431 OUTPUT_INDICATOR_OLD, line, len,
1432 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1433 break;
1434 case DIFF_SYMBOL_WORDS_PORCELAIN:
1435 context = diff_get_color_opt(o, DIFF_CONTEXT);
1436 reset = diff_get_color_opt(o, DIFF_RESET);
1437 emit_line(o, context, reset, line, len);
1438 fputs("~\n", o->file);
1439 break;
1440 case DIFF_SYMBOL_WORDS:
1441 context = diff_get_color_opt(o, DIFF_CONTEXT);
1442 reset = diff_get_color_opt(o, DIFF_RESET);
1444 * Skip the prefix character, if any. With
1445 * diff_suppress_blank_empty, there may be
1446 * none.
1448 if (line[0] != '\n') {
1449 line++;
1450 len--;
1452 emit_line(o, context, reset, line, len);
1453 break;
1454 case DIFF_SYMBOL_FILEPAIR_PLUS:
1455 meta = diff_get_color_opt(o, DIFF_METAINFO);
1456 reset = diff_get_color_opt(o, DIFF_RESET);
1457 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1458 line, reset,
1459 strchr(line, ' ') ? "\t" : "");
1460 break;
1461 case DIFF_SYMBOL_FILEPAIR_MINUS:
1462 meta = diff_get_color_opt(o, DIFF_METAINFO);
1463 reset = diff_get_color_opt(o, DIFF_RESET);
1464 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1465 line, reset,
1466 strchr(line, ' ') ? "\t" : "");
1467 break;
1468 case DIFF_SYMBOL_BINARY_FILES:
1469 case DIFF_SYMBOL_HEADER:
1470 fprintf(o->file, "%s", line);
1471 break;
1472 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1473 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1474 break;
1475 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1476 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1477 break;
1478 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1479 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1480 break;
1481 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1482 fputs(diff_line_prefix(o), o->file);
1483 fputc('\n', o->file);
1484 break;
1485 case DIFF_SYMBOL_REWRITE_DIFF:
1486 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1487 reset = diff_get_color_opt(o, DIFF_RESET);
1488 emit_line(o, fraginfo, reset, line, len);
1489 break;
1490 case DIFF_SYMBOL_SUBMODULE_ADD:
1491 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1492 reset = diff_get_color_opt(o, DIFF_RESET);
1493 emit_line(o, set, reset, line, len);
1494 break;
1495 case DIFF_SYMBOL_SUBMODULE_DEL:
1496 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1497 reset = diff_get_color_opt(o, DIFF_RESET);
1498 emit_line(o, set, reset, line, len);
1499 break;
1500 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1501 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1502 diff_line_prefix(o), line);
1503 break;
1504 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1505 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1506 diff_line_prefix(o), line);
1507 break;
1508 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1509 emit_line(o, "", "", " 0 files changed\n",
1510 strlen(" 0 files changed\n"));
1511 break;
1512 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1513 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1514 break;
1515 case DIFF_SYMBOL_WORD_DIFF:
1516 fprintf(o->file, "%.*s", len, line);
1517 break;
1518 case DIFF_SYMBOL_STAT_SEP:
1519 fputs(o->stat_sep, o->file);
1520 break;
1521 default:
1522 BUG("unknown diff symbol");
1524 strbuf_release(&sb);
1527 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1528 const char *line, int len, unsigned flags)
1530 struct emitted_diff_symbol e = {
1531 .line = line, .len = len, .flags = flags, .s = s
1534 if (o->emitted_symbols)
1535 append_emitted_diff_symbol(o, &e);
1536 else
1537 emit_diff_symbol_from_struct(o, &e);
1540 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1542 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1545 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1547 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1550 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1552 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1553 path, strlen(path), 0);
1556 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1558 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1559 path, strlen(path), 0);
1562 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1564 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1565 header, strlen(header), 0);
1568 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1570 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1573 void diff_emit_submodule_pipethrough(struct diff_options *o,
1574 const char *line, int len)
1576 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1579 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1581 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1582 ecbdata->blank_at_eof_in_preimage &&
1583 ecbdata->blank_at_eof_in_postimage &&
1584 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1585 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1586 return 0;
1587 return ws_blank_line(line, len, ecbdata->ws_rule);
1590 static void emit_add_line(struct emit_callback *ecbdata,
1591 const char *line, int len)
1593 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1594 if (new_blank_line_at_eof(ecbdata, line, len))
1595 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1597 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1600 static void emit_del_line(struct emit_callback *ecbdata,
1601 const char *line, int len)
1603 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1604 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1607 static void emit_context_line(struct emit_callback *ecbdata,
1608 const char *line, int len)
1610 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1611 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1614 static void emit_hunk_header(struct emit_callback *ecbdata,
1615 const char *line, int len)
1617 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1618 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1619 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1620 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1621 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1622 static const char atat[2] = { '@', '@' };
1623 const char *cp, *ep;
1624 struct strbuf msgbuf = STRBUF_INIT;
1625 int org_len = len;
1626 int i = 1;
1629 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1630 * it always is at least 10 bytes long.
1632 if (len < 10 ||
1633 memcmp(line, atat, 2) ||
1634 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1635 emit_diff_symbol(ecbdata->opt,
1636 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1637 return;
1639 ep += 2; /* skip over @@ */
1641 /* The hunk header in fraginfo color */
1642 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1643 strbuf_addstr(&msgbuf, reverse);
1644 strbuf_addstr(&msgbuf, frag);
1645 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1646 strbuf_add(&msgbuf, atat, sizeof(atat));
1647 else
1648 strbuf_add(&msgbuf, line, ep - line);
1649 strbuf_addstr(&msgbuf, reset);
1652 * trailing "\r\n"
1654 for ( ; i < 3; i++)
1655 if (line[len - i] == '\r' || line[len - i] == '\n')
1656 len--;
1658 /* blank before the func header */
1659 for (cp = ep; ep - line < len; ep++)
1660 if (*ep != ' ' && *ep != '\t')
1661 break;
1662 if (ep != cp) {
1663 strbuf_addstr(&msgbuf, context);
1664 strbuf_add(&msgbuf, cp, ep - cp);
1665 strbuf_addstr(&msgbuf, reset);
1668 if (ep < line + len) {
1669 strbuf_addstr(&msgbuf, func);
1670 strbuf_add(&msgbuf, ep, line + len - ep);
1671 strbuf_addstr(&msgbuf, reset);
1674 strbuf_add(&msgbuf, line + len, org_len - len);
1675 strbuf_complete_line(&msgbuf);
1676 emit_diff_symbol(ecbdata->opt,
1677 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1678 strbuf_release(&msgbuf);
1681 static struct diff_tempfile *claim_diff_tempfile(void)
1683 int i;
1684 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1685 if (!diff_temp[i].name)
1686 return diff_temp + i;
1687 BUG("diff is failing to clean up its tempfiles");
1690 static void remove_tempfile(void)
1692 int i;
1693 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1694 if (is_tempfile_active(diff_temp[i].tempfile))
1695 delete_tempfile(&diff_temp[i].tempfile);
1696 diff_temp[i].name = NULL;
1700 static void add_line_count(struct strbuf *out, int count)
1702 switch (count) {
1703 case 0:
1704 strbuf_addstr(out, "0,0");
1705 break;
1706 case 1:
1707 strbuf_addstr(out, "1");
1708 break;
1709 default:
1710 strbuf_addf(out, "1,%d", count);
1711 break;
1715 static void emit_rewrite_lines(struct emit_callback *ecb,
1716 int prefix, const char *data, int size)
1718 const char *endp = NULL;
1720 while (0 < size) {
1721 int len;
1723 endp = memchr(data, '\n', size);
1724 len = endp ? (endp - data + 1) : size;
1725 if (prefix != '+') {
1726 ecb->lno_in_preimage++;
1727 emit_del_line(ecb, data, len);
1728 } else {
1729 ecb->lno_in_postimage++;
1730 emit_add_line(ecb, data, len);
1732 size -= len;
1733 data += len;
1735 if (!endp)
1736 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1739 static void emit_rewrite_diff(const char *name_a,
1740 const char *name_b,
1741 struct diff_filespec *one,
1742 struct diff_filespec *two,
1743 struct userdiff_driver *textconv_one,
1744 struct userdiff_driver *textconv_two,
1745 struct diff_options *o)
1747 int lc_a, lc_b;
1748 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1749 const char *a_prefix, *b_prefix;
1750 char *data_one, *data_two;
1751 size_t size_one, size_two;
1752 struct emit_callback ecbdata;
1753 struct strbuf out = STRBUF_INIT;
1755 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1756 a_prefix = o->b_prefix;
1757 b_prefix = o->a_prefix;
1758 } else {
1759 a_prefix = o->a_prefix;
1760 b_prefix = o->b_prefix;
1763 name_a += (*name_a == '/');
1764 name_b += (*name_b == '/');
1766 strbuf_reset(&a_name);
1767 strbuf_reset(&b_name);
1768 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1769 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1771 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1772 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1774 memset(&ecbdata, 0, sizeof(ecbdata));
1775 ecbdata.color_diff = want_color(o->use_color);
1776 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1777 ecbdata.opt = o;
1778 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1779 mmfile_t mf1, mf2;
1780 mf1.ptr = (char *)data_one;
1781 mf2.ptr = (char *)data_two;
1782 mf1.size = size_one;
1783 mf2.size = size_two;
1784 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1786 ecbdata.lno_in_preimage = 1;
1787 ecbdata.lno_in_postimage = 1;
1789 lc_a = count_lines(data_one, size_one);
1790 lc_b = count_lines(data_two, size_two);
1792 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1793 a_name.buf, a_name.len, 0);
1794 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1795 b_name.buf, b_name.len, 0);
1797 strbuf_addstr(&out, "@@ -");
1798 if (!o->irreversible_delete)
1799 add_line_count(&out, lc_a);
1800 else
1801 strbuf_addstr(&out, "?,?");
1802 strbuf_addstr(&out, " +");
1803 add_line_count(&out, lc_b);
1804 strbuf_addstr(&out, " @@\n");
1805 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1806 strbuf_release(&out);
1808 if (lc_a && !o->irreversible_delete)
1809 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1810 if (lc_b)
1811 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1812 if (textconv_one)
1813 free((char *)data_one);
1814 if (textconv_two)
1815 free((char *)data_two);
1818 struct diff_words_buffer {
1819 mmfile_t text;
1820 unsigned long alloc;
1821 struct diff_words_orig {
1822 const char *begin, *end;
1823 } *orig;
1824 int orig_nr, orig_alloc;
1827 static void diff_words_append(char *line, unsigned long len,
1828 struct diff_words_buffer *buffer)
1830 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1831 line++;
1832 len--;
1833 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1834 buffer->text.size += len;
1835 buffer->text.ptr[buffer->text.size] = '\0';
1838 struct diff_words_style_elem {
1839 const char *prefix;
1840 const char *suffix;
1841 const char *color; /* NULL; filled in by the setup code if
1842 * color is enabled */
1845 struct diff_words_style {
1846 enum diff_words_type type;
1847 struct diff_words_style_elem new_word, old_word, ctx;
1848 const char *newline;
1851 static struct diff_words_style diff_words_styles[] = {
1852 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1853 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1854 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1857 struct diff_words_data {
1858 struct diff_words_buffer minus, plus;
1859 const char *current_plus;
1860 int last_minus;
1861 struct diff_options *opt;
1862 regex_t *word_regex;
1863 enum diff_words_type type;
1864 struct diff_words_style *style;
1867 static int fn_out_diff_words_write_helper(struct diff_options *o,
1868 struct diff_words_style_elem *st_el,
1869 const char *newline,
1870 size_t count, const char *buf)
1872 int print = 0;
1873 struct strbuf sb = STRBUF_INIT;
1875 while (count) {
1876 char *p = memchr(buf, '\n', count);
1877 if (print)
1878 strbuf_addstr(&sb, diff_line_prefix(o));
1880 if (p != buf) {
1881 const char *reset = st_el->color && *st_el->color ?
1882 GIT_COLOR_RESET : NULL;
1883 if (st_el->color && *st_el->color)
1884 strbuf_addstr(&sb, st_el->color);
1885 strbuf_addstr(&sb, st_el->prefix);
1886 strbuf_add(&sb, buf, p ? p - buf : count);
1887 strbuf_addstr(&sb, st_el->suffix);
1888 if (reset)
1889 strbuf_addstr(&sb, reset);
1891 if (!p)
1892 goto out;
1894 strbuf_addstr(&sb, newline);
1895 count -= p + 1 - buf;
1896 buf = p + 1;
1897 print = 1;
1898 if (count) {
1899 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1900 sb.buf, sb.len, 0);
1901 strbuf_reset(&sb);
1905 out:
1906 if (sb.len)
1907 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1908 sb.buf, sb.len, 0);
1909 strbuf_release(&sb);
1910 return 0;
1914 * '--color-words' algorithm can be described as:
1916 * 1. collect the minus/plus lines of a diff hunk, divided into
1917 * minus-lines and plus-lines;
1919 * 2. break both minus-lines and plus-lines into words and
1920 * place them into two mmfile_t with one word for each line;
1922 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1924 * And for the common parts of the both file, we output the plus side text.
1925 * diff_words->current_plus is used to trace the current position of the plus file
1926 * which printed. diff_words->last_minus is used to trace the last minus word
1927 * printed.
1929 * For '--graph' to work with '--color-words', we need to output the graph prefix
1930 * on each line of color words output. Generally, there are two conditions on
1931 * which we should output the prefix.
1933 * 1. diff_words->last_minus == 0 &&
1934 * diff_words->current_plus == diff_words->plus.text.ptr
1936 * that is: the plus text must start as a new line, and if there is no minus
1937 * word printed, a graph prefix must be printed.
1939 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1940 * *(diff_words->current_plus - 1) == '\n'
1942 * that is: a graph prefix must be printed following a '\n'
1944 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1946 if ((diff_words->last_minus == 0 &&
1947 diff_words->current_plus == diff_words->plus.text.ptr) ||
1948 (diff_words->current_plus > diff_words->plus.text.ptr &&
1949 *(diff_words->current_plus - 1) == '\n')) {
1950 return 1;
1951 } else {
1952 return 0;
1956 static void fn_out_diff_words_aux(void *priv,
1957 long minus_first, long minus_len,
1958 long plus_first, long plus_len,
1959 const char *func, long funclen)
1961 struct diff_words_data *diff_words = priv;
1962 struct diff_words_style *style = diff_words->style;
1963 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1964 struct diff_options *opt = diff_words->opt;
1965 const char *line_prefix;
1967 assert(opt);
1968 line_prefix = diff_line_prefix(opt);
1970 /* POSIX requires that first be decremented by one if len == 0... */
1971 if (minus_len) {
1972 minus_begin = diff_words->minus.orig[minus_first].begin;
1973 minus_end =
1974 diff_words->minus.orig[minus_first + minus_len - 1].end;
1975 } else
1976 minus_begin = minus_end =
1977 diff_words->minus.orig[minus_first].end;
1979 if (plus_len) {
1980 plus_begin = diff_words->plus.orig[plus_first].begin;
1981 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1982 } else
1983 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1985 if (color_words_output_graph_prefix(diff_words)) {
1986 fputs(line_prefix, diff_words->opt->file);
1988 if (diff_words->current_plus != plus_begin) {
1989 fn_out_diff_words_write_helper(diff_words->opt,
1990 &style->ctx, style->newline,
1991 plus_begin - diff_words->current_plus,
1992 diff_words->current_plus);
1994 if (minus_begin != minus_end) {
1995 fn_out_diff_words_write_helper(diff_words->opt,
1996 &style->old_word, style->newline,
1997 minus_end - minus_begin, minus_begin);
1999 if (plus_begin != plus_end) {
2000 fn_out_diff_words_write_helper(diff_words->opt,
2001 &style->new_word, style->newline,
2002 plus_end - plus_begin, plus_begin);
2005 diff_words->current_plus = plus_end;
2006 diff_words->last_minus = minus_first;
2009 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2010 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2011 int *begin, int *end)
2013 while (word_regex && *begin < buffer->size) {
2014 regmatch_t match[1];
2015 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2016 buffer->size - *begin, 1, match, 0)) {
2017 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2018 '\n', match[0].rm_eo - match[0].rm_so);
2019 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2020 *begin += match[0].rm_so;
2021 if (*begin == *end)
2022 (*begin)++;
2023 else
2024 return *begin > *end;
2025 } else {
2026 return -1;
2030 /* find the next word */
2031 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2032 (*begin)++;
2033 if (*begin >= buffer->size)
2034 return -1;
2036 /* find the end of the word */
2037 *end = *begin + 1;
2038 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2039 (*end)++;
2041 return 0;
2045 * This function splits the words in buffer->text, stores the list with
2046 * newline separator into out, and saves the offsets of the original words
2047 * in buffer->orig.
2049 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2050 regex_t *word_regex)
2052 int i, j;
2053 long alloc = 0;
2055 out->size = 0;
2056 out->ptr = NULL;
2058 /* fake an empty "0th" word */
2059 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2060 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2061 buffer->orig_nr = 1;
2063 for (i = 0; i < buffer->text.size; i++) {
2064 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2065 return;
2067 /* store original boundaries */
2068 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2069 buffer->orig_alloc);
2070 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2071 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2072 buffer->orig_nr++;
2074 /* store one word */
2075 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2076 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2077 out->ptr[out->size + j - i] = '\n';
2078 out->size += j - i + 1;
2080 i = j - 1;
2084 /* this executes the word diff on the accumulated buffers */
2085 static void diff_words_show(struct diff_words_data *diff_words)
2087 xpparam_t xpp;
2088 xdemitconf_t xecfg;
2089 mmfile_t minus, plus;
2090 struct diff_words_style *style = diff_words->style;
2092 struct diff_options *opt = diff_words->opt;
2093 const char *line_prefix;
2095 assert(opt);
2096 line_prefix = diff_line_prefix(opt);
2098 /* special case: only removal */
2099 if (!diff_words->plus.text.size) {
2100 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2101 line_prefix, strlen(line_prefix), 0);
2102 fn_out_diff_words_write_helper(diff_words->opt,
2103 &style->old_word, style->newline,
2104 diff_words->minus.text.size,
2105 diff_words->minus.text.ptr);
2106 diff_words->minus.text.size = 0;
2107 return;
2110 diff_words->current_plus = diff_words->plus.text.ptr;
2111 diff_words->last_minus = 0;
2113 memset(&xpp, 0, sizeof(xpp));
2114 memset(&xecfg, 0, sizeof(xecfg));
2115 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2116 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2117 xpp.flags = 0;
2118 /* as only the hunk header will be parsed, we need a 0-context */
2119 xecfg.ctxlen = 0;
2120 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2121 diff_words, &xpp, &xecfg))
2122 die("unable to generate word diff");
2123 free(minus.ptr);
2124 free(plus.ptr);
2125 if (diff_words->current_plus != diff_words->plus.text.ptr +
2126 diff_words->plus.text.size) {
2127 if (color_words_output_graph_prefix(diff_words))
2128 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2129 line_prefix, strlen(line_prefix), 0);
2130 fn_out_diff_words_write_helper(diff_words->opt,
2131 &style->ctx, style->newline,
2132 diff_words->plus.text.ptr + diff_words->plus.text.size
2133 - diff_words->current_plus, diff_words->current_plus);
2135 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2138 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2139 static void diff_words_flush(struct emit_callback *ecbdata)
2141 struct diff_options *wo = ecbdata->diff_words->opt;
2143 if (ecbdata->diff_words->minus.text.size ||
2144 ecbdata->diff_words->plus.text.size)
2145 diff_words_show(ecbdata->diff_words);
2147 if (wo->emitted_symbols) {
2148 struct diff_options *o = ecbdata->opt;
2149 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2150 int i;
2153 * NEEDSWORK:
2154 * Instead of appending each, concat all words to a line?
2156 for (i = 0; i < wol->nr; i++)
2157 append_emitted_diff_symbol(o, &wol->buf[i]);
2159 for (i = 0; i < wol->nr; i++)
2160 free((void *)wol->buf[i].line);
2162 wol->nr = 0;
2166 static void diff_filespec_load_driver(struct diff_filespec *one,
2167 struct index_state *istate)
2169 /* Use already-loaded driver */
2170 if (one->driver)
2171 return;
2173 if (S_ISREG(one->mode))
2174 one->driver = userdiff_find_by_path(istate, one->path);
2176 /* Fallback to default settings */
2177 if (!one->driver)
2178 one->driver = userdiff_find_by_name("default");
2181 static const char *userdiff_word_regex(struct diff_filespec *one,
2182 struct index_state *istate)
2184 diff_filespec_load_driver(one, istate);
2185 return one->driver->word_regex;
2188 static void init_diff_words_data(struct emit_callback *ecbdata,
2189 struct diff_options *orig_opts,
2190 struct diff_filespec *one,
2191 struct diff_filespec *two)
2193 int i;
2194 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2195 memcpy(o, orig_opts, sizeof(struct diff_options));
2197 CALLOC_ARRAY(ecbdata->diff_words, 1);
2198 ecbdata->diff_words->type = o->word_diff;
2199 ecbdata->diff_words->opt = o;
2201 if (orig_opts->emitted_symbols)
2202 CALLOC_ARRAY(o->emitted_symbols, 1);
2204 if (!o->word_regex)
2205 o->word_regex = userdiff_word_regex(one, o->repo->index);
2206 if (!o->word_regex)
2207 o->word_regex = userdiff_word_regex(two, o->repo->index);
2208 if (!o->word_regex)
2209 o->word_regex = diff_word_regex_cfg;
2210 if (o->word_regex) {
2211 ecbdata->diff_words->word_regex = (regex_t *)
2212 xmalloc(sizeof(regex_t));
2213 if (regcomp(ecbdata->diff_words->word_regex,
2214 o->word_regex,
2215 REG_EXTENDED | REG_NEWLINE))
2216 die("invalid regular expression: %s",
2217 o->word_regex);
2219 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2220 if (o->word_diff == diff_words_styles[i].type) {
2221 ecbdata->diff_words->style =
2222 &diff_words_styles[i];
2223 break;
2226 if (want_color(o->use_color)) {
2227 struct diff_words_style *st = ecbdata->diff_words->style;
2228 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2229 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2230 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2234 static void free_diff_words_data(struct emit_callback *ecbdata)
2236 if (ecbdata->diff_words) {
2237 diff_words_flush(ecbdata);
2238 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2239 free (ecbdata->diff_words->opt);
2240 free (ecbdata->diff_words->minus.text.ptr);
2241 free (ecbdata->diff_words->minus.orig);
2242 free (ecbdata->diff_words->plus.text.ptr);
2243 free (ecbdata->diff_words->plus.orig);
2244 if (ecbdata->diff_words->word_regex) {
2245 regfree(ecbdata->diff_words->word_regex);
2246 free(ecbdata->diff_words->word_regex);
2248 FREE_AND_NULL(ecbdata->diff_words);
2252 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2254 if (want_color(diff_use_color))
2255 return diff_colors[ix];
2256 return "";
2259 const char *diff_line_prefix(struct diff_options *opt)
2261 struct strbuf *msgbuf;
2262 if (!opt->output_prefix)
2263 return "";
2265 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2266 return msgbuf->buf;
2269 static unsigned long sane_truncate_line(char *line, unsigned long len)
2271 const char *cp;
2272 unsigned long allot;
2273 size_t l = len;
2275 cp = line;
2276 allot = l;
2277 while (0 < l) {
2278 (void) utf8_width(&cp, &l);
2279 if (!cp)
2280 break; /* truncated in the middle? */
2282 return allot - l;
2285 static void find_lno(const char *line, struct emit_callback *ecbdata)
2287 const char *p;
2288 ecbdata->lno_in_preimage = 0;
2289 ecbdata->lno_in_postimage = 0;
2290 p = strchr(line, '-');
2291 if (!p)
2292 return; /* cannot happen */
2293 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2294 p = strchr(p, '+');
2295 if (!p)
2296 return; /* cannot happen */
2297 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2300 static int fn_out_consume(void *priv, char *line, unsigned long len)
2302 struct emit_callback *ecbdata = priv;
2303 struct diff_options *o = ecbdata->opt;
2305 o->found_changes = 1;
2307 if (ecbdata->header) {
2308 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2309 ecbdata->header->buf, ecbdata->header->len, 0);
2310 strbuf_reset(ecbdata->header);
2311 ecbdata->header = NULL;
2314 if (ecbdata->label_path[0]) {
2315 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2316 ecbdata->label_path[0],
2317 strlen(ecbdata->label_path[0]), 0);
2318 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2319 ecbdata->label_path[1],
2320 strlen(ecbdata->label_path[1]), 0);
2321 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2324 if (diff_suppress_blank_empty
2325 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2326 line[0] = '\n';
2327 len = 1;
2330 if (line[0] == '@') {
2331 if (ecbdata->diff_words)
2332 diff_words_flush(ecbdata);
2333 len = sane_truncate_line(line, len);
2334 find_lno(line, ecbdata);
2335 emit_hunk_header(ecbdata, line, len);
2336 return 0;
2339 if (ecbdata->diff_words) {
2340 enum diff_symbol s =
2341 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2342 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2343 if (line[0] == '-') {
2344 diff_words_append(line, len,
2345 &ecbdata->diff_words->minus);
2346 return 0;
2347 } else if (line[0] == '+') {
2348 diff_words_append(line, len,
2349 &ecbdata->diff_words->plus);
2350 return 0;
2351 } else if (starts_with(line, "\\ ")) {
2353 * Eat the "no newline at eof" marker as if we
2354 * saw a "+" or "-" line with nothing on it,
2355 * and return without diff_words_flush() to
2356 * defer processing. If this is the end of
2357 * preimage, more "+" lines may come after it.
2359 return 0;
2361 diff_words_flush(ecbdata);
2362 emit_diff_symbol(o, s, line, len, 0);
2363 return 0;
2366 switch (line[0]) {
2367 case '+':
2368 ecbdata->lno_in_postimage++;
2369 emit_add_line(ecbdata, line + 1, len - 1);
2370 break;
2371 case '-':
2372 ecbdata->lno_in_preimage++;
2373 emit_del_line(ecbdata, line + 1, len - 1);
2374 break;
2375 case ' ':
2376 ecbdata->lno_in_postimage++;
2377 ecbdata->lno_in_preimage++;
2378 emit_context_line(ecbdata, line + 1, len - 1);
2379 break;
2380 default:
2381 /* incomplete line at the end */
2382 ecbdata->lno_in_preimage++;
2383 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2384 line, len, 0);
2385 break;
2387 return 0;
2390 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2392 const char *old_name = a;
2393 const char *new_name = b;
2394 int pfx_length, sfx_length;
2395 int pfx_adjust_for_slash;
2396 int len_a = strlen(a);
2397 int len_b = strlen(b);
2398 int a_midlen, b_midlen;
2399 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2400 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2402 if (qlen_a || qlen_b) {
2403 quote_c_style(a, name, NULL, 0);
2404 strbuf_addstr(name, " => ");
2405 quote_c_style(b, name, NULL, 0);
2406 return;
2409 /* Find common prefix */
2410 pfx_length = 0;
2411 while (*old_name && *new_name && *old_name == *new_name) {
2412 if (*old_name == '/')
2413 pfx_length = old_name - a + 1;
2414 old_name++;
2415 new_name++;
2418 /* Find common suffix */
2419 old_name = a + len_a;
2420 new_name = b + len_b;
2421 sfx_length = 0;
2423 * If there is a common prefix, it must end in a slash. In
2424 * that case we let this loop run 1 into the prefix to see the
2425 * same slash.
2427 * If there is no common prefix, we cannot do this as it would
2428 * underrun the input strings.
2430 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2431 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2432 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2433 *old_name == *new_name) {
2434 if (*old_name == '/')
2435 sfx_length = len_a - (old_name - a);
2436 old_name--;
2437 new_name--;
2441 * pfx{mid-a => mid-b}sfx
2442 * {pfx-a => pfx-b}sfx
2443 * pfx{sfx-a => sfx-b}
2444 * name-a => name-b
2446 a_midlen = len_a - pfx_length - sfx_length;
2447 b_midlen = len_b - pfx_length - sfx_length;
2448 if (a_midlen < 0)
2449 a_midlen = 0;
2450 if (b_midlen < 0)
2451 b_midlen = 0;
2453 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2454 if (pfx_length + sfx_length) {
2455 strbuf_add(name, a, pfx_length);
2456 strbuf_addch(name, '{');
2458 strbuf_add(name, a + pfx_length, a_midlen);
2459 strbuf_addstr(name, " => ");
2460 strbuf_add(name, b + pfx_length, b_midlen);
2461 if (pfx_length + sfx_length) {
2462 strbuf_addch(name, '}');
2463 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2467 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2468 const char *name_a,
2469 const char *name_b)
2471 struct diffstat_file *x;
2472 CALLOC_ARRAY(x, 1);
2473 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2474 diffstat->files[diffstat->nr++] = x;
2475 if (name_b) {
2476 x->from_name = xstrdup(name_a);
2477 x->name = xstrdup(name_b);
2478 x->is_renamed = 1;
2480 else {
2481 x->from_name = NULL;
2482 x->name = xstrdup(name_a);
2484 return x;
2487 static int diffstat_consume(void *priv, char *line, unsigned long len)
2489 struct diffstat_t *diffstat = priv;
2490 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2492 if (line[0] == '+')
2493 x->added++;
2494 else if (line[0] == '-')
2495 x->deleted++;
2496 return 0;
2499 const char mime_boundary_leader[] = "------------";
2501 static int scale_linear(int it, int width, int max_change)
2503 if (!it)
2504 return 0;
2506 * make sure that at least one '-' or '+' is printed if
2507 * there is any change to this path. The easiest way is to
2508 * scale linearly as if the allotted width is one column shorter
2509 * than it is, and then add 1 to the result.
2511 return 1 + (it * (width - 1) / max_change);
2514 static void show_graph(struct strbuf *out, char ch, int cnt,
2515 const char *set, const char *reset)
2517 if (cnt <= 0)
2518 return;
2519 strbuf_addstr(out, set);
2520 strbuf_addchars(out, ch, cnt);
2521 strbuf_addstr(out, reset);
2524 static void fill_print_name(struct diffstat_file *file)
2526 struct strbuf pname = STRBUF_INIT;
2528 if (file->print_name)
2529 return;
2531 if (file->is_renamed)
2532 pprint_rename(&pname, file->from_name, file->name);
2533 else
2534 quote_c_style(file->name, &pname, NULL, 0);
2536 if (file->comments)
2537 strbuf_addf(&pname, " (%s)", file->comments);
2539 file->print_name = strbuf_detach(&pname, NULL);
2542 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2543 int files, int insertions, int deletions)
2545 struct strbuf sb = STRBUF_INIT;
2547 if (!files) {
2548 assert(insertions == 0 && deletions == 0);
2549 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2550 NULL, 0, 0);
2551 return;
2554 strbuf_addf(&sb,
2555 (files == 1) ? " %d file changed" : " %d files changed",
2556 files);
2559 * For binary diff, the caller may want to print "x files
2560 * changed" with insertions == 0 && deletions == 0.
2562 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2563 * is probably less confusing (i.e skip over "2 files changed
2564 * but nothing about added/removed lines? Is this a bug in Git?").
2566 if (insertions || deletions == 0) {
2567 strbuf_addf(&sb,
2568 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2569 insertions);
2572 if (deletions || insertions == 0) {
2573 strbuf_addf(&sb,
2574 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2575 deletions);
2577 strbuf_addch(&sb, '\n');
2578 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2579 sb.buf, sb.len, 0);
2580 strbuf_release(&sb);
2583 void print_stat_summary(FILE *fp, int files,
2584 int insertions, int deletions)
2586 struct diff_options o;
2587 memset(&o, 0, sizeof(o));
2588 o.file = fp;
2590 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2593 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2595 int i, len, add, del, adds = 0, dels = 0;
2596 uintmax_t max_change = 0, max_len = 0;
2597 int total_files = data->nr, count;
2598 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2599 const char *reset, *add_c, *del_c;
2600 int extra_shown = 0;
2601 const char *line_prefix = diff_line_prefix(options);
2602 struct strbuf out = STRBUF_INIT;
2604 if (data->nr == 0)
2605 return;
2607 count = options->stat_count ? options->stat_count : data->nr;
2609 reset = diff_get_color_opt(options, DIFF_RESET);
2610 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2611 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2614 * Find the longest filename and max number of changes
2616 for (i = 0; (i < count) && (i < data->nr); i++) {
2617 struct diffstat_file *file = data->files[i];
2618 uintmax_t change = file->added + file->deleted;
2620 if (!file->is_interesting && (change == 0)) {
2621 count++; /* not shown == room for one more */
2622 continue;
2624 fill_print_name(file);
2625 len = strlen(file->print_name);
2626 if (max_len < len)
2627 max_len = len;
2629 if (file->is_unmerged) {
2630 /* "Unmerged" is 8 characters */
2631 bin_width = bin_width < 8 ? 8 : bin_width;
2632 continue;
2634 if (file->is_binary) {
2635 /* "Bin XXX -> YYY bytes" */
2636 int w = 14 + decimal_width(file->added)
2637 + decimal_width(file->deleted);
2638 bin_width = bin_width < w ? w : bin_width;
2639 /* Display change counts aligned with "Bin" */
2640 number_width = 3;
2641 continue;
2644 if (max_change < change)
2645 max_change = change;
2647 count = i; /* where we can stop scanning in data->files[] */
2650 * We have width = stat_width or term_columns() columns total.
2651 * We want a maximum of min(max_len, stat_name_width) for the name part.
2652 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2653 * We also need 1 for " " and 4 + decimal_width(max_change)
2654 * for " | NNNN " and one the empty column at the end, altogether
2655 * 6 + decimal_width(max_change).
2657 * If there's not enough space, we will use the smaller of
2658 * stat_name_width (if set) and 5/8*width for the filename,
2659 * and the rest for constant elements + graph part, but no more
2660 * than stat_graph_width for the graph part.
2661 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2662 * for the standard terminal size).
2664 * In other words: stat_width limits the maximum width, and
2665 * stat_name_width fixes the maximum width of the filename,
2666 * and is also used to divide available columns if there
2667 * aren't enough.
2669 * Binary files are displayed with "Bin XXX -> YYY bytes"
2670 * instead of the change count and graph. This part is treated
2671 * similarly to the graph part, except that it is not
2672 * "scaled". If total width is too small to accommodate the
2673 * guaranteed minimum width of the filename part and the
2674 * separators and this message, this message will "overflow"
2675 * making the line longer than the maximum width.
2678 if (options->stat_width == -1)
2679 width = term_columns() - strlen(line_prefix);
2680 else
2681 width = options->stat_width ? options->stat_width : 80;
2682 number_width = decimal_width(max_change) > number_width ?
2683 decimal_width(max_change) : number_width;
2685 if (options->stat_graph_width == -1)
2686 options->stat_graph_width = diff_stat_graph_width;
2689 * Guarantee 3/8*16==6 for the graph part
2690 * and 5/8*16==10 for the filename part
2692 if (width < 16 + 6 + number_width)
2693 width = 16 + 6 + number_width;
2696 * First assign sizes that are wanted, ignoring available width.
2697 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2698 * starting from "XXX" should fit in graph_width.
2700 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2701 if (options->stat_graph_width &&
2702 options->stat_graph_width < graph_width)
2703 graph_width = options->stat_graph_width;
2705 name_width = (options->stat_name_width > 0 &&
2706 options->stat_name_width < max_len) ?
2707 options->stat_name_width : max_len;
2710 * Adjust adjustable widths not to exceed maximum width
2712 if (name_width + number_width + 6 + graph_width > width) {
2713 if (graph_width > width * 3/8 - number_width - 6) {
2714 graph_width = width * 3/8 - number_width - 6;
2715 if (graph_width < 6)
2716 graph_width = 6;
2719 if (options->stat_graph_width &&
2720 graph_width > options->stat_graph_width)
2721 graph_width = options->stat_graph_width;
2722 if (name_width > width - number_width - 6 - graph_width)
2723 name_width = width - number_width - 6 - graph_width;
2724 else
2725 graph_width = width - number_width - 6 - name_width;
2729 * From here name_width is the width of the name area,
2730 * and graph_width is the width of the graph area.
2731 * max_change is used to scale graph properly.
2733 for (i = 0; i < count; i++) {
2734 const char *prefix = "";
2735 struct diffstat_file *file = data->files[i];
2736 char *name = file->print_name;
2737 uintmax_t added = file->added;
2738 uintmax_t deleted = file->deleted;
2739 int name_len;
2741 if (!file->is_interesting && (added + deleted == 0))
2742 continue;
2745 * "scale" the filename
2747 len = name_width;
2748 name_len = strlen(name);
2749 if (name_width < name_len) {
2750 char *slash;
2751 prefix = "...";
2752 len -= 3;
2753 name += name_len - len;
2754 slash = strchr(name, '/');
2755 if (slash)
2756 name = slash;
2759 if (file->is_binary) {
2760 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2761 strbuf_addf(&out, " %*s", number_width, "Bin");
2762 if (!added && !deleted) {
2763 strbuf_addch(&out, '\n');
2764 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2765 out.buf, out.len, 0);
2766 strbuf_reset(&out);
2767 continue;
2769 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2770 del_c, deleted, reset);
2771 strbuf_addstr(&out, " -> ");
2772 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2773 add_c, added, reset);
2774 strbuf_addstr(&out, " bytes\n");
2775 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2776 out.buf, out.len, 0);
2777 strbuf_reset(&out);
2778 continue;
2780 else if (file->is_unmerged) {
2781 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2782 strbuf_addstr(&out, " Unmerged\n");
2783 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2784 out.buf, out.len, 0);
2785 strbuf_reset(&out);
2786 continue;
2790 * scale the add/delete
2792 add = added;
2793 del = deleted;
2795 if (graph_width <= max_change) {
2796 int total = scale_linear(add + del, graph_width, max_change);
2797 if (total < 2 && add && del)
2798 /* width >= 2 due to the sanity check */
2799 total = 2;
2800 if (add < del) {
2801 add = scale_linear(add, graph_width, max_change);
2802 del = total - add;
2803 } else {
2804 del = scale_linear(del, graph_width, max_change);
2805 add = total - del;
2808 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2809 strbuf_addf(&out, " %*"PRIuMAX"%s",
2810 number_width, added + deleted,
2811 added + deleted ? " " : "");
2812 show_graph(&out, '+', add, add_c, reset);
2813 show_graph(&out, '-', del, del_c, reset);
2814 strbuf_addch(&out, '\n');
2815 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2816 out.buf, out.len, 0);
2817 strbuf_reset(&out);
2820 for (i = 0; i < data->nr; i++) {
2821 struct diffstat_file *file = data->files[i];
2822 uintmax_t added = file->added;
2823 uintmax_t deleted = file->deleted;
2825 if (file->is_unmerged ||
2826 (!file->is_interesting && (added + deleted == 0))) {
2827 total_files--;
2828 continue;
2831 if (!file->is_binary) {
2832 adds += added;
2833 dels += deleted;
2835 if (i < count)
2836 continue;
2837 if (!extra_shown)
2838 emit_diff_symbol(options,
2839 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2840 NULL, 0, 0);
2841 extra_shown = 1;
2844 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2845 strbuf_release(&out);
2848 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2850 int i, adds = 0, dels = 0, total_files = data->nr;
2852 if (data->nr == 0)
2853 return;
2855 for (i = 0; i < data->nr; i++) {
2856 int added = data->files[i]->added;
2857 int deleted = data->files[i]->deleted;
2859 if (data->files[i]->is_unmerged ||
2860 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2861 total_files--;
2862 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2863 adds += added;
2864 dels += deleted;
2867 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2870 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2872 int i;
2874 if (data->nr == 0)
2875 return;
2877 for (i = 0; i < data->nr; i++) {
2878 struct diffstat_file *file = data->files[i];
2880 fprintf(options->file, "%s", diff_line_prefix(options));
2882 if (file->is_binary)
2883 fprintf(options->file, "-\t-\t");
2884 else
2885 fprintf(options->file,
2886 "%"PRIuMAX"\t%"PRIuMAX"\t",
2887 file->added, file->deleted);
2888 if (options->line_termination) {
2889 fill_print_name(file);
2890 if (!file->is_renamed)
2891 write_name_quoted(file->name, options->file,
2892 options->line_termination);
2893 else {
2894 fputs(file->print_name, options->file);
2895 putc(options->line_termination, options->file);
2897 } else {
2898 if (file->is_renamed) {
2899 putc('\0', options->file);
2900 write_name_quoted(file->from_name, options->file, '\0');
2902 write_name_quoted(file->name, options->file, '\0');
2907 struct dirstat_file {
2908 const char *name;
2909 unsigned long changed;
2912 struct dirstat_dir {
2913 struct dirstat_file *files;
2914 int alloc, nr, permille, cumulative;
2917 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2918 unsigned long changed, const char *base, int baselen)
2920 unsigned long sum_changes = 0;
2921 unsigned int sources = 0;
2922 const char *line_prefix = diff_line_prefix(opt);
2924 while (dir->nr) {
2925 struct dirstat_file *f = dir->files;
2926 int namelen = strlen(f->name);
2927 unsigned long changes;
2928 char *slash;
2930 if (namelen < baselen)
2931 break;
2932 if (memcmp(f->name, base, baselen))
2933 break;
2934 slash = strchr(f->name + baselen, '/');
2935 if (slash) {
2936 int newbaselen = slash + 1 - f->name;
2937 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2938 sources++;
2939 } else {
2940 changes = f->changed;
2941 dir->files++;
2942 dir->nr--;
2943 sources += 2;
2945 sum_changes += changes;
2949 * We don't report dirstat's for
2950 * - the top level
2951 * - or cases where everything came from a single directory
2952 * under this directory (sources == 1).
2954 if (baselen && sources != 1) {
2955 if (sum_changes) {
2956 int permille = sum_changes * 1000 / changed;
2957 if (permille >= dir->permille) {
2958 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2959 permille / 10, permille % 10, baselen, base);
2960 if (!dir->cumulative)
2961 return 0;
2965 return sum_changes;
2968 static int dirstat_compare(const void *_a, const void *_b)
2970 const struct dirstat_file *a = _a;
2971 const struct dirstat_file *b = _b;
2972 return strcmp(a->name, b->name);
2975 static void show_dirstat(struct diff_options *options)
2977 int i;
2978 unsigned long changed;
2979 struct dirstat_dir dir;
2980 struct diff_queue_struct *q = &diff_queued_diff;
2982 dir.files = NULL;
2983 dir.alloc = 0;
2984 dir.nr = 0;
2985 dir.permille = options->dirstat_permille;
2986 dir.cumulative = options->flags.dirstat_cumulative;
2988 changed = 0;
2989 for (i = 0; i < q->nr; i++) {
2990 struct diff_filepair *p = q->queue[i];
2991 const char *name;
2992 unsigned long copied, added, damage;
2993 struct diff_populate_filespec_options dpf_options = {
2994 .check_size_only = 1,
2997 name = p->two->path ? p->two->path : p->one->path;
2999 if (p->one->oid_valid && p->two->oid_valid &&
3000 oideq(&p->one->oid, &p->two->oid)) {
3002 * The SHA1 has not changed, so pre-/post-content is
3003 * identical. We can therefore skip looking at the
3004 * file contents altogether.
3006 damage = 0;
3007 goto found_damage;
3010 if (options->flags.dirstat_by_file) {
3012 * In --dirstat-by-file mode, we don't really need to
3013 * look at the actual file contents at all.
3014 * The fact that the SHA1 changed is enough for us to
3015 * add this file to the list of results
3016 * (with each file contributing equal damage).
3018 damage = 1;
3019 goto found_damage;
3022 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3023 diff_populate_filespec(options->repo, p->one, NULL);
3024 diff_populate_filespec(options->repo, p->two, NULL);
3025 diffcore_count_changes(options->repo,
3026 p->one, p->two, NULL, NULL,
3027 &copied, &added);
3028 diff_free_filespec_data(p->one);
3029 diff_free_filespec_data(p->two);
3030 } else if (DIFF_FILE_VALID(p->one)) {
3031 diff_populate_filespec(options->repo, p->one, &dpf_options);
3032 copied = added = 0;
3033 diff_free_filespec_data(p->one);
3034 } else if (DIFF_FILE_VALID(p->two)) {
3035 diff_populate_filespec(options->repo, p->two, &dpf_options);
3036 copied = 0;
3037 added = p->two->size;
3038 diff_free_filespec_data(p->two);
3039 } else
3040 continue;
3043 * Original minus copied is the removed material,
3044 * added is the new material. They are both damages
3045 * made to the preimage.
3046 * If the resulting damage is zero, we know that
3047 * diffcore_count_changes() considers the two entries to
3048 * be identical, but since the oid changed, we
3049 * know that there must have been _some_ kind of change,
3050 * so we force all entries to have damage > 0.
3052 damage = (p->one->size - copied) + added;
3053 if (!damage)
3054 damage = 1;
3056 found_damage:
3057 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3058 dir.files[dir.nr].name = name;
3059 dir.files[dir.nr].changed = damage;
3060 changed += damage;
3061 dir.nr++;
3064 /* This can happen even with many files, if everything was renames */
3065 if (!changed)
3066 return;
3068 /* Show all directories with more than x% of the changes */
3069 QSORT(dir.files, dir.nr, dirstat_compare);
3070 gather_dirstat(options, &dir, changed, "", 0);
3073 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3075 int i;
3076 unsigned long changed;
3077 struct dirstat_dir dir;
3079 if (data->nr == 0)
3080 return;
3082 dir.files = NULL;
3083 dir.alloc = 0;
3084 dir.nr = 0;
3085 dir.permille = options->dirstat_permille;
3086 dir.cumulative = options->flags.dirstat_cumulative;
3088 changed = 0;
3089 for (i = 0; i < data->nr; i++) {
3090 struct diffstat_file *file = data->files[i];
3091 unsigned long damage = file->added + file->deleted;
3092 if (file->is_binary)
3094 * binary files counts bytes, not lines. Must find some
3095 * way to normalize binary bytes vs. textual lines.
3096 * The following heuristic assumes that there are 64
3097 * bytes per "line".
3098 * This is stupid and ugly, but very cheap...
3100 damage = DIV_ROUND_UP(damage, 64);
3101 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3102 dir.files[dir.nr].name = file->name;
3103 dir.files[dir.nr].changed = damage;
3104 changed += damage;
3105 dir.nr++;
3108 /* This can happen even with many files, if everything was renames */
3109 if (!changed)
3110 return;
3112 /* Show all directories with more than x% of the changes */
3113 QSORT(dir.files, dir.nr, dirstat_compare);
3114 gather_dirstat(options, &dir, changed, "", 0);
3117 static void free_diffstat_file(struct diffstat_file *f)
3119 free(f->print_name);
3120 free(f->name);
3121 free(f->from_name);
3122 free(f);
3125 void free_diffstat_info(struct diffstat_t *diffstat)
3127 int i;
3128 for (i = 0; i < diffstat->nr; i++)
3129 free_diffstat_file(diffstat->files[i]);
3130 free(diffstat->files);
3133 struct checkdiff_t {
3134 const char *filename;
3135 int lineno;
3136 int conflict_marker_size;
3137 struct diff_options *o;
3138 unsigned ws_rule;
3139 unsigned status;
3142 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3144 char firstchar;
3145 int cnt;
3147 if (len < marker_size + 1)
3148 return 0;
3149 firstchar = line[0];
3150 switch (firstchar) {
3151 case '=': case '>': case '<': case '|':
3152 break;
3153 default:
3154 return 0;
3156 for (cnt = 1; cnt < marker_size; cnt++)
3157 if (line[cnt] != firstchar)
3158 return 0;
3159 /* line[1] through line[marker_size-1] are same as firstchar */
3160 if (len < marker_size + 1 || !isspace(line[marker_size]))
3161 return 0;
3162 return 1;
3165 static void checkdiff_consume_hunk(void *priv,
3166 long ob, long on, long nb, long nn,
3167 const char *func, long funclen)
3170 struct checkdiff_t *data = priv;
3171 data->lineno = nb - 1;
3174 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3176 struct checkdiff_t *data = priv;
3177 int marker_size = data->conflict_marker_size;
3178 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3179 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3180 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3181 char *err;
3182 const char *line_prefix;
3184 assert(data->o);
3185 line_prefix = diff_line_prefix(data->o);
3187 if (line[0] == '+') {
3188 unsigned bad;
3189 data->lineno++;
3190 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3191 data->status |= 1;
3192 fprintf(data->o->file,
3193 "%s%s:%d: leftover conflict marker\n",
3194 line_prefix, data->filename, data->lineno);
3196 bad = ws_check(line + 1, len - 1, data->ws_rule);
3197 if (!bad)
3198 return 0;
3199 data->status |= bad;
3200 err = whitespace_error_string(bad);
3201 fprintf(data->o->file, "%s%s:%d: %s.\n",
3202 line_prefix, data->filename, data->lineno, err);
3203 free(err);
3204 emit_line(data->o, set, reset, line, 1);
3205 ws_check_emit(line + 1, len - 1, data->ws_rule,
3206 data->o->file, set, reset, ws);
3207 } else if (line[0] == ' ') {
3208 data->lineno++;
3210 return 0;
3213 static unsigned char *deflate_it(char *data,
3214 unsigned long size,
3215 unsigned long *result_size)
3217 int bound;
3218 unsigned char *deflated;
3219 git_zstream stream;
3221 git_deflate_init(&stream, zlib_compression_level);
3222 bound = git_deflate_bound(&stream, size);
3223 deflated = xmalloc(bound);
3224 stream.next_out = deflated;
3225 stream.avail_out = bound;
3227 stream.next_in = (unsigned char *)data;
3228 stream.avail_in = size;
3229 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3230 ; /* nothing */
3231 git_deflate_end(&stream);
3232 *result_size = stream.total_out;
3233 return deflated;
3236 static void emit_binary_diff_body(struct diff_options *o,
3237 mmfile_t *one, mmfile_t *two)
3239 void *cp;
3240 void *delta;
3241 void *deflated;
3242 void *data;
3243 unsigned long orig_size;
3244 unsigned long delta_size;
3245 unsigned long deflate_size;
3246 unsigned long data_size;
3248 /* We could do deflated delta, or we could do just deflated two,
3249 * whichever is smaller.
3251 delta = NULL;
3252 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3253 if (one->size && two->size) {
3254 delta = diff_delta(one->ptr, one->size,
3255 two->ptr, two->size,
3256 &delta_size, deflate_size);
3257 if (delta) {
3258 void *to_free = delta;
3259 orig_size = delta_size;
3260 delta = deflate_it(delta, delta_size, &delta_size);
3261 free(to_free);
3265 if (delta && delta_size < deflate_size) {
3266 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3267 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3268 s, strlen(s), 0);
3269 free(s);
3270 free(deflated);
3271 data = delta;
3272 data_size = delta_size;
3273 } else {
3274 char *s = xstrfmt("%lu", two->size);
3275 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3276 s, strlen(s), 0);
3277 free(s);
3278 free(delta);
3279 data = deflated;
3280 data_size = deflate_size;
3283 /* emit data encoded in base85 */
3284 cp = data;
3285 while (data_size) {
3286 int len;
3287 int bytes = (52 < data_size) ? 52 : data_size;
3288 char line[71];
3289 data_size -= bytes;
3290 if (bytes <= 26)
3291 line[0] = bytes + 'A' - 1;
3292 else
3293 line[0] = bytes - 26 + 'a' - 1;
3294 encode_85(line + 1, cp, bytes);
3295 cp = (char *) cp + bytes;
3297 len = strlen(line);
3298 line[len++] = '\n';
3299 line[len] = '\0';
3301 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3302 line, len, 0);
3304 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3305 free(data);
3308 static void emit_binary_diff(struct diff_options *o,
3309 mmfile_t *one, mmfile_t *two)
3311 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3312 emit_binary_diff_body(o, one, two);
3313 emit_binary_diff_body(o, two, one);
3316 int diff_filespec_is_binary(struct repository *r,
3317 struct diff_filespec *one)
3319 struct diff_populate_filespec_options dpf_options = {
3320 .check_binary = 1,
3323 if (one->is_binary == -1) {
3324 diff_filespec_load_driver(one, r->index);
3325 if (one->driver->binary != -1)
3326 one->is_binary = one->driver->binary;
3327 else {
3328 if (!one->data && DIFF_FILE_VALID(one))
3329 diff_populate_filespec(r, one, &dpf_options);
3330 if (one->is_binary == -1 && one->data)
3331 one->is_binary = buffer_is_binary(one->data,
3332 one->size);
3333 if (one->is_binary == -1)
3334 one->is_binary = 0;
3337 return one->is_binary;
3340 static const struct userdiff_funcname *
3341 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3343 diff_filespec_load_driver(one, o->repo->index);
3344 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3347 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3349 if (!options->a_prefix)
3350 options->a_prefix = a;
3351 if (!options->b_prefix)
3352 options->b_prefix = b;
3355 struct userdiff_driver *get_textconv(struct repository *r,
3356 struct diff_filespec *one)
3358 if (!DIFF_FILE_VALID(one))
3359 return NULL;
3361 diff_filespec_load_driver(one, r->index);
3362 return userdiff_get_textconv(r, one->driver);
3365 static struct strbuf *additional_headers(struct diff_options *o,
3366 const char *path)
3368 if (!o->additional_path_headers)
3369 return NULL;
3370 return strmap_get(o->additional_path_headers, path);
3373 static void add_formatted_headers(struct strbuf *msg,
3374 struct strbuf *more_headers,
3375 const char *line_prefix,
3376 const char *meta,
3377 const char *reset)
3379 char *next, *newline;
3381 for (next = more_headers->buf; *next; next = newline) {
3382 newline = strchrnul(next, '\n');
3383 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3384 (int)(newline - next), next, reset);
3385 if (*newline)
3386 newline++;
3390 static void builtin_diff(const char *name_a,
3391 const char *name_b,
3392 struct diff_filespec *one,
3393 struct diff_filespec *two,
3394 const char *xfrm_msg,
3395 int must_show_header,
3396 struct diff_options *o,
3397 int complete_rewrite)
3399 mmfile_t mf1, mf2;
3400 const char *lbl[2];
3401 char *a_one, *b_two;
3402 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3403 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3404 const char *a_prefix, *b_prefix;
3405 struct userdiff_driver *textconv_one = NULL;
3406 struct userdiff_driver *textconv_two = NULL;
3407 struct strbuf header = STRBUF_INIT;
3408 const char *line_prefix = diff_line_prefix(o);
3410 diff_set_mnemonic_prefix(o, "a/", "b/");
3411 if (o->flags.reverse_diff) {
3412 a_prefix = o->b_prefix;
3413 b_prefix = o->a_prefix;
3414 } else {
3415 a_prefix = o->a_prefix;
3416 b_prefix = o->b_prefix;
3419 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3420 (!one->mode || S_ISGITLINK(one->mode)) &&
3421 (!two->mode || S_ISGITLINK(two->mode))) {
3422 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3423 &one->oid, &two->oid,
3424 two->dirty_submodule);
3425 return;
3426 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3427 (!one->mode || S_ISGITLINK(one->mode)) &&
3428 (!two->mode || S_ISGITLINK(two->mode))) {
3429 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3430 &one->oid, &two->oid,
3431 two->dirty_submodule);
3432 return;
3435 if (o->flags.allow_textconv) {
3436 textconv_one = get_textconv(o->repo, one);
3437 textconv_two = get_textconv(o->repo, two);
3440 /* Never use a non-valid filename anywhere if at all possible */
3441 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3442 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3444 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3445 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3446 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3447 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3448 if (!DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two)) {
3450 * We should only reach this point for pairs from
3451 * create_filepairs_for_header_only_notifications(). For
3452 * these, we should avoid the "/dev/null" special casing
3453 * above, meaning we avoid showing such pairs as either
3454 * "new file" or "deleted file" below.
3456 lbl[0] = a_one;
3457 lbl[1] = b_two;
3459 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3460 if (lbl[0][0] == '/') {
3461 /* /dev/null */
3462 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3463 if (xfrm_msg)
3464 strbuf_addstr(&header, xfrm_msg);
3465 must_show_header = 1;
3467 else if (lbl[1][0] == '/') {
3468 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3469 if (xfrm_msg)
3470 strbuf_addstr(&header, xfrm_msg);
3471 must_show_header = 1;
3473 else {
3474 if (one->mode != two->mode) {
3475 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3476 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3477 must_show_header = 1;
3479 if (xfrm_msg)
3480 strbuf_addstr(&header, xfrm_msg);
3483 * we do not run diff between different kind
3484 * of objects.
3486 if ((one->mode ^ two->mode) & S_IFMT)
3487 goto free_ab_and_return;
3488 if (complete_rewrite &&
3489 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3490 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3491 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3492 header.buf, header.len, 0);
3493 strbuf_reset(&header);
3494 emit_rewrite_diff(name_a, name_b, one, two,
3495 textconv_one, textconv_two, o);
3496 o->found_changes = 1;
3497 goto free_ab_and_return;
3501 if (o->irreversible_delete && lbl[1][0] == '/') {
3502 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3503 header.len, 0);
3504 strbuf_reset(&header);
3505 goto free_ab_and_return;
3506 } else if (!o->flags.text &&
3507 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3508 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3509 struct strbuf sb = STRBUF_INIT;
3510 if (!one->data && !two->data &&
3511 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3512 !o->flags.binary) {
3513 if (oideq(&one->oid, &two->oid)) {
3514 if (must_show_header)
3515 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3516 header.buf, header.len,
3518 goto free_ab_and_return;
3520 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3521 header.buf, header.len, 0);
3522 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3523 diff_line_prefix(o), lbl[0], lbl[1]);
3524 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3525 sb.buf, sb.len, 0);
3526 strbuf_release(&sb);
3527 goto free_ab_and_return;
3529 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3530 fill_mmfile(o->repo, &mf2, two) < 0)
3531 die("unable to read files to diff");
3532 /* Quite common confusing case */
3533 if (mf1.size == mf2.size &&
3534 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3535 if (must_show_header)
3536 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3537 header.buf, header.len, 0);
3538 goto free_ab_and_return;
3540 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3541 strbuf_reset(&header);
3542 if (o->flags.binary)
3543 emit_binary_diff(o, &mf1, &mf2);
3544 else {
3545 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3546 diff_line_prefix(o), lbl[0], lbl[1]);
3547 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3548 sb.buf, sb.len, 0);
3549 strbuf_release(&sb);
3551 o->found_changes = 1;
3552 } else {
3553 /* Crazy xdl interfaces.. */
3554 const char *diffopts;
3555 const char *v;
3556 xpparam_t xpp;
3557 xdemitconf_t xecfg;
3558 struct emit_callback ecbdata;
3559 const struct userdiff_funcname *pe;
3561 if (must_show_header) {
3562 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3563 header.buf, header.len, 0);
3564 strbuf_reset(&header);
3567 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3568 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3570 pe = diff_funcname_pattern(o, one);
3571 if (!pe)
3572 pe = diff_funcname_pattern(o, two);
3574 memset(&xpp, 0, sizeof(xpp));
3575 memset(&xecfg, 0, sizeof(xecfg));
3576 memset(&ecbdata, 0, sizeof(ecbdata));
3577 if (o->flags.suppress_diff_headers)
3578 lbl[0] = NULL;
3579 ecbdata.label_path = lbl;
3580 ecbdata.color_diff = want_color(o->use_color);
3581 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3582 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3583 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3584 ecbdata.opt = o;
3585 if (header.len && !o->flags.suppress_diff_headers)
3586 ecbdata.header = &header;
3587 xpp.flags = o->xdl_opts;
3588 xpp.ignore_regex = o->ignore_regex;
3589 xpp.ignore_regex_nr = o->ignore_regex_nr;
3590 xpp.anchors = o->anchors;
3591 xpp.anchors_nr = o->anchors_nr;
3592 xecfg.ctxlen = o->context;
3593 xecfg.interhunkctxlen = o->interhunkcontext;
3594 xecfg.flags = XDL_EMIT_FUNCNAMES;
3595 if (o->flags.funccontext)
3596 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3597 if (pe)
3598 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3600 diffopts = getenv("GIT_DIFF_OPTS");
3601 if (!diffopts)
3603 else if (skip_prefix(diffopts, "--unified=", &v))
3604 xecfg.ctxlen = strtoul(v, NULL, 10);
3605 else if (skip_prefix(diffopts, "-u", &v))
3606 xecfg.ctxlen = strtoul(v, NULL, 10);
3608 if (o->word_diff)
3609 init_diff_words_data(&ecbdata, o, one, two);
3610 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3611 &ecbdata, &xpp, &xecfg))
3612 die("unable to generate diff for %s", one->path);
3613 if (o->word_diff)
3614 free_diff_words_data(&ecbdata);
3615 if (textconv_one)
3616 free(mf1.ptr);
3617 if (textconv_two)
3618 free(mf2.ptr);
3619 xdiff_clear_find_func(&xecfg);
3622 free_ab_and_return:
3623 strbuf_release(&header);
3624 diff_free_filespec_data(one);
3625 diff_free_filespec_data(two);
3626 free(a_one);
3627 free(b_two);
3628 return;
3631 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3633 if (!is_renamed) {
3634 if (p->status == DIFF_STATUS_ADDED) {
3635 if (S_ISLNK(p->two->mode))
3636 return "new +l";
3637 else if ((p->two->mode & 0777) == 0755)
3638 return "new +x";
3639 else
3640 return "new";
3641 } else if (p->status == DIFF_STATUS_DELETED)
3642 return "gone";
3644 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3645 return "mode -l";
3646 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3647 return "mode +l";
3648 else if ((p->one->mode & 0777) == 0644 &&
3649 (p->two->mode & 0777) == 0755)
3650 return "mode +x";
3651 else if ((p->one->mode & 0777) == 0755 &&
3652 (p->two->mode & 0777) == 0644)
3653 return "mode -x";
3654 return NULL;
3657 static void builtin_diffstat(const char *name_a, const char *name_b,
3658 struct diff_filespec *one,
3659 struct diff_filespec *two,
3660 struct diffstat_t *diffstat,
3661 struct diff_options *o,
3662 struct diff_filepair *p)
3664 mmfile_t mf1, mf2;
3665 struct diffstat_file *data;
3666 int may_differ;
3667 int complete_rewrite = 0;
3669 if (!DIFF_PAIR_UNMERGED(p)) {
3670 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3671 complete_rewrite = 1;
3674 data = diffstat_add(diffstat, name_a, name_b);
3675 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3676 if (o->flags.stat_with_summary)
3677 data->comments = get_compact_summary(p, data->is_renamed);
3679 if (!one || !two) {
3680 data->is_unmerged = 1;
3681 return;
3684 /* saves some reads if true, not a guarantee of diff outcome */
3685 may_differ = !(one->oid_valid && two->oid_valid &&
3686 oideq(&one->oid, &two->oid));
3688 if (diff_filespec_is_binary(o->repo, one) ||
3689 diff_filespec_is_binary(o->repo, two)) {
3690 data->is_binary = 1;
3691 if (!may_differ) {
3692 data->added = 0;
3693 data->deleted = 0;
3694 } else {
3695 data->added = diff_filespec_size(o->repo, two);
3696 data->deleted = diff_filespec_size(o->repo, one);
3700 else if (complete_rewrite) {
3701 diff_populate_filespec(o->repo, one, NULL);
3702 diff_populate_filespec(o->repo, two, NULL);
3703 data->deleted = count_lines(one->data, one->size);
3704 data->added = count_lines(two->data, two->size);
3707 else if (may_differ) {
3708 /* Crazy xdl interfaces.. */
3709 xpparam_t xpp;
3710 xdemitconf_t xecfg;
3712 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3713 fill_mmfile(o->repo, &mf2, two) < 0)
3714 die("unable to read files to diff");
3716 memset(&xpp, 0, sizeof(xpp));
3717 memset(&xecfg, 0, sizeof(xecfg));
3718 xpp.flags = o->xdl_opts;
3719 xpp.ignore_regex = o->ignore_regex;
3720 xpp.ignore_regex_nr = o->ignore_regex_nr;
3721 xpp.anchors = o->anchors;
3722 xpp.anchors_nr = o->anchors_nr;
3723 xecfg.ctxlen = o->context;
3724 xecfg.interhunkctxlen = o->interhunkcontext;
3725 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3726 if (xdi_diff_outf(&mf1, &mf2, NULL,
3727 diffstat_consume, diffstat, &xpp, &xecfg))
3728 die("unable to generate diffstat for %s", one->path);
3730 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3731 struct diffstat_file *file =
3732 diffstat->files[diffstat->nr - 1];
3734 * Omit diffstats of modified files where nothing changed.
3735 * Even if may_differ, this might be the case due to
3736 * ignoring whitespace changes, etc.
3738 * But note that we special-case additions, deletions,
3739 * renames, and mode changes as adding an empty file,
3740 * for example is still of interest.
3742 if ((p->status == DIFF_STATUS_MODIFIED)
3743 && !file->added
3744 && !file->deleted
3745 && one->mode == two->mode) {
3746 free_diffstat_file(file);
3747 diffstat->nr--;
3752 diff_free_filespec_data(one);
3753 diff_free_filespec_data(two);
3756 static void builtin_checkdiff(const char *name_a, const char *name_b,
3757 const char *attr_path,
3758 struct diff_filespec *one,
3759 struct diff_filespec *two,
3760 struct diff_options *o)
3762 mmfile_t mf1, mf2;
3763 struct checkdiff_t data;
3765 if (!two)
3766 return;
3768 memset(&data, 0, sizeof(data));
3769 data.filename = name_b ? name_b : name_a;
3770 data.lineno = 0;
3771 data.o = o;
3772 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3773 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3775 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3776 fill_mmfile(o->repo, &mf2, two) < 0)
3777 die("unable to read files to diff");
3780 * All the other codepaths check both sides, but not checking
3781 * the "old" side here is deliberate. We are checking the newly
3782 * introduced changes, and as long as the "new" side is text, we
3783 * can and should check what it introduces.
3785 if (diff_filespec_is_binary(o->repo, two))
3786 goto free_and_return;
3787 else {
3788 /* Crazy xdl interfaces.. */
3789 xpparam_t xpp;
3790 xdemitconf_t xecfg;
3792 memset(&xpp, 0, sizeof(xpp));
3793 memset(&xecfg, 0, sizeof(xecfg));
3794 xecfg.ctxlen = 1; /* at least one context line */
3795 xpp.flags = 0;
3796 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3797 checkdiff_consume, &data,
3798 &xpp, &xecfg))
3799 die("unable to generate checkdiff for %s", one->path);
3801 if (data.ws_rule & WS_BLANK_AT_EOF) {
3802 struct emit_callback ecbdata;
3803 int blank_at_eof;
3805 ecbdata.ws_rule = data.ws_rule;
3806 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3807 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3809 if (blank_at_eof) {
3810 static char *err;
3811 if (!err)
3812 err = whitespace_error_string(WS_BLANK_AT_EOF);
3813 fprintf(o->file, "%s:%d: %s.\n",
3814 data.filename, blank_at_eof, err);
3815 data.status = 1; /* report errors */
3819 free_and_return:
3820 diff_free_filespec_data(one);
3821 diff_free_filespec_data(two);
3822 if (data.status)
3823 o->flags.check_failed = 1;
3826 struct diff_filespec *alloc_filespec(const char *path)
3828 struct diff_filespec *spec;
3830 FLEXPTR_ALLOC_STR(spec, path, path);
3831 spec->count = 1;
3832 spec->is_binary = -1;
3833 return spec;
3836 void free_filespec(struct diff_filespec *spec)
3838 if (!--spec->count) {
3839 diff_free_filespec_data(spec);
3840 free(spec);
3844 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3845 int oid_valid, unsigned short mode)
3847 if (mode) {
3848 spec->mode = canon_mode(mode);
3849 oidcpy(&spec->oid, oid);
3850 spec->oid_valid = oid_valid;
3855 * Given a name and sha1 pair, if the index tells us the file in
3856 * the work tree has that object contents, return true, so that
3857 * prepare_temp_file() does not have to inflate and extract.
3859 static int reuse_worktree_file(struct index_state *istate,
3860 const char *name,
3861 const struct object_id *oid,
3862 int want_file)
3864 const struct cache_entry *ce;
3865 struct stat st;
3866 int pos, len;
3869 * We do not read the cache ourselves here, because the
3870 * benchmark with my previous version that always reads cache
3871 * shows that it makes things worse for diff-tree comparing
3872 * two linux-2.6 kernel trees in an already checked out work
3873 * tree. This is because most diff-tree comparisons deal with
3874 * only a small number of files, while reading the cache is
3875 * expensive for a large project, and its cost outweighs the
3876 * savings we get by not inflating the object to a temporary
3877 * file. Practically, this code only helps when we are used
3878 * by diff-cache --cached, which does read the cache before
3879 * calling us.
3881 if (!istate->cache)
3882 return 0;
3884 /* We want to avoid the working directory if our caller
3885 * doesn't need the data in a normal file, this system
3886 * is rather slow with its stat/open/mmap/close syscalls,
3887 * and the object is contained in a pack file. The pack
3888 * is probably already open and will be faster to obtain
3889 * the data through than the working directory. Loose
3890 * objects however would tend to be slower as they need
3891 * to be individually opened and inflated.
3893 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3894 return 0;
3897 * Similarly, if we'd have to convert the file contents anyway, that
3898 * makes the optimization not worthwhile.
3900 if (!want_file && would_convert_to_git(istate, name))
3901 return 0;
3904 * If this path does not match our sparse-checkout definition,
3905 * then the file will not be in the working directory.
3907 if (!path_in_sparse_checkout(name, istate))
3908 return 0;
3910 len = strlen(name);
3911 pos = index_name_pos(istate, name, len);
3912 if (pos < 0)
3913 return 0;
3914 ce = istate->cache[pos];
3917 * This is not the sha1 we are looking for, or
3918 * unreusable because it is not a regular file.
3920 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3921 return 0;
3924 * If ce is marked as "assume unchanged", there is no
3925 * guarantee that work tree matches what we are looking for.
3927 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3928 return 0;
3931 * If ce matches the file in the work tree, we can reuse it.
3933 if (ce_uptodate(ce) ||
3934 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3935 return 1;
3937 return 0;
3940 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3942 struct strbuf buf = STRBUF_INIT;
3943 char *dirty = "";
3945 /* Are we looking at the work tree? */
3946 if (s->dirty_submodule)
3947 dirty = "-dirty";
3949 strbuf_addf(&buf, "Subproject commit %s%s\n",
3950 oid_to_hex(&s->oid), dirty);
3951 s->size = buf.len;
3952 if (size_only) {
3953 s->data = NULL;
3954 strbuf_release(&buf);
3955 } else {
3956 s->data = strbuf_detach(&buf, NULL);
3957 s->should_free = 1;
3959 return 0;
3963 * While doing rename detection and pickaxe operation, we may need to
3964 * grab the data for the blob (or file) for our own in-core comparison.
3965 * diff_filespec has data and size fields for this purpose.
3967 int diff_populate_filespec(struct repository *r,
3968 struct diff_filespec *s,
3969 const struct diff_populate_filespec_options *options)
3971 int size_only = options ? options->check_size_only : 0;
3972 int check_binary = options ? options->check_binary : 0;
3973 int err = 0;
3974 int conv_flags = global_conv_flags_eol;
3976 * demote FAIL to WARN to allow inspecting the situation
3977 * instead of refusing.
3979 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3980 conv_flags = CONV_EOL_RNDTRP_WARN;
3982 if (!DIFF_FILE_VALID(s))
3983 die("internal error: asking to populate invalid file.");
3984 if (S_ISDIR(s->mode))
3985 return -1;
3987 if (s->data)
3988 return 0;
3990 if (size_only && 0 < s->size)
3991 return 0;
3993 if (S_ISGITLINK(s->mode))
3994 return diff_populate_gitlink(s, size_only);
3996 if (!s->oid_valid ||
3997 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3998 struct strbuf buf = STRBUF_INIT;
3999 struct stat st;
4000 int fd;
4002 if (lstat(s->path, &st) < 0) {
4003 err_empty:
4004 err = -1;
4005 empty:
4006 s->data = (char *)"";
4007 s->size = 0;
4008 return err;
4010 s->size = xsize_t(st.st_size);
4011 if (!s->size)
4012 goto empty;
4013 if (S_ISLNK(st.st_mode)) {
4014 struct strbuf sb = STRBUF_INIT;
4016 if (strbuf_readlink(&sb, s->path, s->size))
4017 goto err_empty;
4018 s->size = sb.len;
4019 s->data = strbuf_detach(&sb, NULL);
4020 s->should_free = 1;
4021 return 0;
4025 * Even if the caller would be happy with getting
4026 * only the size, we cannot return early at this
4027 * point if the path requires us to run the content
4028 * conversion.
4030 if (size_only && !would_convert_to_git(r->index, s->path))
4031 return 0;
4034 * Note: this check uses xsize_t(st.st_size) that may
4035 * not be the true size of the blob after it goes
4036 * through convert_to_git(). This may not strictly be
4037 * correct, but the whole point of big_file_threshold
4038 * and is_binary check being that we want to avoid
4039 * opening the file and inspecting the contents, this
4040 * is probably fine.
4042 if (check_binary &&
4043 s->size > big_file_threshold && s->is_binary == -1) {
4044 s->is_binary = 1;
4045 return 0;
4047 fd = open(s->path, O_RDONLY);
4048 if (fd < 0)
4049 goto err_empty;
4050 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4051 close(fd);
4052 s->should_munmap = 1;
4055 * Convert from working tree format to canonical git format
4057 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4058 size_t size = 0;
4059 munmap(s->data, s->size);
4060 s->should_munmap = 0;
4061 s->data = strbuf_detach(&buf, &size);
4062 s->size = size;
4063 s->should_free = 1;
4066 else {
4067 struct object_info info = {
4068 .sizep = &s->size
4071 if (!(size_only || check_binary))
4073 * Set contentp, since there is no chance that merely
4074 * the size is sufficient.
4076 info.contentp = &s->data;
4078 if (options && options->missing_object_cb) {
4079 if (!oid_object_info_extended(r, &s->oid, &info,
4080 OBJECT_INFO_LOOKUP_REPLACE |
4081 OBJECT_INFO_SKIP_FETCH_OBJECT))
4082 goto object_read;
4083 options->missing_object_cb(options->missing_object_data);
4085 if (oid_object_info_extended(r, &s->oid, &info,
4086 OBJECT_INFO_LOOKUP_REPLACE))
4087 die("unable to read %s", oid_to_hex(&s->oid));
4089 object_read:
4090 if (size_only || check_binary) {
4091 if (size_only)
4092 return 0;
4093 if (s->size > big_file_threshold && s->is_binary == -1) {
4094 s->is_binary = 1;
4095 return 0;
4098 if (!info.contentp) {
4099 info.contentp = &s->data;
4100 if (oid_object_info_extended(r, &s->oid, &info,
4101 OBJECT_INFO_LOOKUP_REPLACE))
4102 die("unable to read %s", oid_to_hex(&s->oid));
4104 s->should_free = 1;
4106 return 0;
4109 void diff_free_filespec_blob(struct diff_filespec *s)
4111 if (s->should_free)
4112 free(s->data);
4113 else if (s->should_munmap)
4114 munmap(s->data, s->size);
4116 if (s->should_free || s->should_munmap) {
4117 s->should_free = s->should_munmap = 0;
4118 s->data = NULL;
4122 void diff_free_filespec_data(struct diff_filespec *s)
4124 if (!s)
4125 return;
4127 diff_free_filespec_blob(s);
4128 FREE_AND_NULL(s->cnt_data);
4131 static void prep_temp_blob(struct index_state *istate,
4132 const char *path, struct diff_tempfile *temp,
4133 void *blob,
4134 unsigned long size,
4135 const struct object_id *oid,
4136 int mode)
4138 struct strbuf buf = STRBUF_INIT;
4139 char *path_dup = xstrdup(path);
4140 const char *base = basename(path_dup);
4141 struct checkout_metadata meta;
4143 init_checkout_metadata(&meta, NULL, NULL, oid);
4145 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4146 if (!temp->tempfile)
4147 die_errno("unable to create temp-file");
4148 if (convert_to_working_tree(istate, path,
4149 (const char *)blob, (size_t)size, &buf, &meta)) {
4150 blob = buf.buf;
4151 size = buf.len;
4153 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4154 close_tempfile_gently(temp->tempfile))
4155 die_errno("unable to write temp-file");
4156 temp->name = get_tempfile_path(temp->tempfile);
4157 oid_to_hex_r(temp->hex, oid);
4158 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4159 strbuf_release(&buf);
4160 free(path_dup);
4163 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4164 const char *name,
4165 struct diff_filespec *one)
4167 struct diff_tempfile *temp = claim_diff_tempfile();
4169 if (!DIFF_FILE_VALID(one)) {
4170 not_a_valid_file:
4171 /* A '-' entry produces this for file-2, and
4172 * a '+' entry produces this for file-1.
4174 temp->name = "/dev/null";
4175 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4176 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4177 return temp;
4180 if (!S_ISGITLINK(one->mode) &&
4181 (!one->oid_valid ||
4182 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4183 struct stat st;
4184 if (lstat(name, &st) < 0) {
4185 if (errno == ENOENT)
4186 goto not_a_valid_file;
4187 die_errno("stat(%s)", name);
4189 if (S_ISLNK(st.st_mode)) {
4190 struct strbuf sb = STRBUF_INIT;
4191 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4192 die_errno("readlink(%s)", name);
4193 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4194 (one->oid_valid ?
4195 &one->oid : null_oid()),
4196 (one->oid_valid ?
4197 one->mode : S_IFLNK));
4198 strbuf_release(&sb);
4200 else {
4201 /* we can borrow from the file in the work tree */
4202 temp->name = name;
4203 if (!one->oid_valid)
4204 oid_to_hex_r(temp->hex, null_oid());
4205 else
4206 oid_to_hex_r(temp->hex, &one->oid);
4207 /* Even though we may sometimes borrow the
4208 * contents from the work tree, we always want
4209 * one->mode. mode is trustworthy even when
4210 * !(one->oid_valid), as long as
4211 * DIFF_FILE_VALID(one).
4213 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4215 return temp;
4217 else {
4218 if (diff_populate_filespec(r, one, NULL))
4219 die("cannot read data blob for %s", one->path);
4220 prep_temp_blob(r->index, name, temp,
4221 one->data, one->size,
4222 &one->oid, one->mode);
4224 return temp;
4227 static void add_external_diff_name(struct repository *r,
4228 struct strvec *argv,
4229 const char *name,
4230 struct diff_filespec *df)
4232 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4233 strvec_push(argv, temp->name);
4234 strvec_push(argv, temp->hex);
4235 strvec_push(argv, temp->mode);
4238 /* An external diff command takes:
4240 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4241 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4244 static void run_external_diff(const char *pgm,
4245 const char *name,
4246 const char *other,
4247 struct diff_filespec *one,
4248 struct diff_filespec *two,
4249 const char *xfrm_msg,
4250 struct diff_options *o)
4252 struct strvec argv = STRVEC_INIT;
4253 struct strvec env = STRVEC_INIT;
4254 struct diff_queue_struct *q = &diff_queued_diff;
4256 strvec_push(&argv, pgm);
4257 strvec_push(&argv, name);
4259 if (one && two) {
4260 add_external_diff_name(o->repo, &argv, name, one);
4261 if (!other)
4262 add_external_diff_name(o->repo, &argv, name, two);
4263 else {
4264 add_external_diff_name(o->repo, &argv, other, two);
4265 strvec_push(&argv, other);
4266 strvec_push(&argv, xfrm_msg);
4270 strvec_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4271 strvec_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4273 diff_free_filespec_data(one);
4274 diff_free_filespec_data(two);
4275 if (run_command_v_opt_cd_env(argv.v, RUN_USING_SHELL, NULL, env.v))
4276 die(_("external diff died, stopping at %s"), name);
4278 remove_tempfile();
4279 strvec_clear(&argv);
4280 strvec_clear(&env);
4283 static int similarity_index(struct diff_filepair *p)
4285 return p->score * 100 / MAX_SCORE;
4288 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4290 if (startup_info->have_repository)
4291 return find_unique_abbrev(oid, abbrev);
4292 else {
4293 char *hex = oid_to_hex(oid);
4294 if (abbrev < 0)
4295 abbrev = FALLBACK_DEFAULT_ABBREV;
4296 if (abbrev > the_hash_algo->hexsz)
4297 BUG("oid abbreviation out of range: %d", abbrev);
4298 if (abbrev)
4299 hex[abbrev] = '\0';
4300 return hex;
4304 static void fill_metainfo(struct strbuf *msg,
4305 const char *name,
4306 const char *other,
4307 struct diff_filespec *one,
4308 struct diff_filespec *two,
4309 struct diff_options *o,
4310 struct diff_filepair *p,
4311 int *must_show_header,
4312 int use_color)
4314 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4315 const char *reset = diff_get_color(use_color, DIFF_RESET);
4316 const char *line_prefix = diff_line_prefix(o);
4317 struct strbuf *more_headers = NULL;
4319 *must_show_header = 1;
4320 strbuf_init(msg, PATH_MAX * 2 + 300);
4321 switch (p->status) {
4322 case DIFF_STATUS_COPIED:
4323 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4324 line_prefix, set, similarity_index(p));
4325 strbuf_addf(msg, "%s\n%s%scopy from ",
4326 reset, line_prefix, set);
4327 quote_c_style(name, msg, NULL, 0);
4328 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4329 quote_c_style(other, msg, NULL, 0);
4330 strbuf_addf(msg, "%s\n", reset);
4331 break;
4332 case DIFF_STATUS_RENAMED:
4333 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4334 line_prefix, set, similarity_index(p));
4335 strbuf_addf(msg, "%s\n%s%srename from ",
4336 reset, line_prefix, set);
4337 quote_c_style(name, msg, NULL, 0);
4338 strbuf_addf(msg, "%s\n%s%srename to ",
4339 reset, line_prefix, set);
4340 quote_c_style(other, msg, NULL, 0);
4341 strbuf_addf(msg, "%s\n", reset);
4342 break;
4343 case DIFF_STATUS_MODIFIED:
4344 if (p->score) {
4345 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4346 line_prefix,
4347 set, similarity_index(p), reset);
4348 break;
4350 /* fallthru */
4351 default:
4352 *must_show_header = 0;
4354 if ((more_headers = additional_headers(o, name))) {
4355 add_formatted_headers(msg, more_headers,
4356 line_prefix, set, reset);
4357 *must_show_header = 1;
4359 if (one && two && !oideq(&one->oid, &two->oid)) {
4360 const unsigned hexsz = the_hash_algo->hexsz;
4361 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4363 if (o->flags.full_index)
4364 abbrev = hexsz;
4366 if (o->flags.binary) {
4367 mmfile_t mf;
4368 if ((!fill_mmfile(o->repo, &mf, one) &&
4369 diff_filespec_is_binary(o->repo, one)) ||
4370 (!fill_mmfile(o->repo, &mf, two) &&
4371 diff_filespec_is_binary(o->repo, two)))
4372 abbrev = hexsz;
4374 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4375 diff_abbrev_oid(&one->oid, abbrev),
4376 diff_abbrev_oid(&two->oid, abbrev));
4377 if (one->mode == two->mode)
4378 strbuf_addf(msg, " %06o", one->mode);
4379 strbuf_addf(msg, "%s\n", reset);
4383 static void run_diff_cmd(const char *pgm,
4384 const char *name,
4385 const char *other,
4386 const char *attr_path,
4387 struct diff_filespec *one,
4388 struct diff_filespec *two,
4389 struct strbuf *msg,
4390 struct diff_options *o,
4391 struct diff_filepair *p)
4393 const char *xfrm_msg = NULL;
4394 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4395 int must_show_header = 0;
4398 if (o->flags.allow_external) {
4399 struct userdiff_driver *drv;
4401 drv = userdiff_find_by_path(o->repo->index, attr_path);
4402 if (drv && drv->external)
4403 pgm = drv->external;
4406 if (msg) {
4408 * don't use colors when the header is intended for an
4409 * external diff driver
4411 fill_metainfo(msg, name, other, one, two, o, p,
4412 &must_show_header,
4413 want_color(o->use_color) && !pgm);
4414 xfrm_msg = msg->len ? msg->buf : NULL;
4417 if (pgm) {
4418 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4419 return;
4421 if (one && two)
4422 builtin_diff(name, other ? other : name,
4423 one, two, xfrm_msg, must_show_header,
4424 o, complete_rewrite);
4425 else
4426 fprintf(o->file, "* Unmerged path %s\n", name);
4429 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4431 if (DIFF_FILE_VALID(one)) {
4432 if (!one->oid_valid) {
4433 struct stat st;
4434 if (one->is_stdin) {
4435 oidclr(&one->oid);
4436 return;
4438 if (lstat(one->path, &st) < 0)
4439 die_errno("stat '%s'", one->path);
4440 if (index_path(istate, &one->oid, one->path, &st, 0))
4441 die("cannot hash %s", one->path);
4444 else
4445 oidclr(&one->oid);
4448 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4450 /* Strip the prefix but do not molest /dev/null and absolute paths */
4451 if (*namep && !is_absolute_path(*namep)) {
4452 *namep += prefix_length;
4453 if (**namep == '/')
4454 ++*namep;
4456 if (*otherp && !is_absolute_path(*otherp)) {
4457 *otherp += prefix_length;
4458 if (**otherp == '/')
4459 ++*otherp;
4463 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4465 const char *pgm = external_diff();
4466 struct strbuf msg;
4467 struct diff_filespec *one = p->one;
4468 struct diff_filespec *two = p->two;
4469 const char *name;
4470 const char *other;
4471 const char *attr_path;
4473 name = one->path;
4474 other = (strcmp(name, two->path) ? two->path : NULL);
4475 attr_path = name;
4476 if (o->prefix_length)
4477 strip_prefix(o->prefix_length, &name, &other);
4479 if (!o->flags.allow_external)
4480 pgm = NULL;
4482 if (DIFF_PAIR_UNMERGED(p)) {
4483 run_diff_cmd(pgm, name, NULL, attr_path,
4484 NULL, NULL, NULL, o, p);
4485 return;
4488 diff_fill_oid_info(one, o->repo->index);
4489 diff_fill_oid_info(two, o->repo->index);
4491 if (!pgm &&
4492 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4493 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4495 * a filepair that changes between file and symlink
4496 * needs to be split into deletion and creation.
4498 struct diff_filespec *null = alloc_filespec(two->path);
4499 run_diff_cmd(NULL, name, other, attr_path,
4500 one, null, &msg,
4501 o, p);
4502 free(null);
4503 strbuf_release(&msg);
4505 null = alloc_filespec(one->path);
4506 run_diff_cmd(NULL, name, other, attr_path,
4507 null, two, &msg, o, p);
4508 free(null);
4510 else
4511 run_diff_cmd(pgm, name, other, attr_path,
4512 one, two, &msg, o, p);
4514 strbuf_release(&msg);
4517 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4518 struct diffstat_t *diffstat)
4520 const char *name;
4521 const char *other;
4523 if (DIFF_PAIR_UNMERGED(p)) {
4524 /* unmerged */
4525 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4526 diffstat, o, p);
4527 return;
4530 name = p->one->path;
4531 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4533 if (o->prefix_length)
4534 strip_prefix(o->prefix_length, &name, &other);
4536 diff_fill_oid_info(p->one, o->repo->index);
4537 diff_fill_oid_info(p->two, o->repo->index);
4539 builtin_diffstat(name, other, p->one, p->two,
4540 diffstat, o, p);
4543 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4545 const char *name;
4546 const char *other;
4547 const char *attr_path;
4549 if (DIFF_PAIR_UNMERGED(p)) {
4550 /* unmerged */
4551 return;
4554 name = p->one->path;
4555 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4556 attr_path = other ? other : name;
4558 if (o->prefix_length)
4559 strip_prefix(o->prefix_length, &name, &other);
4561 diff_fill_oid_info(p->one, o->repo->index);
4562 diff_fill_oid_info(p->two, o->repo->index);
4564 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4567 static void prep_parse_options(struct diff_options *options);
4569 void repo_diff_setup(struct repository *r, struct diff_options *options)
4571 memcpy(options, &default_diff_options, sizeof(*options));
4573 options->file = stdout;
4574 options->repo = r;
4576 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4577 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4578 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4579 options->abbrev = DEFAULT_ABBREV;
4580 options->line_termination = '\n';
4581 options->break_opt = -1;
4582 options->rename_limit = -1;
4583 options->dirstat_permille = diff_dirstat_permille_default;
4584 options->context = diff_context_default;
4585 options->interhunkcontext = diff_interhunk_context_default;
4586 options->ws_error_highlight = ws_error_highlight_default;
4587 options->flags.rename_empty = 1;
4588 options->flags.relative_name = diff_relative;
4589 options->objfind = NULL;
4591 /* pathchange left =NULL by default */
4592 options->change = diff_change;
4593 options->add_remove = diff_addremove;
4594 options->use_color = diff_use_color_default;
4595 options->detect_rename = diff_detect_rename_default;
4596 options->xdl_opts |= diff_algorithm;
4597 if (diff_indent_heuristic)
4598 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4600 options->orderfile = diff_order_file_cfg;
4602 if (!options->flags.ignore_submodule_set)
4603 options->flags.ignore_untracked_in_submodules = 1;
4605 if (diff_no_prefix) {
4606 options->a_prefix = options->b_prefix = "";
4607 } else if (!diff_mnemonic_prefix) {
4608 options->a_prefix = "a/";
4609 options->b_prefix = "b/";
4612 options->color_moved = diff_color_moved_default;
4613 options->color_moved_ws_handling = diff_color_moved_ws_default;
4615 prep_parse_options(options);
4618 static const char diff_status_letters[] = {
4619 DIFF_STATUS_ADDED,
4620 DIFF_STATUS_COPIED,
4621 DIFF_STATUS_DELETED,
4622 DIFF_STATUS_MODIFIED,
4623 DIFF_STATUS_RENAMED,
4624 DIFF_STATUS_TYPE_CHANGED,
4625 DIFF_STATUS_UNKNOWN,
4626 DIFF_STATUS_UNMERGED,
4627 DIFF_STATUS_FILTER_AON,
4628 DIFF_STATUS_FILTER_BROKEN,
4629 '\0',
4632 static unsigned int filter_bit['Z' + 1];
4634 static void prepare_filter_bits(void)
4636 int i;
4638 if (!filter_bit[DIFF_STATUS_ADDED]) {
4639 for (i = 0; diff_status_letters[i]; i++)
4640 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4644 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4646 return opt->filter & filter_bit[(int) status];
4649 unsigned diff_filter_bit(char status)
4651 prepare_filter_bits();
4652 return filter_bit[(int) status];
4655 void diff_setup_done(struct diff_options *options)
4657 unsigned check_mask = DIFF_FORMAT_NAME |
4658 DIFF_FORMAT_NAME_STATUS |
4659 DIFF_FORMAT_CHECKDIFF |
4660 DIFF_FORMAT_NO_OUTPUT;
4662 * This must be signed because we're comparing against a potentially
4663 * negative value.
4665 const int hexsz = the_hash_algo->hexsz;
4667 if (options->set_default)
4668 options->set_default(options);
4670 if (HAS_MULTI_BITS(options->output_format & check_mask))
4671 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4672 "--name-only", "--name-status", "--check", "-s");
4674 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4675 die(_("options '%s', '%s', and '%s' cannot be used together"),
4676 "-G", "-S", "--find-object");
4678 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4679 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4680 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4682 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4683 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4684 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4687 * Most of the time we can say "there are changes"
4688 * only by checking if there are changed paths, but
4689 * --ignore-whitespace* options force us to look
4690 * inside contents.
4693 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4694 options->ignore_regex_nr)
4695 options->flags.diff_from_contents = 1;
4696 else
4697 options->flags.diff_from_contents = 0;
4699 if (options->flags.find_copies_harder)
4700 options->detect_rename = DIFF_DETECT_COPY;
4702 if (!options->flags.relative_name)
4703 options->prefix = NULL;
4704 if (options->prefix)
4705 options->prefix_length = strlen(options->prefix);
4706 else
4707 options->prefix_length = 0;
4709 if (options->output_format & (DIFF_FORMAT_NAME |
4710 DIFF_FORMAT_NAME_STATUS |
4711 DIFF_FORMAT_CHECKDIFF |
4712 DIFF_FORMAT_NO_OUTPUT))
4713 options->output_format &= ~(DIFF_FORMAT_RAW |
4714 DIFF_FORMAT_NUMSTAT |
4715 DIFF_FORMAT_DIFFSTAT |
4716 DIFF_FORMAT_SHORTSTAT |
4717 DIFF_FORMAT_DIRSTAT |
4718 DIFF_FORMAT_SUMMARY |
4719 DIFF_FORMAT_PATCH);
4722 * These cases always need recursive; we do not drop caller-supplied
4723 * recursive bits for other formats here.
4725 if (options->output_format & (DIFF_FORMAT_PATCH |
4726 DIFF_FORMAT_NUMSTAT |
4727 DIFF_FORMAT_DIFFSTAT |
4728 DIFF_FORMAT_SHORTSTAT |
4729 DIFF_FORMAT_DIRSTAT |
4730 DIFF_FORMAT_SUMMARY |
4731 DIFF_FORMAT_CHECKDIFF))
4732 options->flags.recursive = 1;
4734 * Also pickaxe would not work very well if you do not say recursive
4736 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4737 options->flags.recursive = 1;
4739 * When patches are generated, submodules diffed against the work tree
4740 * must be checked for dirtiness too so it can be shown in the output
4742 if (options->output_format & DIFF_FORMAT_PATCH)
4743 options->flags.dirty_submodules = 1;
4745 if (options->detect_rename && options->rename_limit < 0)
4746 options->rename_limit = diff_rename_limit_default;
4747 if (hexsz < options->abbrev)
4748 options->abbrev = hexsz; /* full */
4751 * It does not make sense to show the first hit we happened
4752 * to have found. It does not make sense not to return with
4753 * exit code in such a case either.
4755 if (options->flags.quick) {
4756 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4757 options->flags.exit_with_status = 1;
4760 options->diff_path_counter = 0;
4762 if (options->flags.follow_renames && options->pathspec.nr != 1)
4763 die(_("--follow requires exactly one pathspec"));
4765 if (!options->use_color || external_diff())
4766 options->color_moved = 0;
4768 if (options->filter_not) {
4769 if (!options->filter)
4770 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4771 options->filter &= ~options->filter_not;
4774 FREE_AND_NULL(options->parseopts);
4777 int parse_long_opt(const char *opt, const char **argv,
4778 const char **optarg)
4780 const char *arg = argv[0];
4781 if (!skip_prefix(arg, "--", &arg))
4782 return 0;
4783 if (!skip_prefix(arg, opt, &arg))
4784 return 0;
4785 if (*arg == '=') { /* stuck form: --option=value */
4786 *optarg = arg + 1;
4787 return 1;
4789 if (*arg != '\0')
4790 return 0;
4791 /* separate form: --option value */
4792 if (!argv[1])
4793 die("Option '--%s' requires a value", opt);
4794 *optarg = argv[1];
4795 return 2;
4798 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4800 struct diff_options *options = opt->value;
4801 int width = options->stat_width;
4802 int name_width = options->stat_name_width;
4803 int graph_width = options->stat_graph_width;
4804 int count = options->stat_count;
4805 char *end;
4807 BUG_ON_OPT_NEG(unset);
4809 if (!strcmp(opt->long_name, "stat")) {
4810 if (value) {
4811 width = strtoul(value, &end, 10);
4812 if (*end == ',')
4813 name_width = strtoul(end+1, &end, 10);
4814 if (*end == ',')
4815 count = strtoul(end+1, &end, 10);
4816 if (*end)
4817 return error(_("invalid --stat value: %s"), value);
4819 } else if (!strcmp(opt->long_name, "stat-width")) {
4820 width = strtoul(value, &end, 10);
4821 if (*end)
4822 return error(_("%s expects a numerical value"),
4823 opt->long_name);
4824 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4825 name_width = strtoul(value, &end, 10);
4826 if (*end)
4827 return error(_("%s expects a numerical value"),
4828 opt->long_name);
4829 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4830 graph_width = strtoul(value, &end, 10);
4831 if (*end)
4832 return error(_("%s expects a numerical value"),
4833 opt->long_name);
4834 } else if (!strcmp(opt->long_name, "stat-count")) {
4835 count = strtoul(value, &end, 10);
4836 if (*end)
4837 return error(_("%s expects a numerical value"),
4838 opt->long_name);
4839 } else
4840 BUG("%s should not get here", opt->long_name);
4842 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4843 options->stat_name_width = name_width;
4844 options->stat_graph_width = graph_width;
4845 options->stat_width = width;
4846 options->stat_count = count;
4847 return 0;
4850 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4852 struct strbuf errmsg = STRBUF_INIT;
4853 if (parse_dirstat_params(options, params, &errmsg))
4854 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4855 errmsg.buf);
4856 strbuf_release(&errmsg);
4858 * The caller knows a dirstat-related option is given from the command
4859 * line; allow it to say "return this_function();"
4861 options->output_format |= DIFF_FORMAT_DIRSTAT;
4862 return 1;
4865 static int diff_opt_diff_filter(const struct option *option,
4866 const char *optarg, int unset)
4868 struct diff_options *opt = option->value;
4869 int i, optch;
4871 BUG_ON_OPT_NEG(unset);
4872 prepare_filter_bits();
4874 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4875 unsigned int bit;
4876 int negate;
4878 if ('a' <= optch && optch <= 'z') {
4879 negate = 1;
4880 optch = toupper(optch);
4881 } else {
4882 negate = 0;
4885 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4886 if (!bit)
4887 return error(_("unknown change class '%c' in --diff-filter=%s"),
4888 optarg[i], optarg);
4889 if (negate)
4890 opt->filter_not |= bit;
4891 else
4892 opt->filter |= bit;
4894 return 0;
4897 static void enable_patch_output(int *fmt)
4899 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4900 *fmt |= DIFF_FORMAT_PATCH;
4903 static int diff_opt_ws_error_highlight(const struct option *option,
4904 const char *arg, int unset)
4906 struct diff_options *opt = option->value;
4907 int val = parse_ws_error_highlight(arg);
4909 BUG_ON_OPT_NEG(unset);
4910 if (val < 0)
4911 return error(_("unknown value after ws-error-highlight=%.*s"),
4912 -1 - val, arg);
4913 opt->ws_error_highlight = val;
4914 return 0;
4917 static int diff_opt_find_object(const struct option *option,
4918 const char *arg, int unset)
4920 struct diff_options *opt = option->value;
4921 struct object_id oid;
4923 BUG_ON_OPT_NEG(unset);
4924 if (get_oid(arg, &oid))
4925 return error(_("unable to resolve '%s'"), arg);
4927 if (!opt->objfind)
4928 CALLOC_ARRAY(opt->objfind, 1);
4930 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4931 opt->flags.recursive = 1;
4932 opt->flags.tree_in_recursive = 1;
4933 oidset_insert(opt->objfind, &oid);
4934 return 0;
4937 static int diff_opt_anchored(const struct option *opt,
4938 const char *arg, int unset)
4940 struct diff_options *options = opt->value;
4942 BUG_ON_OPT_NEG(unset);
4943 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4944 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4945 options->anchors_alloc);
4946 options->anchors[options->anchors_nr++] = xstrdup(arg);
4947 return 0;
4950 static int diff_opt_binary(const struct option *opt,
4951 const char *arg, int unset)
4953 struct diff_options *options = opt->value;
4955 BUG_ON_OPT_NEG(unset);
4956 BUG_ON_OPT_ARG(arg);
4957 enable_patch_output(&options->output_format);
4958 options->flags.binary = 1;
4959 return 0;
4962 static int diff_opt_break_rewrites(const struct option *opt,
4963 const char *arg, int unset)
4965 int *break_opt = opt->value;
4966 int opt1, opt2;
4968 BUG_ON_OPT_NEG(unset);
4969 if (!arg)
4970 arg = "";
4971 opt1 = parse_rename_score(&arg);
4972 if (*arg == 0)
4973 opt2 = 0;
4974 else if (*arg != '/')
4975 return error(_("%s expects <n>/<m> form"), opt->long_name);
4976 else {
4977 arg++;
4978 opt2 = parse_rename_score(&arg);
4980 if (*arg != 0)
4981 return error(_("%s expects <n>/<m> form"), opt->long_name);
4982 *break_opt = opt1 | (opt2 << 16);
4983 return 0;
4986 static int diff_opt_char(const struct option *opt,
4987 const char *arg, int unset)
4989 char *value = opt->value;
4991 BUG_ON_OPT_NEG(unset);
4992 if (arg[1])
4993 return error(_("%s expects a character, got '%s'"),
4994 opt->long_name, arg);
4995 *value = arg[0];
4996 return 0;
4999 static int diff_opt_color_moved(const struct option *opt,
5000 const char *arg, int unset)
5002 struct diff_options *options = opt->value;
5004 if (unset) {
5005 options->color_moved = COLOR_MOVED_NO;
5006 } else if (!arg) {
5007 if (diff_color_moved_default)
5008 options->color_moved = diff_color_moved_default;
5009 if (options->color_moved == COLOR_MOVED_NO)
5010 options->color_moved = COLOR_MOVED_DEFAULT;
5011 } else {
5012 int cm = parse_color_moved(arg);
5013 if (cm < 0)
5014 return error(_("bad --color-moved argument: %s"), arg);
5015 options->color_moved = cm;
5017 return 0;
5020 static int diff_opt_color_moved_ws(const struct option *opt,
5021 const char *arg, int unset)
5023 struct diff_options *options = opt->value;
5024 unsigned cm;
5026 if (unset) {
5027 options->color_moved_ws_handling = 0;
5028 return 0;
5031 cm = parse_color_moved_ws(arg);
5032 if (cm & COLOR_MOVED_WS_ERROR)
5033 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5034 options->color_moved_ws_handling = cm;
5035 return 0;
5038 static int diff_opt_color_words(const struct option *opt,
5039 const char *arg, int unset)
5041 struct diff_options *options = opt->value;
5043 BUG_ON_OPT_NEG(unset);
5044 options->use_color = 1;
5045 options->word_diff = DIFF_WORDS_COLOR;
5046 options->word_regex = arg;
5047 return 0;
5050 static int diff_opt_compact_summary(const struct option *opt,
5051 const char *arg, int unset)
5053 struct diff_options *options = opt->value;
5055 BUG_ON_OPT_ARG(arg);
5056 if (unset) {
5057 options->flags.stat_with_summary = 0;
5058 } else {
5059 options->flags.stat_with_summary = 1;
5060 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5062 return 0;
5065 static int diff_opt_diff_algorithm(const struct option *opt,
5066 const char *arg, int unset)
5068 struct diff_options *options = opt->value;
5069 long value = parse_algorithm_value(arg);
5071 BUG_ON_OPT_NEG(unset);
5072 if (value < 0)
5073 return error(_("option diff-algorithm accepts \"myers\", "
5074 "\"minimal\", \"patience\" and \"histogram\""));
5076 /* clear out previous settings */
5077 DIFF_XDL_CLR(options, NEED_MINIMAL);
5078 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5079 options->xdl_opts |= value;
5080 return 0;
5083 static int diff_opt_dirstat(const struct option *opt,
5084 const char *arg, int unset)
5086 struct diff_options *options = opt->value;
5088 BUG_ON_OPT_NEG(unset);
5089 if (!strcmp(opt->long_name, "cumulative")) {
5090 if (arg)
5091 BUG("how come --cumulative take a value?");
5092 arg = "cumulative";
5093 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5094 parse_dirstat_opt(options, "files");
5095 parse_dirstat_opt(options, arg ? arg : "");
5096 return 0;
5099 static int diff_opt_find_copies(const struct option *opt,
5100 const char *arg, int unset)
5102 struct diff_options *options = opt->value;
5104 BUG_ON_OPT_NEG(unset);
5105 if (!arg)
5106 arg = "";
5107 options->rename_score = parse_rename_score(&arg);
5108 if (*arg != 0)
5109 return error(_("invalid argument to %s"), opt->long_name);
5111 if (options->detect_rename == DIFF_DETECT_COPY)
5112 options->flags.find_copies_harder = 1;
5113 else
5114 options->detect_rename = DIFF_DETECT_COPY;
5116 return 0;
5119 static int diff_opt_find_renames(const struct option *opt,
5120 const char *arg, int unset)
5122 struct diff_options *options = opt->value;
5124 BUG_ON_OPT_NEG(unset);
5125 if (!arg)
5126 arg = "";
5127 options->rename_score = parse_rename_score(&arg);
5128 if (*arg != 0)
5129 return error(_("invalid argument to %s"), opt->long_name);
5131 options->detect_rename = DIFF_DETECT_RENAME;
5132 return 0;
5135 static int diff_opt_follow(const struct option *opt,
5136 const char *arg, int unset)
5138 struct diff_options *options = opt->value;
5140 BUG_ON_OPT_ARG(arg);
5141 if (unset) {
5142 options->flags.follow_renames = 0;
5143 options->flags.default_follow_renames = 0;
5144 } else {
5145 options->flags.follow_renames = 1;
5147 return 0;
5150 static int diff_opt_ignore_submodules(const struct option *opt,
5151 const char *arg, int unset)
5153 struct diff_options *options = opt->value;
5155 BUG_ON_OPT_NEG(unset);
5156 if (!arg)
5157 arg = "all";
5158 options->flags.override_submodule_config = 1;
5159 handle_ignore_submodules_arg(options, arg);
5160 return 0;
5163 static int diff_opt_line_prefix(const struct option *opt,
5164 const char *optarg, int unset)
5166 struct diff_options *options = opt->value;
5168 BUG_ON_OPT_NEG(unset);
5169 options->line_prefix = optarg;
5170 options->line_prefix_length = strlen(options->line_prefix);
5171 graph_setup_line_prefix(options);
5172 return 0;
5175 static int diff_opt_no_prefix(const struct option *opt,
5176 const char *optarg, int unset)
5178 struct diff_options *options = opt->value;
5180 BUG_ON_OPT_NEG(unset);
5181 BUG_ON_OPT_ARG(optarg);
5182 options->a_prefix = "";
5183 options->b_prefix = "";
5184 return 0;
5187 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5188 const struct option *opt,
5189 const char *arg, int unset)
5191 struct diff_options *options = opt->value;
5192 char *path;
5194 BUG_ON_OPT_NEG(unset);
5195 path = prefix_filename(ctx->prefix, arg);
5196 options->file = xfopen(path, "w");
5197 options->close_file = 1;
5198 if (options->use_color != GIT_COLOR_ALWAYS)
5199 options->use_color = GIT_COLOR_NEVER;
5200 free(path);
5201 return 0;
5204 static int diff_opt_patience(const struct option *opt,
5205 const char *arg, int unset)
5207 struct diff_options *options = opt->value;
5208 int i;
5210 BUG_ON_OPT_NEG(unset);
5211 BUG_ON_OPT_ARG(arg);
5212 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5214 * Both --patience and --anchored use PATIENCE_DIFF
5215 * internally, so remove any anchors previously
5216 * specified.
5218 for (i = 0; i < options->anchors_nr; i++)
5219 free(options->anchors[i]);
5220 options->anchors_nr = 0;
5221 return 0;
5224 static int diff_opt_ignore_regex(const struct option *opt,
5225 const char *arg, int unset)
5227 struct diff_options *options = opt->value;
5228 regex_t *regex;
5230 BUG_ON_OPT_NEG(unset);
5231 regex = xmalloc(sizeof(*regex));
5232 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5233 return error(_("invalid regex given to -I: '%s'"), arg);
5234 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5235 options->ignore_regex_alloc);
5236 options->ignore_regex[options->ignore_regex_nr++] = regex;
5237 return 0;
5240 static int diff_opt_pickaxe_regex(const struct option *opt,
5241 const char *arg, int unset)
5243 struct diff_options *options = opt->value;
5245 BUG_ON_OPT_NEG(unset);
5246 options->pickaxe = arg;
5247 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5248 return 0;
5251 static int diff_opt_pickaxe_string(const struct option *opt,
5252 const char *arg, int unset)
5254 struct diff_options *options = opt->value;
5256 BUG_ON_OPT_NEG(unset);
5257 options->pickaxe = arg;
5258 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5259 return 0;
5262 static int diff_opt_relative(const struct option *opt,
5263 const char *arg, int unset)
5265 struct diff_options *options = opt->value;
5267 options->flags.relative_name = !unset;
5268 if (arg)
5269 options->prefix = arg;
5270 return 0;
5273 static int diff_opt_submodule(const struct option *opt,
5274 const char *arg, int unset)
5276 struct diff_options *options = opt->value;
5278 BUG_ON_OPT_NEG(unset);
5279 if (!arg)
5280 arg = "log";
5281 if (parse_submodule_params(options, arg))
5282 return error(_("failed to parse --submodule option parameter: '%s'"),
5283 arg);
5284 return 0;
5287 static int diff_opt_textconv(const struct option *opt,
5288 const char *arg, int unset)
5290 struct diff_options *options = opt->value;
5292 BUG_ON_OPT_ARG(arg);
5293 if (unset) {
5294 options->flags.allow_textconv = 0;
5295 } else {
5296 options->flags.allow_textconv = 1;
5297 options->flags.textconv_set_via_cmdline = 1;
5299 return 0;
5302 static int diff_opt_unified(const struct option *opt,
5303 const char *arg, int unset)
5305 struct diff_options *options = opt->value;
5306 char *s;
5308 BUG_ON_OPT_NEG(unset);
5310 if (arg) {
5311 options->context = strtol(arg, &s, 10);
5312 if (*s)
5313 return error(_("%s expects a numerical value"), "--unified");
5315 enable_patch_output(&options->output_format);
5317 return 0;
5320 static int diff_opt_word_diff(const struct option *opt,
5321 const char *arg, int unset)
5323 struct diff_options *options = opt->value;
5325 BUG_ON_OPT_NEG(unset);
5326 if (arg) {
5327 if (!strcmp(arg, "plain"))
5328 options->word_diff = DIFF_WORDS_PLAIN;
5329 else if (!strcmp(arg, "color")) {
5330 options->use_color = 1;
5331 options->word_diff = DIFF_WORDS_COLOR;
5333 else if (!strcmp(arg, "porcelain"))
5334 options->word_diff = DIFF_WORDS_PORCELAIN;
5335 else if (!strcmp(arg, "none"))
5336 options->word_diff = DIFF_WORDS_NONE;
5337 else
5338 return error(_("bad --word-diff argument: %s"), arg);
5339 } else {
5340 if (options->word_diff == DIFF_WORDS_NONE)
5341 options->word_diff = DIFF_WORDS_PLAIN;
5343 return 0;
5346 static int diff_opt_word_diff_regex(const struct option *opt,
5347 const char *arg, int unset)
5349 struct diff_options *options = opt->value;
5351 BUG_ON_OPT_NEG(unset);
5352 if (options->word_diff == DIFF_WORDS_NONE)
5353 options->word_diff = DIFF_WORDS_PLAIN;
5354 options->word_regex = arg;
5355 return 0;
5358 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5360 struct diff_options *options = opt->value;
5362 BUG_ON_OPT_NEG(unset);
5363 if (!strcmp(opt->long_name, "skip-to"))
5364 options->skip_instead_of_rotate = 1;
5365 else
5366 options->skip_instead_of_rotate = 0;
5367 options->rotate_to = arg;
5368 return 0;
5371 static void prep_parse_options(struct diff_options *options)
5373 struct option parseopts[] = {
5374 OPT_GROUP(N_("Diff output format options")),
5375 OPT_BITOP('p', "patch", &options->output_format,
5376 N_("generate patch"),
5377 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5378 OPT_BIT_F('s', "no-patch", &options->output_format,
5379 N_("suppress diff output"),
5380 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5381 OPT_BITOP('u', NULL, &options->output_format,
5382 N_("generate patch"),
5383 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5384 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5385 N_("generate diffs with <n> lines context"),
5386 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5387 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5388 N_("generate diffs with <n> lines context")),
5389 OPT_BIT_F(0, "raw", &options->output_format,
5390 N_("generate the diff in raw format"),
5391 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5392 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5393 N_("synonym for '-p --raw'"),
5394 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5395 DIFF_FORMAT_NO_OUTPUT),
5396 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5397 N_("synonym for '-p --stat'"),
5398 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5399 DIFF_FORMAT_NO_OUTPUT),
5400 OPT_BIT_F(0, "numstat", &options->output_format,
5401 N_("machine friendly --stat"),
5402 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5403 OPT_BIT_F(0, "shortstat", &options->output_format,
5404 N_("output only the last line of --stat"),
5405 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5406 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5407 N_("output the distribution of relative amount of changes for each sub-directory"),
5408 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5409 diff_opt_dirstat),
5410 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5411 N_("synonym for --dirstat=cumulative"),
5412 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5413 diff_opt_dirstat),
5414 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5415 N_("synonym for --dirstat=files,param1,param2..."),
5416 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5417 diff_opt_dirstat),
5418 OPT_BIT_F(0, "check", &options->output_format,
5419 N_("warn if changes introduce conflict markers or whitespace errors"),
5420 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5421 OPT_BIT_F(0, "summary", &options->output_format,
5422 N_("condensed summary such as creations, renames and mode changes"),
5423 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5424 OPT_BIT_F(0, "name-only", &options->output_format,
5425 N_("show only names of changed files"),
5426 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5427 OPT_BIT_F(0, "name-status", &options->output_format,
5428 N_("show only names and status of changed files"),
5429 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5430 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5431 N_("generate diffstat"),
5432 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5433 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5434 N_("generate diffstat with a given width"),
5435 PARSE_OPT_NONEG, diff_opt_stat),
5436 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5437 N_("generate diffstat with a given name width"),
5438 PARSE_OPT_NONEG, diff_opt_stat),
5439 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5440 N_("generate diffstat with a given graph width"),
5441 PARSE_OPT_NONEG, diff_opt_stat),
5442 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5443 N_("generate diffstat with limited lines"),
5444 PARSE_OPT_NONEG, diff_opt_stat),
5445 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5446 N_("generate compact summary in diffstat"),
5447 PARSE_OPT_NOARG, diff_opt_compact_summary),
5448 OPT_CALLBACK_F(0, "binary", options, NULL,
5449 N_("output a binary diff that can be applied"),
5450 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5451 OPT_BOOL(0, "full-index", &options->flags.full_index,
5452 N_("show full pre- and post-image object names on the \"index\" lines")),
5453 OPT_COLOR_FLAG(0, "color", &options->use_color,
5454 N_("show colored diff")),
5455 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5456 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5457 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5458 OPT_SET_INT('z', NULL, &options->line_termination,
5459 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5461 OPT__ABBREV(&options->abbrev),
5462 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5463 N_("show the given source prefix instead of \"a/\""),
5464 PARSE_OPT_NONEG),
5465 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5466 N_("show the given destination prefix instead of \"b/\""),
5467 PARSE_OPT_NONEG),
5468 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5469 N_("prepend an additional prefix to every line of output"),
5470 PARSE_OPT_NONEG, diff_opt_line_prefix),
5471 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5472 N_("do not show any source or destination prefix"),
5473 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5474 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5475 N_("show context between diff hunks up to the specified number of lines"),
5476 PARSE_OPT_NONEG),
5477 OPT_CALLBACK_F(0, "output-indicator-new",
5478 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5479 N_("<char>"),
5480 N_("specify the character to indicate a new line instead of '+'"),
5481 PARSE_OPT_NONEG, diff_opt_char),
5482 OPT_CALLBACK_F(0, "output-indicator-old",
5483 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5484 N_("<char>"),
5485 N_("specify the character to indicate an old line instead of '-'"),
5486 PARSE_OPT_NONEG, diff_opt_char),
5487 OPT_CALLBACK_F(0, "output-indicator-context",
5488 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5489 N_("<char>"),
5490 N_("specify the character to indicate a context instead of ' '"),
5491 PARSE_OPT_NONEG, diff_opt_char),
5493 OPT_GROUP(N_("Diff rename options")),
5494 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5495 N_("break complete rewrite changes into pairs of delete and create"),
5496 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5497 diff_opt_break_rewrites),
5498 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5499 N_("detect renames"),
5500 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5501 diff_opt_find_renames),
5502 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5503 N_("omit the preimage for deletes"),
5504 1, PARSE_OPT_NONEG),
5505 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5506 N_("detect copies"),
5507 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5508 diff_opt_find_copies),
5509 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5510 N_("use unmodified files as source to find copies")),
5511 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5512 N_("disable rename detection"),
5513 0, PARSE_OPT_NONEG),
5514 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5515 N_("use empty blobs as rename source")),
5516 OPT_CALLBACK_F(0, "follow", options, NULL,
5517 N_("continue listing the history of a file beyond renames"),
5518 PARSE_OPT_NOARG, diff_opt_follow),
5519 OPT_INTEGER('l', NULL, &options->rename_limit,
5520 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5522 OPT_GROUP(N_("Diff algorithm options")),
5523 OPT_BIT(0, "minimal", &options->xdl_opts,
5524 N_("produce the smallest possible diff"),
5525 XDF_NEED_MINIMAL),
5526 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5527 N_("ignore whitespace when comparing lines"),
5528 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5529 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5530 N_("ignore changes in amount of whitespace"),
5531 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5532 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5533 N_("ignore changes in whitespace at EOL"),
5534 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5535 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5536 N_("ignore carrier-return at the end of line"),
5537 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5538 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5539 N_("ignore changes whose lines are all blank"),
5540 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5541 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5542 N_("ignore changes whose all lines match <regex>"),
5543 0, diff_opt_ignore_regex),
5544 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5545 N_("heuristic to shift diff hunk boundaries for easy reading"),
5546 XDF_INDENT_HEURISTIC),
5547 OPT_CALLBACK_F(0, "patience", options, NULL,
5548 N_("generate diff using the \"patience diff\" algorithm"),
5549 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5550 diff_opt_patience),
5551 OPT_BITOP(0, "histogram", &options->xdl_opts,
5552 N_("generate diff using the \"histogram diff\" algorithm"),
5553 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5554 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5555 N_("choose a diff algorithm"),
5556 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5557 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5558 N_("generate diff using the \"anchored diff\" algorithm"),
5559 PARSE_OPT_NONEG, diff_opt_anchored),
5560 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5561 N_("show word diff, using <mode> to delimit changed words"),
5562 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5563 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5564 N_("use <regex> to decide what a word is"),
5565 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5566 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5567 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5568 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5569 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5570 N_("moved lines of code are colored differently"),
5571 PARSE_OPT_OPTARG, diff_opt_color_moved),
5572 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5573 N_("how white spaces are ignored in --color-moved"),
5574 0, diff_opt_color_moved_ws),
5576 OPT_GROUP(N_("Other diff options")),
5577 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5578 N_("when run from subdir, exclude changes outside and show relative paths"),
5579 PARSE_OPT_OPTARG,
5580 diff_opt_relative),
5581 OPT_BOOL('a', "text", &options->flags.text,
5582 N_("treat all files as text")),
5583 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5584 N_("swap two inputs, reverse the diff")),
5585 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5586 N_("exit with 1 if there were differences, 0 otherwise")),
5587 OPT_BOOL(0, "quiet", &options->flags.quick,
5588 N_("disable all output of the program")),
5589 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5590 N_("allow an external diff helper to be executed")),
5591 OPT_CALLBACK_F(0, "textconv", options, NULL,
5592 N_("run external text conversion filters when comparing binary files"),
5593 PARSE_OPT_NOARG, diff_opt_textconv),
5594 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5595 N_("ignore changes to submodules in the diff generation"),
5596 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5597 diff_opt_ignore_submodules),
5598 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5599 N_("specify how differences in submodules are shown"),
5600 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5601 diff_opt_submodule),
5602 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5603 N_("hide 'git add -N' entries from the index"),
5604 1, PARSE_OPT_NONEG),
5605 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5606 N_("treat 'git add -N' entries as real in the index"),
5607 0, PARSE_OPT_NONEG),
5608 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5609 N_("look for differences that change the number of occurrences of the specified string"),
5610 0, diff_opt_pickaxe_string),
5611 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5612 N_("look for differences that change the number of occurrences of the specified regex"),
5613 0, diff_opt_pickaxe_regex),
5614 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5615 N_("show all changes in the changeset with -S or -G"),
5616 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5617 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5618 N_("treat <string> in -S as extended POSIX regular expression"),
5619 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5620 OPT_FILENAME('O', NULL, &options->orderfile,
5621 N_("control the order in which files appear in the output")),
5622 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5623 N_("show the change in the specified path first"),
5624 PARSE_OPT_NONEG, diff_opt_rotate_to),
5625 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5626 N_("skip the output to the specified path"),
5627 PARSE_OPT_NONEG, diff_opt_rotate_to),
5628 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5629 N_("look for differences that change the number of occurrences of the specified object"),
5630 PARSE_OPT_NONEG, diff_opt_find_object),
5631 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5632 N_("select files by diff type"),
5633 PARSE_OPT_NONEG, diff_opt_diff_filter),
5634 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5635 N_("output to a specific file"),
5636 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5638 OPT_END()
5641 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5642 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5645 int diff_opt_parse(struct diff_options *options,
5646 const char **av, int ac, const char *prefix)
5648 if (!prefix)
5649 prefix = "";
5651 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5652 PARSE_OPT_KEEP_DASHDASH |
5653 PARSE_OPT_KEEP_UNKNOWN |
5654 PARSE_OPT_NO_INTERNAL_HELP |
5655 PARSE_OPT_ONE_SHOT |
5656 PARSE_OPT_STOP_AT_NON_OPTION);
5658 return ac;
5661 int parse_rename_score(const char **cp_p)
5663 unsigned long num, scale;
5664 int ch, dot;
5665 const char *cp = *cp_p;
5667 num = 0;
5668 scale = 1;
5669 dot = 0;
5670 for (;;) {
5671 ch = *cp;
5672 if ( !dot && ch == '.' ) {
5673 scale = 1;
5674 dot = 1;
5675 } else if ( ch == '%' ) {
5676 scale = dot ? scale*100 : 100;
5677 cp++; /* % is always at the end */
5678 break;
5679 } else if ( ch >= '0' && ch <= '9' ) {
5680 if ( scale < 100000 ) {
5681 scale *= 10;
5682 num = (num*10) + (ch-'0');
5684 } else {
5685 break;
5687 cp++;
5689 *cp_p = cp;
5691 /* user says num divided by scale and we say internally that
5692 * is MAX_SCORE * num / scale.
5694 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5697 struct diff_queue_struct diff_queued_diff;
5699 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5701 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5702 queue->queue[queue->nr++] = dp;
5705 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5706 struct diff_filespec *one,
5707 struct diff_filespec *two)
5709 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5710 dp->one = one;
5711 dp->two = two;
5712 if (queue)
5713 diff_q(queue, dp);
5714 return dp;
5717 void diff_free_filepair(struct diff_filepair *p)
5719 free_filespec(p->one);
5720 free_filespec(p->two);
5721 free(p);
5724 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5726 int abblen;
5727 const char *abbrev;
5729 /* Do we want all 40 hex characters? */
5730 if (len == the_hash_algo->hexsz)
5731 return oid_to_hex(oid);
5733 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5734 abbrev = diff_abbrev_oid(oid, len);
5736 if (!print_sha1_ellipsis())
5737 return abbrev;
5739 abblen = strlen(abbrev);
5742 * In well-behaved cases, where the abbreviated result is the
5743 * same as the requested length, append three dots after the
5744 * abbreviation (hence the whole logic is limited to the case
5745 * where abblen < 37); when the actual abbreviated result is a
5746 * bit longer than the requested length, we reduce the number
5747 * of dots so that they match the well-behaved ones. However,
5748 * if the actual abbreviation is longer than the requested
5749 * length by more than three, we give up on aligning, and add
5750 * three dots anyway, to indicate that the output is not the
5751 * full object name. Yes, this may be suboptimal, but this
5752 * appears only in "diff --raw --abbrev" output and it is not
5753 * worth the effort to change it now. Note that this would
5754 * likely to work fine when the automatic sizing of default
5755 * abbreviation length is used--we would be fed -1 in "len" in
5756 * that case, and will end up always appending three-dots, but
5757 * the automatic sizing is supposed to give abblen that ensures
5758 * uniqueness across all objects (statistically speaking).
5760 if (abblen < the_hash_algo->hexsz - 3) {
5761 static char hex[GIT_MAX_HEXSZ + 1];
5762 if (len < abblen && abblen <= len + 2)
5763 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5764 else
5765 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5766 return hex;
5769 return oid_to_hex(oid);
5772 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5774 int line_termination = opt->line_termination;
5775 int inter_name_termination = line_termination ? '\t' : '\0';
5777 fprintf(opt->file, "%s", diff_line_prefix(opt));
5778 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5779 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5780 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5781 fprintf(opt->file, "%s ",
5782 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5784 if (p->score) {
5785 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5786 inter_name_termination);
5787 } else {
5788 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5791 if (p->status == DIFF_STATUS_COPIED ||
5792 p->status == DIFF_STATUS_RENAMED) {
5793 const char *name_a, *name_b;
5794 name_a = p->one->path;
5795 name_b = p->two->path;
5796 strip_prefix(opt->prefix_length, &name_a, &name_b);
5797 write_name_quoted(name_a, opt->file, inter_name_termination);
5798 write_name_quoted(name_b, opt->file, line_termination);
5799 } else {
5800 const char *name_a, *name_b;
5801 name_a = p->one->mode ? p->one->path : p->two->path;
5802 name_b = NULL;
5803 strip_prefix(opt->prefix_length, &name_a, &name_b);
5804 write_name_quoted(name_a, opt->file, line_termination);
5808 int diff_unmodified_pair(struct diff_filepair *p)
5810 /* This function is written stricter than necessary to support
5811 * the currently implemented transformers, but the idea is to
5812 * let transformers to produce diff_filepairs any way they want,
5813 * and filter and clean them up here before producing the output.
5815 struct diff_filespec *one = p->one, *two = p->two;
5817 if (DIFF_PAIR_UNMERGED(p))
5818 return 0; /* unmerged is interesting */
5820 /* deletion, addition, mode or type change
5821 * and rename are all interesting.
5823 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5824 DIFF_PAIR_MODE_CHANGED(p) ||
5825 strcmp(one->path, two->path))
5826 return 0;
5828 /* both are valid and point at the same path. that is, we are
5829 * dealing with a change.
5831 if (one->oid_valid && two->oid_valid &&
5832 oideq(&one->oid, &two->oid) &&
5833 !one->dirty_submodule && !two->dirty_submodule)
5834 return 1; /* no change */
5835 if (!one->oid_valid && !two->oid_valid)
5836 return 1; /* both look at the same file on the filesystem. */
5837 return 0;
5840 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5842 int include_conflict_headers =
5843 (additional_headers(o, p->one->path) &&
5844 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5847 * Check if we can return early without showing a diff. Note that
5848 * diff_filepair only stores {oid, path, mode, is_valid}
5849 * information for each path, and thus diff_unmodified_pair() only
5850 * considers those bits of info. However, we do not want pairs
5851 * created by create_filepairs_for_header_only_notifications()
5852 * (which always look like unmodified pairs) to be ignored, so
5853 * return early if both p is unmodified AND we don't want to
5854 * include_conflict_headers.
5856 if (diff_unmodified_pair(p) && !include_conflict_headers)
5857 return;
5859 /* Actually, we can also return early to avoid showing tree diffs */
5860 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5861 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5862 return;
5864 run_diff(p, o);
5867 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5868 struct diffstat_t *diffstat)
5870 if (diff_unmodified_pair(p))
5871 return;
5873 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5874 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5875 return; /* no useful stat for tree diffs */
5877 run_diffstat(p, o, diffstat);
5880 static void diff_flush_checkdiff(struct diff_filepair *p,
5881 struct diff_options *o)
5883 if (diff_unmodified_pair(p))
5884 return;
5886 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5887 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5888 return; /* nothing to check in tree diffs */
5890 run_checkdiff(p, o);
5893 int diff_queue_is_empty(struct diff_options *o)
5895 struct diff_queue_struct *q = &diff_queued_diff;
5896 int i;
5897 int include_conflict_headers =
5898 (o->additional_path_headers &&
5899 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5901 if (include_conflict_headers)
5902 return 0;
5904 for (i = 0; i < q->nr; i++)
5905 if (!diff_unmodified_pair(q->queue[i]))
5906 return 0;
5907 return 1;
5910 #if DIFF_DEBUG
5911 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5913 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5914 x, one ? one : "",
5915 s->path,
5916 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5917 s->mode,
5918 s->oid_valid ? oid_to_hex(&s->oid) : "");
5919 fprintf(stderr, "queue[%d] %s size %lu\n",
5920 x, one ? one : "",
5921 s->size);
5924 void diff_debug_filepair(const struct diff_filepair *p, int i)
5926 diff_debug_filespec(p->one, i, "one");
5927 diff_debug_filespec(p->two, i, "two");
5928 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5929 p->score, p->status ? p->status : '?',
5930 p->one->rename_used, p->broken_pair);
5933 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5935 int i;
5936 if (msg)
5937 fprintf(stderr, "%s\n", msg);
5938 fprintf(stderr, "q->nr = %d\n", q->nr);
5939 for (i = 0; i < q->nr; i++) {
5940 struct diff_filepair *p = q->queue[i];
5941 diff_debug_filepair(p, i);
5944 #endif
5946 static void diff_resolve_rename_copy(void)
5948 int i;
5949 struct diff_filepair *p;
5950 struct diff_queue_struct *q = &diff_queued_diff;
5952 diff_debug_queue("resolve-rename-copy", q);
5954 for (i = 0; i < q->nr; i++) {
5955 p = q->queue[i];
5956 p->status = 0; /* undecided */
5957 if (DIFF_PAIR_UNMERGED(p))
5958 p->status = DIFF_STATUS_UNMERGED;
5959 else if (!DIFF_FILE_VALID(p->one))
5960 p->status = DIFF_STATUS_ADDED;
5961 else if (!DIFF_FILE_VALID(p->two))
5962 p->status = DIFF_STATUS_DELETED;
5963 else if (DIFF_PAIR_TYPE_CHANGED(p))
5964 p->status = DIFF_STATUS_TYPE_CHANGED;
5966 /* from this point on, we are dealing with a pair
5967 * whose both sides are valid and of the same type, i.e.
5968 * either in-place edit or rename/copy edit.
5970 else if (DIFF_PAIR_RENAME(p)) {
5972 * A rename might have re-connected a broken
5973 * pair up, causing the pathnames to be the
5974 * same again. If so, that's not a rename at
5975 * all, just a modification..
5977 * Otherwise, see if this source was used for
5978 * multiple renames, in which case we decrement
5979 * the count, and call it a copy.
5981 if (!strcmp(p->one->path, p->two->path))
5982 p->status = DIFF_STATUS_MODIFIED;
5983 else if (--p->one->rename_used > 0)
5984 p->status = DIFF_STATUS_COPIED;
5985 else
5986 p->status = DIFF_STATUS_RENAMED;
5988 else if (!oideq(&p->one->oid, &p->two->oid) ||
5989 p->one->mode != p->two->mode ||
5990 p->one->dirty_submodule ||
5991 p->two->dirty_submodule ||
5992 is_null_oid(&p->one->oid))
5993 p->status = DIFF_STATUS_MODIFIED;
5994 else {
5995 /* This is a "no-change" entry and should not
5996 * happen anymore, but prepare for broken callers.
5998 error("feeding unmodified %s to diffcore",
5999 p->one->path);
6000 p->status = DIFF_STATUS_UNKNOWN;
6003 diff_debug_queue("resolve-rename-copy done", q);
6006 static int check_pair_status(struct diff_filepair *p)
6008 switch (p->status) {
6009 case DIFF_STATUS_UNKNOWN:
6010 return 0;
6011 case 0:
6012 die("internal error in diff-resolve-rename-copy");
6013 default:
6014 return 1;
6018 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6020 int fmt = opt->output_format;
6022 if (fmt & DIFF_FORMAT_CHECKDIFF)
6023 diff_flush_checkdiff(p, opt);
6024 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6025 diff_flush_raw(p, opt);
6026 else if (fmt & DIFF_FORMAT_NAME) {
6027 const char *name_a, *name_b;
6028 name_a = p->two->path;
6029 name_b = NULL;
6030 strip_prefix(opt->prefix_length, &name_a, &name_b);
6031 fprintf(opt->file, "%s", diff_line_prefix(opt));
6032 write_name_quoted(name_a, opt->file, opt->line_termination);
6036 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6038 struct strbuf sb = STRBUF_INIT;
6039 if (fs->mode)
6040 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6041 else
6042 strbuf_addf(&sb, " %s ", newdelete);
6044 quote_c_style(fs->path, &sb, NULL, 0);
6045 strbuf_addch(&sb, '\n');
6046 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6047 sb.buf, sb.len, 0);
6048 strbuf_release(&sb);
6051 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6052 int show_name)
6054 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6055 struct strbuf sb = STRBUF_INIT;
6056 strbuf_addf(&sb, " mode change %06o => %06o",
6057 p->one->mode, p->two->mode);
6058 if (show_name) {
6059 strbuf_addch(&sb, ' ');
6060 quote_c_style(p->two->path, &sb, NULL, 0);
6062 strbuf_addch(&sb, '\n');
6063 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6064 sb.buf, sb.len, 0);
6065 strbuf_release(&sb);
6069 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6070 struct diff_filepair *p)
6072 struct strbuf sb = STRBUF_INIT;
6073 struct strbuf names = STRBUF_INIT;
6075 pprint_rename(&names, p->one->path, p->two->path);
6076 strbuf_addf(&sb, " %s %s (%d%%)\n",
6077 renamecopy, names.buf, similarity_index(p));
6078 strbuf_release(&names);
6079 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6080 sb.buf, sb.len, 0);
6081 show_mode_change(opt, p, 0);
6082 strbuf_release(&sb);
6085 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6087 switch(p->status) {
6088 case DIFF_STATUS_DELETED:
6089 show_file_mode_name(opt, "delete", p->one);
6090 break;
6091 case DIFF_STATUS_ADDED:
6092 show_file_mode_name(opt, "create", p->two);
6093 break;
6094 case DIFF_STATUS_COPIED:
6095 show_rename_copy(opt, "copy", p);
6096 break;
6097 case DIFF_STATUS_RENAMED:
6098 show_rename_copy(opt, "rename", p);
6099 break;
6100 default:
6101 if (p->score) {
6102 struct strbuf sb = STRBUF_INIT;
6103 strbuf_addstr(&sb, " rewrite ");
6104 quote_c_style(p->two->path, &sb, NULL, 0);
6105 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6106 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6107 sb.buf, sb.len, 0);
6108 strbuf_release(&sb);
6110 show_mode_change(opt, p, !p->score);
6111 break;
6115 struct patch_id_t {
6116 git_hash_ctx *ctx;
6117 int patchlen;
6120 static int remove_space(char *line, int len)
6122 int i;
6123 char *dst = line;
6124 unsigned char c;
6126 for (i = 0; i < len; i++)
6127 if (!isspace((c = line[i])))
6128 *dst++ = c;
6130 return dst - line;
6133 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6135 unsigned char hash[GIT_MAX_RAWSZ];
6136 unsigned short carry = 0;
6137 int i;
6139 the_hash_algo->final_fn(hash, ctx);
6140 the_hash_algo->init_fn(ctx);
6141 /* 20-byte sum, with carry */
6142 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6143 carry += result->hash[i] + hash[i];
6144 result->hash[i] = carry;
6145 carry >>= 8;
6149 static int patch_id_consume(void *priv, char *line, unsigned long len)
6151 struct patch_id_t *data = priv;
6152 int new_len;
6154 if (len > 12 && starts_with(line, "\\ "))
6155 return 0;
6156 new_len = remove_space(line, len);
6158 the_hash_algo->update_fn(data->ctx, line, new_len);
6159 data->patchlen += new_len;
6160 return 0;
6163 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6165 the_hash_algo->update_fn(ctx, str, strlen(str));
6168 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6170 /* large enough for 2^32 in octal */
6171 char buf[12];
6172 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6173 the_hash_algo->update_fn(ctx, buf, len);
6176 /* returns 0 upon success, and writes result into oid */
6177 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6179 struct diff_queue_struct *q = &diff_queued_diff;
6180 int i;
6181 git_hash_ctx ctx;
6182 struct patch_id_t data;
6184 the_hash_algo->init_fn(&ctx);
6185 memset(&data, 0, sizeof(struct patch_id_t));
6186 data.ctx = &ctx;
6187 oidclr(oid);
6189 for (i = 0; i < q->nr; i++) {
6190 xpparam_t xpp;
6191 xdemitconf_t xecfg;
6192 mmfile_t mf1, mf2;
6193 struct diff_filepair *p = q->queue[i];
6194 int len1, len2;
6196 memset(&xpp, 0, sizeof(xpp));
6197 memset(&xecfg, 0, sizeof(xecfg));
6198 if (p->status == 0)
6199 return error("internal diff status error");
6200 if (p->status == DIFF_STATUS_UNKNOWN)
6201 continue;
6202 if (diff_unmodified_pair(p))
6203 continue;
6204 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6205 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6206 continue;
6207 if (DIFF_PAIR_UNMERGED(p))
6208 continue;
6210 diff_fill_oid_info(p->one, options->repo->index);
6211 diff_fill_oid_info(p->two, options->repo->index);
6213 len1 = remove_space(p->one->path, strlen(p->one->path));
6214 len2 = remove_space(p->two->path, strlen(p->two->path));
6215 patch_id_add_string(&ctx, "diff--git");
6216 patch_id_add_string(&ctx, "a/");
6217 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6218 patch_id_add_string(&ctx, "b/");
6219 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6221 if (p->one->mode == 0) {
6222 patch_id_add_string(&ctx, "newfilemode");
6223 patch_id_add_mode(&ctx, p->two->mode);
6224 patch_id_add_string(&ctx, "---/dev/null");
6225 patch_id_add_string(&ctx, "+++b/");
6226 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6227 } else if (p->two->mode == 0) {
6228 patch_id_add_string(&ctx, "deletedfilemode");
6229 patch_id_add_mode(&ctx, p->one->mode);
6230 patch_id_add_string(&ctx, "---a/");
6231 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6232 patch_id_add_string(&ctx, "+++/dev/null");
6233 } else {
6234 patch_id_add_string(&ctx, "---a/");
6235 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6236 patch_id_add_string(&ctx, "+++b/");
6237 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6240 if (diff_header_only)
6241 continue;
6243 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6244 fill_mmfile(options->repo, &mf2, p->two) < 0)
6245 return error("unable to read files to diff");
6247 if (diff_filespec_is_binary(options->repo, p->one) ||
6248 diff_filespec_is_binary(options->repo, p->two)) {
6249 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6250 the_hash_algo->hexsz);
6251 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6252 the_hash_algo->hexsz);
6253 continue;
6256 xpp.flags = 0;
6257 xecfg.ctxlen = 3;
6258 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6259 if (xdi_diff_outf(&mf1, &mf2, NULL,
6260 patch_id_consume, &data, &xpp, &xecfg))
6261 return error("unable to generate patch-id diff for %s",
6262 p->one->path);
6264 if (stable)
6265 flush_one_hunk(oid, &ctx);
6268 if (!stable)
6269 the_hash_algo->final_oid_fn(oid, &ctx);
6271 return 0;
6274 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6276 struct diff_queue_struct *q = &diff_queued_diff;
6277 int i;
6278 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
6280 for (i = 0; i < q->nr; i++)
6281 diff_free_filepair(q->queue[i]);
6283 free(q->queue);
6284 DIFF_QUEUE_CLEAR(q);
6286 return result;
6289 static int is_summary_empty(const struct diff_queue_struct *q)
6291 int i;
6293 for (i = 0; i < q->nr; i++) {
6294 const struct diff_filepair *p = q->queue[i];
6296 switch (p->status) {
6297 case DIFF_STATUS_DELETED:
6298 case DIFF_STATUS_ADDED:
6299 case DIFF_STATUS_COPIED:
6300 case DIFF_STATUS_RENAMED:
6301 return 0;
6302 default:
6303 if (p->score)
6304 return 0;
6305 if (p->one->mode && p->two->mode &&
6306 p->one->mode != p->two->mode)
6307 return 0;
6308 break;
6311 return 1;
6314 static const char rename_limit_warning[] =
6315 N_("exhaustive rename detection was skipped due to too many files.");
6317 static const char degrade_cc_to_c_warning[] =
6318 N_("only found copies from modified paths due to too many files.");
6320 static const char rename_limit_advice[] =
6321 N_("you may want to set your %s variable to at least "
6322 "%d and retry the command.");
6324 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6326 fflush(stdout);
6327 if (degraded_cc)
6328 warning(_(degrade_cc_to_c_warning));
6329 else if (needed)
6330 warning(_(rename_limit_warning));
6331 else
6332 return;
6333 if (0 < needed)
6334 warning(_(rename_limit_advice), varname, needed);
6337 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6339 struct strset present;
6340 struct diff_queue_struct *q = &diff_queued_diff;
6341 struct hashmap_iter iter;
6342 struct strmap_entry *e;
6343 int i;
6345 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6348 * Find out which paths exist in diff_queued_diff, preferring
6349 * one->path for any pair that has multiple paths.
6351 for (i = 0; i < q->nr; i++) {
6352 struct diff_filepair *p = q->queue[i];
6353 char *path = p->one->path ? p->one->path : p->two->path;
6355 if (strmap_contains(o->additional_path_headers, path))
6356 strset_add(&present, path);
6360 * Loop over paths in additional_path_headers; for each NOT already
6361 * in diff_queued_diff, create a synthetic filepair and insert that
6362 * into diff_queued_diff.
6364 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6365 if (!strset_contains(&present, e->key)) {
6366 struct diff_filespec *one, *two;
6367 struct diff_filepair *p;
6369 one = alloc_filespec(e->key);
6370 two = alloc_filespec(e->key);
6371 fill_filespec(one, null_oid(), 0, 0);
6372 fill_filespec(two, null_oid(), 0, 0);
6373 p = diff_queue(q, one, two);
6374 p->status = DIFF_STATUS_MODIFIED;
6378 /* Re-sort the filepairs */
6379 diffcore_fix_diff_index();
6381 /* Cleanup */
6382 strset_clear(&present);
6385 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6387 int i;
6388 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6389 struct diff_queue_struct *q = &diff_queued_diff;
6391 if (WSEH_NEW & WS_RULE_MASK)
6392 BUG("WS rules bit mask overlaps with diff symbol flags");
6394 if (o->color_moved)
6395 o->emitted_symbols = &esm;
6397 if (o->additional_path_headers)
6398 create_filepairs_for_header_only_notifications(o);
6400 for (i = 0; i < q->nr; i++) {
6401 struct diff_filepair *p = q->queue[i];
6402 if (check_pair_status(p))
6403 diff_flush_patch(p, o);
6406 if (o->emitted_symbols) {
6407 if (o->color_moved) {
6408 struct mem_pool entry_pool;
6409 struct moved_entry_list *entry_list;
6411 mem_pool_init(&entry_pool, 1024 * 1024);
6412 entry_list = add_lines_to_move_detection(o,
6413 &entry_pool);
6414 mark_color_as_moved(o, entry_list);
6415 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6416 dim_moved_lines(o);
6418 mem_pool_discard(&entry_pool, 0);
6419 free(entry_list);
6422 for (i = 0; i < esm.nr; i++)
6423 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6425 for (i = 0; i < esm.nr; i++)
6426 free((void *)esm.buf[i].line);
6427 esm.nr = 0;
6429 o->emitted_symbols = NULL;
6433 static void diff_free_file(struct diff_options *options)
6435 if (options->close_file)
6436 fclose(options->file);
6439 static void diff_free_ignore_regex(struct diff_options *options)
6441 int i;
6443 for (i = 0; i < options->ignore_regex_nr; i++) {
6444 regfree(options->ignore_regex[i]);
6445 free(options->ignore_regex[i]);
6447 free(options->ignore_regex);
6450 void diff_free(struct diff_options *options)
6452 if (options->no_free)
6453 return;
6455 diff_free_file(options);
6456 diff_free_ignore_regex(options);
6457 clear_pathspec(&options->pathspec);
6458 FREE_AND_NULL(options->parseopts);
6461 void diff_flush(struct diff_options *options)
6463 struct diff_queue_struct *q = &diff_queued_diff;
6464 int i, output_format = options->output_format;
6465 int separator = 0;
6466 int dirstat_by_line = 0;
6469 * Order: raw, stat, summary, patch
6470 * or: name/name-status/checkdiff (other bits clear)
6472 if (!q->nr && !options->additional_path_headers)
6473 goto free_queue;
6475 if (output_format & (DIFF_FORMAT_RAW |
6476 DIFF_FORMAT_NAME |
6477 DIFF_FORMAT_NAME_STATUS |
6478 DIFF_FORMAT_CHECKDIFF)) {
6479 for (i = 0; i < q->nr; i++) {
6480 struct diff_filepair *p = q->queue[i];
6481 if (check_pair_status(p))
6482 flush_one_pair(p, options);
6484 separator++;
6487 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6488 dirstat_by_line = 1;
6490 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6491 dirstat_by_line) {
6492 struct diffstat_t diffstat;
6494 compute_diffstat(options, &diffstat, q);
6495 if (output_format & DIFF_FORMAT_NUMSTAT)
6496 show_numstat(&diffstat, options);
6497 if (output_format & DIFF_FORMAT_DIFFSTAT)
6498 show_stats(&diffstat, options);
6499 if (output_format & DIFF_FORMAT_SHORTSTAT)
6500 show_shortstats(&diffstat, options);
6501 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6502 show_dirstat_by_line(&diffstat, options);
6503 free_diffstat_info(&diffstat);
6504 separator++;
6506 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6507 show_dirstat(options);
6509 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6510 for (i = 0; i < q->nr; i++) {
6511 diff_summary(options, q->queue[i]);
6513 separator++;
6516 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6517 options->flags.exit_with_status &&
6518 options->flags.diff_from_contents) {
6520 * run diff_flush_patch for the exit status. setting
6521 * options->file to /dev/null should be safe, because we
6522 * aren't supposed to produce any output anyway.
6524 diff_free_file(options);
6525 options->file = xfopen("/dev/null", "w");
6526 options->close_file = 1;
6527 options->color_moved = 0;
6528 for (i = 0; i < q->nr; i++) {
6529 struct diff_filepair *p = q->queue[i];
6530 if (check_pair_status(p))
6531 diff_flush_patch(p, options);
6532 if (options->found_changes)
6533 break;
6537 if (output_format & DIFF_FORMAT_PATCH) {
6538 if (separator) {
6539 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6540 if (options->stat_sep)
6541 /* attach patch instead of inline */
6542 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6543 NULL, 0, 0);
6546 diff_flush_patch_all_file_pairs(options);
6549 if (output_format & DIFF_FORMAT_CALLBACK)
6550 options->format_callback(q, options, options->format_callback_data);
6552 for (i = 0; i < q->nr; i++)
6553 diff_free_filepair(q->queue[i]);
6554 free_queue:
6555 free(q->queue);
6556 DIFF_QUEUE_CLEAR(q);
6557 diff_free(options);
6560 * Report the content-level differences with HAS_CHANGES;
6561 * diff_addremove/diff_change does not set the bit when
6562 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6564 if (options->flags.diff_from_contents) {
6565 if (options->found_changes)
6566 options->flags.has_changes = 1;
6567 else
6568 options->flags.has_changes = 0;
6572 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6574 return (((p->status == DIFF_STATUS_MODIFIED) &&
6575 ((p->score &&
6576 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6577 (!p->score &&
6578 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6579 ((p->status != DIFF_STATUS_MODIFIED) &&
6580 filter_bit_tst(p->status, options)));
6583 static void diffcore_apply_filter(struct diff_options *options)
6585 int i;
6586 struct diff_queue_struct *q = &diff_queued_diff;
6587 struct diff_queue_struct outq;
6589 DIFF_QUEUE_CLEAR(&outq);
6591 if (!options->filter)
6592 return;
6594 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6595 int found;
6596 for (i = found = 0; !found && i < q->nr; i++) {
6597 if (match_filter(options, q->queue[i]))
6598 found++;
6600 if (found)
6601 return;
6603 /* otherwise we will clear the whole queue
6604 * by copying the empty outq at the end of this
6605 * function, but first clear the current entries
6606 * in the queue.
6608 for (i = 0; i < q->nr; i++)
6609 diff_free_filepair(q->queue[i]);
6611 else {
6612 /* Only the matching ones */
6613 for (i = 0; i < q->nr; i++) {
6614 struct diff_filepair *p = q->queue[i];
6615 if (match_filter(options, p))
6616 diff_q(&outq, p);
6617 else
6618 diff_free_filepair(p);
6621 free(q->queue);
6622 *q = outq;
6625 /* Check whether two filespecs with the same mode and size are identical */
6626 static int diff_filespec_is_identical(struct repository *r,
6627 struct diff_filespec *one,
6628 struct diff_filespec *two)
6630 if (S_ISGITLINK(one->mode))
6631 return 0;
6632 if (diff_populate_filespec(r, one, NULL))
6633 return 0;
6634 if (diff_populate_filespec(r, two, NULL))
6635 return 0;
6636 return !memcmp(one->data, two->data, one->size);
6639 static int diff_filespec_check_stat_unmatch(struct repository *r,
6640 struct diff_filepair *p)
6642 struct diff_populate_filespec_options dpf_options = {
6643 .check_size_only = 1,
6644 .missing_object_cb = diff_queued_diff_prefetch,
6645 .missing_object_data = r,
6648 if (p->done_skip_stat_unmatch)
6649 return p->skip_stat_unmatch_result;
6651 p->done_skip_stat_unmatch = 1;
6652 p->skip_stat_unmatch_result = 0;
6654 * 1. Entries that come from stat info dirtiness
6655 * always have both sides (iow, not create/delete),
6656 * one side of the object name is unknown, with
6657 * the same mode and size. Keep the ones that
6658 * do not match these criteria. They have real
6659 * differences.
6661 * 2. At this point, the file is known to be modified,
6662 * with the same mode and size, and the object
6663 * name of one side is unknown. Need to inspect
6664 * the identical contents.
6666 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6667 !DIFF_FILE_VALID(p->two) ||
6668 (p->one->oid_valid && p->two->oid_valid) ||
6669 (p->one->mode != p->two->mode) ||
6670 diff_populate_filespec(r, p->one, &dpf_options) ||
6671 diff_populate_filespec(r, p->two, &dpf_options) ||
6672 (p->one->size != p->two->size) ||
6673 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6674 p->skip_stat_unmatch_result = 1;
6675 return p->skip_stat_unmatch_result;
6678 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6680 int i;
6681 struct diff_queue_struct *q = &diff_queued_diff;
6682 struct diff_queue_struct outq;
6683 DIFF_QUEUE_CLEAR(&outq);
6685 for (i = 0; i < q->nr; i++) {
6686 struct diff_filepair *p = q->queue[i];
6688 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6689 diff_q(&outq, p);
6690 else {
6692 * The caller can subtract 1 from skip_stat_unmatch
6693 * to determine how many paths were dirty only
6694 * due to stat info mismatch.
6696 if (!diffopt->flags.no_index)
6697 diffopt->skip_stat_unmatch++;
6698 diff_free_filepair(p);
6701 free(q->queue);
6702 *q = outq;
6705 static int diffnamecmp(const void *a_, const void *b_)
6707 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6708 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6709 const char *name_a, *name_b;
6711 name_a = a->one ? a->one->path : a->two->path;
6712 name_b = b->one ? b->one->path : b->two->path;
6713 return strcmp(name_a, name_b);
6716 void diffcore_fix_diff_index(void)
6718 struct diff_queue_struct *q = &diff_queued_diff;
6719 QSORT(q->queue, q->nr, diffnamecmp);
6722 void diff_add_if_missing(struct repository *r,
6723 struct oid_array *to_fetch,
6724 const struct diff_filespec *filespec)
6726 if (filespec && filespec->oid_valid &&
6727 !S_ISGITLINK(filespec->mode) &&
6728 oid_object_info_extended(r, &filespec->oid, NULL,
6729 OBJECT_INFO_FOR_PREFETCH))
6730 oid_array_append(to_fetch, &filespec->oid);
6733 void diff_queued_diff_prefetch(void *repository)
6735 struct repository *repo = repository;
6736 int i;
6737 struct diff_queue_struct *q = &diff_queued_diff;
6738 struct oid_array to_fetch = OID_ARRAY_INIT;
6740 for (i = 0; i < q->nr; i++) {
6741 struct diff_filepair *p = q->queue[i];
6742 diff_add_if_missing(repo, &to_fetch, p->one);
6743 diff_add_if_missing(repo, &to_fetch, p->two);
6747 * NEEDSWORK: Consider deduplicating the OIDs sent.
6749 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6751 oid_array_clear(&to_fetch);
6754 void diffcore_std(struct diff_options *options)
6756 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6757 DIFF_FORMAT_NUMSTAT |
6758 DIFF_FORMAT_PATCH |
6759 DIFF_FORMAT_SHORTSTAT |
6760 DIFF_FORMAT_DIRSTAT;
6763 * Check if the user requested a blob-data-requiring diff output and/or
6764 * break-rewrite detection (which requires blob data). If yes, prefetch
6765 * the diff pairs.
6767 * If no prefetching occurs, diffcore_rename() will prefetch if it
6768 * decides that it needs inexact rename detection.
6770 if (options->repo == the_repository && has_promisor_remote() &&
6771 (options->output_format & output_formats_to_prefetch ||
6772 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6773 diff_queued_diff_prefetch(options->repo);
6775 /* NOTE please keep the following in sync with diff_tree_combined() */
6776 if (options->skip_stat_unmatch)
6777 diffcore_skip_stat_unmatch(options);
6778 if (!options->found_follow) {
6779 /* See try_to_follow_renames() in tree-diff.c */
6780 if (options->break_opt != -1)
6781 diffcore_break(options->repo,
6782 options->break_opt);
6783 if (options->detect_rename)
6784 diffcore_rename(options);
6785 if (options->break_opt != -1)
6786 diffcore_merge_broken();
6788 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6789 diffcore_pickaxe(options);
6790 if (options->orderfile)
6791 diffcore_order(options->orderfile);
6792 if (options->rotate_to)
6793 diffcore_rotate(options);
6794 if (!options->found_follow)
6795 /* See try_to_follow_renames() in tree-diff.c */
6796 diff_resolve_rename_copy();
6797 diffcore_apply_filter(options);
6799 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6800 options->flags.has_changes = 1;
6801 else
6802 options->flags.has_changes = 0;
6804 options->found_follow = 0;
6807 int diff_result_code(struct diff_options *opt, int status)
6809 int result = 0;
6811 diff_warn_rename_limit("diff.renameLimit",
6812 opt->needed_rename_limit,
6813 opt->degraded_cc_to_c);
6814 if (!opt->flags.exit_with_status &&
6815 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6816 return status;
6817 if (opt->flags.exit_with_status &&
6818 opt->flags.has_changes)
6819 result |= 01;
6820 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6821 opt->flags.check_failed)
6822 result |= 02;
6823 return result;
6826 int diff_can_quit_early(struct diff_options *opt)
6828 return (opt->flags.quick &&
6829 !opt->filter &&
6830 opt->flags.has_changes);
6834 * Shall changes to this submodule be ignored?
6836 * Submodule changes can be configured to be ignored separately for each path,
6837 * but that configuration can be overridden from the command line.
6839 static int is_submodule_ignored(const char *path, struct diff_options *options)
6841 int ignored = 0;
6842 struct diff_flags orig_flags = options->flags;
6843 if (!options->flags.override_submodule_config)
6844 set_diffopt_flags_from_submodule_config(options, path);
6845 if (options->flags.ignore_submodules)
6846 ignored = 1;
6847 options->flags = orig_flags;
6848 return ignored;
6851 void compute_diffstat(struct diff_options *options,
6852 struct diffstat_t *diffstat,
6853 struct diff_queue_struct *q)
6855 int i;
6857 memset(diffstat, 0, sizeof(struct diffstat_t));
6858 for (i = 0; i < q->nr; i++) {
6859 struct diff_filepair *p = q->queue[i];
6860 if (check_pair_status(p))
6861 diff_flush_stat(p, options, diffstat);
6865 void diff_addremove(struct diff_options *options,
6866 int addremove, unsigned mode,
6867 const struct object_id *oid,
6868 int oid_valid,
6869 const char *concatpath, unsigned dirty_submodule)
6871 struct diff_filespec *one, *two;
6873 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6874 return;
6876 /* This may look odd, but it is a preparation for
6877 * feeding "there are unchanged files which should
6878 * not produce diffs, but when you are doing copy
6879 * detection you would need them, so here they are"
6880 * entries to the diff-core. They will be prefixed
6881 * with something like '=' or '*' (I haven't decided
6882 * which but should not make any difference).
6883 * Feeding the same new and old to diff_change()
6884 * also has the same effect.
6885 * Before the final output happens, they are pruned after
6886 * merged into rename/copy pairs as appropriate.
6888 if (options->flags.reverse_diff)
6889 addremove = (addremove == '+' ? '-' :
6890 addremove == '-' ? '+' : addremove);
6892 if (options->prefix &&
6893 strncmp(concatpath, options->prefix, options->prefix_length))
6894 return;
6896 one = alloc_filespec(concatpath);
6897 two = alloc_filespec(concatpath);
6899 if (addremove != '+')
6900 fill_filespec(one, oid, oid_valid, mode);
6901 if (addremove != '-') {
6902 fill_filespec(two, oid, oid_valid, mode);
6903 two->dirty_submodule = dirty_submodule;
6906 diff_queue(&diff_queued_diff, one, two);
6907 if (!options->flags.diff_from_contents)
6908 options->flags.has_changes = 1;
6911 void diff_change(struct diff_options *options,
6912 unsigned old_mode, unsigned new_mode,
6913 const struct object_id *old_oid,
6914 const struct object_id *new_oid,
6915 int old_oid_valid, int new_oid_valid,
6916 const char *concatpath,
6917 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6919 struct diff_filespec *one, *two;
6920 struct diff_filepair *p;
6922 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6923 is_submodule_ignored(concatpath, options))
6924 return;
6926 if (options->flags.reverse_diff) {
6927 SWAP(old_mode, new_mode);
6928 SWAP(old_oid, new_oid);
6929 SWAP(old_oid_valid, new_oid_valid);
6930 SWAP(old_dirty_submodule, new_dirty_submodule);
6933 if (options->prefix &&
6934 strncmp(concatpath, options->prefix, options->prefix_length))
6935 return;
6937 one = alloc_filespec(concatpath);
6938 two = alloc_filespec(concatpath);
6939 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6940 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6941 one->dirty_submodule = old_dirty_submodule;
6942 two->dirty_submodule = new_dirty_submodule;
6943 p = diff_queue(&diff_queued_diff, one, two);
6945 if (options->flags.diff_from_contents)
6946 return;
6948 if (options->flags.quick && options->skip_stat_unmatch &&
6949 !diff_filespec_check_stat_unmatch(options->repo, p)) {
6950 diff_free_filespec_data(p->one);
6951 diff_free_filespec_data(p->two);
6952 return;
6955 options->flags.has_changes = 1;
6958 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6960 struct diff_filepair *pair;
6961 struct diff_filespec *one, *two;
6963 if (options->prefix &&
6964 strncmp(path, options->prefix, options->prefix_length))
6965 return NULL;
6967 one = alloc_filespec(path);
6968 two = alloc_filespec(path);
6969 pair = diff_queue(&diff_queued_diff, one, two);
6970 pair->is_unmerged = 1;
6971 return pair;
6974 static char *run_textconv(struct repository *r,
6975 const char *pgm,
6976 struct diff_filespec *spec,
6977 size_t *outsize)
6979 struct diff_tempfile *temp;
6980 struct child_process child = CHILD_PROCESS_INIT;
6981 struct strbuf buf = STRBUF_INIT;
6982 int err = 0;
6984 temp = prepare_temp_file(r, spec->path, spec);
6985 strvec_push(&child.args, pgm);
6986 strvec_push(&child.args, temp->name);
6988 child.use_shell = 1;
6989 child.out = -1;
6990 if (start_command(&child)) {
6991 remove_tempfile();
6992 return NULL;
6995 if (strbuf_read(&buf, child.out, 0) < 0)
6996 err = error("error reading from textconv command '%s'", pgm);
6997 close(child.out);
6999 if (finish_command(&child) || err) {
7000 strbuf_release(&buf);
7001 remove_tempfile();
7002 return NULL;
7004 remove_tempfile();
7006 return strbuf_detach(&buf, outsize);
7009 size_t fill_textconv(struct repository *r,
7010 struct userdiff_driver *driver,
7011 struct diff_filespec *df,
7012 char **outbuf)
7014 size_t size;
7016 if (!driver) {
7017 if (!DIFF_FILE_VALID(df)) {
7018 *outbuf = "";
7019 return 0;
7021 if (diff_populate_filespec(r, df, NULL))
7022 die("unable to read files to diff");
7023 *outbuf = df->data;
7024 return df->size;
7027 if (!driver->textconv)
7028 BUG("fill_textconv called with non-textconv driver");
7030 if (driver->textconv_cache && df->oid_valid) {
7031 *outbuf = notes_cache_get(driver->textconv_cache,
7032 &df->oid,
7033 &size);
7034 if (*outbuf)
7035 return size;
7038 *outbuf = run_textconv(r, driver->textconv, df, &size);
7039 if (!*outbuf)
7040 die("unable to read files to diff");
7042 if (driver->textconv_cache && df->oid_valid) {
7043 /* ignore errors, as we might be in a readonly repository */
7044 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7045 size);
7047 * we could save up changes and flush them all at the end,
7048 * but we would need an extra call after all diffing is done.
7049 * Since generating a cache entry is the slow path anyway,
7050 * this extra overhead probably isn't a big deal.
7052 notes_cache_write(driver->textconv_cache);
7055 return size;
7058 int textconv_object(struct repository *r,
7059 const char *path,
7060 unsigned mode,
7061 const struct object_id *oid,
7062 int oid_valid,
7063 char **buf,
7064 unsigned long *buf_size)
7066 struct diff_filespec *df;
7067 struct userdiff_driver *textconv;
7069 df = alloc_filespec(path);
7070 fill_filespec(df, oid, oid_valid, mode);
7071 textconv = get_textconv(r, df);
7072 if (!textconv) {
7073 free_filespec(df);
7074 return 0;
7077 *buf_size = fill_textconv(r, textconv, df, buf);
7078 free_filespec(df);
7079 return 1;
7082 void setup_diff_pager(struct diff_options *opt)
7085 * If the user asked for our exit code, then either they want --quiet
7086 * or --exit-code. We should definitely not bother with a pager in the
7087 * former case, as we will generate no output. Since we still properly
7088 * report our exit code even when a pager is run, we _could_ run a
7089 * pager with --exit-code. But since we have not done so historically,
7090 * and because it is easy to find people oneline advising "git diff
7091 * --exit-code" in hooks and other scripts, we do not do so.
7093 if (!opt->flags.exit_with_status &&
7094 check_pager_config("diff") != 0)
7095 setup_pager();