Merge branch 'jc/coding-guidelines-decl-in-for-loop'
[alt-git.git] / diff.c
blobef7159968b68c43c361a4cacc4558e14fe82fd4f
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 struct strbuf tempfile = STRBUF_INIT;
4140 char *path_dup = xstrdup(path);
4141 const char *base = basename(path_dup);
4142 struct checkout_metadata meta;
4144 init_checkout_metadata(&meta, NULL, NULL, oid);
4146 /* Generate "XXXXXX_basename.ext" */
4147 strbuf_addstr(&tempfile, "XXXXXX_");
4148 strbuf_addstr(&tempfile, base);
4150 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4151 if (!temp->tempfile)
4152 die_errno("unable to create temp-file");
4153 if (convert_to_working_tree(istate, path,
4154 (const char *)blob, (size_t)size, &buf, &meta)) {
4155 blob = buf.buf;
4156 size = buf.len;
4158 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4159 close_tempfile_gently(temp->tempfile))
4160 die_errno("unable to write temp-file");
4161 temp->name = get_tempfile_path(temp->tempfile);
4162 oid_to_hex_r(temp->hex, oid);
4163 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4164 strbuf_release(&buf);
4165 strbuf_release(&tempfile);
4166 free(path_dup);
4169 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4170 const char *name,
4171 struct diff_filespec *one)
4173 struct diff_tempfile *temp = claim_diff_tempfile();
4175 if (!DIFF_FILE_VALID(one)) {
4176 not_a_valid_file:
4177 /* A '-' entry produces this for file-2, and
4178 * a '+' entry produces this for file-1.
4180 temp->name = "/dev/null";
4181 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4182 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4183 return temp;
4186 if (!S_ISGITLINK(one->mode) &&
4187 (!one->oid_valid ||
4188 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4189 struct stat st;
4190 if (lstat(name, &st) < 0) {
4191 if (errno == ENOENT)
4192 goto not_a_valid_file;
4193 die_errno("stat(%s)", name);
4195 if (S_ISLNK(st.st_mode)) {
4196 struct strbuf sb = STRBUF_INIT;
4197 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4198 die_errno("readlink(%s)", name);
4199 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4200 (one->oid_valid ?
4201 &one->oid : null_oid()),
4202 (one->oid_valid ?
4203 one->mode : S_IFLNK));
4204 strbuf_release(&sb);
4206 else {
4207 /* we can borrow from the file in the work tree */
4208 temp->name = name;
4209 if (!one->oid_valid)
4210 oid_to_hex_r(temp->hex, null_oid());
4211 else
4212 oid_to_hex_r(temp->hex, &one->oid);
4213 /* Even though we may sometimes borrow the
4214 * contents from the work tree, we always want
4215 * one->mode. mode is trustworthy even when
4216 * !(one->oid_valid), as long as
4217 * DIFF_FILE_VALID(one).
4219 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4221 return temp;
4223 else {
4224 if (diff_populate_filespec(r, one, NULL))
4225 die("cannot read data blob for %s", one->path);
4226 prep_temp_blob(r->index, name, temp,
4227 one->data, one->size,
4228 &one->oid, one->mode);
4230 return temp;
4233 static void add_external_diff_name(struct repository *r,
4234 struct strvec *argv,
4235 const char *name,
4236 struct diff_filespec *df)
4238 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4239 strvec_push(argv, temp->name);
4240 strvec_push(argv, temp->hex);
4241 strvec_push(argv, temp->mode);
4244 /* An external diff command takes:
4246 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4247 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4250 static void run_external_diff(const char *pgm,
4251 const char *name,
4252 const char *other,
4253 struct diff_filespec *one,
4254 struct diff_filespec *two,
4255 const char *xfrm_msg,
4256 struct diff_options *o)
4258 struct strvec argv = STRVEC_INIT;
4259 struct strvec env = STRVEC_INIT;
4260 struct diff_queue_struct *q = &diff_queued_diff;
4262 strvec_push(&argv, pgm);
4263 strvec_push(&argv, name);
4265 if (one && two) {
4266 add_external_diff_name(o->repo, &argv, name, one);
4267 if (!other)
4268 add_external_diff_name(o->repo, &argv, name, two);
4269 else {
4270 add_external_diff_name(o->repo, &argv, other, two);
4271 strvec_push(&argv, other);
4272 strvec_push(&argv, xfrm_msg);
4276 strvec_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4277 strvec_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4279 diff_free_filespec_data(one);
4280 diff_free_filespec_data(two);
4281 if (run_command_v_opt_cd_env(argv.v, RUN_USING_SHELL, NULL, env.v))
4282 die(_("external diff died, stopping at %s"), name);
4284 remove_tempfile();
4285 strvec_clear(&argv);
4286 strvec_clear(&env);
4289 static int similarity_index(struct diff_filepair *p)
4291 return p->score * 100 / MAX_SCORE;
4294 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4296 if (startup_info->have_repository)
4297 return find_unique_abbrev(oid, abbrev);
4298 else {
4299 char *hex = oid_to_hex(oid);
4300 if (abbrev < 0)
4301 abbrev = FALLBACK_DEFAULT_ABBREV;
4302 if (abbrev > the_hash_algo->hexsz)
4303 BUG("oid abbreviation out of range: %d", abbrev);
4304 if (abbrev)
4305 hex[abbrev] = '\0';
4306 return hex;
4310 static void fill_metainfo(struct strbuf *msg,
4311 const char *name,
4312 const char *other,
4313 struct diff_filespec *one,
4314 struct diff_filespec *two,
4315 struct diff_options *o,
4316 struct diff_filepair *p,
4317 int *must_show_header,
4318 int use_color)
4320 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4321 const char *reset = diff_get_color(use_color, DIFF_RESET);
4322 const char *line_prefix = diff_line_prefix(o);
4323 struct strbuf *more_headers = NULL;
4325 *must_show_header = 1;
4326 strbuf_init(msg, PATH_MAX * 2 + 300);
4327 switch (p->status) {
4328 case DIFF_STATUS_COPIED:
4329 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4330 line_prefix, set, similarity_index(p));
4331 strbuf_addf(msg, "%s\n%s%scopy from ",
4332 reset, line_prefix, set);
4333 quote_c_style(name, msg, NULL, 0);
4334 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4335 quote_c_style(other, msg, NULL, 0);
4336 strbuf_addf(msg, "%s\n", reset);
4337 break;
4338 case DIFF_STATUS_RENAMED:
4339 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4340 line_prefix, set, similarity_index(p));
4341 strbuf_addf(msg, "%s\n%s%srename from ",
4342 reset, line_prefix, set);
4343 quote_c_style(name, msg, NULL, 0);
4344 strbuf_addf(msg, "%s\n%s%srename to ",
4345 reset, line_prefix, set);
4346 quote_c_style(other, msg, NULL, 0);
4347 strbuf_addf(msg, "%s\n", reset);
4348 break;
4349 case DIFF_STATUS_MODIFIED:
4350 if (p->score) {
4351 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4352 line_prefix,
4353 set, similarity_index(p), reset);
4354 break;
4356 /* fallthru */
4357 default:
4358 *must_show_header = 0;
4360 if ((more_headers = additional_headers(o, name))) {
4361 add_formatted_headers(msg, more_headers,
4362 line_prefix, set, reset);
4363 *must_show_header = 1;
4365 if (one && two && !oideq(&one->oid, &two->oid)) {
4366 const unsigned hexsz = the_hash_algo->hexsz;
4367 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4369 if (o->flags.full_index)
4370 abbrev = hexsz;
4372 if (o->flags.binary) {
4373 mmfile_t mf;
4374 if ((!fill_mmfile(o->repo, &mf, one) &&
4375 diff_filespec_is_binary(o->repo, one)) ||
4376 (!fill_mmfile(o->repo, &mf, two) &&
4377 diff_filespec_is_binary(o->repo, two)))
4378 abbrev = hexsz;
4380 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4381 diff_abbrev_oid(&one->oid, abbrev),
4382 diff_abbrev_oid(&two->oid, abbrev));
4383 if (one->mode == two->mode)
4384 strbuf_addf(msg, " %06o", one->mode);
4385 strbuf_addf(msg, "%s\n", reset);
4389 static void run_diff_cmd(const char *pgm,
4390 const char *name,
4391 const char *other,
4392 const char *attr_path,
4393 struct diff_filespec *one,
4394 struct diff_filespec *two,
4395 struct strbuf *msg,
4396 struct diff_options *o,
4397 struct diff_filepair *p)
4399 const char *xfrm_msg = NULL;
4400 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4401 int must_show_header = 0;
4404 if (o->flags.allow_external) {
4405 struct userdiff_driver *drv;
4407 drv = userdiff_find_by_path(o->repo->index, attr_path);
4408 if (drv && drv->external)
4409 pgm = drv->external;
4412 if (msg) {
4414 * don't use colors when the header is intended for an
4415 * external diff driver
4417 fill_metainfo(msg, name, other, one, two, o, p,
4418 &must_show_header,
4419 want_color(o->use_color) && !pgm);
4420 xfrm_msg = msg->len ? msg->buf : NULL;
4423 if (pgm) {
4424 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4425 return;
4427 if (one && two)
4428 builtin_diff(name, other ? other : name,
4429 one, two, xfrm_msg, must_show_header,
4430 o, complete_rewrite);
4431 else
4432 fprintf(o->file, "* Unmerged path %s\n", name);
4435 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4437 if (DIFF_FILE_VALID(one)) {
4438 if (!one->oid_valid) {
4439 struct stat st;
4440 if (one->is_stdin) {
4441 oidclr(&one->oid);
4442 return;
4444 if (lstat(one->path, &st) < 0)
4445 die_errno("stat '%s'", one->path);
4446 if (index_path(istate, &one->oid, one->path, &st, 0))
4447 die("cannot hash %s", one->path);
4450 else
4451 oidclr(&one->oid);
4454 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4456 /* Strip the prefix but do not molest /dev/null and absolute paths */
4457 if (*namep && !is_absolute_path(*namep)) {
4458 *namep += prefix_length;
4459 if (**namep == '/')
4460 ++*namep;
4462 if (*otherp && !is_absolute_path(*otherp)) {
4463 *otherp += prefix_length;
4464 if (**otherp == '/')
4465 ++*otherp;
4469 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4471 const char *pgm = external_diff();
4472 struct strbuf msg;
4473 struct diff_filespec *one = p->one;
4474 struct diff_filespec *two = p->two;
4475 const char *name;
4476 const char *other;
4477 const char *attr_path;
4479 name = one->path;
4480 other = (strcmp(name, two->path) ? two->path : NULL);
4481 attr_path = name;
4482 if (o->prefix_length)
4483 strip_prefix(o->prefix_length, &name, &other);
4485 if (!o->flags.allow_external)
4486 pgm = NULL;
4488 if (DIFF_PAIR_UNMERGED(p)) {
4489 run_diff_cmd(pgm, name, NULL, attr_path,
4490 NULL, NULL, NULL, o, p);
4491 return;
4494 diff_fill_oid_info(one, o->repo->index);
4495 diff_fill_oid_info(two, o->repo->index);
4497 if (!pgm &&
4498 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4499 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4501 * a filepair that changes between file and symlink
4502 * needs to be split into deletion and creation.
4504 struct diff_filespec *null = alloc_filespec(two->path);
4505 run_diff_cmd(NULL, name, other, attr_path,
4506 one, null, &msg,
4507 o, p);
4508 free(null);
4509 strbuf_release(&msg);
4511 null = alloc_filespec(one->path);
4512 run_diff_cmd(NULL, name, other, attr_path,
4513 null, two, &msg, o, p);
4514 free(null);
4516 else
4517 run_diff_cmd(pgm, name, other, attr_path,
4518 one, two, &msg, o, p);
4520 strbuf_release(&msg);
4523 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4524 struct diffstat_t *diffstat)
4526 const char *name;
4527 const char *other;
4529 if (DIFF_PAIR_UNMERGED(p)) {
4530 /* unmerged */
4531 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4532 diffstat, o, p);
4533 return;
4536 name = p->one->path;
4537 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4539 if (o->prefix_length)
4540 strip_prefix(o->prefix_length, &name, &other);
4542 diff_fill_oid_info(p->one, o->repo->index);
4543 diff_fill_oid_info(p->two, o->repo->index);
4545 builtin_diffstat(name, other, p->one, p->two,
4546 diffstat, o, p);
4549 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4551 const char *name;
4552 const char *other;
4553 const char *attr_path;
4555 if (DIFF_PAIR_UNMERGED(p)) {
4556 /* unmerged */
4557 return;
4560 name = p->one->path;
4561 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4562 attr_path = other ? other : name;
4564 if (o->prefix_length)
4565 strip_prefix(o->prefix_length, &name, &other);
4567 diff_fill_oid_info(p->one, o->repo->index);
4568 diff_fill_oid_info(p->two, o->repo->index);
4570 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4573 static void prep_parse_options(struct diff_options *options);
4575 void repo_diff_setup(struct repository *r, struct diff_options *options)
4577 memcpy(options, &default_diff_options, sizeof(*options));
4579 options->file = stdout;
4580 options->repo = r;
4582 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4583 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4584 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4585 options->abbrev = DEFAULT_ABBREV;
4586 options->line_termination = '\n';
4587 options->break_opt = -1;
4588 options->rename_limit = -1;
4589 options->dirstat_permille = diff_dirstat_permille_default;
4590 options->context = diff_context_default;
4591 options->interhunkcontext = diff_interhunk_context_default;
4592 options->ws_error_highlight = ws_error_highlight_default;
4593 options->flags.rename_empty = 1;
4594 options->flags.relative_name = diff_relative;
4595 options->objfind = NULL;
4597 /* pathchange left =NULL by default */
4598 options->change = diff_change;
4599 options->add_remove = diff_addremove;
4600 options->use_color = diff_use_color_default;
4601 options->detect_rename = diff_detect_rename_default;
4602 options->xdl_opts |= diff_algorithm;
4603 if (diff_indent_heuristic)
4604 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4606 options->orderfile = diff_order_file_cfg;
4608 if (!options->flags.ignore_submodule_set)
4609 options->flags.ignore_untracked_in_submodules = 1;
4611 if (diff_no_prefix) {
4612 options->a_prefix = options->b_prefix = "";
4613 } else if (!diff_mnemonic_prefix) {
4614 options->a_prefix = "a/";
4615 options->b_prefix = "b/";
4618 options->color_moved = diff_color_moved_default;
4619 options->color_moved_ws_handling = diff_color_moved_ws_default;
4621 prep_parse_options(options);
4624 static const char diff_status_letters[] = {
4625 DIFF_STATUS_ADDED,
4626 DIFF_STATUS_COPIED,
4627 DIFF_STATUS_DELETED,
4628 DIFF_STATUS_MODIFIED,
4629 DIFF_STATUS_RENAMED,
4630 DIFF_STATUS_TYPE_CHANGED,
4631 DIFF_STATUS_UNKNOWN,
4632 DIFF_STATUS_UNMERGED,
4633 DIFF_STATUS_FILTER_AON,
4634 DIFF_STATUS_FILTER_BROKEN,
4635 '\0',
4638 static unsigned int filter_bit['Z' + 1];
4640 static void prepare_filter_bits(void)
4642 int i;
4644 if (!filter_bit[DIFF_STATUS_ADDED]) {
4645 for (i = 0; diff_status_letters[i]; i++)
4646 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4650 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4652 return opt->filter & filter_bit[(int) status];
4655 unsigned diff_filter_bit(char status)
4657 prepare_filter_bits();
4658 return filter_bit[(int) status];
4661 void diff_setup_done(struct diff_options *options)
4663 unsigned check_mask = DIFF_FORMAT_NAME |
4664 DIFF_FORMAT_NAME_STATUS |
4665 DIFF_FORMAT_CHECKDIFF |
4666 DIFF_FORMAT_NO_OUTPUT;
4668 * This must be signed because we're comparing against a potentially
4669 * negative value.
4671 const int hexsz = the_hash_algo->hexsz;
4673 if (options->set_default)
4674 options->set_default(options);
4676 if (HAS_MULTI_BITS(options->output_format & check_mask))
4677 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4678 "--name-only", "--name-status", "--check", "-s");
4680 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4681 die(_("options '%s', '%s', and '%s' cannot be used together"),
4682 "-G", "-S", "--find-object");
4684 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4685 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4686 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4688 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4689 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4690 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4693 * Most of the time we can say "there are changes"
4694 * only by checking if there are changed paths, but
4695 * --ignore-whitespace* options force us to look
4696 * inside contents.
4699 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4700 options->ignore_regex_nr)
4701 options->flags.diff_from_contents = 1;
4702 else
4703 options->flags.diff_from_contents = 0;
4705 if (options->flags.find_copies_harder)
4706 options->detect_rename = DIFF_DETECT_COPY;
4708 if (!options->flags.relative_name)
4709 options->prefix = NULL;
4710 if (options->prefix)
4711 options->prefix_length = strlen(options->prefix);
4712 else
4713 options->prefix_length = 0;
4715 if (options->output_format & (DIFF_FORMAT_NAME |
4716 DIFF_FORMAT_NAME_STATUS |
4717 DIFF_FORMAT_CHECKDIFF |
4718 DIFF_FORMAT_NO_OUTPUT))
4719 options->output_format &= ~(DIFF_FORMAT_RAW |
4720 DIFF_FORMAT_NUMSTAT |
4721 DIFF_FORMAT_DIFFSTAT |
4722 DIFF_FORMAT_SHORTSTAT |
4723 DIFF_FORMAT_DIRSTAT |
4724 DIFF_FORMAT_SUMMARY |
4725 DIFF_FORMAT_PATCH);
4728 * These cases always need recursive; we do not drop caller-supplied
4729 * recursive bits for other formats here.
4731 if (options->output_format & (DIFF_FORMAT_PATCH |
4732 DIFF_FORMAT_NUMSTAT |
4733 DIFF_FORMAT_DIFFSTAT |
4734 DIFF_FORMAT_SHORTSTAT |
4735 DIFF_FORMAT_DIRSTAT |
4736 DIFF_FORMAT_SUMMARY |
4737 DIFF_FORMAT_CHECKDIFF))
4738 options->flags.recursive = 1;
4740 * Also pickaxe would not work very well if you do not say recursive
4742 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4743 options->flags.recursive = 1;
4745 * When patches are generated, submodules diffed against the work tree
4746 * must be checked for dirtiness too so it can be shown in the output
4748 if (options->output_format & DIFF_FORMAT_PATCH)
4749 options->flags.dirty_submodules = 1;
4751 if (options->detect_rename && options->rename_limit < 0)
4752 options->rename_limit = diff_rename_limit_default;
4753 if (hexsz < options->abbrev)
4754 options->abbrev = hexsz; /* full */
4757 * It does not make sense to show the first hit we happened
4758 * to have found. It does not make sense not to return with
4759 * exit code in such a case either.
4761 if (options->flags.quick) {
4762 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4763 options->flags.exit_with_status = 1;
4766 options->diff_path_counter = 0;
4768 if (options->flags.follow_renames && options->pathspec.nr != 1)
4769 die(_("--follow requires exactly one pathspec"));
4771 if (!options->use_color || external_diff())
4772 options->color_moved = 0;
4774 if (options->filter_not) {
4775 if (!options->filter)
4776 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4777 options->filter &= ~options->filter_not;
4780 FREE_AND_NULL(options->parseopts);
4783 int parse_long_opt(const char *opt, const char **argv,
4784 const char **optarg)
4786 const char *arg = argv[0];
4787 if (!skip_prefix(arg, "--", &arg))
4788 return 0;
4789 if (!skip_prefix(arg, opt, &arg))
4790 return 0;
4791 if (*arg == '=') { /* stuck form: --option=value */
4792 *optarg = arg + 1;
4793 return 1;
4795 if (*arg != '\0')
4796 return 0;
4797 /* separate form: --option value */
4798 if (!argv[1])
4799 die("Option '--%s' requires a value", opt);
4800 *optarg = argv[1];
4801 return 2;
4804 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4806 struct diff_options *options = opt->value;
4807 int width = options->stat_width;
4808 int name_width = options->stat_name_width;
4809 int graph_width = options->stat_graph_width;
4810 int count = options->stat_count;
4811 char *end;
4813 BUG_ON_OPT_NEG(unset);
4815 if (!strcmp(opt->long_name, "stat")) {
4816 if (value) {
4817 width = strtoul(value, &end, 10);
4818 if (*end == ',')
4819 name_width = strtoul(end+1, &end, 10);
4820 if (*end == ',')
4821 count = strtoul(end+1, &end, 10);
4822 if (*end)
4823 return error(_("invalid --stat value: %s"), value);
4825 } else if (!strcmp(opt->long_name, "stat-width")) {
4826 width = strtoul(value, &end, 10);
4827 if (*end)
4828 return error(_("%s expects a numerical value"),
4829 opt->long_name);
4830 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4831 name_width = strtoul(value, &end, 10);
4832 if (*end)
4833 return error(_("%s expects a numerical value"),
4834 opt->long_name);
4835 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4836 graph_width = strtoul(value, &end, 10);
4837 if (*end)
4838 return error(_("%s expects a numerical value"),
4839 opt->long_name);
4840 } else if (!strcmp(opt->long_name, "stat-count")) {
4841 count = strtoul(value, &end, 10);
4842 if (*end)
4843 return error(_("%s expects a numerical value"),
4844 opt->long_name);
4845 } else
4846 BUG("%s should not get here", opt->long_name);
4848 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4849 options->stat_name_width = name_width;
4850 options->stat_graph_width = graph_width;
4851 options->stat_width = width;
4852 options->stat_count = count;
4853 return 0;
4856 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4858 struct strbuf errmsg = STRBUF_INIT;
4859 if (parse_dirstat_params(options, params, &errmsg))
4860 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4861 errmsg.buf);
4862 strbuf_release(&errmsg);
4864 * The caller knows a dirstat-related option is given from the command
4865 * line; allow it to say "return this_function();"
4867 options->output_format |= DIFF_FORMAT_DIRSTAT;
4868 return 1;
4871 static int diff_opt_diff_filter(const struct option *option,
4872 const char *optarg, int unset)
4874 struct diff_options *opt = option->value;
4875 int i, optch;
4877 BUG_ON_OPT_NEG(unset);
4878 prepare_filter_bits();
4880 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4881 unsigned int bit;
4882 int negate;
4884 if ('a' <= optch && optch <= 'z') {
4885 negate = 1;
4886 optch = toupper(optch);
4887 } else {
4888 negate = 0;
4891 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4892 if (!bit)
4893 return error(_("unknown change class '%c' in --diff-filter=%s"),
4894 optarg[i], optarg);
4895 if (negate)
4896 opt->filter_not |= bit;
4897 else
4898 opt->filter |= bit;
4900 return 0;
4903 static void enable_patch_output(int *fmt)
4905 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4906 *fmt |= DIFF_FORMAT_PATCH;
4909 static int diff_opt_ws_error_highlight(const struct option *option,
4910 const char *arg, int unset)
4912 struct diff_options *opt = option->value;
4913 int val = parse_ws_error_highlight(arg);
4915 BUG_ON_OPT_NEG(unset);
4916 if (val < 0)
4917 return error(_("unknown value after ws-error-highlight=%.*s"),
4918 -1 - val, arg);
4919 opt->ws_error_highlight = val;
4920 return 0;
4923 static int diff_opt_find_object(const struct option *option,
4924 const char *arg, int unset)
4926 struct diff_options *opt = option->value;
4927 struct object_id oid;
4929 BUG_ON_OPT_NEG(unset);
4930 if (get_oid(arg, &oid))
4931 return error(_("unable to resolve '%s'"), arg);
4933 if (!opt->objfind)
4934 CALLOC_ARRAY(opt->objfind, 1);
4936 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4937 opt->flags.recursive = 1;
4938 opt->flags.tree_in_recursive = 1;
4939 oidset_insert(opt->objfind, &oid);
4940 return 0;
4943 static int diff_opt_anchored(const struct option *opt,
4944 const char *arg, int unset)
4946 struct diff_options *options = opt->value;
4948 BUG_ON_OPT_NEG(unset);
4949 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4950 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4951 options->anchors_alloc);
4952 options->anchors[options->anchors_nr++] = xstrdup(arg);
4953 return 0;
4956 static int diff_opt_binary(const struct option *opt,
4957 const char *arg, int unset)
4959 struct diff_options *options = opt->value;
4961 BUG_ON_OPT_NEG(unset);
4962 BUG_ON_OPT_ARG(arg);
4963 enable_patch_output(&options->output_format);
4964 options->flags.binary = 1;
4965 return 0;
4968 static int diff_opt_break_rewrites(const struct option *opt,
4969 const char *arg, int unset)
4971 int *break_opt = opt->value;
4972 int opt1, opt2;
4974 BUG_ON_OPT_NEG(unset);
4975 if (!arg)
4976 arg = "";
4977 opt1 = parse_rename_score(&arg);
4978 if (*arg == 0)
4979 opt2 = 0;
4980 else if (*arg != '/')
4981 return error(_("%s expects <n>/<m> form"), opt->long_name);
4982 else {
4983 arg++;
4984 opt2 = parse_rename_score(&arg);
4986 if (*arg != 0)
4987 return error(_("%s expects <n>/<m> form"), opt->long_name);
4988 *break_opt = opt1 | (opt2 << 16);
4989 return 0;
4992 static int diff_opt_char(const struct option *opt,
4993 const char *arg, int unset)
4995 char *value = opt->value;
4997 BUG_ON_OPT_NEG(unset);
4998 if (arg[1])
4999 return error(_("%s expects a character, got '%s'"),
5000 opt->long_name, arg);
5001 *value = arg[0];
5002 return 0;
5005 static int diff_opt_color_moved(const struct option *opt,
5006 const char *arg, int unset)
5008 struct diff_options *options = opt->value;
5010 if (unset) {
5011 options->color_moved = COLOR_MOVED_NO;
5012 } else if (!arg) {
5013 if (diff_color_moved_default)
5014 options->color_moved = diff_color_moved_default;
5015 if (options->color_moved == COLOR_MOVED_NO)
5016 options->color_moved = COLOR_MOVED_DEFAULT;
5017 } else {
5018 int cm = parse_color_moved(arg);
5019 if (cm < 0)
5020 return error(_("bad --color-moved argument: %s"), arg);
5021 options->color_moved = cm;
5023 return 0;
5026 static int diff_opt_color_moved_ws(const struct option *opt,
5027 const char *arg, int unset)
5029 struct diff_options *options = opt->value;
5030 unsigned cm;
5032 if (unset) {
5033 options->color_moved_ws_handling = 0;
5034 return 0;
5037 cm = parse_color_moved_ws(arg);
5038 if (cm & COLOR_MOVED_WS_ERROR)
5039 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5040 options->color_moved_ws_handling = cm;
5041 return 0;
5044 static int diff_opt_color_words(const struct option *opt,
5045 const char *arg, int unset)
5047 struct diff_options *options = opt->value;
5049 BUG_ON_OPT_NEG(unset);
5050 options->use_color = 1;
5051 options->word_diff = DIFF_WORDS_COLOR;
5052 options->word_regex = arg;
5053 return 0;
5056 static int diff_opt_compact_summary(const struct option *opt,
5057 const char *arg, int unset)
5059 struct diff_options *options = opt->value;
5061 BUG_ON_OPT_ARG(arg);
5062 if (unset) {
5063 options->flags.stat_with_summary = 0;
5064 } else {
5065 options->flags.stat_with_summary = 1;
5066 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5068 return 0;
5071 static int diff_opt_diff_algorithm(const struct option *opt,
5072 const char *arg, int unset)
5074 struct diff_options *options = opt->value;
5075 long value = parse_algorithm_value(arg);
5077 BUG_ON_OPT_NEG(unset);
5078 if (value < 0)
5079 return error(_("option diff-algorithm accepts \"myers\", "
5080 "\"minimal\", \"patience\" and \"histogram\""));
5082 /* clear out previous settings */
5083 DIFF_XDL_CLR(options, NEED_MINIMAL);
5084 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5085 options->xdl_opts |= value;
5086 return 0;
5089 static int diff_opt_dirstat(const struct option *opt,
5090 const char *arg, int unset)
5092 struct diff_options *options = opt->value;
5094 BUG_ON_OPT_NEG(unset);
5095 if (!strcmp(opt->long_name, "cumulative")) {
5096 if (arg)
5097 BUG("how come --cumulative take a value?");
5098 arg = "cumulative";
5099 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5100 parse_dirstat_opt(options, "files");
5101 parse_dirstat_opt(options, arg ? arg : "");
5102 return 0;
5105 static int diff_opt_find_copies(const struct option *opt,
5106 const char *arg, int unset)
5108 struct diff_options *options = opt->value;
5110 BUG_ON_OPT_NEG(unset);
5111 if (!arg)
5112 arg = "";
5113 options->rename_score = parse_rename_score(&arg);
5114 if (*arg != 0)
5115 return error(_("invalid argument to %s"), opt->long_name);
5117 if (options->detect_rename == DIFF_DETECT_COPY)
5118 options->flags.find_copies_harder = 1;
5119 else
5120 options->detect_rename = DIFF_DETECT_COPY;
5122 return 0;
5125 static int diff_opt_find_renames(const struct option *opt,
5126 const char *arg, int unset)
5128 struct diff_options *options = opt->value;
5130 BUG_ON_OPT_NEG(unset);
5131 if (!arg)
5132 arg = "";
5133 options->rename_score = parse_rename_score(&arg);
5134 if (*arg != 0)
5135 return error(_("invalid argument to %s"), opt->long_name);
5137 options->detect_rename = DIFF_DETECT_RENAME;
5138 return 0;
5141 static int diff_opt_follow(const struct option *opt,
5142 const char *arg, int unset)
5144 struct diff_options *options = opt->value;
5146 BUG_ON_OPT_ARG(arg);
5147 if (unset) {
5148 options->flags.follow_renames = 0;
5149 options->flags.default_follow_renames = 0;
5150 } else {
5151 options->flags.follow_renames = 1;
5153 return 0;
5156 static int diff_opt_ignore_submodules(const struct option *opt,
5157 const char *arg, int unset)
5159 struct diff_options *options = opt->value;
5161 BUG_ON_OPT_NEG(unset);
5162 if (!arg)
5163 arg = "all";
5164 options->flags.override_submodule_config = 1;
5165 handle_ignore_submodules_arg(options, arg);
5166 return 0;
5169 static int diff_opt_line_prefix(const struct option *opt,
5170 const char *optarg, int unset)
5172 struct diff_options *options = opt->value;
5174 BUG_ON_OPT_NEG(unset);
5175 options->line_prefix = optarg;
5176 options->line_prefix_length = strlen(options->line_prefix);
5177 graph_setup_line_prefix(options);
5178 return 0;
5181 static int diff_opt_no_prefix(const struct option *opt,
5182 const char *optarg, int unset)
5184 struct diff_options *options = opt->value;
5186 BUG_ON_OPT_NEG(unset);
5187 BUG_ON_OPT_ARG(optarg);
5188 options->a_prefix = "";
5189 options->b_prefix = "";
5190 return 0;
5193 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5194 const struct option *opt,
5195 const char *arg, int unset)
5197 struct diff_options *options = opt->value;
5198 char *path;
5200 BUG_ON_OPT_NEG(unset);
5201 path = prefix_filename(ctx->prefix, arg);
5202 options->file = xfopen(path, "w");
5203 options->close_file = 1;
5204 if (options->use_color != GIT_COLOR_ALWAYS)
5205 options->use_color = GIT_COLOR_NEVER;
5206 free(path);
5207 return 0;
5210 static int diff_opt_patience(const struct option *opt,
5211 const char *arg, int unset)
5213 struct diff_options *options = opt->value;
5214 int i;
5216 BUG_ON_OPT_NEG(unset);
5217 BUG_ON_OPT_ARG(arg);
5218 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5220 * Both --patience and --anchored use PATIENCE_DIFF
5221 * internally, so remove any anchors previously
5222 * specified.
5224 for (i = 0; i < options->anchors_nr; i++)
5225 free(options->anchors[i]);
5226 options->anchors_nr = 0;
5227 return 0;
5230 static int diff_opt_ignore_regex(const struct option *opt,
5231 const char *arg, int unset)
5233 struct diff_options *options = opt->value;
5234 regex_t *regex;
5236 BUG_ON_OPT_NEG(unset);
5237 regex = xmalloc(sizeof(*regex));
5238 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5239 return error(_("invalid regex given to -I: '%s'"), arg);
5240 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5241 options->ignore_regex_alloc);
5242 options->ignore_regex[options->ignore_regex_nr++] = regex;
5243 return 0;
5246 static int diff_opt_pickaxe_regex(const struct option *opt,
5247 const char *arg, int unset)
5249 struct diff_options *options = opt->value;
5251 BUG_ON_OPT_NEG(unset);
5252 options->pickaxe = arg;
5253 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5254 return 0;
5257 static int diff_opt_pickaxe_string(const struct option *opt,
5258 const char *arg, int unset)
5260 struct diff_options *options = opt->value;
5262 BUG_ON_OPT_NEG(unset);
5263 options->pickaxe = arg;
5264 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5265 return 0;
5268 static int diff_opt_relative(const struct option *opt,
5269 const char *arg, int unset)
5271 struct diff_options *options = opt->value;
5273 options->flags.relative_name = !unset;
5274 if (arg)
5275 options->prefix = arg;
5276 return 0;
5279 static int diff_opt_submodule(const struct option *opt,
5280 const char *arg, int unset)
5282 struct diff_options *options = opt->value;
5284 BUG_ON_OPT_NEG(unset);
5285 if (!arg)
5286 arg = "log";
5287 if (parse_submodule_params(options, arg))
5288 return error(_("failed to parse --submodule option parameter: '%s'"),
5289 arg);
5290 return 0;
5293 static int diff_opt_textconv(const struct option *opt,
5294 const char *arg, int unset)
5296 struct diff_options *options = opt->value;
5298 BUG_ON_OPT_ARG(arg);
5299 if (unset) {
5300 options->flags.allow_textconv = 0;
5301 } else {
5302 options->flags.allow_textconv = 1;
5303 options->flags.textconv_set_via_cmdline = 1;
5305 return 0;
5308 static int diff_opt_unified(const struct option *opt,
5309 const char *arg, int unset)
5311 struct diff_options *options = opt->value;
5312 char *s;
5314 BUG_ON_OPT_NEG(unset);
5316 if (arg) {
5317 options->context = strtol(arg, &s, 10);
5318 if (*s)
5319 return error(_("%s expects a numerical value"), "--unified");
5321 enable_patch_output(&options->output_format);
5323 return 0;
5326 static int diff_opt_word_diff(const struct option *opt,
5327 const char *arg, int unset)
5329 struct diff_options *options = opt->value;
5331 BUG_ON_OPT_NEG(unset);
5332 if (arg) {
5333 if (!strcmp(arg, "plain"))
5334 options->word_diff = DIFF_WORDS_PLAIN;
5335 else if (!strcmp(arg, "color")) {
5336 options->use_color = 1;
5337 options->word_diff = DIFF_WORDS_COLOR;
5339 else if (!strcmp(arg, "porcelain"))
5340 options->word_diff = DIFF_WORDS_PORCELAIN;
5341 else if (!strcmp(arg, "none"))
5342 options->word_diff = DIFF_WORDS_NONE;
5343 else
5344 return error(_("bad --word-diff argument: %s"), arg);
5345 } else {
5346 if (options->word_diff == DIFF_WORDS_NONE)
5347 options->word_diff = DIFF_WORDS_PLAIN;
5349 return 0;
5352 static int diff_opt_word_diff_regex(const struct option *opt,
5353 const char *arg, int unset)
5355 struct diff_options *options = opt->value;
5357 BUG_ON_OPT_NEG(unset);
5358 if (options->word_diff == DIFF_WORDS_NONE)
5359 options->word_diff = DIFF_WORDS_PLAIN;
5360 options->word_regex = arg;
5361 return 0;
5364 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5366 struct diff_options *options = opt->value;
5368 BUG_ON_OPT_NEG(unset);
5369 if (!strcmp(opt->long_name, "skip-to"))
5370 options->skip_instead_of_rotate = 1;
5371 else
5372 options->skip_instead_of_rotate = 0;
5373 options->rotate_to = arg;
5374 return 0;
5377 static void prep_parse_options(struct diff_options *options)
5379 struct option parseopts[] = {
5380 OPT_GROUP(N_("Diff output format options")),
5381 OPT_BITOP('p', "patch", &options->output_format,
5382 N_("generate patch"),
5383 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5384 OPT_BIT_F('s', "no-patch", &options->output_format,
5385 N_("suppress diff output"),
5386 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5387 OPT_BITOP('u', NULL, &options->output_format,
5388 N_("generate patch"),
5389 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5390 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5391 N_("generate diffs with <n> lines context"),
5392 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5393 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5394 N_("generate diffs with <n> lines context")),
5395 OPT_BIT_F(0, "raw", &options->output_format,
5396 N_("generate the diff in raw format"),
5397 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5398 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5399 N_("synonym for '-p --raw'"),
5400 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5401 DIFF_FORMAT_NO_OUTPUT),
5402 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5403 N_("synonym for '-p --stat'"),
5404 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5405 DIFF_FORMAT_NO_OUTPUT),
5406 OPT_BIT_F(0, "numstat", &options->output_format,
5407 N_("machine friendly --stat"),
5408 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5409 OPT_BIT_F(0, "shortstat", &options->output_format,
5410 N_("output only the last line of --stat"),
5411 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5412 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5413 N_("output the distribution of relative amount of changes for each sub-directory"),
5414 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5415 diff_opt_dirstat),
5416 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5417 N_("synonym for --dirstat=cumulative"),
5418 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5419 diff_opt_dirstat),
5420 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5421 N_("synonym for --dirstat=files,param1,param2..."),
5422 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5423 diff_opt_dirstat),
5424 OPT_BIT_F(0, "check", &options->output_format,
5425 N_("warn if changes introduce conflict markers or whitespace errors"),
5426 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5427 OPT_BIT_F(0, "summary", &options->output_format,
5428 N_("condensed summary such as creations, renames and mode changes"),
5429 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5430 OPT_BIT_F(0, "name-only", &options->output_format,
5431 N_("show only names of changed files"),
5432 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5433 OPT_BIT_F(0, "name-status", &options->output_format,
5434 N_("show only names and status of changed files"),
5435 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5436 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5437 N_("generate diffstat"),
5438 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5439 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5440 N_("generate diffstat with a given width"),
5441 PARSE_OPT_NONEG, diff_opt_stat),
5442 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5443 N_("generate diffstat with a given name width"),
5444 PARSE_OPT_NONEG, diff_opt_stat),
5445 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5446 N_("generate diffstat with a given graph width"),
5447 PARSE_OPT_NONEG, diff_opt_stat),
5448 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5449 N_("generate diffstat with limited lines"),
5450 PARSE_OPT_NONEG, diff_opt_stat),
5451 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5452 N_("generate compact summary in diffstat"),
5453 PARSE_OPT_NOARG, diff_opt_compact_summary),
5454 OPT_CALLBACK_F(0, "binary", options, NULL,
5455 N_("output a binary diff that can be applied"),
5456 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5457 OPT_BOOL(0, "full-index", &options->flags.full_index,
5458 N_("show full pre- and post-image object names on the \"index\" lines")),
5459 OPT_COLOR_FLAG(0, "color", &options->use_color,
5460 N_("show colored diff")),
5461 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5462 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5463 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5464 OPT_SET_INT('z', NULL, &options->line_termination,
5465 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5467 OPT__ABBREV(&options->abbrev),
5468 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5469 N_("show the given source prefix instead of \"a/\""),
5470 PARSE_OPT_NONEG),
5471 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5472 N_("show the given destination prefix instead of \"b/\""),
5473 PARSE_OPT_NONEG),
5474 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5475 N_("prepend an additional prefix to every line of output"),
5476 PARSE_OPT_NONEG, diff_opt_line_prefix),
5477 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5478 N_("do not show any source or destination prefix"),
5479 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5480 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5481 N_("show context between diff hunks up to the specified number of lines"),
5482 PARSE_OPT_NONEG),
5483 OPT_CALLBACK_F(0, "output-indicator-new",
5484 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5485 N_("<char>"),
5486 N_("specify the character to indicate a new line instead of '+'"),
5487 PARSE_OPT_NONEG, diff_opt_char),
5488 OPT_CALLBACK_F(0, "output-indicator-old",
5489 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5490 N_("<char>"),
5491 N_("specify the character to indicate an old line instead of '-'"),
5492 PARSE_OPT_NONEG, diff_opt_char),
5493 OPT_CALLBACK_F(0, "output-indicator-context",
5494 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5495 N_("<char>"),
5496 N_("specify the character to indicate a context instead of ' '"),
5497 PARSE_OPT_NONEG, diff_opt_char),
5499 OPT_GROUP(N_("Diff rename options")),
5500 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5501 N_("break complete rewrite changes into pairs of delete and create"),
5502 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5503 diff_opt_break_rewrites),
5504 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5505 N_("detect renames"),
5506 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5507 diff_opt_find_renames),
5508 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5509 N_("omit the preimage for deletes"),
5510 1, PARSE_OPT_NONEG),
5511 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5512 N_("detect copies"),
5513 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5514 diff_opt_find_copies),
5515 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5516 N_("use unmodified files as source to find copies")),
5517 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5518 N_("disable rename detection"),
5519 0, PARSE_OPT_NONEG),
5520 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5521 N_("use empty blobs as rename source")),
5522 OPT_CALLBACK_F(0, "follow", options, NULL,
5523 N_("continue listing the history of a file beyond renames"),
5524 PARSE_OPT_NOARG, diff_opt_follow),
5525 OPT_INTEGER('l', NULL, &options->rename_limit,
5526 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5528 OPT_GROUP(N_("Diff algorithm options")),
5529 OPT_BIT(0, "minimal", &options->xdl_opts,
5530 N_("produce the smallest possible diff"),
5531 XDF_NEED_MINIMAL),
5532 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5533 N_("ignore whitespace when comparing lines"),
5534 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5535 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5536 N_("ignore changes in amount of whitespace"),
5537 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5538 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5539 N_("ignore changes in whitespace at EOL"),
5540 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5541 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5542 N_("ignore carrier-return at the end of line"),
5543 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5544 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5545 N_("ignore changes whose lines are all blank"),
5546 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5547 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5548 N_("ignore changes whose all lines match <regex>"),
5549 0, diff_opt_ignore_regex),
5550 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5551 N_("heuristic to shift diff hunk boundaries for easy reading"),
5552 XDF_INDENT_HEURISTIC),
5553 OPT_CALLBACK_F(0, "patience", options, NULL,
5554 N_("generate diff using the \"patience diff\" algorithm"),
5555 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5556 diff_opt_patience),
5557 OPT_BITOP(0, "histogram", &options->xdl_opts,
5558 N_("generate diff using the \"histogram diff\" algorithm"),
5559 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5560 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5561 N_("choose a diff algorithm"),
5562 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5563 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5564 N_("generate diff using the \"anchored diff\" algorithm"),
5565 PARSE_OPT_NONEG, diff_opt_anchored),
5566 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5567 N_("show word diff, using <mode> to delimit changed words"),
5568 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5569 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5570 N_("use <regex> to decide what a word is"),
5571 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5572 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5573 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5574 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5575 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5576 N_("moved lines of code are colored differently"),
5577 PARSE_OPT_OPTARG, diff_opt_color_moved),
5578 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5579 N_("how white spaces are ignored in --color-moved"),
5580 0, diff_opt_color_moved_ws),
5582 OPT_GROUP(N_("Other diff options")),
5583 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5584 N_("when run from subdir, exclude changes outside and show relative paths"),
5585 PARSE_OPT_OPTARG,
5586 diff_opt_relative),
5587 OPT_BOOL('a', "text", &options->flags.text,
5588 N_("treat all files as text")),
5589 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5590 N_("swap two inputs, reverse the diff")),
5591 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5592 N_("exit with 1 if there were differences, 0 otherwise")),
5593 OPT_BOOL(0, "quiet", &options->flags.quick,
5594 N_("disable all output of the program")),
5595 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5596 N_("allow an external diff helper to be executed")),
5597 OPT_CALLBACK_F(0, "textconv", options, NULL,
5598 N_("run external text conversion filters when comparing binary files"),
5599 PARSE_OPT_NOARG, diff_opt_textconv),
5600 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5601 N_("ignore changes to submodules in the diff generation"),
5602 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5603 diff_opt_ignore_submodules),
5604 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5605 N_("specify how differences in submodules are shown"),
5606 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5607 diff_opt_submodule),
5608 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5609 N_("hide 'git add -N' entries from the index"),
5610 1, PARSE_OPT_NONEG),
5611 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5612 N_("treat 'git add -N' entries as real in the index"),
5613 0, PARSE_OPT_NONEG),
5614 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5615 N_("look for differences that change the number of occurrences of the specified string"),
5616 0, diff_opt_pickaxe_string),
5617 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5618 N_("look for differences that change the number of occurrences of the specified regex"),
5619 0, diff_opt_pickaxe_regex),
5620 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5621 N_("show all changes in the changeset with -S or -G"),
5622 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5623 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5624 N_("treat <string> in -S as extended POSIX regular expression"),
5625 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5626 OPT_FILENAME('O', NULL, &options->orderfile,
5627 N_("control the order in which files appear in the output")),
5628 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5629 N_("show the change in the specified path first"),
5630 PARSE_OPT_NONEG, diff_opt_rotate_to),
5631 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5632 N_("skip the output to the specified path"),
5633 PARSE_OPT_NONEG, diff_opt_rotate_to),
5634 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5635 N_("look for differences that change the number of occurrences of the specified object"),
5636 PARSE_OPT_NONEG, diff_opt_find_object),
5637 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5638 N_("select files by diff type"),
5639 PARSE_OPT_NONEG, diff_opt_diff_filter),
5640 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5641 N_("output to a specific file"),
5642 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5644 OPT_END()
5647 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5648 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5651 int diff_opt_parse(struct diff_options *options,
5652 const char **av, int ac, const char *prefix)
5654 if (!prefix)
5655 prefix = "";
5657 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5658 PARSE_OPT_KEEP_DASHDASH |
5659 PARSE_OPT_KEEP_UNKNOWN |
5660 PARSE_OPT_NO_INTERNAL_HELP |
5661 PARSE_OPT_ONE_SHOT |
5662 PARSE_OPT_STOP_AT_NON_OPTION);
5664 return ac;
5667 int parse_rename_score(const char **cp_p)
5669 unsigned long num, scale;
5670 int ch, dot;
5671 const char *cp = *cp_p;
5673 num = 0;
5674 scale = 1;
5675 dot = 0;
5676 for (;;) {
5677 ch = *cp;
5678 if ( !dot && ch == '.' ) {
5679 scale = 1;
5680 dot = 1;
5681 } else if ( ch == '%' ) {
5682 scale = dot ? scale*100 : 100;
5683 cp++; /* % is always at the end */
5684 break;
5685 } else if ( ch >= '0' && ch <= '9' ) {
5686 if ( scale < 100000 ) {
5687 scale *= 10;
5688 num = (num*10) + (ch-'0');
5690 } else {
5691 break;
5693 cp++;
5695 *cp_p = cp;
5697 /* user says num divided by scale and we say internally that
5698 * is MAX_SCORE * num / scale.
5700 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5703 struct diff_queue_struct diff_queued_diff;
5705 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5707 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5708 queue->queue[queue->nr++] = dp;
5711 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5712 struct diff_filespec *one,
5713 struct diff_filespec *two)
5715 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5716 dp->one = one;
5717 dp->two = two;
5718 if (queue)
5719 diff_q(queue, dp);
5720 return dp;
5723 void diff_free_filepair(struct diff_filepair *p)
5725 free_filespec(p->one);
5726 free_filespec(p->two);
5727 free(p);
5730 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5732 int abblen;
5733 const char *abbrev;
5735 /* Do we want all 40 hex characters? */
5736 if (len == the_hash_algo->hexsz)
5737 return oid_to_hex(oid);
5739 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5740 abbrev = diff_abbrev_oid(oid, len);
5742 if (!print_sha1_ellipsis())
5743 return abbrev;
5745 abblen = strlen(abbrev);
5748 * In well-behaved cases, where the abbreviated result is the
5749 * same as the requested length, append three dots after the
5750 * abbreviation (hence the whole logic is limited to the case
5751 * where abblen < 37); when the actual abbreviated result is a
5752 * bit longer than the requested length, we reduce the number
5753 * of dots so that they match the well-behaved ones. However,
5754 * if the actual abbreviation is longer than the requested
5755 * length by more than three, we give up on aligning, and add
5756 * three dots anyway, to indicate that the output is not the
5757 * full object name. Yes, this may be suboptimal, but this
5758 * appears only in "diff --raw --abbrev" output and it is not
5759 * worth the effort to change it now. Note that this would
5760 * likely to work fine when the automatic sizing of default
5761 * abbreviation length is used--we would be fed -1 in "len" in
5762 * that case, and will end up always appending three-dots, but
5763 * the automatic sizing is supposed to give abblen that ensures
5764 * uniqueness across all objects (statistically speaking).
5766 if (abblen < the_hash_algo->hexsz - 3) {
5767 static char hex[GIT_MAX_HEXSZ + 1];
5768 if (len < abblen && abblen <= len + 2)
5769 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5770 else
5771 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5772 return hex;
5775 return oid_to_hex(oid);
5778 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5780 int line_termination = opt->line_termination;
5781 int inter_name_termination = line_termination ? '\t' : '\0';
5783 fprintf(opt->file, "%s", diff_line_prefix(opt));
5784 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5785 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5786 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5787 fprintf(opt->file, "%s ",
5788 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5790 if (p->score) {
5791 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5792 inter_name_termination);
5793 } else {
5794 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5797 if (p->status == DIFF_STATUS_COPIED ||
5798 p->status == DIFF_STATUS_RENAMED) {
5799 const char *name_a, *name_b;
5800 name_a = p->one->path;
5801 name_b = p->two->path;
5802 strip_prefix(opt->prefix_length, &name_a, &name_b);
5803 write_name_quoted(name_a, opt->file, inter_name_termination);
5804 write_name_quoted(name_b, opt->file, line_termination);
5805 } else {
5806 const char *name_a, *name_b;
5807 name_a = p->one->mode ? p->one->path : p->two->path;
5808 name_b = NULL;
5809 strip_prefix(opt->prefix_length, &name_a, &name_b);
5810 write_name_quoted(name_a, opt->file, line_termination);
5814 int diff_unmodified_pair(struct diff_filepair *p)
5816 /* This function is written stricter than necessary to support
5817 * the currently implemented transformers, but the idea is to
5818 * let transformers to produce diff_filepairs any way they want,
5819 * and filter and clean them up here before producing the output.
5821 struct diff_filespec *one = p->one, *two = p->two;
5823 if (DIFF_PAIR_UNMERGED(p))
5824 return 0; /* unmerged is interesting */
5826 /* deletion, addition, mode or type change
5827 * and rename are all interesting.
5829 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5830 DIFF_PAIR_MODE_CHANGED(p) ||
5831 strcmp(one->path, two->path))
5832 return 0;
5834 /* both are valid and point at the same path. that is, we are
5835 * dealing with a change.
5837 if (one->oid_valid && two->oid_valid &&
5838 oideq(&one->oid, &two->oid) &&
5839 !one->dirty_submodule && !two->dirty_submodule)
5840 return 1; /* no change */
5841 if (!one->oid_valid && !two->oid_valid)
5842 return 1; /* both look at the same file on the filesystem. */
5843 return 0;
5846 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5848 int include_conflict_headers =
5849 (additional_headers(o, p->one->path) &&
5850 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5853 * Check if we can return early without showing a diff. Note that
5854 * diff_filepair only stores {oid, path, mode, is_valid}
5855 * information for each path, and thus diff_unmodified_pair() only
5856 * considers those bits of info. However, we do not want pairs
5857 * created by create_filepairs_for_header_only_notifications()
5858 * (which always look like unmodified pairs) to be ignored, so
5859 * return early if both p is unmodified AND we don't want to
5860 * include_conflict_headers.
5862 if (diff_unmodified_pair(p) && !include_conflict_headers)
5863 return;
5865 /* Actually, we can also return early to avoid showing tree diffs */
5866 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5867 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5868 return;
5870 run_diff(p, o);
5873 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5874 struct diffstat_t *diffstat)
5876 if (diff_unmodified_pair(p))
5877 return;
5879 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5880 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5881 return; /* no useful stat for tree diffs */
5883 run_diffstat(p, o, diffstat);
5886 static void diff_flush_checkdiff(struct diff_filepair *p,
5887 struct diff_options *o)
5889 if (diff_unmodified_pair(p))
5890 return;
5892 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5893 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5894 return; /* nothing to check in tree diffs */
5896 run_checkdiff(p, o);
5899 int diff_queue_is_empty(struct diff_options *o)
5901 struct diff_queue_struct *q = &diff_queued_diff;
5902 int i;
5903 int include_conflict_headers =
5904 (o->additional_path_headers &&
5905 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5907 if (include_conflict_headers)
5908 return 0;
5910 for (i = 0; i < q->nr; i++)
5911 if (!diff_unmodified_pair(q->queue[i]))
5912 return 0;
5913 return 1;
5916 #if DIFF_DEBUG
5917 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5919 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5920 x, one ? one : "",
5921 s->path,
5922 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5923 s->mode,
5924 s->oid_valid ? oid_to_hex(&s->oid) : "");
5925 fprintf(stderr, "queue[%d] %s size %lu\n",
5926 x, one ? one : "",
5927 s->size);
5930 void diff_debug_filepair(const struct diff_filepair *p, int i)
5932 diff_debug_filespec(p->one, i, "one");
5933 diff_debug_filespec(p->two, i, "two");
5934 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5935 p->score, p->status ? p->status : '?',
5936 p->one->rename_used, p->broken_pair);
5939 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5941 int i;
5942 if (msg)
5943 fprintf(stderr, "%s\n", msg);
5944 fprintf(stderr, "q->nr = %d\n", q->nr);
5945 for (i = 0; i < q->nr; i++) {
5946 struct diff_filepair *p = q->queue[i];
5947 diff_debug_filepair(p, i);
5950 #endif
5952 static void diff_resolve_rename_copy(void)
5954 int i;
5955 struct diff_filepair *p;
5956 struct diff_queue_struct *q = &diff_queued_diff;
5958 diff_debug_queue("resolve-rename-copy", q);
5960 for (i = 0; i < q->nr; i++) {
5961 p = q->queue[i];
5962 p->status = 0; /* undecided */
5963 if (DIFF_PAIR_UNMERGED(p))
5964 p->status = DIFF_STATUS_UNMERGED;
5965 else if (!DIFF_FILE_VALID(p->one))
5966 p->status = DIFF_STATUS_ADDED;
5967 else if (!DIFF_FILE_VALID(p->two))
5968 p->status = DIFF_STATUS_DELETED;
5969 else if (DIFF_PAIR_TYPE_CHANGED(p))
5970 p->status = DIFF_STATUS_TYPE_CHANGED;
5972 /* from this point on, we are dealing with a pair
5973 * whose both sides are valid and of the same type, i.e.
5974 * either in-place edit or rename/copy edit.
5976 else if (DIFF_PAIR_RENAME(p)) {
5978 * A rename might have re-connected a broken
5979 * pair up, causing the pathnames to be the
5980 * same again. If so, that's not a rename at
5981 * all, just a modification..
5983 * Otherwise, see if this source was used for
5984 * multiple renames, in which case we decrement
5985 * the count, and call it a copy.
5987 if (!strcmp(p->one->path, p->two->path))
5988 p->status = DIFF_STATUS_MODIFIED;
5989 else if (--p->one->rename_used > 0)
5990 p->status = DIFF_STATUS_COPIED;
5991 else
5992 p->status = DIFF_STATUS_RENAMED;
5994 else if (!oideq(&p->one->oid, &p->two->oid) ||
5995 p->one->mode != p->two->mode ||
5996 p->one->dirty_submodule ||
5997 p->two->dirty_submodule ||
5998 is_null_oid(&p->one->oid))
5999 p->status = DIFF_STATUS_MODIFIED;
6000 else {
6001 /* This is a "no-change" entry and should not
6002 * happen anymore, but prepare for broken callers.
6004 error("feeding unmodified %s to diffcore",
6005 p->one->path);
6006 p->status = DIFF_STATUS_UNKNOWN;
6009 diff_debug_queue("resolve-rename-copy done", q);
6012 static int check_pair_status(struct diff_filepair *p)
6014 switch (p->status) {
6015 case DIFF_STATUS_UNKNOWN:
6016 return 0;
6017 case 0:
6018 die("internal error in diff-resolve-rename-copy");
6019 default:
6020 return 1;
6024 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6026 int fmt = opt->output_format;
6028 if (fmt & DIFF_FORMAT_CHECKDIFF)
6029 diff_flush_checkdiff(p, opt);
6030 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6031 diff_flush_raw(p, opt);
6032 else if (fmt & DIFF_FORMAT_NAME) {
6033 const char *name_a, *name_b;
6034 name_a = p->two->path;
6035 name_b = NULL;
6036 strip_prefix(opt->prefix_length, &name_a, &name_b);
6037 fprintf(opt->file, "%s", diff_line_prefix(opt));
6038 write_name_quoted(name_a, opt->file, opt->line_termination);
6042 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6044 struct strbuf sb = STRBUF_INIT;
6045 if (fs->mode)
6046 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6047 else
6048 strbuf_addf(&sb, " %s ", newdelete);
6050 quote_c_style(fs->path, &sb, NULL, 0);
6051 strbuf_addch(&sb, '\n');
6052 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6053 sb.buf, sb.len, 0);
6054 strbuf_release(&sb);
6057 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6058 int show_name)
6060 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6061 struct strbuf sb = STRBUF_INIT;
6062 strbuf_addf(&sb, " mode change %06o => %06o",
6063 p->one->mode, p->two->mode);
6064 if (show_name) {
6065 strbuf_addch(&sb, ' ');
6066 quote_c_style(p->two->path, &sb, NULL, 0);
6068 strbuf_addch(&sb, '\n');
6069 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6070 sb.buf, sb.len, 0);
6071 strbuf_release(&sb);
6075 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6076 struct diff_filepair *p)
6078 struct strbuf sb = STRBUF_INIT;
6079 struct strbuf names = STRBUF_INIT;
6081 pprint_rename(&names, p->one->path, p->two->path);
6082 strbuf_addf(&sb, " %s %s (%d%%)\n",
6083 renamecopy, names.buf, similarity_index(p));
6084 strbuf_release(&names);
6085 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6086 sb.buf, sb.len, 0);
6087 show_mode_change(opt, p, 0);
6088 strbuf_release(&sb);
6091 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6093 switch(p->status) {
6094 case DIFF_STATUS_DELETED:
6095 show_file_mode_name(opt, "delete", p->one);
6096 break;
6097 case DIFF_STATUS_ADDED:
6098 show_file_mode_name(opt, "create", p->two);
6099 break;
6100 case DIFF_STATUS_COPIED:
6101 show_rename_copy(opt, "copy", p);
6102 break;
6103 case DIFF_STATUS_RENAMED:
6104 show_rename_copy(opt, "rename", p);
6105 break;
6106 default:
6107 if (p->score) {
6108 struct strbuf sb = STRBUF_INIT;
6109 strbuf_addstr(&sb, " rewrite ");
6110 quote_c_style(p->two->path, &sb, NULL, 0);
6111 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6112 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6113 sb.buf, sb.len, 0);
6114 strbuf_release(&sb);
6116 show_mode_change(opt, p, !p->score);
6117 break;
6121 struct patch_id_t {
6122 git_hash_ctx *ctx;
6123 int patchlen;
6126 static int remove_space(char *line, int len)
6128 int i;
6129 char *dst = line;
6130 unsigned char c;
6132 for (i = 0; i < len; i++)
6133 if (!isspace((c = line[i])))
6134 *dst++ = c;
6136 return dst - line;
6139 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6141 unsigned char hash[GIT_MAX_RAWSZ];
6142 unsigned short carry = 0;
6143 int i;
6145 the_hash_algo->final_fn(hash, ctx);
6146 the_hash_algo->init_fn(ctx);
6147 /* 20-byte sum, with carry */
6148 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6149 carry += result->hash[i] + hash[i];
6150 result->hash[i] = carry;
6151 carry >>= 8;
6155 static int patch_id_consume(void *priv, char *line, unsigned long len)
6157 struct patch_id_t *data = priv;
6158 int new_len;
6160 if (len > 12 && starts_with(line, "\\ "))
6161 return 0;
6162 new_len = remove_space(line, len);
6164 the_hash_algo->update_fn(data->ctx, line, new_len);
6165 data->patchlen += new_len;
6166 return 0;
6169 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6171 the_hash_algo->update_fn(ctx, str, strlen(str));
6174 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6176 /* large enough for 2^32 in octal */
6177 char buf[12];
6178 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6179 the_hash_algo->update_fn(ctx, buf, len);
6182 /* returns 0 upon success, and writes result into oid */
6183 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6185 struct diff_queue_struct *q = &diff_queued_diff;
6186 int i;
6187 git_hash_ctx ctx;
6188 struct patch_id_t data;
6190 the_hash_algo->init_fn(&ctx);
6191 memset(&data, 0, sizeof(struct patch_id_t));
6192 data.ctx = &ctx;
6193 oidclr(oid);
6195 for (i = 0; i < q->nr; i++) {
6196 xpparam_t xpp;
6197 xdemitconf_t xecfg;
6198 mmfile_t mf1, mf2;
6199 struct diff_filepair *p = q->queue[i];
6200 int len1, len2;
6202 memset(&xpp, 0, sizeof(xpp));
6203 memset(&xecfg, 0, sizeof(xecfg));
6204 if (p->status == 0)
6205 return error("internal diff status error");
6206 if (p->status == DIFF_STATUS_UNKNOWN)
6207 continue;
6208 if (diff_unmodified_pair(p))
6209 continue;
6210 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6211 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6212 continue;
6213 if (DIFF_PAIR_UNMERGED(p))
6214 continue;
6216 diff_fill_oid_info(p->one, options->repo->index);
6217 diff_fill_oid_info(p->two, options->repo->index);
6219 len1 = remove_space(p->one->path, strlen(p->one->path));
6220 len2 = remove_space(p->two->path, strlen(p->two->path));
6221 patch_id_add_string(&ctx, "diff--git");
6222 patch_id_add_string(&ctx, "a/");
6223 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6224 patch_id_add_string(&ctx, "b/");
6225 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6227 if (p->one->mode == 0) {
6228 patch_id_add_string(&ctx, "newfilemode");
6229 patch_id_add_mode(&ctx, p->two->mode);
6230 patch_id_add_string(&ctx, "---/dev/null");
6231 patch_id_add_string(&ctx, "+++b/");
6232 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6233 } else if (p->two->mode == 0) {
6234 patch_id_add_string(&ctx, "deletedfilemode");
6235 patch_id_add_mode(&ctx, p->one->mode);
6236 patch_id_add_string(&ctx, "---a/");
6237 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6238 patch_id_add_string(&ctx, "+++/dev/null");
6239 } else {
6240 patch_id_add_string(&ctx, "---a/");
6241 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6242 patch_id_add_string(&ctx, "+++b/");
6243 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6246 if (diff_header_only)
6247 continue;
6249 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6250 fill_mmfile(options->repo, &mf2, p->two) < 0)
6251 return error("unable to read files to diff");
6253 if (diff_filespec_is_binary(options->repo, p->one) ||
6254 diff_filespec_is_binary(options->repo, p->two)) {
6255 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6256 the_hash_algo->hexsz);
6257 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6258 the_hash_algo->hexsz);
6259 continue;
6262 xpp.flags = 0;
6263 xecfg.ctxlen = 3;
6264 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6265 if (xdi_diff_outf(&mf1, &mf2, NULL,
6266 patch_id_consume, &data, &xpp, &xecfg))
6267 return error("unable to generate patch-id diff for %s",
6268 p->one->path);
6270 if (stable)
6271 flush_one_hunk(oid, &ctx);
6274 if (!stable)
6275 the_hash_algo->final_oid_fn(oid, &ctx);
6277 return 0;
6280 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6282 struct diff_queue_struct *q = &diff_queued_diff;
6283 int i;
6284 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
6286 for (i = 0; i < q->nr; i++)
6287 diff_free_filepair(q->queue[i]);
6289 free(q->queue);
6290 DIFF_QUEUE_CLEAR(q);
6292 return result;
6295 static int is_summary_empty(const struct diff_queue_struct *q)
6297 int i;
6299 for (i = 0; i < q->nr; i++) {
6300 const struct diff_filepair *p = q->queue[i];
6302 switch (p->status) {
6303 case DIFF_STATUS_DELETED:
6304 case DIFF_STATUS_ADDED:
6305 case DIFF_STATUS_COPIED:
6306 case DIFF_STATUS_RENAMED:
6307 return 0;
6308 default:
6309 if (p->score)
6310 return 0;
6311 if (p->one->mode && p->two->mode &&
6312 p->one->mode != p->two->mode)
6313 return 0;
6314 break;
6317 return 1;
6320 static const char rename_limit_warning[] =
6321 N_("exhaustive rename detection was skipped due to too many files.");
6323 static const char degrade_cc_to_c_warning[] =
6324 N_("only found copies from modified paths due to too many files.");
6326 static const char rename_limit_advice[] =
6327 N_("you may want to set your %s variable to at least "
6328 "%d and retry the command.");
6330 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6332 fflush(stdout);
6333 if (degraded_cc)
6334 warning(_(degrade_cc_to_c_warning));
6335 else if (needed)
6336 warning(_(rename_limit_warning));
6337 else
6338 return;
6339 if (0 < needed)
6340 warning(_(rename_limit_advice), varname, needed);
6343 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6345 struct strset present;
6346 struct diff_queue_struct *q = &diff_queued_diff;
6347 struct hashmap_iter iter;
6348 struct strmap_entry *e;
6349 int i;
6351 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6354 * Find out which paths exist in diff_queued_diff, preferring
6355 * one->path for any pair that has multiple paths.
6357 for (i = 0; i < q->nr; i++) {
6358 struct diff_filepair *p = q->queue[i];
6359 char *path = p->one->path ? p->one->path : p->two->path;
6361 if (strmap_contains(o->additional_path_headers, path))
6362 strset_add(&present, path);
6366 * Loop over paths in additional_path_headers; for each NOT already
6367 * in diff_queued_diff, create a synthetic filepair and insert that
6368 * into diff_queued_diff.
6370 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6371 if (!strset_contains(&present, e->key)) {
6372 struct diff_filespec *one, *two;
6373 struct diff_filepair *p;
6375 one = alloc_filespec(e->key);
6376 two = alloc_filespec(e->key);
6377 fill_filespec(one, null_oid(), 0, 0);
6378 fill_filespec(two, null_oid(), 0, 0);
6379 p = diff_queue(q, one, two);
6380 p->status = DIFF_STATUS_MODIFIED;
6384 /* Re-sort the filepairs */
6385 diffcore_fix_diff_index();
6387 /* Cleanup */
6388 strset_clear(&present);
6391 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6393 int i;
6394 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6395 struct diff_queue_struct *q = &diff_queued_diff;
6397 if (WSEH_NEW & WS_RULE_MASK)
6398 BUG("WS rules bit mask overlaps with diff symbol flags");
6400 if (o->color_moved)
6401 o->emitted_symbols = &esm;
6403 if (o->additional_path_headers)
6404 create_filepairs_for_header_only_notifications(o);
6406 for (i = 0; i < q->nr; i++) {
6407 struct diff_filepair *p = q->queue[i];
6408 if (check_pair_status(p))
6409 diff_flush_patch(p, o);
6412 if (o->emitted_symbols) {
6413 if (o->color_moved) {
6414 struct mem_pool entry_pool;
6415 struct moved_entry_list *entry_list;
6417 mem_pool_init(&entry_pool, 1024 * 1024);
6418 entry_list = add_lines_to_move_detection(o,
6419 &entry_pool);
6420 mark_color_as_moved(o, entry_list);
6421 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6422 dim_moved_lines(o);
6424 mem_pool_discard(&entry_pool, 0);
6425 free(entry_list);
6428 for (i = 0; i < esm.nr; i++)
6429 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6431 for (i = 0; i < esm.nr; i++)
6432 free((void *)esm.buf[i].line);
6433 esm.nr = 0;
6435 o->emitted_symbols = NULL;
6439 static void diff_free_file(struct diff_options *options)
6441 if (options->close_file)
6442 fclose(options->file);
6445 static void diff_free_ignore_regex(struct diff_options *options)
6447 int i;
6449 for (i = 0; i < options->ignore_regex_nr; i++) {
6450 regfree(options->ignore_regex[i]);
6451 free(options->ignore_regex[i]);
6453 free(options->ignore_regex);
6456 void diff_free(struct diff_options *options)
6458 if (options->no_free)
6459 return;
6461 diff_free_file(options);
6462 diff_free_ignore_regex(options);
6463 clear_pathspec(&options->pathspec);
6464 FREE_AND_NULL(options->parseopts);
6467 void diff_flush(struct diff_options *options)
6469 struct diff_queue_struct *q = &diff_queued_diff;
6470 int i, output_format = options->output_format;
6471 int separator = 0;
6472 int dirstat_by_line = 0;
6475 * Order: raw, stat, summary, patch
6476 * or: name/name-status/checkdiff (other bits clear)
6478 if (!q->nr && !options->additional_path_headers)
6479 goto free_queue;
6481 if (output_format & (DIFF_FORMAT_RAW |
6482 DIFF_FORMAT_NAME |
6483 DIFF_FORMAT_NAME_STATUS |
6484 DIFF_FORMAT_CHECKDIFF)) {
6485 for (i = 0; i < q->nr; i++) {
6486 struct diff_filepair *p = q->queue[i];
6487 if (check_pair_status(p))
6488 flush_one_pair(p, options);
6490 separator++;
6493 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6494 dirstat_by_line = 1;
6496 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6497 dirstat_by_line) {
6498 struct diffstat_t diffstat;
6500 compute_diffstat(options, &diffstat, q);
6501 if (output_format & DIFF_FORMAT_NUMSTAT)
6502 show_numstat(&diffstat, options);
6503 if (output_format & DIFF_FORMAT_DIFFSTAT)
6504 show_stats(&diffstat, options);
6505 if (output_format & DIFF_FORMAT_SHORTSTAT)
6506 show_shortstats(&diffstat, options);
6507 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6508 show_dirstat_by_line(&diffstat, options);
6509 free_diffstat_info(&diffstat);
6510 separator++;
6512 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6513 show_dirstat(options);
6515 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6516 for (i = 0; i < q->nr; i++) {
6517 diff_summary(options, q->queue[i]);
6519 separator++;
6522 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6523 options->flags.exit_with_status &&
6524 options->flags.diff_from_contents) {
6526 * run diff_flush_patch for the exit status. setting
6527 * options->file to /dev/null should be safe, because we
6528 * aren't supposed to produce any output anyway.
6530 diff_free_file(options);
6531 options->file = xfopen("/dev/null", "w");
6532 options->close_file = 1;
6533 options->color_moved = 0;
6534 for (i = 0; i < q->nr; i++) {
6535 struct diff_filepair *p = q->queue[i];
6536 if (check_pair_status(p))
6537 diff_flush_patch(p, options);
6538 if (options->found_changes)
6539 break;
6543 if (output_format & DIFF_FORMAT_PATCH) {
6544 if (separator) {
6545 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6546 if (options->stat_sep)
6547 /* attach patch instead of inline */
6548 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6549 NULL, 0, 0);
6552 diff_flush_patch_all_file_pairs(options);
6555 if (output_format & DIFF_FORMAT_CALLBACK)
6556 options->format_callback(q, options, options->format_callback_data);
6558 for (i = 0; i < q->nr; i++)
6559 diff_free_filepair(q->queue[i]);
6560 free_queue:
6561 free(q->queue);
6562 DIFF_QUEUE_CLEAR(q);
6563 diff_free(options);
6566 * Report the content-level differences with HAS_CHANGES;
6567 * diff_addremove/diff_change does not set the bit when
6568 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6570 if (options->flags.diff_from_contents) {
6571 if (options->found_changes)
6572 options->flags.has_changes = 1;
6573 else
6574 options->flags.has_changes = 0;
6578 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6580 return (((p->status == DIFF_STATUS_MODIFIED) &&
6581 ((p->score &&
6582 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6583 (!p->score &&
6584 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6585 ((p->status != DIFF_STATUS_MODIFIED) &&
6586 filter_bit_tst(p->status, options)));
6589 static void diffcore_apply_filter(struct diff_options *options)
6591 int i;
6592 struct diff_queue_struct *q = &diff_queued_diff;
6593 struct diff_queue_struct outq;
6595 DIFF_QUEUE_CLEAR(&outq);
6597 if (!options->filter)
6598 return;
6600 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6601 int found;
6602 for (i = found = 0; !found && i < q->nr; i++) {
6603 if (match_filter(options, q->queue[i]))
6604 found++;
6606 if (found)
6607 return;
6609 /* otherwise we will clear the whole queue
6610 * by copying the empty outq at the end of this
6611 * function, but first clear the current entries
6612 * in the queue.
6614 for (i = 0; i < q->nr; i++)
6615 diff_free_filepair(q->queue[i]);
6617 else {
6618 /* Only the matching ones */
6619 for (i = 0; i < q->nr; i++) {
6620 struct diff_filepair *p = q->queue[i];
6621 if (match_filter(options, p))
6622 diff_q(&outq, p);
6623 else
6624 diff_free_filepair(p);
6627 free(q->queue);
6628 *q = outq;
6631 /* Check whether two filespecs with the same mode and size are identical */
6632 static int diff_filespec_is_identical(struct repository *r,
6633 struct diff_filespec *one,
6634 struct diff_filespec *two)
6636 if (S_ISGITLINK(one->mode))
6637 return 0;
6638 if (diff_populate_filespec(r, one, NULL))
6639 return 0;
6640 if (diff_populate_filespec(r, two, NULL))
6641 return 0;
6642 return !memcmp(one->data, two->data, one->size);
6645 static int diff_filespec_check_stat_unmatch(struct repository *r,
6646 struct diff_filepair *p)
6648 struct diff_populate_filespec_options dpf_options = {
6649 .check_size_only = 1,
6650 .missing_object_cb = diff_queued_diff_prefetch,
6651 .missing_object_data = r,
6654 if (p->done_skip_stat_unmatch)
6655 return p->skip_stat_unmatch_result;
6657 p->done_skip_stat_unmatch = 1;
6658 p->skip_stat_unmatch_result = 0;
6660 * 1. Entries that come from stat info dirtiness
6661 * always have both sides (iow, not create/delete),
6662 * one side of the object name is unknown, with
6663 * the same mode and size. Keep the ones that
6664 * do not match these criteria. They have real
6665 * differences.
6667 * 2. At this point, the file is known to be modified,
6668 * with the same mode and size, and the object
6669 * name of one side is unknown. Need to inspect
6670 * the identical contents.
6672 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6673 !DIFF_FILE_VALID(p->two) ||
6674 (p->one->oid_valid && p->two->oid_valid) ||
6675 (p->one->mode != p->two->mode) ||
6676 diff_populate_filespec(r, p->one, &dpf_options) ||
6677 diff_populate_filespec(r, p->two, &dpf_options) ||
6678 (p->one->size != p->two->size) ||
6679 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6680 p->skip_stat_unmatch_result = 1;
6681 return p->skip_stat_unmatch_result;
6684 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6686 int i;
6687 struct diff_queue_struct *q = &diff_queued_diff;
6688 struct diff_queue_struct outq;
6689 DIFF_QUEUE_CLEAR(&outq);
6691 for (i = 0; i < q->nr; i++) {
6692 struct diff_filepair *p = q->queue[i];
6694 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6695 diff_q(&outq, p);
6696 else {
6698 * The caller can subtract 1 from skip_stat_unmatch
6699 * to determine how many paths were dirty only
6700 * due to stat info mismatch.
6702 if (!diffopt->flags.no_index)
6703 diffopt->skip_stat_unmatch++;
6704 diff_free_filepair(p);
6707 free(q->queue);
6708 *q = outq;
6711 static int diffnamecmp(const void *a_, const void *b_)
6713 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6714 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6715 const char *name_a, *name_b;
6717 name_a = a->one ? a->one->path : a->two->path;
6718 name_b = b->one ? b->one->path : b->two->path;
6719 return strcmp(name_a, name_b);
6722 void diffcore_fix_diff_index(void)
6724 struct diff_queue_struct *q = &diff_queued_diff;
6725 QSORT(q->queue, q->nr, diffnamecmp);
6728 void diff_add_if_missing(struct repository *r,
6729 struct oid_array *to_fetch,
6730 const struct diff_filespec *filespec)
6732 if (filespec && filespec->oid_valid &&
6733 !S_ISGITLINK(filespec->mode) &&
6734 oid_object_info_extended(r, &filespec->oid, NULL,
6735 OBJECT_INFO_FOR_PREFETCH))
6736 oid_array_append(to_fetch, &filespec->oid);
6739 void diff_queued_diff_prefetch(void *repository)
6741 struct repository *repo = repository;
6742 int i;
6743 struct diff_queue_struct *q = &diff_queued_diff;
6744 struct oid_array to_fetch = OID_ARRAY_INIT;
6746 for (i = 0; i < q->nr; i++) {
6747 struct diff_filepair *p = q->queue[i];
6748 diff_add_if_missing(repo, &to_fetch, p->one);
6749 diff_add_if_missing(repo, &to_fetch, p->two);
6753 * NEEDSWORK: Consider deduplicating the OIDs sent.
6755 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6757 oid_array_clear(&to_fetch);
6760 void diffcore_std(struct diff_options *options)
6762 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6763 DIFF_FORMAT_NUMSTAT |
6764 DIFF_FORMAT_PATCH |
6765 DIFF_FORMAT_SHORTSTAT |
6766 DIFF_FORMAT_DIRSTAT;
6769 * Check if the user requested a blob-data-requiring diff output and/or
6770 * break-rewrite detection (which requires blob data). If yes, prefetch
6771 * the diff pairs.
6773 * If no prefetching occurs, diffcore_rename() will prefetch if it
6774 * decides that it needs inexact rename detection.
6776 if (options->repo == the_repository && has_promisor_remote() &&
6777 (options->output_format & output_formats_to_prefetch ||
6778 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6779 diff_queued_diff_prefetch(options->repo);
6781 /* NOTE please keep the following in sync with diff_tree_combined() */
6782 if (options->skip_stat_unmatch)
6783 diffcore_skip_stat_unmatch(options);
6784 if (!options->found_follow) {
6785 /* See try_to_follow_renames() in tree-diff.c */
6786 if (options->break_opt != -1)
6787 diffcore_break(options->repo,
6788 options->break_opt);
6789 if (options->detect_rename)
6790 diffcore_rename(options);
6791 if (options->break_opt != -1)
6792 diffcore_merge_broken();
6794 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6795 diffcore_pickaxe(options);
6796 if (options->orderfile)
6797 diffcore_order(options->orderfile);
6798 if (options->rotate_to)
6799 diffcore_rotate(options);
6800 if (!options->found_follow)
6801 /* See try_to_follow_renames() in tree-diff.c */
6802 diff_resolve_rename_copy();
6803 diffcore_apply_filter(options);
6805 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6806 options->flags.has_changes = 1;
6807 else
6808 options->flags.has_changes = 0;
6810 options->found_follow = 0;
6813 int diff_result_code(struct diff_options *opt, int status)
6815 int result = 0;
6817 diff_warn_rename_limit("diff.renameLimit",
6818 opt->needed_rename_limit,
6819 opt->degraded_cc_to_c);
6820 if (!opt->flags.exit_with_status &&
6821 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6822 return status;
6823 if (opt->flags.exit_with_status &&
6824 opt->flags.has_changes)
6825 result |= 01;
6826 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6827 opt->flags.check_failed)
6828 result |= 02;
6829 return result;
6832 int diff_can_quit_early(struct diff_options *opt)
6834 return (opt->flags.quick &&
6835 !opt->filter &&
6836 opt->flags.has_changes);
6840 * Shall changes to this submodule be ignored?
6842 * Submodule changes can be configured to be ignored separately for each path,
6843 * but that configuration can be overridden from the command line.
6845 static int is_submodule_ignored(const char *path, struct diff_options *options)
6847 int ignored = 0;
6848 struct diff_flags orig_flags = options->flags;
6849 if (!options->flags.override_submodule_config)
6850 set_diffopt_flags_from_submodule_config(options, path);
6851 if (options->flags.ignore_submodules)
6852 ignored = 1;
6853 options->flags = orig_flags;
6854 return ignored;
6857 void compute_diffstat(struct diff_options *options,
6858 struct diffstat_t *diffstat,
6859 struct diff_queue_struct *q)
6861 int i;
6863 memset(diffstat, 0, sizeof(struct diffstat_t));
6864 for (i = 0; i < q->nr; i++) {
6865 struct diff_filepair *p = q->queue[i];
6866 if (check_pair_status(p))
6867 diff_flush_stat(p, options, diffstat);
6871 void diff_addremove(struct diff_options *options,
6872 int addremove, unsigned mode,
6873 const struct object_id *oid,
6874 int oid_valid,
6875 const char *concatpath, unsigned dirty_submodule)
6877 struct diff_filespec *one, *two;
6879 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6880 return;
6882 /* This may look odd, but it is a preparation for
6883 * feeding "there are unchanged files which should
6884 * not produce diffs, but when you are doing copy
6885 * detection you would need them, so here they are"
6886 * entries to the diff-core. They will be prefixed
6887 * with something like '=' or '*' (I haven't decided
6888 * which but should not make any difference).
6889 * Feeding the same new and old to diff_change()
6890 * also has the same effect.
6891 * Before the final output happens, they are pruned after
6892 * merged into rename/copy pairs as appropriate.
6894 if (options->flags.reverse_diff)
6895 addremove = (addremove == '+' ? '-' :
6896 addremove == '-' ? '+' : addremove);
6898 if (options->prefix &&
6899 strncmp(concatpath, options->prefix, options->prefix_length))
6900 return;
6902 one = alloc_filespec(concatpath);
6903 two = alloc_filespec(concatpath);
6905 if (addremove != '+')
6906 fill_filespec(one, oid, oid_valid, mode);
6907 if (addremove != '-') {
6908 fill_filespec(two, oid, oid_valid, mode);
6909 two->dirty_submodule = dirty_submodule;
6912 diff_queue(&diff_queued_diff, one, two);
6913 if (!options->flags.diff_from_contents)
6914 options->flags.has_changes = 1;
6917 void diff_change(struct diff_options *options,
6918 unsigned old_mode, unsigned new_mode,
6919 const struct object_id *old_oid,
6920 const struct object_id *new_oid,
6921 int old_oid_valid, int new_oid_valid,
6922 const char *concatpath,
6923 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6925 struct diff_filespec *one, *two;
6926 struct diff_filepair *p;
6928 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6929 is_submodule_ignored(concatpath, options))
6930 return;
6932 if (options->flags.reverse_diff) {
6933 SWAP(old_mode, new_mode);
6934 SWAP(old_oid, new_oid);
6935 SWAP(old_oid_valid, new_oid_valid);
6936 SWAP(old_dirty_submodule, new_dirty_submodule);
6939 if (options->prefix &&
6940 strncmp(concatpath, options->prefix, options->prefix_length))
6941 return;
6943 one = alloc_filespec(concatpath);
6944 two = alloc_filespec(concatpath);
6945 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6946 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6947 one->dirty_submodule = old_dirty_submodule;
6948 two->dirty_submodule = new_dirty_submodule;
6949 p = diff_queue(&diff_queued_diff, one, two);
6951 if (options->flags.diff_from_contents)
6952 return;
6954 if (options->flags.quick && options->skip_stat_unmatch &&
6955 !diff_filespec_check_stat_unmatch(options->repo, p)) {
6956 diff_free_filespec_data(p->one);
6957 diff_free_filespec_data(p->two);
6958 return;
6961 options->flags.has_changes = 1;
6964 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6966 struct diff_filepair *pair;
6967 struct diff_filespec *one, *two;
6969 if (options->prefix &&
6970 strncmp(path, options->prefix, options->prefix_length))
6971 return NULL;
6973 one = alloc_filespec(path);
6974 two = alloc_filespec(path);
6975 pair = diff_queue(&diff_queued_diff, one, two);
6976 pair->is_unmerged = 1;
6977 return pair;
6980 static char *run_textconv(struct repository *r,
6981 const char *pgm,
6982 struct diff_filespec *spec,
6983 size_t *outsize)
6985 struct diff_tempfile *temp;
6986 struct child_process child = CHILD_PROCESS_INIT;
6987 struct strbuf buf = STRBUF_INIT;
6988 int err = 0;
6990 temp = prepare_temp_file(r, spec->path, spec);
6991 strvec_push(&child.args, pgm);
6992 strvec_push(&child.args, temp->name);
6994 child.use_shell = 1;
6995 child.out = -1;
6996 if (start_command(&child)) {
6997 remove_tempfile();
6998 return NULL;
7001 if (strbuf_read(&buf, child.out, 0) < 0)
7002 err = error("error reading from textconv command '%s'", pgm);
7003 close(child.out);
7005 if (finish_command(&child) || err) {
7006 strbuf_release(&buf);
7007 remove_tempfile();
7008 return NULL;
7010 remove_tempfile();
7012 return strbuf_detach(&buf, outsize);
7015 size_t fill_textconv(struct repository *r,
7016 struct userdiff_driver *driver,
7017 struct diff_filespec *df,
7018 char **outbuf)
7020 size_t size;
7022 if (!driver) {
7023 if (!DIFF_FILE_VALID(df)) {
7024 *outbuf = "";
7025 return 0;
7027 if (diff_populate_filespec(r, df, NULL))
7028 die("unable to read files to diff");
7029 *outbuf = df->data;
7030 return df->size;
7033 if (!driver->textconv)
7034 BUG("fill_textconv called with non-textconv driver");
7036 if (driver->textconv_cache && df->oid_valid) {
7037 *outbuf = notes_cache_get(driver->textconv_cache,
7038 &df->oid,
7039 &size);
7040 if (*outbuf)
7041 return size;
7044 *outbuf = run_textconv(r, driver->textconv, df, &size);
7045 if (!*outbuf)
7046 die("unable to read files to diff");
7048 if (driver->textconv_cache && df->oid_valid) {
7049 /* ignore errors, as we might be in a readonly repository */
7050 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7051 size);
7053 * we could save up changes and flush them all at the end,
7054 * but we would need an extra call after all diffing is done.
7055 * Since generating a cache entry is the slow path anyway,
7056 * this extra overhead probably isn't a big deal.
7058 notes_cache_write(driver->textconv_cache);
7061 return size;
7064 int textconv_object(struct repository *r,
7065 const char *path,
7066 unsigned mode,
7067 const struct object_id *oid,
7068 int oid_valid,
7069 char **buf,
7070 unsigned long *buf_size)
7072 struct diff_filespec *df;
7073 struct userdiff_driver *textconv;
7075 df = alloc_filespec(path);
7076 fill_filespec(df, oid, oid_valid, mode);
7077 textconv = get_textconv(r, df);
7078 if (!textconv) {
7079 free_filespec(df);
7080 return 0;
7083 *buf_size = fill_textconv(r, textconv, df, buf);
7084 free_filespec(df);
7085 return 1;
7088 void setup_diff_pager(struct diff_options *opt)
7091 * If the user asked for our exit code, then either they want --quiet
7092 * or --exit-code. We should definitely not bother with a pager in the
7093 * former case, as we will generate no output. Since we still properly
7094 * report our exit code even when a pager is run, we _could_ run a
7095 * pager with --exit-code. But since we have not done so historically,
7096 * and because it is easy to find people oneline advising "git diff
7097 * --exit-code" in hooks and other scripts, we do not do so.
7099 if (!opt->flags.exit_with_status &&
7100 check_pager_config("diff") != 0)
7101 setup_pager();