l10n: git.pot: v2.34.0 round 1 (134 new, 154 removed)
[alt-git.git] / diff.c
blob861282db1c3283ad5cd6234237408bb5cf223d2b
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 "ll-merge.h"
22 #include "string-list.h"
23 #include "strvec.h"
24 #include "graph.h"
25 #include "packfile.h"
26 #include "parse-options.h"
27 #include "help.h"
28 #include "promisor-remote.h"
29 #include "dir.h"
31 #ifdef NO_FAST_WORKING_DIRECTORY
32 #define FAST_WORKING_DIRECTORY 0
33 #else
34 #define FAST_WORKING_DIRECTORY 1
35 #endif
37 static int diff_detect_rename_default;
38 static int diff_indent_heuristic = 1;
39 static int diff_rename_limit_default = 1000;
40 static int diff_suppress_blank_empty;
41 static int diff_use_color_default = -1;
42 static int diff_color_moved_default;
43 static int diff_color_moved_ws_default;
44 static int diff_context_default = 3;
45 static int diff_interhunk_context_default;
46 static const char *diff_word_regex_cfg;
47 static const char *external_diff_cmd_cfg;
48 static const char *diff_order_file_cfg;
49 int diff_auto_refresh_index = 1;
50 static int diff_mnemonic_prefix;
51 static int diff_no_prefix;
52 static int diff_relative;
53 static int diff_stat_graph_width;
54 static int diff_dirstat_permille_default = 30;
55 static struct diff_options default_diff_options;
56 static long diff_algorithm;
57 static unsigned ws_error_highlight_default = WSEH_NEW;
59 static char diff_colors[][COLOR_MAXLEN] = {
60 GIT_COLOR_RESET,
61 GIT_COLOR_NORMAL, /* CONTEXT */
62 GIT_COLOR_BOLD, /* METAINFO */
63 GIT_COLOR_CYAN, /* FRAGINFO */
64 GIT_COLOR_RED, /* OLD */
65 GIT_COLOR_GREEN, /* NEW */
66 GIT_COLOR_YELLOW, /* COMMIT */
67 GIT_COLOR_BG_RED, /* WHITESPACE */
68 GIT_COLOR_NORMAL, /* FUNCINFO */
69 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
70 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
71 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
72 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
73 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
74 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
75 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
76 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
77 GIT_COLOR_FAINT, /* CONTEXT_DIM */
78 GIT_COLOR_FAINT_RED, /* OLD_DIM */
79 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
80 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
81 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
82 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
85 static const char *color_diff_slots[] = {
86 [DIFF_CONTEXT] = "context",
87 [DIFF_METAINFO] = "meta",
88 [DIFF_FRAGINFO] = "frag",
89 [DIFF_FILE_OLD] = "old",
90 [DIFF_FILE_NEW] = "new",
91 [DIFF_COMMIT] = "commit",
92 [DIFF_WHITESPACE] = "whitespace",
93 [DIFF_FUNCINFO] = "func",
94 [DIFF_FILE_OLD_MOVED] = "oldMoved",
95 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
96 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
97 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
98 [DIFF_FILE_NEW_MOVED] = "newMoved",
99 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
100 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
101 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
102 [DIFF_CONTEXT_DIM] = "contextDimmed",
103 [DIFF_FILE_OLD_DIM] = "oldDimmed",
104 [DIFF_FILE_NEW_DIM] = "newDimmed",
105 [DIFF_CONTEXT_BOLD] = "contextBold",
106 [DIFF_FILE_OLD_BOLD] = "oldBold",
107 [DIFF_FILE_NEW_BOLD] = "newBold",
110 define_list_config_array_extra(color_diff_slots, {"plain"});
112 static int parse_diff_color_slot(const char *var)
114 if (!strcasecmp(var, "plain"))
115 return DIFF_CONTEXT;
116 return LOOKUP_CONFIG(color_diff_slots, var);
119 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
120 struct strbuf *errmsg)
122 char *params_copy = xstrdup(params_string);
123 struct string_list params = STRING_LIST_INIT_NODUP;
124 int ret = 0;
125 int i;
127 if (*params_copy)
128 string_list_split_in_place(&params, params_copy, ',', -1);
129 for (i = 0; i < params.nr; i++) {
130 const char *p = params.items[i].string;
131 if (!strcmp(p, "changes")) {
132 options->flags.dirstat_by_line = 0;
133 options->flags.dirstat_by_file = 0;
134 } else if (!strcmp(p, "lines")) {
135 options->flags.dirstat_by_line = 1;
136 options->flags.dirstat_by_file = 0;
137 } else if (!strcmp(p, "files")) {
138 options->flags.dirstat_by_line = 0;
139 options->flags.dirstat_by_file = 1;
140 } else if (!strcmp(p, "noncumulative")) {
141 options->flags.dirstat_cumulative = 0;
142 } else if (!strcmp(p, "cumulative")) {
143 options->flags.dirstat_cumulative = 1;
144 } else if (isdigit(*p)) {
145 char *end;
146 int permille = strtoul(p, &end, 10) * 10;
147 if (*end == '.' && isdigit(*++end)) {
148 /* only use first digit */
149 permille += *end - '0';
150 /* .. and ignore any further digits */
151 while (isdigit(*++end))
152 ; /* nothing */
154 if (!*end)
155 options->dirstat_permille = permille;
156 else {
157 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
159 ret++;
161 } else {
162 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
163 ret++;
167 string_list_clear(&params, 0);
168 free(params_copy);
169 return ret;
172 static int parse_submodule_params(struct diff_options *options, const char *value)
174 if (!strcmp(value, "log"))
175 options->submodule_format = DIFF_SUBMODULE_LOG;
176 else if (!strcmp(value, "short"))
177 options->submodule_format = DIFF_SUBMODULE_SHORT;
178 else if (!strcmp(value, "diff"))
179 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
181 * Please update $__git_diff_submodule_formats in
182 * git-completion.bash when you add new formats.
184 else
185 return -1;
186 return 0;
189 int git_config_rename(const char *var, const char *value)
191 if (!value)
192 return DIFF_DETECT_RENAME;
193 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
194 return DIFF_DETECT_COPY;
195 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
198 long parse_algorithm_value(const char *value)
200 if (!value)
201 return -1;
202 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
203 return 0;
204 else if (!strcasecmp(value, "minimal"))
205 return XDF_NEED_MINIMAL;
206 else if (!strcasecmp(value, "patience"))
207 return XDF_PATIENCE_DIFF;
208 else if (!strcasecmp(value, "histogram"))
209 return XDF_HISTOGRAM_DIFF;
211 * Please update $__git_diff_algorithms in git-completion.bash
212 * when you add new algorithms.
214 return -1;
217 static int parse_one_token(const char **arg, const char *token)
219 const char *rest;
220 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
221 *arg = rest;
222 return 1;
224 return 0;
227 static int parse_ws_error_highlight(const char *arg)
229 const char *orig_arg = arg;
230 unsigned val = 0;
232 while (*arg) {
233 if (parse_one_token(&arg, "none"))
234 val = 0;
235 else if (parse_one_token(&arg, "default"))
236 val = WSEH_NEW;
237 else if (parse_one_token(&arg, "all"))
238 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
239 else if (parse_one_token(&arg, "new"))
240 val |= WSEH_NEW;
241 else if (parse_one_token(&arg, "old"))
242 val |= WSEH_OLD;
243 else if (parse_one_token(&arg, "context"))
244 val |= WSEH_CONTEXT;
245 else {
246 return -1 - (int)(arg - orig_arg);
248 if (*arg)
249 arg++;
251 return val;
255 * These are to give UI layer defaults.
256 * The core-level commands such as git-diff-files should
257 * never be affected by the setting of diff.renames
258 * the user happens to have in the configuration file.
260 void init_diff_ui_defaults(void)
262 diff_detect_rename_default = DIFF_DETECT_RENAME;
265 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
267 if (!strcmp(var, "diff.indentheuristic"))
268 diff_indent_heuristic = git_config_bool(var, value);
269 return 0;
272 static int parse_color_moved(const char *arg)
274 switch (git_parse_maybe_bool(arg)) {
275 case 0:
276 return COLOR_MOVED_NO;
277 case 1:
278 return COLOR_MOVED_DEFAULT;
279 default:
280 break;
283 if (!strcmp(arg, "no"))
284 return COLOR_MOVED_NO;
285 else if (!strcmp(arg, "plain"))
286 return COLOR_MOVED_PLAIN;
287 else if (!strcmp(arg, "blocks"))
288 return COLOR_MOVED_BLOCKS;
289 else if (!strcmp(arg, "zebra"))
290 return COLOR_MOVED_ZEBRA;
291 else if (!strcmp(arg, "default"))
292 return COLOR_MOVED_DEFAULT;
293 else if (!strcmp(arg, "dimmed-zebra"))
294 return COLOR_MOVED_ZEBRA_DIM;
295 else if (!strcmp(arg, "dimmed_zebra"))
296 return COLOR_MOVED_ZEBRA_DIM;
297 else
298 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
301 static unsigned parse_color_moved_ws(const char *arg)
303 int ret = 0;
304 struct string_list l = STRING_LIST_INIT_DUP;
305 struct string_list_item *i;
307 string_list_split(&l, arg, ',', -1);
309 for_each_string_list_item(i, &l) {
310 struct strbuf sb = STRBUF_INIT;
311 strbuf_addstr(&sb, i->string);
312 strbuf_trim(&sb);
314 if (!strcmp(sb.buf, "no"))
315 ret = 0;
316 else if (!strcmp(sb.buf, "ignore-space-change"))
317 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
318 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
319 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
320 else if (!strcmp(sb.buf, "ignore-all-space"))
321 ret |= XDF_IGNORE_WHITESPACE;
322 else if (!strcmp(sb.buf, "allow-indentation-change"))
323 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
324 else {
325 ret |= COLOR_MOVED_WS_ERROR;
326 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);
329 strbuf_release(&sb);
332 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
333 (ret & XDF_WHITESPACE_FLAGS)) {
334 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
335 ret |= COLOR_MOVED_WS_ERROR;
338 string_list_clear(&l, 0);
340 return ret;
343 int git_diff_ui_config(const char *var, const char *value, void *cb)
345 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
346 diff_use_color_default = git_config_colorbool(var, value);
347 return 0;
349 if (!strcmp(var, "diff.colormoved")) {
350 int cm = parse_color_moved(value);
351 if (cm < 0)
352 return -1;
353 diff_color_moved_default = cm;
354 return 0;
356 if (!strcmp(var, "diff.colormovedws")) {
357 unsigned cm = parse_color_moved_ws(value);
358 if (cm & COLOR_MOVED_WS_ERROR)
359 return -1;
360 diff_color_moved_ws_default = cm;
361 return 0;
363 if (!strcmp(var, "diff.context")) {
364 diff_context_default = git_config_int(var, value);
365 if (diff_context_default < 0)
366 return -1;
367 return 0;
369 if (!strcmp(var, "diff.interhunkcontext")) {
370 diff_interhunk_context_default = git_config_int(var, value);
371 if (diff_interhunk_context_default < 0)
372 return -1;
373 return 0;
375 if (!strcmp(var, "diff.renames")) {
376 diff_detect_rename_default = git_config_rename(var, value);
377 return 0;
379 if (!strcmp(var, "diff.autorefreshindex")) {
380 diff_auto_refresh_index = git_config_bool(var, value);
381 return 0;
383 if (!strcmp(var, "diff.mnemonicprefix")) {
384 diff_mnemonic_prefix = git_config_bool(var, value);
385 return 0;
387 if (!strcmp(var, "diff.noprefix")) {
388 diff_no_prefix = git_config_bool(var, value);
389 return 0;
391 if (!strcmp(var, "diff.relative")) {
392 diff_relative = git_config_bool(var, value);
393 return 0;
395 if (!strcmp(var, "diff.statgraphwidth")) {
396 diff_stat_graph_width = git_config_int(var, value);
397 return 0;
399 if (!strcmp(var, "diff.external"))
400 return git_config_string(&external_diff_cmd_cfg, var, value);
401 if (!strcmp(var, "diff.wordregex"))
402 return git_config_string(&diff_word_regex_cfg, var, value);
403 if (!strcmp(var, "diff.orderfile"))
404 return git_config_pathname(&diff_order_file_cfg, var, value);
406 if (!strcmp(var, "diff.ignoresubmodules"))
407 handle_ignore_submodules_arg(&default_diff_options, value);
409 if (!strcmp(var, "diff.submodule")) {
410 if (parse_submodule_params(&default_diff_options, value))
411 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
412 value);
413 return 0;
416 if (!strcmp(var, "diff.algorithm")) {
417 diff_algorithm = parse_algorithm_value(value);
418 if (diff_algorithm < 0)
419 return -1;
420 return 0;
423 if (git_color_config(var, value, cb) < 0)
424 return -1;
426 return git_diff_basic_config(var, value, cb);
429 int git_diff_basic_config(const char *var, const char *value, void *cb)
431 const char *name;
433 if (!strcmp(var, "diff.renamelimit")) {
434 diff_rename_limit_default = git_config_int(var, value);
435 return 0;
438 if (userdiff_config(var, value) < 0)
439 return -1;
441 if (skip_prefix(var, "diff.color.", &name) ||
442 skip_prefix(var, "color.diff.", &name)) {
443 int slot = parse_diff_color_slot(name);
444 if (slot < 0)
445 return 0;
446 if (!value)
447 return config_error_nonbool(var);
448 return color_parse(value, diff_colors[slot]);
451 if (!strcmp(var, "diff.wserrorhighlight")) {
452 int val = parse_ws_error_highlight(value);
453 if (val < 0)
454 return -1;
455 ws_error_highlight_default = val;
456 return 0;
459 /* like GNU diff's --suppress-blank-empty option */
460 if (!strcmp(var, "diff.suppressblankempty") ||
461 /* for backwards compatibility */
462 !strcmp(var, "diff.suppress-blank-empty")) {
463 diff_suppress_blank_empty = git_config_bool(var, value);
464 return 0;
467 if (!strcmp(var, "diff.dirstat")) {
468 struct strbuf errmsg = STRBUF_INIT;
469 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
470 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
471 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
472 errmsg.buf);
473 strbuf_release(&errmsg);
474 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
475 return 0;
478 if (git_diff_heuristic_config(var, value, cb) < 0)
479 return -1;
481 return git_default_config(var, value, cb);
484 static char *quote_two(const char *one, const char *two)
486 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
487 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
488 struct strbuf res = STRBUF_INIT;
490 if (need_one + need_two) {
491 strbuf_addch(&res, '"');
492 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
493 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
494 strbuf_addch(&res, '"');
495 } else {
496 strbuf_addstr(&res, one);
497 strbuf_addstr(&res, two);
499 return strbuf_detach(&res, NULL);
502 static const char *external_diff(void)
504 static const char *external_diff_cmd = NULL;
505 static int done_preparing = 0;
507 if (done_preparing)
508 return external_diff_cmd;
509 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
510 if (!external_diff_cmd)
511 external_diff_cmd = external_diff_cmd_cfg;
512 done_preparing = 1;
513 return external_diff_cmd;
517 * Keep track of files used for diffing. Sometimes such an entry
518 * refers to a temporary file, sometimes to an existing file, and
519 * sometimes to "/dev/null".
521 static struct diff_tempfile {
523 * filename external diff should read from, or NULL if this
524 * entry is currently not in use:
526 const char *name;
528 char hex[GIT_MAX_HEXSZ + 1];
529 char mode[10];
532 * If this diff_tempfile instance refers to a temporary file,
533 * this tempfile object is used to manage its lifetime.
535 struct tempfile *tempfile;
536 } diff_temp[2];
538 struct emit_callback {
539 int color_diff;
540 unsigned ws_rule;
541 int blank_at_eof_in_preimage;
542 int blank_at_eof_in_postimage;
543 int lno_in_preimage;
544 int lno_in_postimage;
545 const char **label_path;
546 struct diff_words_data *diff_words;
547 struct diff_options *opt;
548 struct strbuf *header;
551 static int count_lines(const char *data, int size)
553 int count, ch, completely_empty = 1, nl_just_seen = 0;
554 count = 0;
555 while (0 < size--) {
556 ch = *data++;
557 if (ch == '\n') {
558 count++;
559 nl_just_seen = 1;
560 completely_empty = 0;
562 else {
563 nl_just_seen = 0;
564 completely_empty = 0;
567 if (completely_empty)
568 return 0;
569 if (!nl_just_seen)
570 count++; /* no trailing newline */
571 return count;
574 static int fill_mmfile(struct repository *r, mmfile_t *mf,
575 struct diff_filespec *one)
577 if (!DIFF_FILE_VALID(one)) {
578 mf->ptr = (char *)""; /* does not matter */
579 mf->size = 0;
580 return 0;
582 else if (diff_populate_filespec(r, one, NULL))
583 return -1;
585 mf->ptr = one->data;
586 mf->size = one->size;
587 return 0;
590 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
591 static unsigned long diff_filespec_size(struct repository *r,
592 struct diff_filespec *one)
594 struct diff_populate_filespec_options dpf_options = {
595 .check_size_only = 1,
598 if (!DIFF_FILE_VALID(one))
599 return 0;
600 diff_populate_filespec(r, one, &dpf_options);
601 return one->size;
604 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
606 char *ptr = mf->ptr;
607 long size = mf->size;
608 int cnt = 0;
610 if (!size)
611 return cnt;
612 ptr += size - 1; /* pointing at the very end */
613 if (*ptr != '\n')
614 ; /* incomplete line */
615 else
616 ptr--; /* skip the last LF */
617 while (mf->ptr < ptr) {
618 char *prev_eol;
619 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
620 if (*prev_eol == '\n')
621 break;
622 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
623 break;
624 cnt++;
625 ptr = prev_eol - 1;
627 return cnt;
630 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
631 struct emit_callback *ecbdata)
633 int l1, l2, at;
634 unsigned ws_rule = ecbdata->ws_rule;
635 l1 = count_trailing_blank(mf1, ws_rule);
636 l2 = count_trailing_blank(mf2, ws_rule);
637 if (l2 <= l1) {
638 ecbdata->blank_at_eof_in_preimage = 0;
639 ecbdata->blank_at_eof_in_postimage = 0;
640 return;
642 at = count_lines(mf1->ptr, mf1->size);
643 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
645 at = count_lines(mf2->ptr, mf2->size);
646 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
649 static void emit_line_0(struct diff_options *o,
650 const char *set_sign, const char *set, unsigned reverse, const char *reset,
651 int first, const char *line, int len)
653 int has_trailing_newline, has_trailing_carriage_return;
654 int needs_reset = 0; /* at the end of the line */
655 FILE *file = o->file;
657 fputs(diff_line_prefix(o), file);
659 has_trailing_newline = (len > 0 && line[len-1] == '\n');
660 if (has_trailing_newline)
661 len--;
663 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
664 if (has_trailing_carriage_return)
665 len--;
667 if (!len && !first)
668 goto end_of_line;
670 if (reverse && want_color(o->use_color)) {
671 fputs(GIT_COLOR_REVERSE, file);
672 needs_reset = 1;
675 if (set_sign) {
676 fputs(set_sign, file);
677 needs_reset = 1;
680 if (first)
681 fputc(first, file);
683 if (!len)
684 goto end_of_line;
686 if (set) {
687 if (set_sign && set != set_sign)
688 fputs(reset, file);
689 fputs(set, file);
690 needs_reset = 1;
692 fwrite(line, len, 1, file);
693 needs_reset = 1; /* 'line' may contain color codes. */
695 end_of_line:
696 if (needs_reset)
697 fputs(reset, file);
698 if (has_trailing_carriage_return)
699 fputc('\r', file);
700 if (has_trailing_newline)
701 fputc('\n', file);
704 static void emit_line(struct diff_options *o, const char *set, const char *reset,
705 const char *line, int len)
707 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
710 enum diff_symbol {
711 DIFF_SYMBOL_BINARY_DIFF_HEADER,
712 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
713 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
714 DIFF_SYMBOL_BINARY_DIFF_BODY,
715 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
716 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
717 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
718 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
719 DIFF_SYMBOL_STATS_LINE,
720 DIFF_SYMBOL_WORD_DIFF,
721 DIFF_SYMBOL_STAT_SEP,
722 DIFF_SYMBOL_SUMMARY,
723 DIFF_SYMBOL_SUBMODULE_ADD,
724 DIFF_SYMBOL_SUBMODULE_DEL,
725 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
726 DIFF_SYMBOL_SUBMODULE_MODIFIED,
727 DIFF_SYMBOL_SUBMODULE_HEADER,
728 DIFF_SYMBOL_SUBMODULE_ERROR,
729 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
730 DIFF_SYMBOL_REWRITE_DIFF,
731 DIFF_SYMBOL_BINARY_FILES,
732 DIFF_SYMBOL_HEADER,
733 DIFF_SYMBOL_FILEPAIR_PLUS,
734 DIFF_SYMBOL_FILEPAIR_MINUS,
735 DIFF_SYMBOL_WORDS_PORCELAIN,
736 DIFF_SYMBOL_WORDS,
737 DIFF_SYMBOL_CONTEXT,
738 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
739 DIFF_SYMBOL_PLUS,
740 DIFF_SYMBOL_MINUS,
741 DIFF_SYMBOL_NO_LF_EOF,
742 DIFF_SYMBOL_CONTEXT_FRAGINFO,
743 DIFF_SYMBOL_CONTEXT_MARKER,
744 DIFF_SYMBOL_SEPARATOR
747 * Flags for content lines:
748 * 0..12 are whitespace rules
749 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
750 * 16 is marking if the line is blank at EOF
752 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
753 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
754 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
755 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
756 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
759 * This struct is used when we need to buffer the output of the diff output.
761 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
762 * into the pre/post image file. This pointer could be a union with the
763 * line pointer. By storing an offset into the file instead of the literal line,
764 * we can decrease the memory footprint for the buffered output. At first we
765 * may want to only have indirection for the content lines, but we could also
766 * enhance the state for emitting prefabricated lines, e.g. the similarity
767 * score line or hunk/file headers would only need to store a number or path
768 * and then the output can be constructed later on depending on state.
770 struct emitted_diff_symbol {
771 const char *line;
772 int len;
773 int flags;
774 int indent_off; /* Offset to first non-whitespace character */
775 int indent_width; /* The visual width of the indentation */
776 enum diff_symbol s;
778 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
780 struct emitted_diff_symbols {
781 struct emitted_diff_symbol *buf;
782 int nr, alloc;
784 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
786 static void append_emitted_diff_symbol(struct diff_options *o,
787 struct emitted_diff_symbol *e)
789 struct emitted_diff_symbol *f;
791 ALLOC_GROW(o->emitted_symbols->buf,
792 o->emitted_symbols->nr + 1,
793 o->emitted_symbols->alloc);
794 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
796 memcpy(f, e, sizeof(struct emitted_diff_symbol));
797 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
800 struct moved_entry {
801 struct hashmap_entry ent;
802 const struct emitted_diff_symbol *es;
803 struct moved_entry *next_line;
806 struct moved_block {
807 struct moved_entry *match;
808 int wsd; /* The whitespace delta of this block */
811 static void moved_block_clear(struct moved_block *b)
813 memset(b, 0, sizeof(*b));
816 #define INDENT_BLANKLINE INT_MIN
818 static void fill_es_indent_data(struct emitted_diff_symbol *es)
820 unsigned int off = 0, i;
821 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
822 const char *s = es->line;
823 const int len = es->len;
825 /* skip any \v \f \r at start of indentation */
826 while (s[off] == '\f' || s[off] == '\v' ||
827 (s[off] == '\r' && off < len - 1))
828 off++;
830 /* calculate the visual width of indentation */
831 while(1) {
832 if (s[off] == ' ') {
833 width++;
834 off++;
835 } else if (s[off] == '\t') {
836 width += tab_width - (width % tab_width);
837 while (s[++off] == '\t')
838 width += tab_width;
839 } else {
840 break;
844 /* check if this line is blank */
845 for (i = off; i < len; i++)
846 if (!isspace(s[i]))
847 break;
849 if (i == len) {
850 es->indent_width = INDENT_BLANKLINE;
851 es->indent_off = len;
852 } else {
853 es->indent_off = off;
854 es->indent_width = width;
858 static int compute_ws_delta(const struct emitted_diff_symbol *a,
859 const struct emitted_diff_symbol *b,
860 int *out)
862 int a_len = a->len,
863 b_len = b->len,
864 a_off = a->indent_off,
865 a_width = a->indent_width,
866 b_off = b->indent_off,
867 b_width = b->indent_width;
868 int delta;
870 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE) {
871 *out = INDENT_BLANKLINE;
872 return 1;
875 if (a->s == DIFF_SYMBOL_PLUS)
876 delta = a_width - b_width;
877 else
878 delta = b_width - a_width;
880 if (a_len - a_off != b_len - b_off ||
881 memcmp(a->line + a_off, b->line + b_off, a_len - a_off))
882 return 0;
884 *out = delta;
886 return 1;
889 static int cmp_in_block_with_wsd(const struct diff_options *o,
890 const struct moved_entry *cur,
891 const struct moved_entry *match,
892 struct moved_block *pmb,
893 int n)
895 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
896 int al = cur->es->len, bl = match->es->len, cl = l->len;
897 const char *a = cur->es->line,
898 *b = match->es->line,
899 *c = l->line;
900 int a_off = cur->es->indent_off,
901 a_width = cur->es->indent_width,
902 c_off = l->indent_off,
903 c_width = l->indent_width;
904 int delta;
907 * We need to check if 'cur' is equal to 'match'. As those
908 * are from the same (+/-) side, we do not need to adjust for
909 * indent changes. However these were found using fuzzy
910 * matching so we do have to check if they are equal. Here we
911 * just check the lengths. We delay calling memcmp() to check
912 * the contents until later as if the length comparison for a
913 * and c fails we can avoid the call all together.
915 if (al != bl)
916 return 1;
918 /* If 'l' and 'cur' are both blank then they match. */
919 if (a_width == INDENT_BLANKLINE && c_width == INDENT_BLANKLINE)
920 return 0;
923 * The indent changes of the block are known and stored in pmb->wsd;
924 * however we need to check if the indent changes of the current line
925 * match those of the current block and that the text of 'l' and 'cur'
926 * after the indentation match.
928 if (cur->es->s == DIFF_SYMBOL_PLUS)
929 delta = a_width - c_width;
930 else
931 delta = c_width - a_width;
934 * If the previous lines of this block were all blank then set its
935 * whitespace delta.
937 if (pmb->wsd == INDENT_BLANKLINE)
938 pmb->wsd = delta;
940 return !(delta == pmb->wsd && al - a_off == cl - c_off &&
941 !memcmp(a, b, al) && !
942 memcmp(a + a_off, c + c_off, al - a_off));
945 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
946 const struct hashmap_entry *eptr,
947 const struct hashmap_entry *entry_or_key,
948 const void *keydata)
950 const struct diff_options *diffopt = hashmap_cmp_fn_data;
951 const struct moved_entry *a, *b;
952 unsigned flags = diffopt->color_moved_ws_handling
953 & XDF_WHITESPACE_FLAGS;
955 a = container_of(eptr, const struct moved_entry, ent);
956 b = container_of(entry_or_key, const struct moved_entry, ent);
958 if (diffopt->color_moved_ws_handling &
959 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
961 * As there is not specific white space config given,
962 * we'd need to check for a new block, so ignore all
963 * white space. The setup of the white space
964 * configuration for the next block is done else where
966 flags |= XDF_IGNORE_WHITESPACE;
968 return !xdiff_compare_lines(a->es->line, a->es->len,
969 b->es->line, b->es->len,
970 flags);
973 static struct moved_entry *prepare_entry(struct diff_options *o,
974 int line_no)
976 struct moved_entry *ret = xmalloc(sizeof(*ret));
977 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
978 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
979 unsigned int hash = xdiff_hash_string(l->line, l->len, flags);
981 hashmap_entry_init(&ret->ent, hash);
982 ret->es = l;
983 ret->next_line = NULL;
985 return ret;
988 static void add_lines_to_move_detection(struct diff_options *o,
989 struct hashmap *add_lines,
990 struct hashmap *del_lines)
992 struct moved_entry *prev_line = NULL;
994 int n;
995 for (n = 0; n < o->emitted_symbols->nr; n++) {
996 struct hashmap *hm;
997 struct moved_entry *key;
999 switch (o->emitted_symbols->buf[n].s) {
1000 case DIFF_SYMBOL_PLUS:
1001 hm = add_lines;
1002 break;
1003 case DIFF_SYMBOL_MINUS:
1004 hm = del_lines;
1005 break;
1006 default:
1007 prev_line = NULL;
1008 continue;
1011 if (o->color_moved_ws_handling &
1012 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1013 fill_es_indent_data(&o->emitted_symbols->buf[n]);
1014 key = prepare_entry(o, n);
1015 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
1016 prev_line->next_line = key;
1018 hashmap_add(hm, &key->ent);
1019 prev_line = key;
1023 static void pmb_advance_or_null(struct diff_options *o,
1024 struct moved_entry *match,
1025 struct hashmap *hm,
1026 struct moved_block *pmb,
1027 int pmb_nr)
1029 int i;
1030 for (i = 0; i < pmb_nr; i++) {
1031 struct moved_entry *prev = pmb[i].match;
1032 struct moved_entry *cur = (prev && prev->next_line) ?
1033 prev->next_line : NULL;
1034 if (cur && !hm->cmpfn(o, &cur->ent, &match->ent, NULL)) {
1035 pmb[i].match = cur;
1036 } else {
1037 pmb[i].match = NULL;
1042 static void pmb_advance_or_null_multi_match(struct diff_options *o,
1043 struct moved_entry *match,
1044 struct hashmap *hm,
1045 struct moved_block *pmb,
1046 int pmb_nr, int n)
1048 int i;
1049 char *got_match = xcalloc(1, pmb_nr);
1051 hashmap_for_each_entry_from(hm, match, ent) {
1052 for (i = 0; i < pmb_nr; i++) {
1053 struct moved_entry *prev = pmb[i].match;
1054 struct moved_entry *cur = (prev && prev->next_line) ?
1055 prev->next_line : NULL;
1056 if (!cur)
1057 continue;
1058 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
1059 got_match[i] |= 1;
1063 for (i = 0; i < pmb_nr; i++) {
1064 if (got_match[i]) {
1065 /* Advance to the next line */
1066 pmb[i].match = pmb[i].match->next_line;
1067 } else {
1068 moved_block_clear(&pmb[i]);
1072 free(got_match);
1075 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1076 int pmb_nr)
1078 int lp, rp;
1080 /* Shrink the set of potential block to the remaining running */
1081 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1082 while (lp < pmb_nr && pmb[lp].match)
1083 lp++;
1084 /* lp points at the first NULL now */
1086 while (rp > -1 && !pmb[rp].match)
1087 rp--;
1088 /* rp points at the last non-NULL */
1090 if (lp < pmb_nr && rp > -1 && lp < rp) {
1091 pmb[lp] = pmb[rp];
1092 memset(&pmb[rp], 0, sizeof(pmb[rp]));
1093 rp--;
1094 lp++;
1098 /* Remember the number of running sets */
1099 return rp + 1;
1103 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1105 * Otherwise, if the last block has fewer alphanumeric characters than
1106 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1107 * that block.
1109 * The last block consists of the (n - block_length)'th line up to but not
1110 * including the nth line.
1112 * Returns 0 if the last block is empty or is unset by this function, non zero
1113 * otherwise.
1115 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1116 * Think of a way to unify them.
1118 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1120 int i, alnum_count = 0;
1121 if (o->color_moved == COLOR_MOVED_PLAIN)
1122 return block_length;
1123 for (i = 1; i < block_length + 1; i++) {
1124 const char *c = o->emitted_symbols->buf[n - i].line;
1125 for (; *c; c++) {
1126 if (!isalnum(*c))
1127 continue;
1128 alnum_count++;
1129 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1130 return 1;
1133 for (i = 1; i < block_length + 1; i++)
1134 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1135 return 0;
1138 /* Find blocks of moved code, delegate actual coloring decision to helper */
1139 static void mark_color_as_moved(struct diff_options *o,
1140 struct hashmap *add_lines,
1141 struct hashmap *del_lines)
1143 struct moved_block *pmb = NULL; /* potentially moved blocks */
1144 int pmb_nr = 0, pmb_alloc = 0;
1145 int n, flipped_block = 0, block_length = 0;
1148 for (n = 0; n < o->emitted_symbols->nr; n++) {
1149 struct hashmap *hm = NULL;
1150 struct moved_entry *key;
1151 struct moved_entry *match = NULL;
1152 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1153 enum diff_symbol last_symbol = 0;
1155 switch (l->s) {
1156 case DIFF_SYMBOL_PLUS:
1157 hm = del_lines;
1158 key = prepare_entry(o, n);
1159 match = hashmap_get_entry(hm, key, ent, NULL);
1160 free(key);
1161 break;
1162 case DIFF_SYMBOL_MINUS:
1163 hm = add_lines;
1164 key = prepare_entry(o, n);
1165 match = hashmap_get_entry(hm, key, ent, NULL);
1166 free(key);
1167 break;
1168 default:
1169 flipped_block = 0;
1172 if (!match) {
1173 int i;
1175 adjust_last_block(o, n, block_length);
1176 for(i = 0; i < pmb_nr; i++)
1177 moved_block_clear(&pmb[i]);
1178 pmb_nr = 0;
1179 block_length = 0;
1180 flipped_block = 0;
1181 last_symbol = l->s;
1182 continue;
1185 if (o->color_moved == COLOR_MOVED_PLAIN) {
1186 last_symbol = l->s;
1187 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1188 continue;
1191 if (o->color_moved_ws_handling &
1192 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1193 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1194 else
1195 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1197 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1199 if (pmb_nr == 0) {
1201 * The current line is the start of a new block.
1202 * Setup the set of potential blocks.
1204 hashmap_for_each_entry_from(hm, match, ent) {
1205 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1206 if (o->color_moved_ws_handling &
1207 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1208 if (compute_ws_delta(l, match->es,
1209 &pmb[pmb_nr].wsd))
1210 pmb[pmb_nr++].match = match;
1211 } else {
1212 pmb[pmb_nr].wsd = 0;
1213 pmb[pmb_nr++].match = match;
1217 if (adjust_last_block(o, n, block_length) &&
1218 pmb_nr && last_symbol != l->s)
1219 flipped_block = (flipped_block + 1) % 2;
1220 else
1221 flipped_block = 0;
1223 block_length = 0;
1226 if (pmb_nr) {
1227 block_length++;
1228 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1229 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1230 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1232 last_symbol = l->s;
1234 adjust_last_block(o, n, block_length);
1236 for(n = 0; n < pmb_nr; n++)
1237 moved_block_clear(&pmb[n]);
1238 free(pmb);
1241 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1242 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1243 static void dim_moved_lines(struct diff_options *o)
1245 int n;
1246 for (n = 0; n < o->emitted_symbols->nr; n++) {
1247 struct emitted_diff_symbol *prev = (n != 0) ?
1248 &o->emitted_symbols->buf[n - 1] : NULL;
1249 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1250 struct emitted_diff_symbol *next =
1251 (n < o->emitted_symbols->nr - 1) ?
1252 &o->emitted_symbols->buf[n + 1] : NULL;
1254 /* Not a plus or minus line? */
1255 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1256 continue;
1258 /* Not a moved line? */
1259 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1260 continue;
1263 * If prev or next are not a plus or minus line,
1264 * pretend they don't exist
1266 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1267 prev->s != DIFF_SYMBOL_MINUS)
1268 prev = NULL;
1269 if (next && next->s != DIFF_SYMBOL_PLUS &&
1270 next->s != DIFF_SYMBOL_MINUS)
1271 next = NULL;
1273 /* Inside a block? */
1274 if ((prev &&
1275 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1276 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1277 (next &&
1278 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1279 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1280 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1281 continue;
1284 /* Check if we are at an interesting bound: */
1285 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1286 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1287 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1288 continue;
1289 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1290 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1291 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1292 continue;
1295 * The boundary to prev and next are not interesting,
1296 * so this line is not interesting as a whole
1298 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1302 static void emit_line_ws_markup(struct diff_options *o,
1303 const char *set_sign, const char *set,
1304 const char *reset,
1305 int sign_index, const char *line, int len,
1306 unsigned ws_rule, int blank_at_eof)
1308 const char *ws = NULL;
1309 int sign = o->output_indicators[sign_index];
1311 if (o->ws_error_highlight & ws_rule) {
1312 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1313 if (!*ws)
1314 ws = NULL;
1317 if (!ws && !set_sign)
1318 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1319 else if (!ws) {
1320 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1321 } else if (blank_at_eof)
1322 /* Blank line at EOF - paint '+' as well */
1323 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1324 else {
1325 /* Emit just the prefix, then the rest. */
1326 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1327 sign, "", 0);
1328 ws_check_emit(line, len, ws_rule,
1329 o->file, set, reset, ws);
1333 static void emit_diff_symbol_from_struct(struct diff_options *o,
1334 struct emitted_diff_symbol *eds)
1336 static const char *nneof = " No newline at end of file\n";
1337 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1338 struct strbuf sb = STRBUF_INIT;
1340 enum diff_symbol s = eds->s;
1341 const char *line = eds->line;
1342 int len = eds->len;
1343 unsigned flags = eds->flags;
1345 switch (s) {
1346 case DIFF_SYMBOL_NO_LF_EOF:
1347 context = diff_get_color_opt(o, DIFF_CONTEXT);
1348 reset = diff_get_color_opt(o, DIFF_RESET);
1349 putc('\n', o->file);
1350 emit_line_0(o, context, NULL, 0, reset, '\\',
1351 nneof, strlen(nneof));
1352 break;
1353 case DIFF_SYMBOL_SUBMODULE_HEADER:
1354 case DIFF_SYMBOL_SUBMODULE_ERROR:
1355 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1356 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1357 case DIFF_SYMBOL_SUMMARY:
1358 case DIFF_SYMBOL_STATS_LINE:
1359 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1360 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1361 emit_line(o, "", "", line, len);
1362 break;
1363 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1364 case DIFF_SYMBOL_CONTEXT_MARKER:
1365 context = diff_get_color_opt(o, DIFF_CONTEXT);
1366 reset = diff_get_color_opt(o, DIFF_RESET);
1367 emit_line(o, context, reset, line, len);
1368 break;
1369 case DIFF_SYMBOL_SEPARATOR:
1370 fprintf(o->file, "%s%c",
1371 diff_line_prefix(o),
1372 o->line_termination);
1373 break;
1374 case DIFF_SYMBOL_CONTEXT:
1375 set = diff_get_color_opt(o, DIFF_CONTEXT);
1376 reset = diff_get_color_opt(o, DIFF_RESET);
1377 set_sign = NULL;
1378 if (o->flags.dual_color_diffed_diffs) {
1379 char c = !len ? 0 : line[0];
1381 if (c == '+')
1382 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1383 else if (c == '@')
1384 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1385 else if (c == '-')
1386 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1388 emit_line_ws_markup(o, set_sign, set, reset,
1389 OUTPUT_INDICATOR_CONTEXT, line, len,
1390 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1391 break;
1392 case DIFF_SYMBOL_PLUS:
1393 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1394 DIFF_SYMBOL_MOVED_LINE_ALT |
1395 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1396 case DIFF_SYMBOL_MOVED_LINE |
1397 DIFF_SYMBOL_MOVED_LINE_ALT |
1398 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1399 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1400 break;
1401 case DIFF_SYMBOL_MOVED_LINE |
1402 DIFF_SYMBOL_MOVED_LINE_ALT:
1403 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1404 break;
1405 case DIFF_SYMBOL_MOVED_LINE |
1406 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1407 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1408 break;
1409 case DIFF_SYMBOL_MOVED_LINE:
1410 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1411 break;
1412 default:
1413 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1415 reset = diff_get_color_opt(o, DIFF_RESET);
1416 if (!o->flags.dual_color_diffed_diffs)
1417 set_sign = NULL;
1418 else {
1419 char c = !len ? 0 : line[0];
1421 set_sign = set;
1422 if (c == '-')
1423 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1424 else if (c == '@')
1425 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1426 else if (c == '+')
1427 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1428 else
1429 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1430 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1432 emit_line_ws_markup(o, set_sign, set, reset,
1433 OUTPUT_INDICATOR_NEW, line, len,
1434 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1435 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1436 break;
1437 case DIFF_SYMBOL_MINUS:
1438 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1439 DIFF_SYMBOL_MOVED_LINE_ALT |
1440 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1441 case DIFF_SYMBOL_MOVED_LINE |
1442 DIFF_SYMBOL_MOVED_LINE_ALT |
1443 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1444 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1445 break;
1446 case DIFF_SYMBOL_MOVED_LINE |
1447 DIFF_SYMBOL_MOVED_LINE_ALT:
1448 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1449 break;
1450 case DIFF_SYMBOL_MOVED_LINE |
1451 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1452 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1453 break;
1454 case DIFF_SYMBOL_MOVED_LINE:
1455 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1456 break;
1457 default:
1458 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1460 reset = diff_get_color_opt(o, DIFF_RESET);
1461 if (!o->flags.dual_color_diffed_diffs)
1462 set_sign = NULL;
1463 else {
1464 char c = !len ? 0 : line[0];
1466 set_sign = set;
1467 if (c == '+')
1468 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1469 else if (c == '@')
1470 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1471 else if (c == '-')
1472 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1473 else
1474 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1476 emit_line_ws_markup(o, set_sign, set, reset,
1477 OUTPUT_INDICATOR_OLD, line, len,
1478 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1479 break;
1480 case DIFF_SYMBOL_WORDS_PORCELAIN:
1481 context = diff_get_color_opt(o, DIFF_CONTEXT);
1482 reset = diff_get_color_opt(o, DIFF_RESET);
1483 emit_line(o, context, reset, line, len);
1484 fputs("~\n", o->file);
1485 break;
1486 case DIFF_SYMBOL_WORDS:
1487 context = diff_get_color_opt(o, DIFF_CONTEXT);
1488 reset = diff_get_color_opt(o, DIFF_RESET);
1490 * Skip the prefix character, if any. With
1491 * diff_suppress_blank_empty, there may be
1492 * none.
1494 if (line[0] != '\n') {
1495 line++;
1496 len--;
1498 emit_line(o, context, reset, line, len);
1499 break;
1500 case DIFF_SYMBOL_FILEPAIR_PLUS:
1501 meta = diff_get_color_opt(o, DIFF_METAINFO);
1502 reset = diff_get_color_opt(o, DIFF_RESET);
1503 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1504 line, reset,
1505 strchr(line, ' ') ? "\t" : "");
1506 break;
1507 case DIFF_SYMBOL_FILEPAIR_MINUS:
1508 meta = diff_get_color_opt(o, DIFF_METAINFO);
1509 reset = diff_get_color_opt(o, DIFF_RESET);
1510 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1511 line, reset,
1512 strchr(line, ' ') ? "\t" : "");
1513 break;
1514 case DIFF_SYMBOL_BINARY_FILES:
1515 case DIFF_SYMBOL_HEADER:
1516 fprintf(o->file, "%s", line);
1517 break;
1518 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1519 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1520 break;
1521 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1522 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1523 break;
1524 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1525 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1526 break;
1527 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1528 fputs(diff_line_prefix(o), o->file);
1529 fputc('\n', o->file);
1530 break;
1531 case DIFF_SYMBOL_REWRITE_DIFF:
1532 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1533 reset = diff_get_color_opt(o, DIFF_RESET);
1534 emit_line(o, fraginfo, reset, line, len);
1535 break;
1536 case DIFF_SYMBOL_SUBMODULE_ADD:
1537 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1538 reset = diff_get_color_opt(o, DIFF_RESET);
1539 emit_line(o, set, reset, line, len);
1540 break;
1541 case DIFF_SYMBOL_SUBMODULE_DEL:
1542 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1543 reset = diff_get_color_opt(o, DIFF_RESET);
1544 emit_line(o, set, reset, line, len);
1545 break;
1546 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1547 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1548 diff_line_prefix(o), line);
1549 break;
1550 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1551 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1552 diff_line_prefix(o), line);
1553 break;
1554 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1555 emit_line(o, "", "", " 0 files changed\n",
1556 strlen(" 0 files changed\n"));
1557 break;
1558 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1559 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1560 break;
1561 case DIFF_SYMBOL_WORD_DIFF:
1562 fprintf(o->file, "%.*s", len, line);
1563 break;
1564 case DIFF_SYMBOL_STAT_SEP:
1565 fputs(o->stat_sep, o->file);
1566 break;
1567 default:
1568 BUG("unknown diff symbol");
1570 strbuf_release(&sb);
1573 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1574 const char *line, int len, unsigned flags)
1576 struct emitted_diff_symbol e = {line, len, flags, 0, 0, s};
1578 if (o->emitted_symbols)
1579 append_emitted_diff_symbol(o, &e);
1580 else
1581 emit_diff_symbol_from_struct(o, &e);
1584 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1586 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1589 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1591 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1594 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1596 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1597 path, strlen(path), 0);
1600 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1602 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1603 path, strlen(path), 0);
1606 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1608 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1609 header, strlen(header), 0);
1612 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1614 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1617 void diff_emit_submodule_pipethrough(struct diff_options *o,
1618 const char *line, int len)
1620 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1623 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1625 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1626 ecbdata->blank_at_eof_in_preimage &&
1627 ecbdata->blank_at_eof_in_postimage &&
1628 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1629 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1630 return 0;
1631 return ws_blank_line(line, len, ecbdata->ws_rule);
1634 static void emit_add_line(struct emit_callback *ecbdata,
1635 const char *line, int len)
1637 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1638 if (new_blank_line_at_eof(ecbdata, line, len))
1639 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1641 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1644 static void emit_del_line(struct emit_callback *ecbdata,
1645 const char *line, int len)
1647 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1648 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1651 static void emit_context_line(struct emit_callback *ecbdata,
1652 const char *line, int len)
1654 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1655 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1658 static void emit_hunk_header(struct emit_callback *ecbdata,
1659 const char *line, int len)
1661 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1662 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1663 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1664 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1665 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1666 static const char atat[2] = { '@', '@' };
1667 const char *cp, *ep;
1668 struct strbuf msgbuf = STRBUF_INIT;
1669 int org_len = len;
1670 int i = 1;
1673 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1674 * it always is at least 10 bytes long.
1676 if (len < 10 ||
1677 memcmp(line, atat, 2) ||
1678 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1679 emit_diff_symbol(ecbdata->opt,
1680 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1681 return;
1683 ep += 2; /* skip over @@ */
1685 /* The hunk header in fraginfo color */
1686 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1687 strbuf_addstr(&msgbuf, reverse);
1688 strbuf_addstr(&msgbuf, frag);
1689 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1690 strbuf_add(&msgbuf, atat, sizeof(atat));
1691 else
1692 strbuf_add(&msgbuf, line, ep - line);
1693 strbuf_addstr(&msgbuf, reset);
1696 * trailing "\r\n"
1698 for ( ; i < 3; i++)
1699 if (line[len - i] == '\r' || line[len - i] == '\n')
1700 len--;
1702 /* blank before the func header */
1703 for (cp = ep; ep - line < len; ep++)
1704 if (*ep != ' ' && *ep != '\t')
1705 break;
1706 if (ep != cp) {
1707 strbuf_addstr(&msgbuf, context);
1708 strbuf_add(&msgbuf, cp, ep - cp);
1709 strbuf_addstr(&msgbuf, reset);
1712 if (ep < line + len) {
1713 strbuf_addstr(&msgbuf, func);
1714 strbuf_add(&msgbuf, ep, line + len - ep);
1715 strbuf_addstr(&msgbuf, reset);
1718 strbuf_add(&msgbuf, line + len, org_len - len);
1719 strbuf_complete_line(&msgbuf);
1720 emit_diff_symbol(ecbdata->opt,
1721 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1722 strbuf_release(&msgbuf);
1725 static struct diff_tempfile *claim_diff_tempfile(void)
1727 int i;
1728 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1729 if (!diff_temp[i].name)
1730 return diff_temp + i;
1731 BUG("diff is failing to clean up its tempfiles");
1734 static void remove_tempfile(void)
1736 int i;
1737 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1738 if (is_tempfile_active(diff_temp[i].tempfile))
1739 delete_tempfile(&diff_temp[i].tempfile);
1740 diff_temp[i].name = NULL;
1744 static void add_line_count(struct strbuf *out, int count)
1746 switch (count) {
1747 case 0:
1748 strbuf_addstr(out, "0,0");
1749 break;
1750 case 1:
1751 strbuf_addstr(out, "1");
1752 break;
1753 default:
1754 strbuf_addf(out, "1,%d", count);
1755 break;
1759 static void emit_rewrite_lines(struct emit_callback *ecb,
1760 int prefix, const char *data, int size)
1762 const char *endp = NULL;
1764 while (0 < size) {
1765 int len;
1767 endp = memchr(data, '\n', size);
1768 len = endp ? (endp - data + 1) : size;
1769 if (prefix != '+') {
1770 ecb->lno_in_preimage++;
1771 emit_del_line(ecb, data, len);
1772 } else {
1773 ecb->lno_in_postimage++;
1774 emit_add_line(ecb, data, len);
1776 size -= len;
1777 data += len;
1779 if (!endp)
1780 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1783 static void emit_rewrite_diff(const char *name_a,
1784 const char *name_b,
1785 struct diff_filespec *one,
1786 struct diff_filespec *two,
1787 struct userdiff_driver *textconv_one,
1788 struct userdiff_driver *textconv_two,
1789 struct diff_options *o)
1791 int lc_a, lc_b;
1792 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1793 const char *a_prefix, *b_prefix;
1794 char *data_one, *data_two;
1795 size_t size_one, size_two;
1796 struct emit_callback ecbdata;
1797 struct strbuf out = STRBUF_INIT;
1799 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1800 a_prefix = o->b_prefix;
1801 b_prefix = o->a_prefix;
1802 } else {
1803 a_prefix = o->a_prefix;
1804 b_prefix = o->b_prefix;
1807 name_a += (*name_a == '/');
1808 name_b += (*name_b == '/');
1810 strbuf_reset(&a_name);
1811 strbuf_reset(&b_name);
1812 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1813 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1815 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1816 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1818 memset(&ecbdata, 0, sizeof(ecbdata));
1819 ecbdata.color_diff = want_color(o->use_color);
1820 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1821 ecbdata.opt = o;
1822 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1823 mmfile_t mf1, mf2;
1824 mf1.ptr = (char *)data_one;
1825 mf2.ptr = (char *)data_two;
1826 mf1.size = size_one;
1827 mf2.size = size_two;
1828 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1830 ecbdata.lno_in_preimage = 1;
1831 ecbdata.lno_in_postimage = 1;
1833 lc_a = count_lines(data_one, size_one);
1834 lc_b = count_lines(data_two, size_two);
1836 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1837 a_name.buf, a_name.len, 0);
1838 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1839 b_name.buf, b_name.len, 0);
1841 strbuf_addstr(&out, "@@ -");
1842 if (!o->irreversible_delete)
1843 add_line_count(&out, lc_a);
1844 else
1845 strbuf_addstr(&out, "?,?");
1846 strbuf_addstr(&out, " +");
1847 add_line_count(&out, lc_b);
1848 strbuf_addstr(&out, " @@\n");
1849 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1850 strbuf_release(&out);
1852 if (lc_a && !o->irreversible_delete)
1853 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1854 if (lc_b)
1855 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1856 if (textconv_one)
1857 free((char *)data_one);
1858 if (textconv_two)
1859 free((char *)data_two);
1862 struct diff_words_buffer {
1863 mmfile_t text;
1864 unsigned long alloc;
1865 struct diff_words_orig {
1866 const char *begin, *end;
1867 } *orig;
1868 int orig_nr, orig_alloc;
1871 static void diff_words_append(char *line, unsigned long len,
1872 struct diff_words_buffer *buffer)
1874 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1875 line++;
1876 len--;
1877 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1878 buffer->text.size += len;
1879 buffer->text.ptr[buffer->text.size] = '\0';
1882 struct diff_words_style_elem {
1883 const char *prefix;
1884 const char *suffix;
1885 const char *color; /* NULL; filled in by the setup code if
1886 * color is enabled */
1889 struct diff_words_style {
1890 enum diff_words_type type;
1891 struct diff_words_style_elem new_word, old_word, ctx;
1892 const char *newline;
1895 static struct diff_words_style diff_words_styles[] = {
1896 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1897 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1898 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1901 struct diff_words_data {
1902 struct diff_words_buffer minus, plus;
1903 const char *current_plus;
1904 int last_minus;
1905 struct diff_options *opt;
1906 regex_t *word_regex;
1907 enum diff_words_type type;
1908 struct diff_words_style *style;
1911 static int fn_out_diff_words_write_helper(struct diff_options *o,
1912 struct diff_words_style_elem *st_el,
1913 const char *newline,
1914 size_t count, const char *buf)
1916 int print = 0;
1917 struct strbuf sb = STRBUF_INIT;
1919 while (count) {
1920 char *p = memchr(buf, '\n', count);
1921 if (print)
1922 strbuf_addstr(&sb, diff_line_prefix(o));
1924 if (p != buf) {
1925 const char *reset = st_el->color && *st_el->color ?
1926 GIT_COLOR_RESET : NULL;
1927 if (st_el->color && *st_el->color)
1928 strbuf_addstr(&sb, st_el->color);
1929 strbuf_addstr(&sb, st_el->prefix);
1930 strbuf_add(&sb, buf, p ? p - buf : count);
1931 strbuf_addstr(&sb, st_el->suffix);
1932 if (reset)
1933 strbuf_addstr(&sb, reset);
1935 if (!p)
1936 goto out;
1938 strbuf_addstr(&sb, newline);
1939 count -= p + 1 - buf;
1940 buf = p + 1;
1941 print = 1;
1942 if (count) {
1943 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1944 sb.buf, sb.len, 0);
1945 strbuf_reset(&sb);
1949 out:
1950 if (sb.len)
1951 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1952 sb.buf, sb.len, 0);
1953 strbuf_release(&sb);
1954 return 0;
1958 * '--color-words' algorithm can be described as:
1960 * 1. collect the minus/plus lines of a diff hunk, divided into
1961 * minus-lines and plus-lines;
1963 * 2. break both minus-lines and plus-lines into words and
1964 * place them into two mmfile_t with one word for each line;
1966 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1968 * And for the common parts of the both file, we output the plus side text.
1969 * diff_words->current_plus is used to trace the current position of the plus file
1970 * which printed. diff_words->last_minus is used to trace the last minus word
1971 * printed.
1973 * For '--graph' to work with '--color-words', we need to output the graph prefix
1974 * on each line of color words output. Generally, there are two conditions on
1975 * which we should output the prefix.
1977 * 1. diff_words->last_minus == 0 &&
1978 * diff_words->current_plus == diff_words->plus.text.ptr
1980 * that is: the plus text must start as a new line, and if there is no minus
1981 * word printed, a graph prefix must be printed.
1983 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1984 * *(diff_words->current_plus - 1) == '\n'
1986 * that is: a graph prefix must be printed following a '\n'
1988 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1990 if ((diff_words->last_minus == 0 &&
1991 diff_words->current_plus == diff_words->plus.text.ptr) ||
1992 (diff_words->current_plus > diff_words->plus.text.ptr &&
1993 *(diff_words->current_plus - 1) == '\n')) {
1994 return 1;
1995 } else {
1996 return 0;
2000 static void fn_out_diff_words_aux(void *priv,
2001 long minus_first, long minus_len,
2002 long plus_first, long plus_len,
2003 const char *func, long funclen)
2005 struct diff_words_data *diff_words = priv;
2006 struct diff_words_style *style = diff_words->style;
2007 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2008 struct diff_options *opt = diff_words->opt;
2009 const char *line_prefix;
2011 assert(opt);
2012 line_prefix = diff_line_prefix(opt);
2014 /* POSIX requires that first be decremented by one if len == 0... */
2015 if (minus_len) {
2016 minus_begin = diff_words->minus.orig[minus_first].begin;
2017 minus_end =
2018 diff_words->minus.orig[minus_first + minus_len - 1].end;
2019 } else
2020 minus_begin = minus_end =
2021 diff_words->minus.orig[minus_first].end;
2023 if (plus_len) {
2024 plus_begin = diff_words->plus.orig[plus_first].begin;
2025 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2026 } else
2027 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2029 if (color_words_output_graph_prefix(diff_words)) {
2030 fputs(line_prefix, diff_words->opt->file);
2032 if (diff_words->current_plus != plus_begin) {
2033 fn_out_diff_words_write_helper(diff_words->opt,
2034 &style->ctx, style->newline,
2035 plus_begin - diff_words->current_plus,
2036 diff_words->current_plus);
2038 if (minus_begin != minus_end) {
2039 fn_out_diff_words_write_helper(diff_words->opt,
2040 &style->old_word, style->newline,
2041 minus_end - minus_begin, minus_begin);
2043 if (plus_begin != plus_end) {
2044 fn_out_diff_words_write_helper(diff_words->opt,
2045 &style->new_word, style->newline,
2046 plus_end - plus_begin, plus_begin);
2049 diff_words->current_plus = plus_end;
2050 diff_words->last_minus = minus_first;
2053 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2054 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2055 int *begin, int *end)
2057 while (word_regex && *begin < buffer->size) {
2058 regmatch_t match[1];
2059 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2060 buffer->size - *begin, 1, match, 0)) {
2061 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2062 '\n', match[0].rm_eo - match[0].rm_so);
2063 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2064 *begin += match[0].rm_so;
2065 if (*begin == *end)
2066 (*begin)++;
2067 else
2068 return *begin > *end;
2069 } else {
2070 return -1;
2074 /* find the next word */
2075 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2076 (*begin)++;
2077 if (*begin >= buffer->size)
2078 return -1;
2080 /* find the end of the word */
2081 *end = *begin + 1;
2082 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2083 (*end)++;
2085 return 0;
2089 * This function splits the words in buffer->text, stores the list with
2090 * newline separator into out, and saves the offsets of the original words
2091 * in buffer->orig.
2093 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2094 regex_t *word_regex)
2096 int i, j;
2097 long alloc = 0;
2099 out->size = 0;
2100 out->ptr = NULL;
2102 /* fake an empty "0th" word */
2103 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2104 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2105 buffer->orig_nr = 1;
2107 for (i = 0; i < buffer->text.size; i++) {
2108 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2109 return;
2111 /* store original boundaries */
2112 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2113 buffer->orig_alloc);
2114 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2115 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2116 buffer->orig_nr++;
2118 /* store one word */
2119 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2120 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2121 out->ptr[out->size + j - i] = '\n';
2122 out->size += j - i + 1;
2124 i = j - 1;
2128 /* this executes the word diff on the accumulated buffers */
2129 static void diff_words_show(struct diff_words_data *diff_words)
2131 xpparam_t xpp;
2132 xdemitconf_t xecfg;
2133 mmfile_t minus, plus;
2134 struct diff_words_style *style = diff_words->style;
2136 struct diff_options *opt = diff_words->opt;
2137 const char *line_prefix;
2139 assert(opt);
2140 line_prefix = diff_line_prefix(opt);
2142 /* special case: only removal */
2143 if (!diff_words->plus.text.size) {
2144 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2145 line_prefix, strlen(line_prefix), 0);
2146 fn_out_diff_words_write_helper(diff_words->opt,
2147 &style->old_word, style->newline,
2148 diff_words->minus.text.size,
2149 diff_words->minus.text.ptr);
2150 diff_words->minus.text.size = 0;
2151 return;
2154 diff_words->current_plus = diff_words->plus.text.ptr;
2155 diff_words->last_minus = 0;
2157 memset(&xpp, 0, sizeof(xpp));
2158 memset(&xecfg, 0, sizeof(xecfg));
2159 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2160 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2161 xpp.flags = 0;
2162 /* as only the hunk header will be parsed, we need a 0-context */
2163 xecfg.ctxlen = 0;
2164 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2165 diff_words, &xpp, &xecfg))
2166 die("unable to generate word diff");
2167 free(minus.ptr);
2168 free(plus.ptr);
2169 if (diff_words->current_plus != diff_words->plus.text.ptr +
2170 diff_words->plus.text.size) {
2171 if (color_words_output_graph_prefix(diff_words))
2172 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2173 line_prefix, strlen(line_prefix), 0);
2174 fn_out_diff_words_write_helper(diff_words->opt,
2175 &style->ctx, style->newline,
2176 diff_words->plus.text.ptr + diff_words->plus.text.size
2177 - diff_words->current_plus, diff_words->current_plus);
2179 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2182 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2183 static void diff_words_flush(struct emit_callback *ecbdata)
2185 struct diff_options *wo = ecbdata->diff_words->opt;
2187 if (ecbdata->diff_words->minus.text.size ||
2188 ecbdata->diff_words->plus.text.size)
2189 diff_words_show(ecbdata->diff_words);
2191 if (wo->emitted_symbols) {
2192 struct diff_options *o = ecbdata->opt;
2193 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2194 int i;
2197 * NEEDSWORK:
2198 * Instead of appending each, concat all words to a line?
2200 for (i = 0; i < wol->nr; i++)
2201 append_emitted_diff_symbol(o, &wol->buf[i]);
2203 for (i = 0; i < wol->nr; i++)
2204 free((void *)wol->buf[i].line);
2206 wol->nr = 0;
2210 static void diff_filespec_load_driver(struct diff_filespec *one,
2211 struct index_state *istate)
2213 /* Use already-loaded driver */
2214 if (one->driver)
2215 return;
2217 if (S_ISREG(one->mode))
2218 one->driver = userdiff_find_by_path(istate, one->path);
2220 /* Fallback to default settings */
2221 if (!one->driver)
2222 one->driver = userdiff_find_by_name("default");
2225 static const char *userdiff_word_regex(struct diff_filespec *one,
2226 struct index_state *istate)
2228 diff_filespec_load_driver(one, istate);
2229 return one->driver->word_regex;
2232 static void init_diff_words_data(struct emit_callback *ecbdata,
2233 struct diff_options *orig_opts,
2234 struct diff_filespec *one,
2235 struct diff_filespec *two)
2237 int i;
2238 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2239 memcpy(o, orig_opts, sizeof(struct diff_options));
2241 CALLOC_ARRAY(ecbdata->diff_words, 1);
2242 ecbdata->diff_words->type = o->word_diff;
2243 ecbdata->diff_words->opt = o;
2245 if (orig_opts->emitted_symbols)
2246 CALLOC_ARRAY(o->emitted_symbols, 1);
2248 if (!o->word_regex)
2249 o->word_regex = userdiff_word_regex(one, o->repo->index);
2250 if (!o->word_regex)
2251 o->word_regex = userdiff_word_regex(two, o->repo->index);
2252 if (!o->word_regex)
2253 o->word_regex = diff_word_regex_cfg;
2254 if (o->word_regex) {
2255 ecbdata->diff_words->word_regex = (regex_t *)
2256 xmalloc(sizeof(regex_t));
2257 if (regcomp(ecbdata->diff_words->word_regex,
2258 o->word_regex,
2259 REG_EXTENDED | REG_NEWLINE))
2260 die("invalid regular expression: %s",
2261 o->word_regex);
2263 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2264 if (o->word_diff == diff_words_styles[i].type) {
2265 ecbdata->diff_words->style =
2266 &diff_words_styles[i];
2267 break;
2270 if (want_color(o->use_color)) {
2271 struct diff_words_style *st = ecbdata->diff_words->style;
2272 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2273 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2274 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2278 static void free_diff_words_data(struct emit_callback *ecbdata)
2280 if (ecbdata->diff_words) {
2281 diff_words_flush(ecbdata);
2282 free (ecbdata->diff_words->opt->emitted_symbols);
2283 free (ecbdata->diff_words->opt);
2284 free (ecbdata->diff_words->minus.text.ptr);
2285 free (ecbdata->diff_words->minus.orig);
2286 free (ecbdata->diff_words->plus.text.ptr);
2287 free (ecbdata->diff_words->plus.orig);
2288 if (ecbdata->diff_words->word_regex) {
2289 regfree(ecbdata->diff_words->word_regex);
2290 free(ecbdata->diff_words->word_regex);
2292 FREE_AND_NULL(ecbdata->diff_words);
2296 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2298 if (want_color(diff_use_color))
2299 return diff_colors[ix];
2300 return "";
2303 const char *diff_line_prefix(struct diff_options *opt)
2305 struct strbuf *msgbuf;
2306 if (!opt->output_prefix)
2307 return "";
2309 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2310 return msgbuf->buf;
2313 static unsigned long sane_truncate_line(char *line, unsigned long len)
2315 const char *cp;
2316 unsigned long allot;
2317 size_t l = len;
2319 cp = line;
2320 allot = l;
2321 while (0 < l) {
2322 (void) utf8_width(&cp, &l);
2323 if (!cp)
2324 break; /* truncated in the middle? */
2326 return allot - l;
2329 static void find_lno(const char *line, struct emit_callback *ecbdata)
2331 const char *p;
2332 ecbdata->lno_in_preimage = 0;
2333 ecbdata->lno_in_postimage = 0;
2334 p = strchr(line, '-');
2335 if (!p)
2336 return; /* cannot happen */
2337 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2338 p = strchr(p, '+');
2339 if (!p)
2340 return; /* cannot happen */
2341 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2344 static int fn_out_consume(void *priv, char *line, unsigned long len)
2346 struct emit_callback *ecbdata = priv;
2347 struct diff_options *o = ecbdata->opt;
2349 o->found_changes = 1;
2351 if (ecbdata->header) {
2352 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2353 ecbdata->header->buf, ecbdata->header->len, 0);
2354 strbuf_reset(ecbdata->header);
2355 ecbdata->header = NULL;
2358 if (ecbdata->label_path[0]) {
2359 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2360 ecbdata->label_path[0],
2361 strlen(ecbdata->label_path[0]), 0);
2362 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2363 ecbdata->label_path[1],
2364 strlen(ecbdata->label_path[1]), 0);
2365 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2368 if (diff_suppress_blank_empty
2369 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2370 line[0] = '\n';
2371 len = 1;
2374 if (line[0] == '@') {
2375 if (ecbdata->diff_words)
2376 diff_words_flush(ecbdata);
2377 len = sane_truncate_line(line, len);
2378 find_lno(line, ecbdata);
2379 emit_hunk_header(ecbdata, line, len);
2380 return 0;
2383 if (ecbdata->diff_words) {
2384 enum diff_symbol s =
2385 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2386 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2387 if (line[0] == '-') {
2388 diff_words_append(line, len,
2389 &ecbdata->diff_words->minus);
2390 return 0;
2391 } else if (line[0] == '+') {
2392 diff_words_append(line, len,
2393 &ecbdata->diff_words->plus);
2394 return 0;
2395 } else if (starts_with(line, "\\ ")) {
2397 * Eat the "no newline at eof" marker as if we
2398 * saw a "+" or "-" line with nothing on it,
2399 * and return without diff_words_flush() to
2400 * defer processing. If this is the end of
2401 * preimage, more "+" lines may come after it.
2403 return 0;
2405 diff_words_flush(ecbdata);
2406 emit_diff_symbol(o, s, line, len, 0);
2407 return 0;
2410 switch (line[0]) {
2411 case '+':
2412 ecbdata->lno_in_postimage++;
2413 emit_add_line(ecbdata, line + 1, len - 1);
2414 break;
2415 case '-':
2416 ecbdata->lno_in_preimage++;
2417 emit_del_line(ecbdata, line + 1, len - 1);
2418 break;
2419 case ' ':
2420 ecbdata->lno_in_postimage++;
2421 ecbdata->lno_in_preimage++;
2422 emit_context_line(ecbdata, line + 1, len - 1);
2423 break;
2424 default:
2425 /* incomplete line at the end */
2426 ecbdata->lno_in_preimage++;
2427 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2428 line, len, 0);
2429 break;
2431 return 0;
2434 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2436 const char *old_name = a;
2437 const char *new_name = b;
2438 int pfx_length, sfx_length;
2439 int pfx_adjust_for_slash;
2440 int len_a = strlen(a);
2441 int len_b = strlen(b);
2442 int a_midlen, b_midlen;
2443 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2444 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2446 if (qlen_a || qlen_b) {
2447 quote_c_style(a, name, NULL, 0);
2448 strbuf_addstr(name, " => ");
2449 quote_c_style(b, name, NULL, 0);
2450 return;
2453 /* Find common prefix */
2454 pfx_length = 0;
2455 while (*old_name && *new_name && *old_name == *new_name) {
2456 if (*old_name == '/')
2457 pfx_length = old_name - a + 1;
2458 old_name++;
2459 new_name++;
2462 /* Find common suffix */
2463 old_name = a + len_a;
2464 new_name = b + len_b;
2465 sfx_length = 0;
2467 * If there is a common prefix, it must end in a slash. In
2468 * that case we let this loop run 1 into the prefix to see the
2469 * same slash.
2471 * If there is no common prefix, we cannot do this as it would
2472 * underrun the input strings.
2474 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2475 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2476 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2477 *old_name == *new_name) {
2478 if (*old_name == '/')
2479 sfx_length = len_a - (old_name - a);
2480 old_name--;
2481 new_name--;
2485 * pfx{mid-a => mid-b}sfx
2486 * {pfx-a => pfx-b}sfx
2487 * pfx{sfx-a => sfx-b}
2488 * name-a => name-b
2490 a_midlen = len_a - pfx_length - sfx_length;
2491 b_midlen = len_b - pfx_length - sfx_length;
2492 if (a_midlen < 0)
2493 a_midlen = 0;
2494 if (b_midlen < 0)
2495 b_midlen = 0;
2497 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2498 if (pfx_length + sfx_length) {
2499 strbuf_add(name, a, pfx_length);
2500 strbuf_addch(name, '{');
2502 strbuf_add(name, a + pfx_length, a_midlen);
2503 strbuf_addstr(name, " => ");
2504 strbuf_add(name, b + pfx_length, b_midlen);
2505 if (pfx_length + sfx_length) {
2506 strbuf_addch(name, '}');
2507 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2511 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2512 const char *name_a,
2513 const char *name_b)
2515 struct diffstat_file *x;
2516 CALLOC_ARRAY(x, 1);
2517 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2518 diffstat->files[diffstat->nr++] = x;
2519 if (name_b) {
2520 x->from_name = xstrdup(name_a);
2521 x->name = xstrdup(name_b);
2522 x->is_renamed = 1;
2524 else {
2525 x->from_name = NULL;
2526 x->name = xstrdup(name_a);
2528 return x;
2531 static int diffstat_consume(void *priv, char *line, unsigned long len)
2533 struct diffstat_t *diffstat = priv;
2534 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2536 if (line[0] == '+')
2537 x->added++;
2538 else if (line[0] == '-')
2539 x->deleted++;
2540 return 0;
2543 const char mime_boundary_leader[] = "------------";
2545 static int scale_linear(int it, int width, int max_change)
2547 if (!it)
2548 return 0;
2550 * make sure that at least one '-' or '+' is printed if
2551 * there is any change to this path. The easiest way is to
2552 * scale linearly as if the allotted width is one column shorter
2553 * than it is, and then add 1 to the result.
2555 return 1 + (it * (width - 1) / max_change);
2558 static void show_graph(struct strbuf *out, char ch, int cnt,
2559 const char *set, const char *reset)
2561 if (cnt <= 0)
2562 return;
2563 strbuf_addstr(out, set);
2564 strbuf_addchars(out, ch, cnt);
2565 strbuf_addstr(out, reset);
2568 static void fill_print_name(struct diffstat_file *file)
2570 struct strbuf pname = STRBUF_INIT;
2572 if (file->print_name)
2573 return;
2575 if (file->is_renamed)
2576 pprint_rename(&pname, file->from_name, file->name);
2577 else
2578 quote_c_style(file->name, &pname, NULL, 0);
2580 if (file->comments)
2581 strbuf_addf(&pname, " (%s)", file->comments);
2583 file->print_name = strbuf_detach(&pname, NULL);
2586 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2587 int files, int insertions, int deletions)
2589 struct strbuf sb = STRBUF_INIT;
2591 if (!files) {
2592 assert(insertions == 0 && deletions == 0);
2593 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2594 NULL, 0, 0);
2595 return;
2598 strbuf_addf(&sb,
2599 (files == 1) ? " %d file changed" : " %d files changed",
2600 files);
2603 * For binary diff, the caller may want to print "x files
2604 * changed" with insertions == 0 && deletions == 0.
2606 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2607 * is probably less confusing (i.e skip over "2 files changed
2608 * but nothing about added/removed lines? Is this a bug in Git?").
2610 if (insertions || deletions == 0) {
2611 strbuf_addf(&sb,
2612 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2613 insertions);
2616 if (deletions || insertions == 0) {
2617 strbuf_addf(&sb,
2618 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2619 deletions);
2621 strbuf_addch(&sb, '\n');
2622 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2623 sb.buf, sb.len, 0);
2624 strbuf_release(&sb);
2627 void print_stat_summary(FILE *fp, int files,
2628 int insertions, int deletions)
2630 struct diff_options o;
2631 memset(&o, 0, sizeof(o));
2632 o.file = fp;
2634 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2637 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2639 int i, len, add, del, adds = 0, dels = 0;
2640 uintmax_t max_change = 0, max_len = 0;
2641 int total_files = data->nr, count;
2642 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2643 const char *reset, *add_c, *del_c;
2644 int extra_shown = 0;
2645 const char *line_prefix = diff_line_prefix(options);
2646 struct strbuf out = STRBUF_INIT;
2648 if (data->nr == 0)
2649 return;
2651 count = options->stat_count ? options->stat_count : data->nr;
2653 reset = diff_get_color_opt(options, DIFF_RESET);
2654 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2655 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2658 * Find the longest filename and max number of changes
2660 for (i = 0; (i < count) && (i < data->nr); i++) {
2661 struct diffstat_file *file = data->files[i];
2662 uintmax_t change = file->added + file->deleted;
2664 if (!file->is_interesting && (change == 0)) {
2665 count++; /* not shown == room for one more */
2666 continue;
2668 fill_print_name(file);
2669 len = strlen(file->print_name);
2670 if (max_len < len)
2671 max_len = len;
2673 if (file->is_unmerged) {
2674 /* "Unmerged" is 8 characters */
2675 bin_width = bin_width < 8 ? 8 : bin_width;
2676 continue;
2678 if (file->is_binary) {
2679 /* "Bin XXX -> YYY bytes" */
2680 int w = 14 + decimal_width(file->added)
2681 + decimal_width(file->deleted);
2682 bin_width = bin_width < w ? w : bin_width;
2683 /* Display change counts aligned with "Bin" */
2684 number_width = 3;
2685 continue;
2688 if (max_change < change)
2689 max_change = change;
2691 count = i; /* where we can stop scanning in data->files[] */
2694 * We have width = stat_width or term_columns() columns total.
2695 * We want a maximum of min(max_len, stat_name_width) for the name part.
2696 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2697 * We also need 1 for " " and 4 + decimal_width(max_change)
2698 * for " | NNNN " and one the empty column at the end, altogether
2699 * 6 + decimal_width(max_change).
2701 * If there's not enough space, we will use the smaller of
2702 * stat_name_width (if set) and 5/8*width for the filename,
2703 * and the rest for constant elements + graph part, but no more
2704 * than stat_graph_width for the graph part.
2705 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2706 * for the standard terminal size).
2708 * In other words: stat_width limits the maximum width, and
2709 * stat_name_width fixes the maximum width of the filename,
2710 * and is also used to divide available columns if there
2711 * aren't enough.
2713 * Binary files are displayed with "Bin XXX -> YYY bytes"
2714 * instead of the change count and graph. This part is treated
2715 * similarly to the graph part, except that it is not
2716 * "scaled". If total width is too small to accommodate the
2717 * guaranteed minimum width of the filename part and the
2718 * separators and this message, this message will "overflow"
2719 * making the line longer than the maximum width.
2722 if (options->stat_width == -1)
2723 width = term_columns() - strlen(line_prefix);
2724 else
2725 width = options->stat_width ? options->stat_width : 80;
2726 number_width = decimal_width(max_change) > number_width ?
2727 decimal_width(max_change) : number_width;
2729 if (options->stat_graph_width == -1)
2730 options->stat_graph_width = diff_stat_graph_width;
2733 * Guarantee 3/8*16==6 for the graph part
2734 * and 5/8*16==10 for the filename part
2736 if (width < 16 + 6 + number_width)
2737 width = 16 + 6 + number_width;
2740 * First assign sizes that are wanted, ignoring available width.
2741 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2742 * starting from "XXX" should fit in graph_width.
2744 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2745 if (options->stat_graph_width &&
2746 options->stat_graph_width < graph_width)
2747 graph_width = options->stat_graph_width;
2749 name_width = (options->stat_name_width > 0 &&
2750 options->stat_name_width < max_len) ?
2751 options->stat_name_width : max_len;
2754 * Adjust adjustable widths not to exceed maximum width
2756 if (name_width + number_width + 6 + graph_width > width) {
2757 if (graph_width > width * 3/8 - number_width - 6) {
2758 graph_width = width * 3/8 - number_width - 6;
2759 if (graph_width < 6)
2760 graph_width = 6;
2763 if (options->stat_graph_width &&
2764 graph_width > options->stat_graph_width)
2765 graph_width = options->stat_graph_width;
2766 if (name_width > width - number_width - 6 - graph_width)
2767 name_width = width - number_width - 6 - graph_width;
2768 else
2769 graph_width = width - number_width - 6 - name_width;
2773 * From here name_width is the width of the name area,
2774 * and graph_width is the width of the graph area.
2775 * max_change is used to scale graph properly.
2777 for (i = 0; i < count; i++) {
2778 const char *prefix = "";
2779 struct diffstat_file *file = data->files[i];
2780 char *name = file->print_name;
2781 uintmax_t added = file->added;
2782 uintmax_t deleted = file->deleted;
2783 int name_len;
2785 if (!file->is_interesting && (added + deleted == 0))
2786 continue;
2789 * "scale" the filename
2791 len = name_width;
2792 name_len = strlen(name);
2793 if (name_width < name_len) {
2794 char *slash;
2795 prefix = "...";
2796 len -= 3;
2797 name += name_len - len;
2798 slash = strchr(name, '/');
2799 if (slash)
2800 name = slash;
2803 if (file->is_binary) {
2804 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2805 strbuf_addf(&out, " %*s", number_width, "Bin");
2806 if (!added && !deleted) {
2807 strbuf_addch(&out, '\n');
2808 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2809 out.buf, out.len, 0);
2810 strbuf_reset(&out);
2811 continue;
2813 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2814 del_c, deleted, reset);
2815 strbuf_addstr(&out, " -> ");
2816 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2817 add_c, added, reset);
2818 strbuf_addstr(&out, " bytes\n");
2819 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2820 out.buf, out.len, 0);
2821 strbuf_reset(&out);
2822 continue;
2824 else if (file->is_unmerged) {
2825 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2826 strbuf_addstr(&out, " Unmerged\n");
2827 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2828 out.buf, out.len, 0);
2829 strbuf_reset(&out);
2830 continue;
2834 * scale the add/delete
2836 add = added;
2837 del = deleted;
2839 if (graph_width <= max_change) {
2840 int total = scale_linear(add + del, graph_width, max_change);
2841 if (total < 2 && add && del)
2842 /* width >= 2 due to the sanity check */
2843 total = 2;
2844 if (add < del) {
2845 add = scale_linear(add, graph_width, max_change);
2846 del = total - add;
2847 } else {
2848 del = scale_linear(del, graph_width, max_change);
2849 add = total - del;
2852 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2853 strbuf_addf(&out, " %*"PRIuMAX"%s",
2854 number_width, added + deleted,
2855 added + deleted ? " " : "");
2856 show_graph(&out, '+', add, add_c, reset);
2857 show_graph(&out, '-', del, del_c, reset);
2858 strbuf_addch(&out, '\n');
2859 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2860 out.buf, out.len, 0);
2861 strbuf_reset(&out);
2864 for (i = 0; i < data->nr; i++) {
2865 struct diffstat_file *file = data->files[i];
2866 uintmax_t added = file->added;
2867 uintmax_t deleted = file->deleted;
2869 if (file->is_unmerged ||
2870 (!file->is_interesting && (added + deleted == 0))) {
2871 total_files--;
2872 continue;
2875 if (!file->is_binary) {
2876 adds += added;
2877 dels += deleted;
2879 if (i < count)
2880 continue;
2881 if (!extra_shown)
2882 emit_diff_symbol(options,
2883 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2884 NULL, 0, 0);
2885 extra_shown = 1;
2888 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2889 strbuf_release(&out);
2892 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2894 int i, adds = 0, dels = 0, total_files = data->nr;
2896 if (data->nr == 0)
2897 return;
2899 for (i = 0; i < data->nr; i++) {
2900 int added = data->files[i]->added;
2901 int deleted = data->files[i]->deleted;
2903 if (data->files[i]->is_unmerged ||
2904 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2905 total_files--;
2906 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2907 adds += added;
2908 dels += deleted;
2911 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2914 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2916 int i;
2918 if (data->nr == 0)
2919 return;
2921 for (i = 0; i < data->nr; i++) {
2922 struct diffstat_file *file = data->files[i];
2924 fprintf(options->file, "%s", diff_line_prefix(options));
2926 if (file->is_binary)
2927 fprintf(options->file, "-\t-\t");
2928 else
2929 fprintf(options->file,
2930 "%"PRIuMAX"\t%"PRIuMAX"\t",
2931 file->added, file->deleted);
2932 if (options->line_termination) {
2933 fill_print_name(file);
2934 if (!file->is_renamed)
2935 write_name_quoted(file->name, options->file,
2936 options->line_termination);
2937 else {
2938 fputs(file->print_name, options->file);
2939 putc(options->line_termination, options->file);
2941 } else {
2942 if (file->is_renamed) {
2943 putc('\0', options->file);
2944 write_name_quoted(file->from_name, options->file, '\0');
2946 write_name_quoted(file->name, options->file, '\0');
2951 struct dirstat_file {
2952 const char *name;
2953 unsigned long changed;
2956 struct dirstat_dir {
2957 struct dirstat_file *files;
2958 int alloc, nr, permille, cumulative;
2961 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2962 unsigned long changed, const char *base, int baselen)
2964 unsigned long sum_changes = 0;
2965 unsigned int sources = 0;
2966 const char *line_prefix = diff_line_prefix(opt);
2968 while (dir->nr) {
2969 struct dirstat_file *f = dir->files;
2970 int namelen = strlen(f->name);
2971 unsigned long changes;
2972 char *slash;
2974 if (namelen < baselen)
2975 break;
2976 if (memcmp(f->name, base, baselen))
2977 break;
2978 slash = strchr(f->name + baselen, '/');
2979 if (slash) {
2980 int newbaselen = slash + 1 - f->name;
2981 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2982 sources++;
2983 } else {
2984 changes = f->changed;
2985 dir->files++;
2986 dir->nr--;
2987 sources += 2;
2989 sum_changes += changes;
2993 * We don't report dirstat's for
2994 * - the top level
2995 * - or cases where everything came from a single directory
2996 * under this directory (sources == 1).
2998 if (baselen && sources != 1) {
2999 if (sum_changes) {
3000 int permille = sum_changes * 1000 / changed;
3001 if (permille >= dir->permille) {
3002 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3003 permille / 10, permille % 10, baselen, base);
3004 if (!dir->cumulative)
3005 return 0;
3009 return sum_changes;
3012 static int dirstat_compare(const void *_a, const void *_b)
3014 const struct dirstat_file *a = _a;
3015 const struct dirstat_file *b = _b;
3016 return strcmp(a->name, b->name);
3019 static void show_dirstat(struct diff_options *options)
3021 int i;
3022 unsigned long changed;
3023 struct dirstat_dir dir;
3024 struct diff_queue_struct *q = &diff_queued_diff;
3026 dir.files = NULL;
3027 dir.alloc = 0;
3028 dir.nr = 0;
3029 dir.permille = options->dirstat_permille;
3030 dir.cumulative = options->flags.dirstat_cumulative;
3032 changed = 0;
3033 for (i = 0; i < q->nr; i++) {
3034 struct diff_filepair *p = q->queue[i];
3035 const char *name;
3036 unsigned long copied, added, damage;
3037 struct diff_populate_filespec_options dpf_options = {
3038 .check_size_only = 1,
3041 name = p->two->path ? p->two->path : p->one->path;
3043 if (p->one->oid_valid && p->two->oid_valid &&
3044 oideq(&p->one->oid, &p->two->oid)) {
3046 * The SHA1 has not changed, so pre-/post-content is
3047 * identical. We can therefore skip looking at the
3048 * file contents altogether.
3050 damage = 0;
3051 goto found_damage;
3054 if (options->flags.dirstat_by_file) {
3056 * In --dirstat-by-file mode, we don't really need to
3057 * look at the actual file contents at all.
3058 * The fact that the SHA1 changed is enough for us to
3059 * add this file to the list of results
3060 * (with each file contributing equal damage).
3062 damage = 1;
3063 goto found_damage;
3066 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3067 diff_populate_filespec(options->repo, p->one, NULL);
3068 diff_populate_filespec(options->repo, p->two, NULL);
3069 diffcore_count_changes(options->repo,
3070 p->one, p->two, NULL, NULL,
3071 &copied, &added);
3072 diff_free_filespec_data(p->one);
3073 diff_free_filespec_data(p->two);
3074 } else if (DIFF_FILE_VALID(p->one)) {
3075 diff_populate_filespec(options->repo, p->one, &dpf_options);
3076 copied = added = 0;
3077 diff_free_filespec_data(p->one);
3078 } else if (DIFF_FILE_VALID(p->two)) {
3079 diff_populate_filespec(options->repo, p->two, &dpf_options);
3080 copied = 0;
3081 added = p->two->size;
3082 diff_free_filespec_data(p->two);
3083 } else
3084 continue;
3087 * Original minus copied is the removed material,
3088 * added is the new material. They are both damages
3089 * made to the preimage.
3090 * If the resulting damage is zero, we know that
3091 * diffcore_count_changes() considers the two entries to
3092 * be identical, but since the oid changed, we
3093 * know that there must have been _some_ kind of change,
3094 * so we force all entries to have damage > 0.
3096 damage = (p->one->size - copied) + added;
3097 if (!damage)
3098 damage = 1;
3100 found_damage:
3101 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3102 dir.files[dir.nr].name = 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 show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3119 int i;
3120 unsigned long changed;
3121 struct dirstat_dir dir;
3123 if (data->nr == 0)
3124 return;
3126 dir.files = NULL;
3127 dir.alloc = 0;
3128 dir.nr = 0;
3129 dir.permille = options->dirstat_permille;
3130 dir.cumulative = options->flags.dirstat_cumulative;
3132 changed = 0;
3133 for (i = 0; i < data->nr; i++) {
3134 struct diffstat_file *file = data->files[i];
3135 unsigned long damage = file->added + file->deleted;
3136 if (file->is_binary)
3138 * binary files counts bytes, not lines. Must find some
3139 * way to normalize binary bytes vs. textual lines.
3140 * The following heuristic assumes that there are 64
3141 * bytes per "line".
3142 * This is stupid and ugly, but very cheap...
3144 damage = DIV_ROUND_UP(damage, 64);
3145 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3146 dir.files[dir.nr].name = file->name;
3147 dir.files[dir.nr].changed = damage;
3148 changed += damage;
3149 dir.nr++;
3152 /* This can happen even with many files, if everything was renames */
3153 if (!changed)
3154 return;
3156 /* Show all directories with more than x% of the changes */
3157 QSORT(dir.files, dir.nr, dirstat_compare);
3158 gather_dirstat(options, &dir, changed, "", 0);
3161 static void free_diffstat_file(struct diffstat_file *f)
3163 free(f->print_name);
3164 free(f->name);
3165 free(f->from_name);
3166 free(f);
3169 void free_diffstat_info(struct diffstat_t *diffstat)
3171 int i;
3172 for (i = 0; i < diffstat->nr; i++)
3173 free_diffstat_file(diffstat->files[i]);
3174 free(diffstat->files);
3177 struct checkdiff_t {
3178 const char *filename;
3179 int lineno;
3180 int conflict_marker_size;
3181 struct diff_options *o;
3182 unsigned ws_rule;
3183 unsigned status;
3186 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3188 char firstchar;
3189 int cnt;
3191 if (len < marker_size + 1)
3192 return 0;
3193 firstchar = line[0];
3194 switch (firstchar) {
3195 case '=': case '>': case '<': case '|':
3196 break;
3197 default:
3198 return 0;
3200 for (cnt = 1; cnt < marker_size; cnt++)
3201 if (line[cnt] != firstchar)
3202 return 0;
3203 /* line[1] through line[marker_size-1] are same as firstchar */
3204 if (len < marker_size + 1 || !isspace(line[marker_size]))
3205 return 0;
3206 return 1;
3209 static void checkdiff_consume_hunk(void *priv,
3210 long ob, long on, long nb, long nn,
3211 const char *func, long funclen)
3214 struct checkdiff_t *data = priv;
3215 data->lineno = nb - 1;
3218 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3220 struct checkdiff_t *data = priv;
3221 int marker_size = data->conflict_marker_size;
3222 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3223 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3224 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3225 char *err;
3226 const char *line_prefix;
3228 assert(data->o);
3229 line_prefix = diff_line_prefix(data->o);
3231 if (line[0] == '+') {
3232 unsigned bad;
3233 data->lineno++;
3234 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3235 data->status |= 1;
3236 fprintf(data->o->file,
3237 "%s%s:%d: leftover conflict marker\n",
3238 line_prefix, data->filename, data->lineno);
3240 bad = ws_check(line + 1, len - 1, data->ws_rule);
3241 if (!bad)
3242 return 0;
3243 data->status |= bad;
3244 err = whitespace_error_string(bad);
3245 fprintf(data->o->file, "%s%s:%d: %s.\n",
3246 line_prefix, data->filename, data->lineno, err);
3247 free(err);
3248 emit_line(data->o, set, reset, line, 1);
3249 ws_check_emit(line + 1, len - 1, data->ws_rule,
3250 data->o->file, set, reset, ws);
3251 } else if (line[0] == ' ') {
3252 data->lineno++;
3254 return 0;
3257 static unsigned char *deflate_it(char *data,
3258 unsigned long size,
3259 unsigned long *result_size)
3261 int bound;
3262 unsigned char *deflated;
3263 git_zstream stream;
3265 git_deflate_init(&stream, zlib_compression_level);
3266 bound = git_deflate_bound(&stream, size);
3267 deflated = xmalloc(bound);
3268 stream.next_out = deflated;
3269 stream.avail_out = bound;
3271 stream.next_in = (unsigned char *)data;
3272 stream.avail_in = size;
3273 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3274 ; /* nothing */
3275 git_deflate_end(&stream);
3276 *result_size = stream.total_out;
3277 return deflated;
3280 static void emit_binary_diff_body(struct diff_options *o,
3281 mmfile_t *one, mmfile_t *two)
3283 void *cp;
3284 void *delta;
3285 void *deflated;
3286 void *data;
3287 unsigned long orig_size;
3288 unsigned long delta_size;
3289 unsigned long deflate_size;
3290 unsigned long data_size;
3292 /* We could do deflated delta, or we could do just deflated two,
3293 * whichever is smaller.
3295 delta = NULL;
3296 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3297 if (one->size && two->size) {
3298 delta = diff_delta(one->ptr, one->size,
3299 two->ptr, two->size,
3300 &delta_size, deflate_size);
3301 if (delta) {
3302 void *to_free = delta;
3303 orig_size = delta_size;
3304 delta = deflate_it(delta, delta_size, &delta_size);
3305 free(to_free);
3309 if (delta && delta_size < deflate_size) {
3310 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3311 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3312 s, strlen(s), 0);
3313 free(s);
3314 free(deflated);
3315 data = delta;
3316 data_size = delta_size;
3317 } else {
3318 char *s = xstrfmt("%lu", two->size);
3319 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3320 s, strlen(s), 0);
3321 free(s);
3322 free(delta);
3323 data = deflated;
3324 data_size = deflate_size;
3327 /* emit data encoded in base85 */
3328 cp = data;
3329 while (data_size) {
3330 int len;
3331 int bytes = (52 < data_size) ? 52 : data_size;
3332 char line[71];
3333 data_size -= bytes;
3334 if (bytes <= 26)
3335 line[0] = bytes + 'A' - 1;
3336 else
3337 line[0] = bytes - 26 + 'a' - 1;
3338 encode_85(line + 1, cp, bytes);
3339 cp = (char *) cp + bytes;
3341 len = strlen(line);
3342 line[len++] = '\n';
3343 line[len] = '\0';
3345 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3346 line, len, 0);
3348 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3349 free(data);
3352 static void emit_binary_diff(struct diff_options *o,
3353 mmfile_t *one, mmfile_t *two)
3355 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3356 emit_binary_diff_body(o, one, two);
3357 emit_binary_diff_body(o, two, one);
3360 int diff_filespec_is_binary(struct repository *r,
3361 struct diff_filespec *one)
3363 struct diff_populate_filespec_options dpf_options = {
3364 .check_binary = 1,
3367 if (one->is_binary == -1) {
3368 diff_filespec_load_driver(one, r->index);
3369 if (one->driver->binary != -1)
3370 one->is_binary = one->driver->binary;
3371 else {
3372 if (!one->data && DIFF_FILE_VALID(one))
3373 diff_populate_filespec(r, one, &dpf_options);
3374 if (one->is_binary == -1 && one->data)
3375 one->is_binary = buffer_is_binary(one->data,
3376 one->size);
3377 if (one->is_binary == -1)
3378 one->is_binary = 0;
3381 return one->is_binary;
3384 static const struct userdiff_funcname *
3385 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3387 diff_filespec_load_driver(one, o->repo->index);
3388 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3391 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3393 if (!options->a_prefix)
3394 options->a_prefix = a;
3395 if (!options->b_prefix)
3396 options->b_prefix = b;
3399 struct userdiff_driver *get_textconv(struct repository *r,
3400 struct diff_filespec *one)
3402 if (!DIFF_FILE_VALID(one))
3403 return NULL;
3405 diff_filespec_load_driver(one, r->index);
3406 return userdiff_get_textconv(r, one->driver);
3409 static void builtin_diff(const char *name_a,
3410 const char *name_b,
3411 struct diff_filespec *one,
3412 struct diff_filespec *two,
3413 const char *xfrm_msg,
3414 int must_show_header,
3415 struct diff_options *o,
3416 int complete_rewrite)
3418 mmfile_t mf1, mf2;
3419 const char *lbl[2];
3420 char *a_one, *b_two;
3421 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3422 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3423 const char *a_prefix, *b_prefix;
3424 struct userdiff_driver *textconv_one = NULL;
3425 struct userdiff_driver *textconv_two = NULL;
3426 struct strbuf header = STRBUF_INIT;
3427 const char *line_prefix = diff_line_prefix(o);
3429 diff_set_mnemonic_prefix(o, "a/", "b/");
3430 if (o->flags.reverse_diff) {
3431 a_prefix = o->b_prefix;
3432 b_prefix = o->a_prefix;
3433 } else {
3434 a_prefix = o->a_prefix;
3435 b_prefix = o->b_prefix;
3438 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3439 (!one->mode || S_ISGITLINK(one->mode)) &&
3440 (!two->mode || S_ISGITLINK(two->mode))) {
3441 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3442 &one->oid, &two->oid,
3443 two->dirty_submodule);
3444 return;
3445 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3446 (!one->mode || S_ISGITLINK(one->mode)) &&
3447 (!two->mode || S_ISGITLINK(two->mode))) {
3448 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3449 &one->oid, &two->oid,
3450 two->dirty_submodule);
3451 return;
3454 if (o->flags.allow_textconv) {
3455 textconv_one = get_textconv(o->repo, one);
3456 textconv_two = get_textconv(o->repo, two);
3459 /* Never use a non-valid filename anywhere if at all possible */
3460 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3461 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3463 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3464 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3465 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3466 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3467 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3468 if (lbl[0][0] == '/') {
3469 /* /dev/null */
3470 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3471 if (xfrm_msg)
3472 strbuf_addstr(&header, xfrm_msg);
3473 must_show_header = 1;
3475 else if (lbl[1][0] == '/') {
3476 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3477 if (xfrm_msg)
3478 strbuf_addstr(&header, xfrm_msg);
3479 must_show_header = 1;
3481 else {
3482 if (one->mode != two->mode) {
3483 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3484 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3485 must_show_header = 1;
3487 if (xfrm_msg)
3488 strbuf_addstr(&header, xfrm_msg);
3491 * we do not run diff between different kind
3492 * of objects.
3494 if ((one->mode ^ two->mode) & S_IFMT)
3495 goto free_ab_and_return;
3496 if (complete_rewrite &&
3497 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3498 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3499 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3500 header.buf, header.len, 0);
3501 strbuf_reset(&header);
3502 emit_rewrite_diff(name_a, name_b, one, two,
3503 textconv_one, textconv_two, o);
3504 o->found_changes = 1;
3505 goto free_ab_and_return;
3509 if (o->irreversible_delete && lbl[1][0] == '/') {
3510 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3511 header.len, 0);
3512 strbuf_reset(&header);
3513 goto free_ab_and_return;
3514 } else if (!o->flags.text &&
3515 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3516 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3517 struct strbuf sb = STRBUF_INIT;
3518 if (!one->data && !two->data &&
3519 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3520 !o->flags.binary) {
3521 if (oideq(&one->oid, &two->oid)) {
3522 if (must_show_header)
3523 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3524 header.buf, header.len,
3526 goto free_ab_and_return;
3528 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3529 header.buf, header.len, 0);
3530 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3531 diff_line_prefix(o), lbl[0], lbl[1]);
3532 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3533 sb.buf, sb.len, 0);
3534 strbuf_release(&sb);
3535 goto free_ab_and_return;
3537 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3538 fill_mmfile(o->repo, &mf2, two) < 0)
3539 die("unable to read files to diff");
3540 /* Quite common confusing case */
3541 if (mf1.size == mf2.size &&
3542 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3543 if (must_show_header)
3544 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3545 header.buf, header.len, 0);
3546 goto free_ab_and_return;
3548 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3549 strbuf_reset(&header);
3550 if (o->flags.binary)
3551 emit_binary_diff(o, &mf1, &mf2);
3552 else {
3553 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3554 diff_line_prefix(o), lbl[0], lbl[1]);
3555 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3556 sb.buf, sb.len, 0);
3557 strbuf_release(&sb);
3559 o->found_changes = 1;
3560 } else {
3561 /* Crazy xdl interfaces.. */
3562 const char *diffopts;
3563 const char *v;
3564 xpparam_t xpp;
3565 xdemitconf_t xecfg;
3566 struct emit_callback ecbdata;
3567 const struct userdiff_funcname *pe;
3569 if (must_show_header) {
3570 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3571 header.buf, header.len, 0);
3572 strbuf_reset(&header);
3575 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3576 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3578 pe = diff_funcname_pattern(o, one);
3579 if (!pe)
3580 pe = diff_funcname_pattern(o, two);
3582 memset(&xpp, 0, sizeof(xpp));
3583 memset(&xecfg, 0, sizeof(xecfg));
3584 memset(&ecbdata, 0, sizeof(ecbdata));
3585 if (o->flags.suppress_diff_headers)
3586 lbl[0] = NULL;
3587 ecbdata.label_path = lbl;
3588 ecbdata.color_diff = want_color(o->use_color);
3589 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3590 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3591 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3592 ecbdata.opt = o;
3593 if (header.len && !o->flags.suppress_diff_headers)
3594 ecbdata.header = &header;
3595 xpp.flags = o->xdl_opts;
3596 xpp.ignore_regex = o->ignore_regex;
3597 xpp.ignore_regex_nr = o->ignore_regex_nr;
3598 xpp.anchors = o->anchors;
3599 xpp.anchors_nr = o->anchors_nr;
3600 xecfg.ctxlen = o->context;
3601 xecfg.interhunkctxlen = o->interhunkcontext;
3602 xecfg.flags = XDL_EMIT_FUNCNAMES;
3603 if (o->flags.funccontext)
3604 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3605 if (pe)
3606 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3608 diffopts = getenv("GIT_DIFF_OPTS");
3609 if (!diffopts)
3611 else if (skip_prefix(diffopts, "--unified=", &v))
3612 xecfg.ctxlen = strtoul(v, NULL, 10);
3613 else if (skip_prefix(diffopts, "-u", &v))
3614 xecfg.ctxlen = strtoul(v, NULL, 10);
3616 if (o->word_diff)
3617 init_diff_words_data(&ecbdata, o, one, two);
3618 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3619 &ecbdata, &xpp, &xecfg))
3620 die("unable to generate diff for %s", one->path);
3621 if (o->word_diff)
3622 free_diff_words_data(&ecbdata);
3623 if (textconv_one)
3624 free(mf1.ptr);
3625 if (textconv_two)
3626 free(mf2.ptr);
3627 xdiff_clear_find_func(&xecfg);
3630 free_ab_and_return:
3631 strbuf_release(&header);
3632 diff_free_filespec_data(one);
3633 diff_free_filespec_data(two);
3634 free(a_one);
3635 free(b_two);
3636 return;
3639 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3641 if (!is_renamed) {
3642 if (p->status == DIFF_STATUS_ADDED) {
3643 if (S_ISLNK(p->two->mode))
3644 return "new +l";
3645 else if ((p->two->mode & 0777) == 0755)
3646 return "new +x";
3647 else
3648 return "new";
3649 } else if (p->status == DIFF_STATUS_DELETED)
3650 return "gone";
3652 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3653 return "mode -l";
3654 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3655 return "mode +l";
3656 else if ((p->one->mode & 0777) == 0644 &&
3657 (p->two->mode & 0777) == 0755)
3658 return "mode +x";
3659 else if ((p->one->mode & 0777) == 0755 &&
3660 (p->two->mode & 0777) == 0644)
3661 return "mode -x";
3662 return NULL;
3665 static void builtin_diffstat(const char *name_a, const char *name_b,
3666 struct diff_filespec *one,
3667 struct diff_filespec *two,
3668 struct diffstat_t *diffstat,
3669 struct diff_options *o,
3670 struct diff_filepair *p)
3672 mmfile_t mf1, mf2;
3673 struct diffstat_file *data;
3674 int may_differ;
3675 int complete_rewrite = 0;
3677 if (!DIFF_PAIR_UNMERGED(p)) {
3678 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3679 complete_rewrite = 1;
3682 data = diffstat_add(diffstat, name_a, name_b);
3683 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3684 if (o->flags.stat_with_summary)
3685 data->comments = get_compact_summary(p, data->is_renamed);
3687 if (!one || !two) {
3688 data->is_unmerged = 1;
3689 return;
3692 /* saves some reads if true, not a guarantee of diff outcome */
3693 may_differ = !(one->oid_valid && two->oid_valid &&
3694 oideq(&one->oid, &two->oid));
3696 if (diff_filespec_is_binary(o->repo, one) ||
3697 diff_filespec_is_binary(o->repo, two)) {
3698 data->is_binary = 1;
3699 if (!may_differ) {
3700 data->added = 0;
3701 data->deleted = 0;
3702 } else {
3703 data->added = diff_filespec_size(o->repo, two);
3704 data->deleted = diff_filespec_size(o->repo, one);
3708 else if (complete_rewrite) {
3709 diff_populate_filespec(o->repo, one, NULL);
3710 diff_populate_filespec(o->repo, two, NULL);
3711 data->deleted = count_lines(one->data, one->size);
3712 data->added = count_lines(two->data, two->size);
3715 else if (may_differ) {
3716 /* Crazy xdl interfaces.. */
3717 xpparam_t xpp;
3718 xdemitconf_t xecfg;
3720 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3721 fill_mmfile(o->repo, &mf2, two) < 0)
3722 die("unable to read files to diff");
3724 memset(&xpp, 0, sizeof(xpp));
3725 memset(&xecfg, 0, sizeof(xecfg));
3726 xpp.flags = o->xdl_opts;
3727 xpp.ignore_regex = o->ignore_regex;
3728 xpp.ignore_regex_nr = o->ignore_regex_nr;
3729 xpp.anchors = o->anchors;
3730 xpp.anchors_nr = o->anchors_nr;
3731 xecfg.ctxlen = o->context;
3732 xecfg.interhunkctxlen = o->interhunkcontext;
3733 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3734 if (xdi_diff_outf(&mf1, &mf2, NULL,
3735 diffstat_consume, diffstat, &xpp, &xecfg))
3736 die("unable to generate diffstat for %s", one->path);
3738 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3739 struct diffstat_file *file =
3740 diffstat->files[diffstat->nr - 1];
3742 * Omit diffstats of modified files where nothing changed.
3743 * Even if may_differ, this might be the case due to
3744 * ignoring whitespace changes, etc.
3746 * But note that we special-case additions, deletions,
3747 * renames, and mode changes as adding an empty file,
3748 * for example is still of interest.
3750 if ((p->status == DIFF_STATUS_MODIFIED)
3751 && !file->added
3752 && !file->deleted
3753 && one->mode == two->mode) {
3754 free_diffstat_file(file);
3755 diffstat->nr--;
3760 diff_free_filespec_data(one);
3761 diff_free_filespec_data(two);
3764 static void builtin_checkdiff(const char *name_a, const char *name_b,
3765 const char *attr_path,
3766 struct diff_filespec *one,
3767 struct diff_filespec *two,
3768 struct diff_options *o)
3770 mmfile_t mf1, mf2;
3771 struct checkdiff_t data;
3773 if (!two)
3774 return;
3776 memset(&data, 0, sizeof(data));
3777 data.filename = name_b ? name_b : name_a;
3778 data.lineno = 0;
3779 data.o = o;
3780 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3781 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3783 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3784 fill_mmfile(o->repo, &mf2, two) < 0)
3785 die("unable to read files to diff");
3788 * All the other codepaths check both sides, but not checking
3789 * the "old" side here is deliberate. We are checking the newly
3790 * introduced changes, and as long as the "new" side is text, we
3791 * can and should check what it introduces.
3793 if (diff_filespec_is_binary(o->repo, two))
3794 goto free_and_return;
3795 else {
3796 /* Crazy xdl interfaces.. */
3797 xpparam_t xpp;
3798 xdemitconf_t xecfg;
3800 memset(&xpp, 0, sizeof(xpp));
3801 memset(&xecfg, 0, sizeof(xecfg));
3802 xecfg.ctxlen = 1; /* at least one context line */
3803 xpp.flags = 0;
3804 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3805 checkdiff_consume, &data,
3806 &xpp, &xecfg))
3807 die("unable to generate checkdiff for %s", one->path);
3809 if (data.ws_rule & WS_BLANK_AT_EOF) {
3810 struct emit_callback ecbdata;
3811 int blank_at_eof;
3813 ecbdata.ws_rule = data.ws_rule;
3814 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3815 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3817 if (blank_at_eof) {
3818 static char *err;
3819 if (!err)
3820 err = whitespace_error_string(WS_BLANK_AT_EOF);
3821 fprintf(o->file, "%s:%d: %s.\n",
3822 data.filename, blank_at_eof, err);
3823 data.status = 1; /* report errors */
3827 free_and_return:
3828 diff_free_filespec_data(one);
3829 diff_free_filespec_data(two);
3830 if (data.status)
3831 o->flags.check_failed = 1;
3834 struct diff_filespec *alloc_filespec(const char *path)
3836 struct diff_filespec *spec;
3838 FLEXPTR_ALLOC_STR(spec, path, path);
3839 spec->count = 1;
3840 spec->is_binary = -1;
3841 return spec;
3844 void free_filespec(struct diff_filespec *spec)
3846 if (!--spec->count) {
3847 diff_free_filespec_data(spec);
3848 free(spec);
3852 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3853 int oid_valid, unsigned short mode)
3855 if (mode) {
3856 spec->mode = canon_mode(mode);
3857 oidcpy(&spec->oid, oid);
3858 spec->oid_valid = oid_valid;
3863 * Given a name and sha1 pair, if the index tells us the file in
3864 * the work tree has that object contents, return true, so that
3865 * prepare_temp_file() does not have to inflate and extract.
3867 static int reuse_worktree_file(struct index_state *istate,
3868 const char *name,
3869 const struct object_id *oid,
3870 int want_file)
3872 const struct cache_entry *ce;
3873 struct stat st;
3874 int pos, len;
3877 * We do not read the cache ourselves here, because the
3878 * benchmark with my previous version that always reads cache
3879 * shows that it makes things worse for diff-tree comparing
3880 * two linux-2.6 kernel trees in an already checked out work
3881 * tree. This is because most diff-tree comparisons deal with
3882 * only a small number of files, while reading the cache is
3883 * expensive for a large project, and its cost outweighs the
3884 * savings we get by not inflating the object to a temporary
3885 * file. Practically, this code only helps when we are used
3886 * by diff-cache --cached, which does read the cache before
3887 * calling us.
3889 if (!istate->cache)
3890 return 0;
3892 /* We want to avoid the working directory if our caller
3893 * doesn't need the data in a normal file, this system
3894 * is rather slow with its stat/open/mmap/close syscalls,
3895 * and the object is contained in a pack file. The pack
3896 * is probably already open and will be faster to obtain
3897 * the data through than the working directory. Loose
3898 * objects however would tend to be slower as they need
3899 * to be individually opened and inflated.
3901 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3902 return 0;
3905 * Similarly, if we'd have to convert the file contents anyway, that
3906 * makes the optimization not worthwhile.
3908 if (!want_file && would_convert_to_git(istate, name))
3909 return 0;
3912 * If this path does not match our sparse-checkout definition,
3913 * then the file will not be in the working directory.
3915 if (!path_in_sparse_checkout(name, istate))
3916 return 0;
3918 len = strlen(name);
3919 pos = index_name_pos(istate, name, len);
3920 if (pos < 0)
3921 return 0;
3922 ce = istate->cache[pos];
3925 * This is not the sha1 we are looking for, or
3926 * unreusable because it is not a regular file.
3928 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3929 return 0;
3932 * If ce is marked as "assume unchanged", there is no
3933 * guarantee that work tree matches what we are looking for.
3935 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3936 return 0;
3939 * If ce matches the file in the work tree, we can reuse it.
3941 if (ce_uptodate(ce) ||
3942 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3943 return 1;
3945 return 0;
3948 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3950 struct strbuf buf = STRBUF_INIT;
3951 char *dirty = "";
3953 /* Are we looking at the work tree? */
3954 if (s->dirty_submodule)
3955 dirty = "-dirty";
3957 strbuf_addf(&buf, "Subproject commit %s%s\n",
3958 oid_to_hex(&s->oid), dirty);
3959 s->size = buf.len;
3960 if (size_only) {
3961 s->data = NULL;
3962 strbuf_release(&buf);
3963 } else {
3964 s->data = strbuf_detach(&buf, NULL);
3965 s->should_free = 1;
3967 return 0;
3971 * While doing rename detection and pickaxe operation, we may need to
3972 * grab the data for the blob (or file) for our own in-core comparison.
3973 * diff_filespec has data and size fields for this purpose.
3975 int diff_populate_filespec(struct repository *r,
3976 struct diff_filespec *s,
3977 const struct diff_populate_filespec_options *options)
3979 int size_only = options ? options->check_size_only : 0;
3980 int check_binary = options ? options->check_binary : 0;
3981 int err = 0;
3982 int conv_flags = global_conv_flags_eol;
3984 * demote FAIL to WARN to allow inspecting the situation
3985 * instead of refusing.
3987 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3988 conv_flags = CONV_EOL_RNDTRP_WARN;
3990 if (!DIFF_FILE_VALID(s))
3991 die("internal error: asking to populate invalid file.");
3992 if (S_ISDIR(s->mode))
3993 return -1;
3995 if (s->data)
3996 return 0;
3998 if (size_only && 0 < s->size)
3999 return 0;
4001 if (S_ISGITLINK(s->mode))
4002 return diff_populate_gitlink(s, size_only);
4004 if (!s->oid_valid ||
4005 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4006 struct strbuf buf = STRBUF_INIT;
4007 struct stat st;
4008 int fd;
4010 if (lstat(s->path, &st) < 0) {
4011 err_empty:
4012 err = -1;
4013 empty:
4014 s->data = (char *)"";
4015 s->size = 0;
4016 return err;
4018 s->size = xsize_t(st.st_size);
4019 if (!s->size)
4020 goto empty;
4021 if (S_ISLNK(st.st_mode)) {
4022 struct strbuf sb = STRBUF_INIT;
4024 if (strbuf_readlink(&sb, s->path, s->size))
4025 goto err_empty;
4026 s->size = sb.len;
4027 s->data = strbuf_detach(&sb, NULL);
4028 s->should_free = 1;
4029 return 0;
4033 * Even if the caller would be happy with getting
4034 * only the size, we cannot return early at this
4035 * point if the path requires us to run the content
4036 * conversion.
4038 if (size_only && !would_convert_to_git(r->index, s->path))
4039 return 0;
4042 * Note: this check uses xsize_t(st.st_size) that may
4043 * not be the true size of the blob after it goes
4044 * through convert_to_git(). This may not strictly be
4045 * correct, but the whole point of big_file_threshold
4046 * and is_binary check being that we want to avoid
4047 * opening the file and inspecting the contents, this
4048 * is probably fine.
4050 if (check_binary &&
4051 s->size > big_file_threshold && s->is_binary == -1) {
4052 s->is_binary = 1;
4053 return 0;
4055 fd = open(s->path, O_RDONLY);
4056 if (fd < 0)
4057 goto err_empty;
4058 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4059 close(fd);
4060 s->should_munmap = 1;
4063 * Convert from working tree format to canonical git format
4065 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4066 size_t size = 0;
4067 munmap(s->data, s->size);
4068 s->should_munmap = 0;
4069 s->data = strbuf_detach(&buf, &size);
4070 s->size = size;
4071 s->should_free = 1;
4074 else {
4075 struct object_info info = {
4076 .sizep = &s->size
4079 if (!(size_only || check_binary))
4081 * Set contentp, since there is no chance that merely
4082 * the size is sufficient.
4084 info.contentp = &s->data;
4086 if (options && options->missing_object_cb) {
4087 if (!oid_object_info_extended(r, &s->oid, &info,
4088 OBJECT_INFO_LOOKUP_REPLACE |
4089 OBJECT_INFO_SKIP_FETCH_OBJECT))
4090 goto object_read;
4091 options->missing_object_cb(options->missing_object_data);
4093 if (oid_object_info_extended(r, &s->oid, &info,
4094 OBJECT_INFO_LOOKUP_REPLACE))
4095 die("unable to read %s", oid_to_hex(&s->oid));
4097 object_read:
4098 if (size_only || check_binary) {
4099 if (size_only)
4100 return 0;
4101 if (s->size > big_file_threshold && s->is_binary == -1) {
4102 s->is_binary = 1;
4103 return 0;
4106 if (!info.contentp) {
4107 info.contentp = &s->data;
4108 if (oid_object_info_extended(r, &s->oid, &info,
4109 OBJECT_INFO_LOOKUP_REPLACE))
4110 die("unable to read %s", oid_to_hex(&s->oid));
4112 s->should_free = 1;
4114 return 0;
4117 void diff_free_filespec_blob(struct diff_filespec *s)
4119 if (s->should_free)
4120 free(s->data);
4121 else if (s->should_munmap)
4122 munmap(s->data, s->size);
4124 if (s->should_free || s->should_munmap) {
4125 s->should_free = s->should_munmap = 0;
4126 s->data = NULL;
4130 void diff_free_filespec_data(struct diff_filespec *s)
4132 if (!s)
4133 return;
4135 diff_free_filespec_blob(s);
4136 FREE_AND_NULL(s->cnt_data);
4139 static void prep_temp_blob(struct index_state *istate,
4140 const char *path, struct diff_tempfile *temp,
4141 void *blob,
4142 unsigned long size,
4143 const struct object_id *oid,
4144 int mode)
4146 struct strbuf buf = STRBUF_INIT;
4147 struct strbuf tempfile = STRBUF_INIT;
4148 char *path_dup = xstrdup(path);
4149 const char *base = basename(path_dup);
4150 struct checkout_metadata meta;
4152 init_checkout_metadata(&meta, NULL, NULL, oid);
4154 /* Generate "XXXXXX_basename.ext" */
4155 strbuf_addstr(&tempfile, "XXXXXX_");
4156 strbuf_addstr(&tempfile, base);
4158 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4159 if (!temp->tempfile)
4160 die_errno("unable to create temp-file");
4161 if (convert_to_working_tree(istate, path,
4162 (const char *)blob, (size_t)size, &buf, &meta)) {
4163 blob = buf.buf;
4164 size = buf.len;
4166 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4167 close_tempfile_gently(temp->tempfile))
4168 die_errno("unable to write temp-file");
4169 temp->name = get_tempfile_path(temp->tempfile);
4170 oid_to_hex_r(temp->hex, oid);
4171 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4172 strbuf_release(&buf);
4173 strbuf_release(&tempfile);
4174 free(path_dup);
4177 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4178 const char *name,
4179 struct diff_filespec *one)
4181 struct diff_tempfile *temp = claim_diff_tempfile();
4183 if (!DIFF_FILE_VALID(one)) {
4184 not_a_valid_file:
4185 /* A '-' entry produces this for file-2, and
4186 * a '+' entry produces this for file-1.
4188 temp->name = "/dev/null";
4189 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4190 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4191 return temp;
4194 if (!S_ISGITLINK(one->mode) &&
4195 (!one->oid_valid ||
4196 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4197 struct stat st;
4198 if (lstat(name, &st) < 0) {
4199 if (errno == ENOENT)
4200 goto not_a_valid_file;
4201 die_errno("stat(%s)", name);
4203 if (S_ISLNK(st.st_mode)) {
4204 struct strbuf sb = STRBUF_INIT;
4205 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4206 die_errno("readlink(%s)", name);
4207 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4208 (one->oid_valid ?
4209 &one->oid : null_oid()),
4210 (one->oid_valid ?
4211 one->mode : S_IFLNK));
4212 strbuf_release(&sb);
4214 else {
4215 /* we can borrow from the file in the work tree */
4216 temp->name = name;
4217 if (!one->oid_valid)
4218 oid_to_hex_r(temp->hex, null_oid());
4219 else
4220 oid_to_hex_r(temp->hex, &one->oid);
4221 /* Even though we may sometimes borrow the
4222 * contents from the work tree, we always want
4223 * one->mode. mode is trustworthy even when
4224 * !(one->oid_valid), as long as
4225 * DIFF_FILE_VALID(one).
4227 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4229 return temp;
4231 else {
4232 if (diff_populate_filespec(r, one, NULL))
4233 die("cannot read data blob for %s", one->path);
4234 prep_temp_blob(r->index, name, temp,
4235 one->data, one->size,
4236 &one->oid, one->mode);
4238 return temp;
4241 static void add_external_diff_name(struct repository *r,
4242 struct strvec *argv,
4243 const char *name,
4244 struct diff_filespec *df)
4246 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4247 strvec_push(argv, temp->name);
4248 strvec_push(argv, temp->hex);
4249 strvec_push(argv, temp->mode);
4252 /* An external diff command takes:
4254 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4255 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4258 static void run_external_diff(const char *pgm,
4259 const char *name,
4260 const char *other,
4261 struct diff_filespec *one,
4262 struct diff_filespec *two,
4263 const char *xfrm_msg,
4264 struct diff_options *o)
4266 struct strvec argv = STRVEC_INIT;
4267 struct strvec env = STRVEC_INIT;
4268 struct diff_queue_struct *q = &diff_queued_diff;
4270 strvec_push(&argv, pgm);
4271 strvec_push(&argv, name);
4273 if (one && two) {
4274 add_external_diff_name(o->repo, &argv, name, one);
4275 if (!other)
4276 add_external_diff_name(o->repo, &argv, name, two);
4277 else {
4278 add_external_diff_name(o->repo, &argv, other, two);
4279 strvec_push(&argv, other);
4280 strvec_push(&argv, xfrm_msg);
4284 strvec_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4285 strvec_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4287 diff_free_filespec_data(one);
4288 diff_free_filespec_data(two);
4289 if (run_command_v_opt_cd_env(argv.v, RUN_USING_SHELL, NULL, env.v))
4290 die(_("external diff died, stopping at %s"), name);
4292 remove_tempfile();
4293 strvec_clear(&argv);
4294 strvec_clear(&env);
4297 static int similarity_index(struct diff_filepair *p)
4299 return p->score * 100 / MAX_SCORE;
4302 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4304 if (startup_info->have_repository)
4305 return find_unique_abbrev(oid, abbrev);
4306 else {
4307 char *hex = oid_to_hex(oid);
4308 if (abbrev < 0)
4309 abbrev = FALLBACK_DEFAULT_ABBREV;
4310 if (abbrev > the_hash_algo->hexsz)
4311 BUG("oid abbreviation out of range: %d", abbrev);
4312 if (abbrev)
4313 hex[abbrev] = '\0';
4314 return hex;
4318 static void fill_metainfo(struct strbuf *msg,
4319 const char *name,
4320 const char *other,
4321 struct diff_filespec *one,
4322 struct diff_filespec *two,
4323 struct diff_options *o,
4324 struct diff_filepair *p,
4325 int *must_show_header,
4326 int use_color)
4328 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4329 const char *reset = diff_get_color(use_color, DIFF_RESET);
4330 const char *line_prefix = diff_line_prefix(o);
4332 *must_show_header = 1;
4333 strbuf_init(msg, PATH_MAX * 2 + 300);
4334 switch (p->status) {
4335 case DIFF_STATUS_COPIED:
4336 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4337 line_prefix, set, similarity_index(p));
4338 strbuf_addf(msg, "%s\n%s%scopy from ",
4339 reset, line_prefix, set);
4340 quote_c_style(name, msg, NULL, 0);
4341 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4342 quote_c_style(other, msg, NULL, 0);
4343 strbuf_addf(msg, "%s\n", reset);
4344 break;
4345 case DIFF_STATUS_RENAMED:
4346 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4347 line_prefix, set, similarity_index(p));
4348 strbuf_addf(msg, "%s\n%s%srename from ",
4349 reset, line_prefix, set);
4350 quote_c_style(name, msg, NULL, 0);
4351 strbuf_addf(msg, "%s\n%s%srename to ",
4352 reset, line_prefix, set);
4353 quote_c_style(other, msg, NULL, 0);
4354 strbuf_addf(msg, "%s\n", reset);
4355 break;
4356 case DIFF_STATUS_MODIFIED:
4357 if (p->score) {
4358 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4359 line_prefix,
4360 set, similarity_index(p), reset);
4361 break;
4363 /* fallthru */
4364 default:
4365 *must_show_header = 0;
4367 if (one && two && !oideq(&one->oid, &two->oid)) {
4368 const unsigned hexsz = the_hash_algo->hexsz;
4369 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4371 if (o->flags.full_index)
4372 abbrev = hexsz;
4374 if (o->flags.binary) {
4375 mmfile_t mf;
4376 if ((!fill_mmfile(o->repo, &mf, one) &&
4377 diff_filespec_is_binary(o->repo, one)) ||
4378 (!fill_mmfile(o->repo, &mf, two) &&
4379 diff_filespec_is_binary(o->repo, two)))
4380 abbrev = hexsz;
4382 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4383 diff_abbrev_oid(&one->oid, abbrev),
4384 diff_abbrev_oid(&two->oid, abbrev));
4385 if (one->mode == two->mode)
4386 strbuf_addf(msg, " %06o", one->mode);
4387 strbuf_addf(msg, "%s\n", reset);
4391 static void run_diff_cmd(const char *pgm,
4392 const char *name,
4393 const char *other,
4394 const char *attr_path,
4395 struct diff_filespec *one,
4396 struct diff_filespec *two,
4397 struct strbuf *msg,
4398 struct diff_options *o,
4399 struct diff_filepair *p)
4401 const char *xfrm_msg = NULL;
4402 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4403 int must_show_header = 0;
4406 if (o->flags.allow_external) {
4407 struct userdiff_driver *drv;
4409 drv = userdiff_find_by_path(o->repo->index, attr_path);
4410 if (drv && drv->external)
4411 pgm = drv->external;
4414 if (msg) {
4416 * don't use colors when the header is intended for an
4417 * external diff driver
4419 fill_metainfo(msg, name, other, one, two, o, p,
4420 &must_show_header,
4421 want_color(o->use_color) && !pgm);
4422 xfrm_msg = msg->len ? msg->buf : NULL;
4425 if (pgm) {
4426 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4427 return;
4429 if (one && two)
4430 builtin_diff(name, other ? other : name,
4431 one, two, xfrm_msg, must_show_header,
4432 o, complete_rewrite);
4433 else
4434 fprintf(o->file, "* Unmerged path %s\n", name);
4437 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4439 if (DIFF_FILE_VALID(one)) {
4440 if (!one->oid_valid) {
4441 struct stat st;
4442 if (one->is_stdin) {
4443 oidclr(&one->oid);
4444 return;
4446 if (lstat(one->path, &st) < 0)
4447 die_errno("stat '%s'", one->path);
4448 if (index_path(istate, &one->oid, one->path, &st, 0))
4449 die("cannot hash %s", one->path);
4452 else
4453 oidclr(&one->oid);
4456 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4458 /* Strip the prefix but do not molest /dev/null and absolute paths */
4459 if (*namep && !is_absolute_path(*namep)) {
4460 *namep += prefix_length;
4461 if (**namep == '/')
4462 ++*namep;
4464 if (*otherp && !is_absolute_path(*otherp)) {
4465 *otherp += prefix_length;
4466 if (**otherp == '/')
4467 ++*otherp;
4471 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4473 const char *pgm = external_diff();
4474 struct strbuf msg;
4475 struct diff_filespec *one = p->one;
4476 struct diff_filespec *two = p->two;
4477 const char *name;
4478 const char *other;
4479 const char *attr_path;
4481 name = one->path;
4482 other = (strcmp(name, two->path) ? two->path : NULL);
4483 attr_path = name;
4484 if (o->prefix_length)
4485 strip_prefix(o->prefix_length, &name, &other);
4487 if (!o->flags.allow_external)
4488 pgm = NULL;
4490 if (DIFF_PAIR_UNMERGED(p)) {
4491 run_diff_cmd(pgm, name, NULL, attr_path,
4492 NULL, NULL, NULL, o, p);
4493 return;
4496 diff_fill_oid_info(one, o->repo->index);
4497 diff_fill_oid_info(two, o->repo->index);
4499 if (!pgm &&
4500 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4501 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4503 * a filepair that changes between file and symlink
4504 * needs to be split into deletion and creation.
4506 struct diff_filespec *null = alloc_filespec(two->path);
4507 run_diff_cmd(NULL, name, other, attr_path,
4508 one, null, &msg,
4509 o, p);
4510 free(null);
4511 strbuf_release(&msg);
4513 null = alloc_filespec(one->path);
4514 run_diff_cmd(NULL, name, other, attr_path,
4515 null, two, &msg, o, p);
4516 free(null);
4518 else
4519 run_diff_cmd(pgm, name, other, attr_path,
4520 one, two, &msg, o, p);
4522 strbuf_release(&msg);
4525 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4526 struct diffstat_t *diffstat)
4528 const char *name;
4529 const char *other;
4531 if (DIFF_PAIR_UNMERGED(p)) {
4532 /* unmerged */
4533 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4534 diffstat, o, p);
4535 return;
4538 name = p->one->path;
4539 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4541 if (o->prefix_length)
4542 strip_prefix(o->prefix_length, &name, &other);
4544 diff_fill_oid_info(p->one, o->repo->index);
4545 diff_fill_oid_info(p->two, o->repo->index);
4547 builtin_diffstat(name, other, p->one, p->two,
4548 diffstat, o, p);
4551 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4553 const char *name;
4554 const char *other;
4555 const char *attr_path;
4557 if (DIFF_PAIR_UNMERGED(p)) {
4558 /* unmerged */
4559 return;
4562 name = p->one->path;
4563 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4564 attr_path = other ? other : name;
4566 if (o->prefix_length)
4567 strip_prefix(o->prefix_length, &name, &other);
4569 diff_fill_oid_info(p->one, o->repo->index);
4570 diff_fill_oid_info(p->two, o->repo->index);
4572 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4575 static void prep_parse_options(struct diff_options *options);
4577 void repo_diff_setup(struct repository *r, struct diff_options *options)
4579 memcpy(options, &default_diff_options, sizeof(*options));
4581 options->file = stdout;
4582 options->repo = r;
4584 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4585 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4586 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4587 options->abbrev = DEFAULT_ABBREV;
4588 options->line_termination = '\n';
4589 options->break_opt = -1;
4590 options->rename_limit = -1;
4591 options->dirstat_permille = diff_dirstat_permille_default;
4592 options->context = diff_context_default;
4593 options->interhunkcontext = diff_interhunk_context_default;
4594 options->ws_error_highlight = ws_error_highlight_default;
4595 options->flags.rename_empty = 1;
4596 options->flags.relative_name = diff_relative;
4597 options->objfind = NULL;
4599 /* pathchange left =NULL by default */
4600 options->change = diff_change;
4601 options->add_remove = diff_addremove;
4602 options->use_color = diff_use_color_default;
4603 options->detect_rename = diff_detect_rename_default;
4604 options->xdl_opts |= diff_algorithm;
4605 if (diff_indent_heuristic)
4606 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4608 options->orderfile = diff_order_file_cfg;
4610 if (!options->flags.ignore_submodule_set)
4611 options->flags.ignore_untracked_in_submodules = 1;
4613 if (diff_no_prefix) {
4614 options->a_prefix = options->b_prefix = "";
4615 } else if (!diff_mnemonic_prefix) {
4616 options->a_prefix = "a/";
4617 options->b_prefix = "b/";
4620 options->color_moved = diff_color_moved_default;
4621 options->color_moved_ws_handling = diff_color_moved_ws_default;
4623 prep_parse_options(options);
4626 void diff_setup_done(struct diff_options *options)
4628 unsigned check_mask = DIFF_FORMAT_NAME |
4629 DIFF_FORMAT_NAME_STATUS |
4630 DIFF_FORMAT_CHECKDIFF |
4631 DIFF_FORMAT_NO_OUTPUT;
4633 * This must be signed because we're comparing against a potentially
4634 * negative value.
4636 const int hexsz = the_hash_algo->hexsz;
4638 if (options->set_default)
4639 options->set_default(options);
4641 if (HAS_MULTI_BITS(options->output_format & check_mask))
4642 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4644 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4645 die(_("-G, -S and --find-object are mutually exclusive"));
4647 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4648 die(_("-G and --pickaxe-regex are mutually exclusive, use --pickaxe-regex with -S"));
4650 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4651 die(_("--pickaxe-all and --find-object are mutually exclusive, use --pickaxe-all with -G and -S"));
4654 * Most of the time we can say "there are changes"
4655 * only by checking if there are changed paths, but
4656 * --ignore-whitespace* options force us to look
4657 * inside contents.
4660 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4661 options->ignore_regex_nr)
4662 options->flags.diff_from_contents = 1;
4663 else
4664 options->flags.diff_from_contents = 0;
4666 if (options->flags.find_copies_harder)
4667 options->detect_rename = DIFF_DETECT_COPY;
4669 if (!options->flags.relative_name)
4670 options->prefix = NULL;
4671 if (options->prefix)
4672 options->prefix_length = strlen(options->prefix);
4673 else
4674 options->prefix_length = 0;
4676 if (options->output_format & (DIFF_FORMAT_NAME |
4677 DIFF_FORMAT_NAME_STATUS |
4678 DIFF_FORMAT_CHECKDIFF |
4679 DIFF_FORMAT_NO_OUTPUT))
4680 options->output_format &= ~(DIFF_FORMAT_RAW |
4681 DIFF_FORMAT_NUMSTAT |
4682 DIFF_FORMAT_DIFFSTAT |
4683 DIFF_FORMAT_SHORTSTAT |
4684 DIFF_FORMAT_DIRSTAT |
4685 DIFF_FORMAT_SUMMARY |
4686 DIFF_FORMAT_PATCH);
4689 * These cases always need recursive; we do not drop caller-supplied
4690 * recursive bits for other formats here.
4692 if (options->output_format & (DIFF_FORMAT_PATCH |
4693 DIFF_FORMAT_NUMSTAT |
4694 DIFF_FORMAT_DIFFSTAT |
4695 DIFF_FORMAT_SHORTSTAT |
4696 DIFF_FORMAT_DIRSTAT |
4697 DIFF_FORMAT_SUMMARY |
4698 DIFF_FORMAT_CHECKDIFF))
4699 options->flags.recursive = 1;
4701 * Also pickaxe would not work very well if you do not say recursive
4703 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4704 options->flags.recursive = 1;
4706 * When patches are generated, submodules diffed against the work tree
4707 * must be checked for dirtiness too so it can be shown in the output
4709 if (options->output_format & DIFF_FORMAT_PATCH)
4710 options->flags.dirty_submodules = 1;
4712 if (options->detect_rename && options->rename_limit < 0)
4713 options->rename_limit = diff_rename_limit_default;
4714 if (hexsz < options->abbrev)
4715 options->abbrev = hexsz; /* full */
4718 * It does not make sense to show the first hit we happened
4719 * to have found. It does not make sense not to return with
4720 * exit code in such a case either.
4722 if (options->flags.quick) {
4723 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4724 options->flags.exit_with_status = 1;
4727 options->diff_path_counter = 0;
4729 if (options->flags.follow_renames && options->pathspec.nr != 1)
4730 die(_("--follow requires exactly one pathspec"));
4732 if (!options->use_color || external_diff())
4733 options->color_moved = 0;
4735 FREE_AND_NULL(options->parseopts);
4738 int parse_long_opt(const char *opt, const char **argv,
4739 const char **optarg)
4741 const char *arg = argv[0];
4742 if (!skip_prefix(arg, "--", &arg))
4743 return 0;
4744 if (!skip_prefix(arg, opt, &arg))
4745 return 0;
4746 if (*arg == '=') { /* stuck form: --option=value */
4747 *optarg = arg + 1;
4748 return 1;
4750 if (*arg != '\0')
4751 return 0;
4752 /* separate form: --option value */
4753 if (!argv[1])
4754 die("Option '--%s' requires a value", opt);
4755 *optarg = argv[1];
4756 return 2;
4759 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4761 struct diff_options *options = opt->value;
4762 int width = options->stat_width;
4763 int name_width = options->stat_name_width;
4764 int graph_width = options->stat_graph_width;
4765 int count = options->stat_count;
4766 char *end;
4768 BUG_ON_OPT_NEG(unset);
4770 if (!strcmp(opt->long_name, "stat")) {
4771 if (value) {
4772 width = strtoul(value, &end, 10);
4773 if (*end == ',')
4774 name_width = strtoul(end+1, &end, 10);
4775 if (*end == ',')
4776 count = strtoul(end+1, &end, 10);
4777 if (*end)
4778 return error(_("invalid --stat value: %s"), value);
4780 } else if (!strcmp(opt->long_name, "stat-width")) {
4781 width = strtoul(value, &end, 10);
4782 if (*end)
4783 return error(_("%s expects a numerical value"),
4784 opt->long_name);
4785 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4786 name_width = strtoul(value, &end, 10);
4787 if (*end)
4788 return error(_("%s expects a numerical value"),
4789 opt->long_name);
4790 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4791 graph_width = strtoul(value, &end, 10);
4792 if (*end)
4793 return error(_("%s expects a numerical value"),
4794 opt->long_name);
4795 } else if (!strcmp(opt->long_name, "stat-count")) {
4796 count = strtoul(value, &end, 10);
4797 if (*end)
4798 return error(_("%s expects a numerical value"),
4799 opt->long_name);
4800 } else
4801 BUG("%s should not get here", opt->long_name);
4803 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4804 options->stat_name_width = name_width;
4805 options->stat_graph_width = graph_width;
4806 options->stat_width = width;
4807 options->stat_count = count;
4808 return 0;
4811 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4813 struct strbuf errmsg = STRBUF_INIT;
4814 if (parse_dirstat_params(options, params, &errmsg))
4815 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4816 errmsg.buf);
4817 strbuf_release(&errmsg);
4819 * The caller knows a dirstat-related option is given from the command
4820 * line; allow it to say "return this_function();"
4822 options->output_format |= DIFF_FORMAT_DIRSTAT;
4823 return 1;
4826 static const char diff_status_letters[] = {
4827 DIFF_STATUS_ADDED,
4828 DIFF_STATUS_COPIED,
4829 DIFF_STATUS_DELETED,
4830 DIFF_STATUS_MODIFIED,
4831 DIFF_STATUS_RENAMED,
4832 DIFF_STATUS_TYPE_CHANGED,
4833 DIFF_STATUS_UNKNOWN,
4834 DIFF_STATUS_UNMERGED,
4835 DIFF_STATUS_FILTER_AON,
4836 DIFF_STATUS_FILTER_BROKEN,
4837 '\0',
4840 static unsigned int filter_bit['Z' + 1];
4842 static void prepare_filter_bits(void)
4844 int i;
4846 if (!filter_bit[DIFF_STATUS_ADDED]) {
4847 for (i = 0; diff_status_letters[i]; i++)
4848 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4852 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4854 return opt->filter & filter_bit[(int) status];
4857 unsigned diff_filter_bit(char status)
4859 prepare_filter_bits();
4860 return filter_bit[(int) status];
4863 static int diff_opt_diff_filter(const struct option *option,
4864 const char *optarg, int unset)
4866 struct diff_options *opt = option->value;
4867 int i, optch;
4869 BUG_ON_OPT_NEG(unset);
4870 prepare_filter_bits();
4873 * If there is a negation e.g. 'd' in the input, and we haven't
4874 * initialized the filter field with another --diff-filter, start
4875 * from full set of bits, except for AON.
4877 if (!opt->filter) {
4878 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4879 if (optch < 'a' || 'z' < optch)
4880 continue;
4881 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4882 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4883 break;
4887 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4888 unsigned int bit;
4889 int negate;
4891 if ('a' <= optch && optch <= 'z') {
4892 negate = 1;
4893 optch = toupper(optch);
4894 } else {
4895 negate = 0;
4898 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4899 if (!bit)
4900 return error(_("unknown change class '%c' in --diff-filter=%s"),
4901 optarg[i], optarg);
4902 if (negate)
4903 opt->filter &= ~bit;
4904 else
4905 opt->filter |= bit;
4907 return 0;
4910 static void enable_patch_output(int *fmt)
4912 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4913 *fmt |= DIFF_FORMAT_PATCH;
4916 static int diff_opt_ws_error_highlight(const struct option *option,
4917 const char *arg, int unset)
4919 struct diff_options *opt = option->value;
4920 int val = parse_ws_error_highlight(arg);
4922 BUG_ON_OPT_NEG(unset);
4923 if (val < 0)
4924 return error(_("unknown value after ws-error-highlight=%.*s"),
4925 -1 - val, arg);
4926 opt->ws_error_highlight = val;
4927 return 0;
4930 static int diff_opt_find_object(const struct option *option,
4931 const char *arg, int unset)
4933 struct diff_options *opt = option->value;
4934 struct object_id oid;
4936 BUG_ON_OPT_NEG(unset);
4937 if (get_oid(arg, &oid))
4938 return error(_("unable to resolve '%s'"), arg);
4940 if (!opt->objfind)
4941 CALLOC_ARRAY(opt->objfind, 1);
4943 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4944 opt->flags.recursive = 1;
4945 opt->flags.tree_in_recursive = 1;
4946 oidset_insert(opt->objfind, &oid);
4947 return 0;
4950 static int diff_opt_anchored(const struct option *opt,
4951 const char *arg, int unset)
4953 struct diff_options *options = opt->value;
4955 BUG_ON_OPT_NEG(unset);
4956 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4957 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4958 options->anchors_alloc);
4959 options->anchors[options->anchors_nr++] = xstrdup(arg);
4960 return 0;
4963 static int diff_opt_binary(const struct option *opt,
4964 const char *arg, int unset)
4966 struct diff_options *options = opt->value;
4968 BUG_ON_OPT_NEG(unset);
4969 BUG_ON_OPT_ARG(arg);
4970 enable_patch_output(&options->output_format);
4971 options->flags.binary = 1;
4972 return 0;
4975 static int diff_opt_break_rewrites(const struct option *opt,
4976 const char *arg, int unset)
4978 int *break_opt = opt->value;
4979 int opt1, opt2;
4981 BUG_ON_OPT_NEG(unset);
4982 if (!arg)
4983 arg = "";
4984 opt1 = parse_rename_score(&arg);
4985 if (*arg == 0)
4986 opt2 = 0;
4987 else if (*arg != '/')
4988 return error(_("%s expects <n>/<m> form"), opt->long_name);
4989 else {
4990 arg++;
4991 opt2 = parse_rename_score(&arg);
4993 if (*arg != 0)
4994 return error(_("%s expects <n>/<m> form"), opt->long_name);
4995 *break_opt = opt1 | (opt2 << 16);
4996 return 0;
4999 static int diff_opt_char(const struct option *opt,
5000 const char *arg, int unset)
5002 char *value = opt->value;
5004 BUG_ON_OPT_NEG(unset);
5005 if (arg[1])
5006 return error(_("%s expects a character, got '%s'"),
5007 opt->long_name, arg);
5008 *value = arg[0];
5009 return 0;
5012 static int diff_opt_color_moved(const struct option *opt,
5013 const char *arg, int unset)
5015 struct diff_options *options = opt->value;
5017 if (unset) {
5018 options->color_moved = COLOR_MOVED_NO;
5019 } else if (!arg) {
5020 if (diff_color_moved_default)
5021 options->color_moved = diff_color_moved_default;
5022 if (options->color_moved == COLOR_MOVED_NO)
5023 options->color_moved = COLOR_MOVED_DEFAULT;
5024 } else {
5025 int cm = parse_color_moved(arg);
5026 if (cm < 0)
5027 return error(_("bad --color-moved argument: %s"), arg);
5028 options->color_moved = cm;
5030 return 0;
5033 static int diff_opt_color_moved_ws(const struct option *opt,
5034 const char *arg, int unset)
5036 struct diff_options *options = opt->value;
5037 unsigned cm;
5039 if (unset) {
5040 options->color_moved_ws_handling = 0;
5041 return 0;
5044 cm = parse_color_moved_ws(arg);
5045 if (cm & COLOR_MOVED_WS_ERROR)
5046 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5047 options->color_moved_ws_handling = cm;
5048 return 0;
5051 static int diff_opt_color_words(const struct option *opt,
5052 const char *arg, int unset)
5054 struct diff_options *options = opt->value;
5056 BUG_ON_OPT_NEG(unset);
5057 options->use_color = 1;
5058 options->word_diff = DIFF_WORDS_COLOR;
5059 options->word_regex = arg;
5060 return 0;
5063 static int diff_opt_compact_summary(const struct option *opt,
5064 const char *arg, int unset)
5066 struct diff_options *options = opt->value;
5068 BUG_ON_OPT_ARG(arg);
5069 if (unset) {
5070 options->flags.stat_with_summary = 0;
5071 } else {
5072 options->flags.stat_with_summary = 1;
5073 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5075 return 0;
5078 static int diff_opt_diff_algorithm(const struct option *opt,
5079 const char *arg, int unset)
5081 struct diff_options *options = opt->value;
5082 long value = parse_algorithm_value(arg);
5084 BUG_ON_OPT_NEG(unset);
5085 if (value < 0)
5086 return error(_("option diff-algorithm accepts \"myers\", "
5087 "\"minimal\", \"patience\" and \"histogram\""));
5089 /* clear out previous settings */
5090 DIFF_XDL_CLR(options, NEED_MINIMAL);
5091 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5092 options->xdl_opts |= value;
5093 return 0;
5096 static int diff_opt_dirstat(const struct option *opt,
5097 const char *arg, int unset)
5099 struct diff_options *options = opt->value;
5101 BUG_ON_OPT_NEG(unset);
5102 if (!strcmp(opt->long_name, "cumulative")) {
5103 if (arg)
5104 BUG("how come --cumulative take a value?");
5105 arg = "cumulative";
5106 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5107 parse_dirstat_opt(options, "files");
5108 parse_dirstat_opt(options, arg ? arg : "");
5109 return 0;
5112 static int diff_opt_find_copies(const struct option *opt,
5113 const char *arg, int unset)
5115 struct diff_options *options = opt->value;
5117 BUG_ON_OPT_NEG(unset);
5118 if (!arg)
5119 arg = "";
5120 options->rename_score = parse_rename_score(&arg);
5121 if (*arg != 0)
5122 return error(_("invalid argument to %s"), opt->long_name);
5124 if (options->detect_rename == DIFF_DETECT_COPY)
5125 options->flags.find_copies_harder = 1;
5126 else
5127 options->detect_rename = DIFF_DETECT_COPY;
5129 return 0;
5132 static int diff_opt_find_renames(const struct option *opt,
5133 const char *arg, int unset)
5135 struct diff_options *options = opt->value;
5137 BUG_ON_OPT_NEG(unset);
5138 if (!arg)
5139 arg = "";
5140 options->rename_score = parse_rename_score(&arg);
5141 if (*arg != 0)
5142 return error(_("invalid argument to %s"), opt->long_name);
5144 options->detect_rename = DIFF_DETECT_RENAME;
5145 return 0;
5148 static int diff_opt_follow(const struct option *opt,
5149 const char *arg, int unset)
5151 struct diff_options *options = opt->value;
5153 BUG_ON_OPT_ARG(arg);
5154 if (unset) {
5155 options->flags.follow_renames = 0;
5156 options->flags.default_follow_renames = 0;
5157 } else {
5158 options->flags.follow_renames = 1;
5160 return 0;
5163 static int diff_opt_ignore_submodules(const struct option *opt,
5164 const char *arg, int unset)
5166 struct diff_options *options = opt->value;
5168 BUG_ON_OPT_NEG(unset);
5169 if (!arg)
5170 arg = "all";
5171 options->flags.override_submodule_config = 1;
5172 handle_ignore_submodules_arg(options, arg);
5173 return 0;
5176 static int diff_opt_line_prefix(const struct option *opt,
5177 const char *optarg, int unset)
5179 struct diff_options *options = opt->value;
5181 BUG_ON_OPT_NEG(unset);
5182 options->line_prefix = optarg;
5183 options->line_prefix_length = strlen(options->line_prefix);
5184 graph_setup_line_prefix(options);
5185 return 0;
5188 static int diff_opt_no_prefix(const struct option *opt,
5189 const char *optarg, int unset)
5191 struct diff_options *options = opt->value;
5193 BUG_ON_OPT_NEG(unset);
5194 BUG_ON_OPT_ARG(optarg);
5195 options->a_prefix = "";
5196 options->b_prefix = "";
5197 return 0;
5200 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5201 const struct option *opt,
5202 const char *arg, int unset)
5204 struct diff_options *options = opt->value;
5205 char *path;
5207 BUG_ON_OPT_NEG(unset);
5208 path = prefix_filename(ctx->prefix, arg);
5209 options->file = xfopen(path, "w");
5210 options->close_file = 1;
5211 if (options->use_color != GIT_COLOR_ALWAYS)
5212 options->use_color = GIT_COLOR_NEVER;
5213 free(path);
5214 return 0;
5217 static int diff_opt_patience(const struct option *opt,
5218 const char *arg, int unset)
5220 struct diff_options *options = opt->value;
5221 int i;
5223 BUG_ON_OPT_NEG(unset);
5224 BUG_ON_OPT_ARG(arg);
5225 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5227 * Both --patience and --anchored use PATIENCE_DIFF
5228 * internally, so remove any anchors previously
5229 * specified.
5231 for (i = 0; i < options->anchors_nr; i++)
5232 free(options->anchors[i]);
5233 options->anchors_nr = 0;
5234 return 0;
5237 static int diff_opt_ignore_regex(const struct option *opt,
5238 const char *arg, int unset)
5240 struct diff_options *options = opt->value;
5241 regex_t *regex;
5243 BUG_ON_OPT_NEG(unset);
5244 regex = xmalloc(sizeof(*regex));
5245 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5246 return error(_("invalid regex given to -I: '%s'"), arg);
5247 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5248 options->ignore_regex_alloc);
5249 options->ignore_regex[options->ignore_regex_nr++] = regex;
5250 return 0;
5253 static int diff_opt_pickaxe_regex(const struct option *opt,
5254 const char *arg, int unset)
5256 struct diff_options *options = opt->value;
5258 BUG_ON_OPT_NEG(unset);
5259 options->pickaxe = arg;
5260 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5261 return 0;
5264 static int diff_opt_pickaxe_string(const struct option *opt,
5265 const char *arg, int unset)
5267 struct diff_options *options = opt->value;
5269 BUG_ON_OPT_NEG(unset);
5270 options->pickaxe = arg;
5271 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5272 return 0;
5275 static int diff_opt_relative(const struct option *opt,
5276 const char *arg, int unset)
5278 struct diff_options *options = opt->value;
5280 options->flags.relative_name = !unset;
5281 if (arg)
5282 options->prefix = arg;
5283 return 0;
5286 static int diff_opt_submodule(const struct option *opt,
5287 const char *arg, int unset)
5289 struct diff_options *options = opt->value;
5291 BUG_ON_OPT_NEG(unset);
5292 if (!arg)
5293 arg = "log";
5294 if (parse_submodule_params(options, arg))
5295 return error(_("failed to parse --submodule option parameter: '%s'"),
5296 arg);
5297 return 0;
5300 static int diff_opt_textconv(const struct option *opt,
5301 const char *arg, int unset)
5303 struct diff_options *options = opt->value;
5305 BUG_ON_OPT_ARG(arg);
5306 if (unset) {
5307 options->flags.allow_textconv = 0;
5308 } else {
5309 options->flags.allow_textconv = 1;
5310 options->flags.textconv_set_via_cmdline = 1;
5312 return 0;
5315 static int diff_opt_unified(const struct option *opt,
5316 const char *arg, int unset)
5318 struct diff_options *options = opt->value;
5319 char *s;
5321 BUG_ON_OPT_NEG(unset);
5323 if (arg) {
5324 options->context = strtol(arg, &s, 10);
5325 if (*s)
5326 return error(_("%s expects a numerical value"), "--unified");
5328 enable_patch_output(&options->output_format);
5330 return 0;
5333 static int diff_opt_word_diff(const struct option *opt,
5334 const char *arg, int unset)
5336 struct diff_options *options = opt->value;
5338 BUG_ON_OPT_NEG(unset);
5339 if (arg) {
5340 if (!strcmp(arg, "plain"))
5341 options->word_diff = DIFF_WORDS_PLAIN;
5342 else if (!strcmp(arg, "color")) {
5343 options->use_color = 1;
5344 options->word_diff = DIFF_WORDS_COLOR;
5346 else if (!strcmp(arg, "porcelain"))
5347 options->word_diff = DIFF_WORDS_PORCELAIN;
5348 else if (!strcmp(arg, "none"))
5349 options->word_diff = DIFF_WORDS_NONE;
5350 else
5351 return error(_("bad --word-diff argument: %s"), arg);
5352 } else {
5353 if (options->word_diff == DIFF_WORDS_NONE)
5354 options->word_diff = DIFF_WORDS_PLAIN;
5356 return 0;
5359 static int diff_opt_word_diff_regex(const struct option *opt,
5360 const char *arg, int unset)
5362 struct diff_options *options = opt->value;
5364 BUG_ON_OPT_NEG(unset);
5365 if (options->word_diff == DIFF_WORDS_NONE)
5366 options->word_diff = DIFF_WORDS_PLAIN;
5367 options->word_regex = arg;
5368 return 0;
5371 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5373 struct diff_options *options = opt->value;
5375 BUG_ON_OPT_NEG(unset);
5376 if (!strcmp(opt->long_name, "skip-to"))
5377 options->skip_instead_of_rotate = 1;
5378 else
5379 options->skip_instead_of_rotate = 0;
5380 options->rotate_to = arg;
5381 return 0;
5384 static void prep_parse_options(struct diff_options *options)
5386 struct option parseopts[] = {
5387 OPT_GROUP(N_("Diff output format options")),
5388 OPT_BITOP('p', "patch", &options->output_format,
5389 N_("generate patch"),
5390 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5391 OPT_BIT_F('s', "no-patch", &options->output_format,
5392 N_("suppress diff output"),
5393 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5394 OPT_BITOP('u', NULL, &options->output_format,
5395 N_("generate patch"),
5396 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5397 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5398 N_("generate diffs with <n> lines context"),
5399 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5400 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5401 N_("generate diffs with <n> lines context")),
5402 OPT_BIT_F(0, "raw", &options->output_format,
5403 N_("generate the diff in raw format"),
5404 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5405 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5406 N_("synonym for '-p --raw'"),
5407 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5408 DIFF_FORMAT_NO_OUTPUT),
5409 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5410 N_("synonym for '-p --stat'"),
5411 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5412 DIFF_FORMAT_NO_OUTPUT),
5413 OPT_BIT_F(0, "numstat", &options->output_format,
5414 N_("machine friendly --stat"),
5415 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5416 OPT_BIT_F(0, "shortstat", &options->output_format,
5417 N_("output only the last line of --stat"),
5418 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5419 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5420 N_("output the distribution of relative amount of changes for each sub-directory"),
5421 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5422 diff_opt_dirstat),
5423 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5424 N_("synonym for --dirstat=cumulative"),
5425 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5426 diff_opt_dirstat),
5427 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5428 N_("synonym for --dirstat=files,param1,param2..."),
5429 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5430 diff_opt_dirstat),
5431 OPT_BIT_F(0, "check", &options->output_format,
5432 N_("warn if changes introduce conflict markers or whitespace errors"),
5433 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5434 OPT_BIT_F(0, "summary", &options->output_format,
5435 N_("condensed summary such as creations, renames and mode changes"),
5436 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5437 OPT_BIT_F(0, "name-only", &options->output_format,
5438 N_("show only names of changed files"),
5439 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5440 OPT_BIT_F(0, "name-status", &options->output_format,
5441 N_("show only names and status of changed files"),
5442 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5443 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5444 N_("generate diffstat"),
5445 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5446 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5447 N_("generate diffstat with a given width"),
5448 PARSE_OPT_NONEG, diff_opt_stat),
5449 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5450 N_("generate diffstat with a given name width"),
5451 PARSE_OPT_NONEG, diff_opt_stat),
5452 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5453 N_("generate diffstat with a given graph width"),
5454 PARSE_OPT_NONEG, diff_opt_stat),
5455 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5456 N_("generate diffstat with limited lines"),
5457 PARSE_OPT_NONEG, diff_opt_stat),
5458 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5459 N_("generate compact summary in diffstat"),
5460 PARSE_OPT_NOARG, diff_opt_compact_summary),
5461 OPT_CALLBACK_F(0, "binary", options, NULL,
5462 N_("output a binary diff that can be applied"),
5463 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5464 OPT_BOOL(0, "full-index", &options->flags.full_index,
5465 N_("show full pre- and post-image object names on the \"index\" lines")),
5466 OPT_COLOR_FLAG(0, "color", &options->use_color,
5467 N_("show colored diff")),
5468 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5469 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5470 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5471 OPT_SET_INT('z', NULL, &options->line_termination,
5472 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5474 OPT__ABBREV(&options->abbrev),
5475 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5476 N_("show the given source prefix instead of \"a/\""),
5477 PARSE_OPT_NONEG),
5478 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5479 N_("show the given destination prefix instead of \"b/\""),
5480 PARSE_OPT_NONEG),
5481 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5482 N_("prepend an additional prefix to every line of output"),
5483 PARSE_OPT_NONEG, diff_opt_line_prefix),
5484 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5485 N_("do not show any source or destination prefix"),
5486 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5487 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5488 N_("show context between diff hunks up to the specified number of lines"),
5489 PARSE_OPT_NONEG),
5490 OPT_CALLBACK_F(0, "output-indicator-new",
5491 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5492 N_("<char>"),
5493 N_("specify the character to indicate a new line instead of '+'"),
5494 PARSE_OPT_NONEG, diff_opt_char),
5495 OPT_CALLBACK_F(0, "output-indicator-old",
5496 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5497 N_("<char>"),
5498 N_("specify the character to indicate an old line instead of '-'"),
5499 PARSE_OPT_NONEG, diff_opt_char),
5500 OPT_CALLBACK_F(0, "output-indicator-context",
5501 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5502 N_("<char>"),
5503 N_("specify the character to indicate a context instead of ' '"),
5504 PARSE_OPT_NONEG, diff_opt_char),
5506 OPT_GROUP(N_("Diff rename options")),
5507 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5508 N_("break complete rewrite changes into pairs of delete and create"),
5509 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5510 diff_opt_break_rewrites),
5511 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5512 N_("detect renames"),
5513 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5514 diff_opt_find_renames),
5515 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5516 N_("omit the preimage for deletes"),
5517 1, PARSE_OPT_NONEG),
5518 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5519 N_("detect copies"),
5520 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5521 diff_opt_find_copies),
5522 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5523 N_("use unmodified files as source to find copies")),
5524 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5525 N_("disable rename detection"),
5526 0, PARSE_OPT_NONEG),
5527 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5528 N_("use empty blobs as rename source")),
5529 OPT_CALLBACK_F(0, "follow", options, NULL,
5530 N_("continue listing the history of a file beyond renames"),
5531 PARSE_OPT_NOARG, diff_opt_follow),
5532 OPT_INTEGER('l', NULL, &options->rename_limit,
5533 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5535 OPT_GROUP(N_("Diff algorithm options")),
5536 OPT_BIT(0, "minimal", &options->xdl_opts,
5537 N_("produce the smallest possible diff"),
5538 XDF_NEED_MINIMAL),
5539 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5540 N_("ignore whitespace when comparing lines"),
5541 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5542 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5543 N_("ignore changes in amount of whitespace"),
5544 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5545 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5546 N_("ignore changes in whitespace at EOL"),
5547 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5548 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5549 N_("ignore carrier-return at the end of line"),
5550 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5551 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5552 N_("ignore changes whose lines are all blank"),
5553 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5554 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5555 N_("ignore changes whose all lines match <regex>"),
5556 0, diff_opt_ignore_regex),
5557 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5558 N_("heuristic to shift diff hunk boundaries for easy reading"),
5559 XDF_INDENT_HEURISTIC),
5560 OPT_CALLBACK_F(0, "patience", options, NULL,
5561 N_("generate diff using the \"patience diff\" algorithm"),
5562 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5563 diff_opt_patience),
5564 OPT_BITOP(0, "histogram", &options->xdl_opts,
5565 N_("generate diff using the \"histogram diff\" algorithm"),
5566 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5567 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5568 N_("choose a diff algorithm"),
5569 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5570 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5571 N_("generate diff using the \"anchored diff\" algorithm"),
5572 PARSE_OPT_NONEG, diff_opt_anchored),
5573 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5574 N_("show word diff, using <mode> to delimit changed words"),
5575 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5576 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5577 N_("use <regex> to decide what a word is"),
5578 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5579 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5580 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5581 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5582 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5583 N_("moved lines of code are colored differently"),
5584 PARSE_OPT_OPTARG, diff_opt_color_moved),
5585 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5586 N_("how white spaces are ignored in --color-moved"),
5587 0, diff_opt_color_moved_ws),
5589 OPT_GROUP(N_("Other diff options")),
5590 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5591 N_("when run from subdir, exclude changes outside and show relative paths"),
5592 PARSE_OPT_OPTARG,
5593 diff_opt_relative),
5594 OPT_BOOL('a', "text", &options->flags.text,
5595 N_("treat all files as text")),
5596 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5597 N_("swap two inputs, reverse the diff")),
5598 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5599 N_("exit with 1 if there were differences, 0 otherwise")),
5600 OPT_BOOL(0, "quiet", &options->flags.quick,
5601 N_("disable all output of the program")),
5602 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5603 N_("allow an external diff helper to be executed")),
5604 OPT_CALLBACK_F(0, "textconv", options, NULL,
5605 N_("run external text conversion filters when comparing binary files"),
5606 PARSE_OPT_NOARG, diff_opt_textconv),
5607 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5608 N_("ignore changes to submodules in the diff generation"),
5609 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5610 diff_opt_ignore_submodules),
5611 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5612 N_("specify how differences in submodules are shown"),
5613 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5614 diff_opt_submodule),
5615 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5616 N_("hide 'git add -N' entries from the index"),
5617 1, PARSE_OPT_NONEG),
5618 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5619 N_("treat 'git add -N' entries as real in the index"),
5620 0, PARSE_OPT_NONEG),
5621 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5622 N_("look for differences that change the number of occurrences of the specified string"),
5623 0, diff_opt_pickaxe_string),
5624 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5625 N_("look for differences that change the number of occurrences of the specified regex"),
5626 0, diff_opt_pickaxe_regex),
5627 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5628 N_("show all changes in the changeset with -S or -G"),
5629 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5630 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5631 N_("treat <string> in -S as extended POSIX regular expression"),
5632 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5633 OPT_FILENAME('O', NULL, &options->orderfile,
5634 N_("control the order in which files appear in the output")),
5635 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5636 N_("show the change in the specified path first"),
5637 PARSE_OPT_NONEG, diff_opt_rotate_to),
5638 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5639 N_("skip the output to the specified path"),
5640 PARSE_OPT_NONEG, diff_opt_rotate_to),
5641 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5642 N_("look for differences that change the number of occurrences of the specified object"),
5643 PARSE_OPT_NONEG, diff_opt_find_object),
5644 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5645 N_("select files by diff type"),
5646 PARSE_OPT_NONEG, diff_opt_diff_filter),
5647 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5648 N_("Output to a specific file"),
5649 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5651 OPT_END()
5654 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5655 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5658 int diff_opt_parse(struct diff_options *options,
5659 const char **av, int ac, const char *prefix)
5661 if (!prefix)
5662 prefix = "";
5664 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5665 PARSE_OPT_KEEP_DASHDASH |
5666 PARSE_OPT_KEEP_UNKNOWN |
5667 PARSE_OPT_NO_INTERNAL_HELP |
5668 PARSE_OPT_ONE_SHOT |
5669 PARSE_OPT_STOP_AT_NON_OPTION);
5671 return ac;
5674 int parse_rename_score(const char **cp_p)
5676 unsigned long num, scale;
5677 int ch, dot;
5678 const char *cp = *cp_p;
5680 num = 0;
5681 scale = 1;
5682 dot = 0;
5683 for (;;) {
5684 ch = *cp;
5685 if ( !dot && ch == '.' ) {
5686 scale = 1;
5687 dot = 1;
5688 } else if ( ch == '%' ) {
5689 scale = dot ? scale*100 : 100;
5690 cp++; /* % is always at the end */
5691 break;
5692 } else if ( ch >= '0' && ch <= '9' ) {
5693 if ( scale < 100000 ) {
5694 scale *= 10;
5695 num = (num*10) + (ch-'0');
5697 } else {
5698 break;
5700 cp++;
5702 *cp_p = cp;
5704 /* user says num divided by scale and we say internally that
5705 * is MAX_SCORE * num / scale.
5707 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5710 struct diff_queue_struct diff_queued_diff;
5712 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5714 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5715 queue->queue[queue->nr++] = dp;
5718 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5719 struct diff_filespec *one,
5720 struct diff_filespec *two)
5722 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5723 dp->one = one;
5724 dp->two = two;
5725 if (queue)
5726 diff_q(queue, dp);
5727 return dp;
5730 void diff_free_filepair(struct diff_filepair *p)
5732 free_filespec(p->one);
5733 free_filespec(p->two);
5734 free(p);
5737 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5739 int abblen;
5740 const char *abbrev;
5742 /* Do we want all 40 hex characters? */
5743 if (len == the_hash_algo->hexsz)
5744 return oid_to_hex(oid);
5746 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5747 abbrev = diff_abbrev_oid(oid, len);
5749 if (!print_sha1_ellipsis())
5750 return abbrev;
5752 abblen = strlen(abbrev);
5755 * In well-behaved cases, where the abbreviated result is the
5756 * same as the requested length, append three dots after the
5757 * abbreviation (hence the whole logic is limited to the case
5758 * where abblen < 37); when the actual abbreviated result is a
5759 * bit longer than the requested length, we reduce the number
5760 * of dots so that they match the well-behaved ones. However,
5761 * if the actual abbreviation is longer than the requested
5762 * length by more than three, we give up on aligning, and add
5763 * three dots anyway, to indicate that the output is not the
5764 * full object name. Yes, this may be suboptimal, but this
5765 * appears only in "diff --raw --abbrev" output and it is not
5766 * worth the effort to change it now. Note that this would
5767 * likely to work fine when the automatic sizing of default
5768 * abbreviation length is used--we would be fed -1 in "len" in
5769 * that case, and will end up always appending three-dots, but
5770 * the automatic sizing is supposed to give abblen that ensures
5771 * uniqueness across all objects (statistically speaking).
5773 if (abblen < the_hash_algo->hexsz - 3) {
5774 static char hex[GIT_MAX_HEXSZ + 1];
5775 if (len < abblen && abblen <= len + 2)
5776 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5777 else
5778 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5779 return hex;
5782 return oid_to_hex(oid);
5785 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5787 int line_termination = opt->line_termination;
5788 int inter_name_termination = line_termination ? '\t' : '\0';
5790 fprintf(opt->file, "%s", diff_line_prefix(opt));
5791 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5792 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5793 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5794 fprintf(opt->file, "%s ",
5795 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5797 if (p->score) {
5798 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5799 inter_name_termination);
5800 } else {
5801 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5804 if (p->status == DIFF_STATUS_COPIED ||
5805 p->status == DIFF_STATUS_RENAMED) {
5806 const char *name_a, *name_b;
5807 name_a = p->one->path;
5808 name_b = p->two->path;
5809 strip_prefix(opt->prefix_length, &name_a, &name_b);
5810 write_name_quoted(name_a, opt->file, inter_name_termination);
5811 write_name_quoted(name_b, opt->file, line_termination);
5812 } else {
5813 const char *name_a, *name_b;
5814 name_a = p->one->mode ? p->one->path : p->two->path;
5815 name_b = NULL;
5816 strip_prefix(opt->prefix_length, &name_a, &name_b);
5817 write_name_quoted(name_a, opt->file, line_termination);
5821 int diff_unmodified_pair(struct diff_filepair *p)
5823 /* This function is written stricter than necessary to support
5824 * the currently implemented transformers, but the idea is to
5825 * let transformers to produce diff_filepairs any way they want,
5826 * and filter and clean them up here before producing the output.
5828 struct diff_filespec *one = p->one, *two = p->two;
5830 if (DIFF_PAIR_UNMERGED(p))
5831 return 0; /* unmerged is interesting */
5833 /* deletion, addition, mode or type change
5834 * and rename are all interesting.
5836 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5837 DIFF_PAIR_MODE_CHANGED(p) ||
5838 strcmp(one->path, two->path))
5839 return 0;
5841 /* both are valid and point at the same path. that is, we are
5842 * dealing with a change.
5844 if (one->oid_valid && two->oid_valid &&
5845 oideq(&one->oid, &two->oid) &&
5846 !one->dirty_submodule && !two->dirty_submodule)
5847 return 1; /* no change */
5848 if (!one->oid_valid && !two->oid_valid)
5849 return 1; /* both look at the same file on the filesystem. */
5850 return 0;
5853 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5855 if (diff_unmodified_pair(p))
5856 return;
5858 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5859 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5860 return; /* no tree diffs in patch format */
5862 run_diff(p, o);
5865 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5866 struct diffstat_t *diffstat)
5868 if (diff_unmodified_pair(p))
5869 return;
5871 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5872 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5873 return; /* no useful stat for tree diffs */
5875 run_diffstat(p, o, diffstat);
5878 static void diff_flush_checkdiff(struct diff_filepair *p,
5879 struct diff_options *o)
5881 if (diff_unmodified_pair(p))
5882 return;
5884 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5885 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5886 return; /* nothing to check in tree diffs */
5888 run_checkdiff(p, o);
5891 int diff_queue_is_empty(void)
5893 struct diff_queue_struct *q = &diff_queued_diff;
5894 int i;
5895 for (i = 0; i < q->nr; i++)
5896 if (!diff_unmodified_pair(q->queue[i]))
5897 return 0;
5898 return 1;
5901 #if DIFF_DEBUG
5902 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5904 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5905 x, one ? one : "",
5906 s->path,
5907 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5908 s->mode,
5909 s->oid_valid ? oid_to_hex(&s->oid) : "");
5910 fprintf(stderr, "queue[%d] %s size %lu\n",
5911 x, one ? one : "",
5912 s->size);
5915 void diff_debug_filepair(const struct diff_filepair *p, int i)
5917 diff_debug_filespec(p->one, i, "one");
5918 diff_debug_filespec(p->two, i, "two");
5919 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5920 p->score, p->status ? p->status : '?',
5921 p->one->rename_used, p->broken_pair);
5924 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5926 int i;
5927 if (msg)
5928 fprintf(stderr, "%s\n", msg);
5929 fprintf(stderr, "q->nr = %d\n", q->nr);
5930 for (i = 0; i < q->nr; i++) {
5931 struct diff_filepair *p = q->queue[i];
5932 diff_debug_filepair(p, i);
5935 #endif
5937 static void diff_resolve_rename_copy(void)
5939 int i;
5940 struct diff_filepair *p;
5941 struct diff_queue_struct *q = &diff_queued_diff;
5943 diff_debug_queue("resolve-rename-copy", q);
5945 for (i = 0; i < q->nr; i++) {
5946 p = q->queue[i];
5947 p->status = 0; /* undecided */
5948 if (DIFF_PAIR_UNMERGED(p))
5949 p->status = DIFF_STATUS_UNMERGED;
5950 else if (!DIFF_FILE_VALID(p->one))
5951 p->status = DIFF_STATUS_ADDED;
5952 else if (!DIFF_FILE_VALID(p->two))
5953 p->status = DIFF_STATUS_DELETED;
5954 else if (DIFF_PAIR_TYPE_CHANGED(p))
5955 p->status = DIFF_STATUS_TYPE_CHANGED;
5957 /* from this point on, we are dealing with a pair
5958 * whose both sides are valid and of the same type, i.e.
5959 * either in-place edit or rename/copy edit.
5961 else if (DIFF_PAIR_RENAME(p)) {
5963 * A rename might have re-connected a broken
5964 * pair up, causing the pathnames to be the
5965 * same again. If so, that's not a rename at
5966 * all, just a modification..
5968 * Otherwise, see if this source was used for
5969 * multiple renames, in which case we decrement
5970 * the count, and call it a copy.
5972 if (!strcmp(p->one->path, p->two->path))
5973 p->status = DIFF_STATUS_MODIFIED;
5974 else if (--p->one->rename_used > 0)
5975 p->status = DIFF_STATUS_COPIED;
5976 else
5977 p->status = DIFF_STATUS_RENAMED;
5979 else if (!oideq(&p->one->oid, &p->two->oid) ||
5980 p->one->mode != p->two->mode ||
5981 p->one->dirty_submodule ||
5982 p->two->dirty_submodule ||
5983 is_null_oid(&p->one->oid))
5984 p->status = DIFF_STATUS_MODIFIED;
5985 else {
5986 /* This is a "no-change" entry and should not
5987 * happen anymore, but prepare for broken callers.
5989 error("feeding unmodified %s to diffcore",
5990 p->one->path);
5991 p->status = DIFF_STATUS_UNKNOWN;
5994 diff_debug_queue("resolve-rename-copy done", q);
5997 static int check_pair_status(struct diff_filepair *p)
5999 switch (p->status) {
6000 case DIFF_STATUS_UNKNOWN:
6001 return 0;
6002 case 0:
6003 die("internal error in diff-resolve-rename-copy");
6004 default:
6005 return 1;
6009 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6011 int fmt = opt->output_format;
6013 if (fmt & DIFF_FORMAT_CHECKDIFF)
6014 diff_flush_checkdiff(p, opt);
6015 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6016 diff_flush_raw(p, opt);
6017 else if (fmt & DIFF_FORMAT_NAME) {
6018 const char *name_a, *name_b;
6019 name_a = p->two->path;
6020 name_b = NULL;
6021 strip_prefix(opt->prefix_length, &name_a, &name_b);
6022 fprintf(opt->file, "%s", diff_line_prefix(opt));
6023 write_name_quoted(name_a, opt->file, opt->line_termination);
6027 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6029 struct strbuf sb = STRBUF_INIT;
6030 if (fs->mode)
6031 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6032 else
6033 strbuf_addf(&sb, " %s ", newdelete);
6035 quote_c_style(fs->path, &sb, NULL, 0);
6036 strbuf_addch(&sb, '\n');
6037 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6038 sb.buf, sb.len, 0);
6039 strbuf_release(&sb);
6042 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6043 int show_name)
6045 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6046 struct strbuf sb = STRBUF_INIT;
6047 strbuf_addf(&sb, " mode change %06o => %06o",
6048 p->one->mode, p->two->mode);
6049 if (show_name) {
6050 strbuf_addch(&sb, ' ');
6051 quote_c_style(p->two->path, &sb, NULL, 0);
6053 strbuf_addch(&sb, '\n');
6054 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6055 sb.buf, sb.len, 0);
6056 strbuf_release(&sb);
6060 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6061 struct diff_filepair *p)
6063 struct strbuf sb = STRBUF_INIT;
6064 struct strbuf names = STRBUF_INIT;
6066 pprint_rename(&names, p->one->path, p->two->path);
6067 strbuf_addf(&sb, " %s %s (%d%%)\n",
6068 renamecopy, names.buf, similarity_index(p));
6069 strbuf_release(&names);
6070 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6071 sb.buf, sb.len, 0);
6072 show_mode_change(opt, p, 0);
6073 strbuf_release(&sb);
6076 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6078 switch(p->status) {
6079 case DIFF_STATUS_DELETED:
6080 show_file_mode_name(opt, "delete", p->one);
6081 break;
6082 case DIFF_STATUS_ADDED:
6083 show_file_mode_name(opt, "create", p->two);
6084 break;
6085 case DIFF_STATUS_COPIED:
6086 show_rename_copy(opt, "copy", p);
6087 break;
6088 case DIFF_STATUS_RENAMED:
6089 show_rename_copy(opt, "rename", p);
6090 break;
6091 default:
6092 if (p->score) {
6093 struct strbuf sb = STRBUF_INIT;
6094 strbuf_addstr(&sb, " rewrite ");
6095 quote_c_style(p->two->path, &sb, NULL, 0);
6096 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6097 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6098 sb.buf, sb.len, 0);
6099 strbuf_release(&sb);
6101 show_mode_change(opt, p, !p->score);
6102 break;
6106 struct patch_id_t {
6107 git_hash_ctx *ctx;
6108 int patchlen;
6111 static int remove_space(char *line, int len)
6113 int i;
6114 char *dst = line;
6115 unsigned char c;
6117 for (i = 0; i < len; i++)
6118 if (!isspace((c = line[i])))
6119 *dst++ = c;
6121 return dst - line;
6124 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6126 unsigned char hash[GIT_MAX_RAWSZ];
6127 unsigned short carry = 0;
6128 int i;
6130 the_hash_algo->final_fn(hash, ctx);
6131 the_hash_algo->init_fn(ctx);
6132 /* 20-byte sum, with carry */
6133 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6134 carry += result->hash[i] + hash[i];
6135 result->hash[i] = carry;
6136 carry >>= 8;
6140 static int patch_id_consume(void *priv, char *line, unsigned long len)
6142 struct patch_id_t *data = priv;
6143 int new_len;
6145 if (len > 12 && starts_with(line, "\\ "))
6146 return 0;
6147 new_len = remove_space(line, len);
6149 the_hash_algo->update_fn(data->ctx, line, new_len);
6150 data->patchlen += new_len;
6151 return 0;
6154 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6156 the_hash_algo->update_fn(ctx, str, strlen(str));
6159 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6161 /* large enough for 2^32 in octal */
6162 char buf[12];
6163 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6164 the_hash_algo->update_fn(ctx, buf, len);
6167 /* returns 0 upon success, and writes result into oid */
6168 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6170 struct diff_queue_struct *q = &diff_queued_diff;
6171 int i;
6172 git_hash_ctx ctx;
6173 struct patch_id_t data;
6175 the_hash_algo->init_fn(&ctx);
6176 memset(&data, 0, sizeof(struct patch_id_t));
6177 data.ctx = &ctx;
6178 oidclr(oid);
6180 for (i = 0; i < q->nr; i++) {
6181 xpparam_t xpp;
6182 xdemitconf_t xecfg;
6183 mmfile_t mf1, mf2;
6184 struct diff_filepair *p = q->queue[i];
6185 int len1, len2;
6187 memset(&xpp, 0, sizeof(xpp));
6188 memset(&xecfg, 0, sizeof(xecfg));
6189 if (p->status == 0)
6190 return error("internal diff status error");
6191 if (p->status == DIFF_STATUS_UNKNOWN)
6192 continue;
6193 if (diff_unmodified_pair(p))
6194 continue;
6195 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6196 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6197 continue;
6198 if (DIFF_PAIR_UNMERGED(p))
6199 continue;
6201 diff_fill_oid_info(p->one, options->repo->index);
6202 diff_fill_oid_info(p->two, options->repo->index);
6204 len1 = remove_space(p->one->path, strlen(p->one->path));
6205 len2 = remove_space(p->two->path, strlen(p->two->path));
6206 patch_id_add_string(&ctx, "diff--git");
6207 patch_id_add_string(&ctx, "a/");
6208 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6209 patch_id_add_string(&ctx, "b/");
6210 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6212 if (p->one->mode == 0) {
6213 patch_id_add_string(&ctx, "newfilemode");
6214 patch_id_add_mode(&ctx, p->two->mode);
6215 patch_id_add_string(&ctx, "---/dev/null");
6216 patch_id_add_string(&ctx, "+++b/");
6217 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6218 } else if (p->two->mode == 0) {
6219 patch_id_add_string(&ctx, "deletedfilemode");
6220 patch_id_add_mode(&ctx, p->one->mode);
6221 patch_id_add_string(&ctx, "---a/");
6222 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6223 patch_id_add_string(&ctx, "+++/dev/null");
6224 } else {
6225 patch_id_add_string(&ctx, "---a/");
6226 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6227 patch_id_add_string(&ctx, "+++b/");
6228 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6231 if (diff_header_only)
6232 continue;
6234 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6235 fill_mmfile(options->repo, &mf2, p->two) < 0)
6236 return error("unable to read files to diff");
6238 if (diff_filespec_is_binary(options->repo, p->one) ||
6239 diff_filespec_is_binary(options->repo, p->two)) {
6240 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6241 the_hash_algo->hexsz);
6242 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6243 the_hash_algo->hexsz);
6244 continue;
6247 xpp.flags = 0;
6248 xecfg.ctxlen = 3;
6249 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6250 if (xdi_diff_outf(&mf1, &mf2, NULL,
6251 patch_id_consume, &data, &xpp, &xecfg))
6252 return error("unable to generate patch-id diff for %s",
6253 p->one->path);
6255 if (stable)
6256 flush_one_hunk(oid, &ctx);
6259 if (!stable)
6260 the_hash_algo->final_oid_fn(oid, &ctx);
6262 return 0;
6265 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6267 struct diff_queue_struct *q = &diff_queued_diff;
6268 int i;
6269 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
6271 for (i = 0; i < q->nr; i++)
6272 diff_free_filepair(q->queue[i]);
6274 free(q->queue);
6275 DIFF_QUEUE_CLEAR(q);
6277 return result;
6280 static int is_summary_empty(const struct diff_queue_struct *q)
6282 int i;
6284 for (i = 0; i < q->nr; i++) {
6285 const struct diff_filepair *p = q->queue[i];
6287 switch (p->status) {
6288 case DIFF_STATUS_DELETED:
6289 case DIFF_STATUS_ADDED:
6290 case DIFF_STATUS_COPIED:
6291 case DIFF_STATUS_RENAMED:
6292 return 0;
6293 default:
6294 if (p->score)
6295 return 0;
6296 if (p->one->mode && p->two->mode &&
6297 p->one->mode != p->two->mode)
6298 return 0;
6299 break;
6302 return 1;
6305 static const char rename_limit_warning[] =
6306 N_("exhaustive rename detection was skipped due to too many files.");
6308 static const char degrade_cc_to_c_warning[] =
6309 N_("only found copies from modified paths due to too many files.");
6311 static const char rename_limit_advice[] =
6312 N_("you may want to set your %s variable to at least "
6313 "%d and retry the command.");
6315 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6317 fflush(stdout);
6318 if (degraded_cc)
6319 warning(_(degrade_cc_to_c_warning));
6320 else if (needed)
6321 warning(_(rename_limit_warning));
6322 else
6323 return;
6324 if (0 < needed)
6325 warning(_(rename_limit_advice), varname, needed);
6328 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6330 int i;
6331 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6332 struct diff_queue_struct *q = &diff_queued_diff;
6334 if (WSEH_NEW & WS_RULE_MASK)
6335 BUG("WS rules bit mask overlaps with diff symbol flags");
6337 if (o->color_moved)
6338 o->emitted_symbols = &esm;
6340 for (i = 0; i < q->nr; i++) {
6341 struct diff_filepair *p = q->queue[i];
6342 if (check_pair_status(p))
6343 diff_flush_patch(p, o);
6346 if (o->emitted_symbols) {
6347 if (o->color_moved) {
6348 struct hashmap add_lines, del_lines;
6350 if (o->color_moved_ws_handling &
6351 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
6352 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
6354 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
6355 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
6357 add_lines_to_move_detection(o, &add_lines, &del_lines);
6358 mark_color_as_moved(o, &add_lines, &del_lines);
6359 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6360 dim_moved_lines(o);
6362 hashmap_clear_and_free(&add_lines, struct moved_entry,
6363 ent);
6364 hashmap_clear_and_free(&del_lines, struct moved_entry,
6365 ent);
6368 for (i = 0; i < esm.nr; i++)
6369 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6371 for (i = 0; i < esm.nr; i++)
6372 free((void *)esm.buf[i].line);
6373 esm.nr = 0;
6375 o->emitted_symbols = NULL;
6379 static void diff_free_file(struct diff_options *options)
6381 if (options->close_file)
6382 fclose(options->file);
6385 static void diff_free_ignore_regex(struct diff_options *options)
6387 int i;
6389 for (i = 0; i < options->ignore_regex_nr; i++) {
6390 regfree(options->ignore_regex[i]);
6391 free(options->ignore_regex[i]);
6393 free(options->ignore_regex);
6396 void diff_free(struct diff_options *options)
6398 if (options->no_free)
6399 return;
6401 diff_free_file(options);
6402 diff_free_ignore_regex(options);
6405 void diff_flush(struct diff_options *options)
6407 struct diff_queue_struct *q = &diff_queued_diff;
6408 int i, output_format = options->output_format;
6409 int separator = 0;
6410 int dirstat_by_line = 0;
6413 * Order: raw, stat, summary, patch
6414 * or: name/name-status/checkdiff (other bits clear)
6416 if (!q->nr)
6417 goto free_queue;
6419 if (output_format & (DIFF_FORMAT_RAW |
6420 DIFF_FORMAT_NAME |
6421 DIFF_FORMAT_NAME_STATUS |
6422 DIFF_FORMAT_CHECKDIFF)) {
6423 for (i = 0; i < q->nr; i++) {
6424 struct diff_filepair *p = q->queue[i];
6425 if (check_pair_status(p))
6426 flush_one_pair(p, options);
6428 separator++;
6431 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6432 dirstat_by_line = 1;
6434 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6435 dirstat_by_line) {
6436 struct diffstat_t diffstat;
6438 compute_diffstat(options, &diffstat, q);
6439 if (output_format & DIFF_FORMAT_NUMSTAT)
6440 show_numstat(&diffstat, options);
6441 if (output_format & DIFF_FORMAT_DIFFSTAT)
6442 show_stats(&diffstat, options);
6443 if (output_format & DIFF_FORMAT_SHORTSTAT)
6444 show_shortstats(&diffstat, options);
6445 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6446 show_dirstat_by_line(&diffstat, options);
6447 free_diffstat_info(&diffstat);
6448 separator++;
6450 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6451 show_dirstat(options);
6453 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6454 for (i = 0; i < q->nr; i++) {
6455 diff_summary(options, q->queue[i]);
6457 separator++;
6460 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6461 options->flags.exit_with_status &&
6462 options->flags.diff_from_contents) {
6464 * run diff_flush_patch for the exit status. setting
6465 * options->file to /dev/null should be safe, because we
6466 * aren't supposed to produce any output anyway.
6468 diff_free_file(options);
6469 options->file = xfopen("/dev/null", "w");
6470 options->close_file = 1;
6471 options->color_moved = 0;
6472 for (i = 0; i < q->nr; i++) {
6473 struct diff_filepair *p = q->queue[i];
6474 if (check_pair_status(p))
6475 diff_flush_patch(p, options);
6476 if (options->found_changes)
6477 break;
6481 if (output_format & DIFF_FORMAT_PATCH) {
6482 if (separator) {
6483 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6484 if (options->stat_sep)
6485 /* attach patch instead of inline */
6486 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6487 NULL, 0, 0);
6490 diff_flush_patch_all_file_pairs(options);
6493 if (output_format & DIFF_FORMAT_CALLBACK)
6494 options->format_callback(q, options, options->format_callback_data);
6496 for (i = 0; i < q->nr; i++)
6497 diff_free_filepair(q->queue[i]);
6498 free_queue:
6499 free(q->queue);
6500 DIFF_QUEUE_CLEAR(q);
6501 diff_free(options);
6504 * Report the content-level differences with HAS_CHANGES;
6505 * diff_addremove/diff_change does not set the bit when
6506 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6508 if (options->flags.diff_from_contents) {
6509 if (options->found_changes)
6510 options->flags.has_changes = 1;
6511 else
6512 options->flags.has_changes = 0;
6516 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6518 return (((p->status == DIFF_STATUS_MODIFIED) &&
6519 ((p->score &&
6520 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6521 (!p->score &&
6522 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6523 ((p->status != DIFF_STATUS_MODIFIED) &&
6524 filter_bit_tst(p->status, options)));
6527 static void diffcore_apply_filter(struct diff_options *options)
6529 int i;
6530 struct diff_queue_struct *q = &diff_queued_diff;
6531 struct diff_queue_struct outq;
6533 DIFF_QUEUE_CLEAR(&outq);
6535 if (!options->filter)
6536 return;
6538 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6539 int found;
6540 for (i = found = 0; !found && i < q->nr; i++) {
6541 if (match_filter(options, q->queue[i]))
6542 found++;
6544 if (found)
6545 return;
6547 /* otherwise we will clear the whole queue
6548 * by copying the empty outq at the end of this
6549 * function, but first clear the current entries
6550 * in the queue.
6552 for (i = 0; i < q->nr; i++)
6553 diff_free_filepair(q->queue[i]);
6555 else {
6556 /* Only the matching ones */
6557 for (i = 0; i < q->nr; i++) {
6558 struct diff_filepair *p = q->queue[i];
6559 if (match_filter(options, p))
6560 diff_q(&outq, p);
6561 else
6562 diff_free_filepair(p);
6565 free(q->queue);
6566 *q = outq;
6569 /* Check whether two filespecs with the same mode and size are identical */
6570 static int diff_filespec_is_identical(struct repository *r,
6571 struct diff_filespec *one,
6572 struct diff_filespec *two)
6574 if (S_ISGITLINK(one->mode))
6575 return 0;
6576 if (diff_populate_filespec(r, one, NULL))
6577 return 0;
6578 if (diff_populate_filespec(r, two, NULL))
6579 return 0;
6580 return !memcmp(one->data, two->data, one->size);
6583 static int diff_filespec_check_stat_unmatch(struct repository *r,
6584 struct diff_filepair *p)
6586 struct diff_populate_filespec_options dpf_options = {
6587 .check_size_only = 1,
6588 .missing_object_cb = diff_queued_diff_prefetch,
6589 .missing_object_data = r,
6592 if (p->done_skip_stat_unmatch)
6593 return p->skip_stat_unmatch_result;
6595 p->done_skip_stat_unmatch = 1;
6596 p->skip_stat_unmatch_result = 0;
6598 * 1. Entries that come from stat info dirtiness
6599 * always have both sides (iow, not create/delete),
6600 * one side of the object name is unknown, with
6601 * the same mode and size. Keep the ones that
6602 * do not match these criteria. They have real
6603 * differences.
6605 * 2. At this point, the file is known to be modified,
6606 * with the same mode and size, and the object
6607 * name of one side is unknown. Need to inspect
6608 * the identical contents.
6610 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6611 !DIFF_FILE_VALID(p->two) ||
6612 (p->one->oid_valid && p->two->oid_valid) ||
6613 (p->one->mode != p->two->mode) ||
6614 diff_populate_filespec(r, p->one, &dpf_options) ||
6615 diff_populate_filespec(r, p->two, &dpf_options) ||
6616 (p->one->size != p->two->size) ||
6617 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6618 p->skip_stat_unmatch_result = 1;
6619 return p->skip_stat_unmatch_result;
6622 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6624 int i;
6625 struct diff_queue_struct *q = &diff_queued_diff;
6626 struct diff_queue_struct outq;
6627 DIFF_QUEUE_CLEAR(&outq);
6629 for (i = 0; i < q->nr; i++) {
6630 struct diff_filepair *p = q->queue[i];
6632 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6633 diff_q(&outq, p);
6634 else {
6636 * The caller can subtract 1 from skip_stat_unmatch
6637 * to determine how many paths were dirty only
6638 * due to stat info mismatch.
6640 if (!diffopt->flags.no_index)
6641 diffopt->skip_stat_unmatch++;
6642 diff_free_filepair(p);
6645 free(q->queue);
6646 *q = outq;
6649 static int diffnamecmp(const void *a_, const void *b_)
6651 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6652 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6653 const char *name_a, *name_b;
6655 name_a = a->one ? a->one->path : a->two->path;
6656 name_b = b->one ? b->one->path : b->two->path;
6657 return strcmp(name_a, name_b);
6660 void diffcore_fix_diff_index(void)
6662 struct diff_queue_struct *q = &diff_queued_diff;
6663 QSORT(q->queue, q->nr, diffnamecmp);
6666 void diff_add_if_missing(struct repository *r,
6667 struct oid_array *to_fetch,
6668 const struct diff_filespec *filespec)
6670 if (filespec && filespec->oid_valid &&
6671 !S_ISGITLINK(filespec->mode) &&
6672 oid_object_info_extended(r, &filespec->oid, NULL,
6673 OBJECT_INFO_FOR_PREFETCH))
6674 oid_array_append(to_fetch, &filespec->oid);
6677 void diff_queued_diff_prefetch(void *repository)
6679 struct repository *repo = repository;
6680 int i;
6681 struct diff_queue_struct *q = &diff_queued_diff;
6682 struct oid_array to_fetch = OID_ARRAY_INIT;
6684 for (i = 0; i < q->nr; i++) {
6685 struct diff_filepair *p = q->queue[i];
6686 diff_add_if_missing(repo, &to_fetch, p->one);
6687 diff_add_if_missing(repo, &to_fetch, p->two);
6691 * NEEDSWORK: Consider deduplicating the OIDs sent.
6693 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6695 oid_array_clear(&to_fetch);
6698 void diffcore_std(struct diff_options *options)
6700 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6701 DIFF_FORMAT_NUMSTAT |
6702 DIFF_FORMAT_PATCH |
6703 DIFF_FORMAT_SHORTSTAT |
6704 DIFF_FORMAT_DIRSTAT;
6707 * Check if the user requested a blob-data-requiring diff output and/or
6708 * break-rewrite detection (which requires blob data). If yes, prefetch
6709 * the diff pairs.
6711 * If no prefetching occurs, diffcore_rename() will prefetch if it
6712 * decides that it needs inexact rename detection.
6714 if (options->repo == the_repository && has_promisor_remote() &&
6715 (options->output_format & output_formats_to_prefetch ||
6716 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6717 diff_queued_diff_prefetch(options->repo);
6719 /* NOTE please keep the following in sync with diff_tree_combined() */
6720 if (options->skip_stat_unmatch)
6721 diffcore_skip_stat_unmatch(options);
6722 if (!options->found_follow) {
6723 /* See try_to_follow_renames() in tree-diff.c */
6724 if (options->break_opt != -1)
6725 diffcore_break(options->repo,
6726 options->break_opt);
6727 if (options->detect_rename)
6728 diffcore_rename(options);
6729 if (options->break_opt != -1)
6730 diffcore_merge_broken();
6732 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6733 diffcore_pickaxe(options);
6734 if (options->orderfile)
6735 diffcore_order(options->orderfile);
6736 if (options->rotate_to)
6737 diffcore_rotate(options);
6738 if (!options->found_follow)
6739 /* See try_to_follow_renames() in tree-diff.c */
6740 diff_resolve_rename_copy();
6741 diffcore_apply_filter(options);
6743 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6744 options->flags.has_changes = 1;
6745 else
6746 options->flags.has_changes = 0;
6748 options->found_follow = 0;
6751 int diff_result_code(struct diff_options *opt, int status)
6753 int result = 0;
6755 diff_warn_rename_limit("diff.renameLimit",
6756 opt->needed_rename_limit,
6757 opt->degraded_cc_to_c);
6758 if (!opt->flags.exit_with_status &&
6759 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6760 return status;
6761 if (opt->flags.exit_with_status &&
6762 opt->flags.has_changes)
6763 result |= 01;
6764 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6765 opt->flags.check_failed)
6766 result |= 02;
6767 return result;
6770 int diff_can_quit_early(struct diff_options *opt)
6772 return (opt->flags.quick &&
6773 !opt->filter &&
6774 opt->flags.has_changes);
6778 * Shall changes to this submodule be ignored?
6780 * Submodule changes can be configured to be ignored separately for each path,
6781 * but that configuration can be overridden from the command line.
6783 static int is_submodule_ignored(const char *path, struct diff_options *options)
6785 int ignored = 0;
6786 struct diff_flags orig_flags = options->flags;
6787 if (!options->flags.override_submodule_config)
6788 set_diffopt_flags_from_submodule_config(options, path);
6789 if (options->flags.ignore_submodules)
6790 ignored = 1;
6791 options->flags = orig_flags;
6792 return ignored;
6795 void compute_diffstat(struct diff_options *options,
6796 struct diffstat_t *diffstat,
6797 struct diff_queue_struct *q)
6799 int i;
6801 memset(diffstat, 0, sizeof(struct diffstat_t));
6802 for (i = 0; i < q->nr; i++) {
6803 struct diff_filepair *p = q->queue[i];
6804 if (check_pair_status(p))
6805 diff_flush_stat(p, options, diffstat);
6809 void diff_addremove(struct diff_options *options,
6810 int addremove, unsigned mode,
6811 const struct object_id *oid,
6812 int oid_valid,
6813 const char *concatpath, unsigned dirty_submodule)
6815 struct diff_filespec *one, *two;
6817 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6818 return;
6820 /* This may look odd, but it is a preparation for
6821 * feeding "there are unchanged files which should
6822 * not produce diffs, but when you are doing copy
6823 * detection you would need them, so here they are"
6824 * entries to the diff-core. They will be prefixed
6825 * with something like '=' or '*' (I haven't decided
6826 * which but should not make any difference).
6827 * Feeding the same new and old to diff_change()
6828 * also has the same effect.
6829 * Before the final output happens, they are pruned after
6830 * merged into rename/copy pairs as appropriate.
6832 if (options->flags.reverse_diff)
6833 addremove = (addremove == '+' ? '-' :
6834 addremove == '-' ? '+' : addremove);
6836 if (options->prefix &&
6837 strncmp(concatpath, options->prefix, options->prefix_length))
6838 return;
6840 one = alloc_filespec(concatpath);
6841 two = alloc_filespec(concatpath);
6843 if (addremove != '+')
6844 fill_filespec(one, oid, oid_valid, mode);
6845 if (addremove != '-') {
6846 fill_filespec(two, oid, oid_valid, mode);
6847 two->dirty_submodule = dirty_submodule;
6850 diff_queue(&diff_queued_diff, one, two);
6851 if (!options->flags.diff_from_contents)
6852 options->flags.has_changes = 1;
6855 void diff_change(struct diff_options *options,
6856 unsigned old_mode, unsigned new_mode,
6857 const struct object_id *old_oid,
6858 const struct object_id *new_oid,
6859 int old_oid_valid, int new_oid_valid,
6860 const char *concatpath,
6861 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6863 struct diff_filespec *one, *two;
6864 struct diff_filepair *p;
6866 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6867 is_submodule_ignored(concatpath, options))
6868 return;
6870 if (options->flags.reverse_diff) {
6871 SWAP(old_mode, new_mode);
6872 SWAP(old_oid, new_oid);
6873 SWAP(old_oid_valid, new_oid_valid);
6874 SWAP(old_dirty_submodule, new_dirty_submodule);
6877 if (options->prefix &&
6878 strncmp(concatpath, options->prefix, options->prefix_length))
6879 return;
6881 one = alloc_filespec(concatpath);
6882 two = alloc_filespec(concatpath);
6883 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6884 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6885 one->dirty_submodule = old_dirty_submodule;
6886 two->dirty_submodule = new_dirty_submodule;
6887 p = diff_queue(&diff_queued_diff, one, two);
6889 if (options->flags.diff_from_contents)
6890 return;
6892 if (options->flags.quick && options->skip_stat_unmatch &&
6893 !diff_filespec_check_stat_unmatch(options->repo, p)) {
6894 diff_free_filespec_data(p->one);
6895 diff_free_filespec_data(p->two);
6896 return;
6899 options->flags.has_changes = 1;
6902 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6904 struct diff_filepair *pair;
6905 struct diff_filespec *one, *two;
6907 if (options->prefix &&
6908 strncmp(path, options->prefix, options->prefix_length))
6909 return NULL;
6911 one = alloc_filespec(path);
6912 two = alloc_filespec(path);
6913 pair = diff_queue(&diff_queued_diff, one, two);
6914 pair->is_unmerged = 1;
6915 return pair;
6918 static char *run_textconv(struct repository *r,
6919 const char *pgm,
6920 struct diff_filespec *spec,
6921 size_t *outsize)
6923 struct diff_tempfile *temp;
6924 const char *argv[3];
6925 const char **arg = argv;
6926 struct child_process child = CHILD_PROCESS_INIT;
6927 struct strbuf buf = STRBUF_INIT;
6928 int err = 0;
6930 temp = prepare_temp_file(r, spec->path, spec);
6931 *arg++ = pgm;
6932 *arg++ = temp->name;
6933 *arg = NULL;
6935 child.use_shell = 1;
6936 child.argv = argv;
6937 child.out = -1;
6938 if (start_command(&child)) {
6939 remove_tempfile();
6940 return NULL;
6943 if (strbuf_read(&buf, child.out, 0) < 0)
6944 err = error("error reading from textconv command '%s'", pgm);
6945 close(child.out);
6947 if (finish_command(&child) || err) {
6948 strbuf_release(&buf);
6949 remove_tempfile();
6950 return NULL;
6952 remove_tempfile();
6954 return strbuf_detach(&buf, outsize);
6957 size_t fill_textconv(struct repository *r,
6958 struct userdiff_driver *driver,
6959 struct diff_filespec *df,
6960 char **outbuf)
6962 size_t size;
6964 if (!driver) {
6965 if (!DIFF_FILE_VALID(df)) {
6966 *outbuf = "";
6967 return 0;
6969 if (diff_populate_filespec(r, df, NULL))
6970 die("unable to read files to diff");
6971 *outbuf = df->data;
6972 return df->size;
6975 if (!driver->textconv)
6976 BUG("fill_textconv called with non-textconv driver");
6978 if (driver->textconv_cache && df->oid_valid) {
6979 *outbuf = notes_cache_get(driver->textconv_cache,
6980 &df->oid,
6981 &size);
6982 if (*outbuf)
6983 return size;
6986 *outbuf = run_textconv(r, driver->textconv, df, &size);
6987 if (!*outbuf)
6988 die("unable to read files to diff");
6990 if (driver->textconv_cache && df->oid_valid) {
6991 /* ignore errors, as we might be in a readonly repository */
6992 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6993 size);
6995 * we could save up changes and flush them all at the end,
6996 * but we would need an extra call after all diffing is done.
6997 * Since generating a cache entry is the slow path anyway,
6998 * this extra overhead probably isn't a big deal.
7000 notes_cache_write(driver->textconv_cache);
7003 return size;
7006 int textconv_object(struct repository *r,
7007 const char *path,
7008 unsigned mode,
7009 const struct object_id *oid,
7010 int oid_valid,
7011 char **buf,
7012 unsigned long *buf_size)
7014 struct diff_filespec *df;
7015 struct userdiff_driver *textconv;
7017 df = alloc_filespec(path);
7018 fill_filespec(df, oid, oid_valid, mode);
7019 textconv = get_textconv(r, df);
7020 if (!textconv) {
7021 free_filespec(df);
7022 return 0;
7025 *buf_size = fill_textconv(r, textconv, df, buf);
7026 free_filespec(df);
7027 return 1;
7030 void setup_diff_pager(struct diff_options *opt)
7033 * If the user asked for our exit code, then either they want --quiet
7034 * or --exit-code. We should definitely not bother with a pager in the
7035 * former case, as we will generate no output. Since we still properly
7036 * report our exit code even when a pager is run, we _could_ run a
7037 * pager with --exit-code. But since we have not done so historically,
7038 * and because it is easy to find people oneline advising "git diff
7039 * --exit-code" in hooks and other scripts, we do not do so.
7041 if (!opt->flags.exit_with_status &&
7042 check_pager_config("diff") != 0)
7043 setup_pager();