object-store.h: move struct object_info from cache.h
[git/debian.git] / diff.c
blobec911bdf18c90d9416daddc419898b6bd40f5cbd
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "alloc.h"
6 #include "config.h"
7 #include "tempfile.h"
8 #include "quote.h"
9 #include "diff.h"
10 #include "diffcore.h"
11 #include "delta.h"
12 #include "hex.h"
13 #include "xdiff-interface.h"
14 #include "color.h"
15 #include "attr.h"
16 #include "run-command.h"
17 #include "utf8.h"
18 #include "object-store.h"
19 #include "userdiff.h"
20 #include "submodule-config.h"
21 #include "submodule.h"
22 #include "hashmap.h"
23 #include "mem-pool.h"
24 #include "ll-merge.h"
25 #include "string-list.h"
26 #include "strvec.h"
27 #include "graph.h"
28 #include "packfile.h"
29 #include "parse-options.h"
30 #include "help.h"
31 #include "promisor-remote.h"
32 #include "dir.h"
33 #include "strmap.h"
35 #ifdef NO_FAST_WORKING_DIRECTORY
36 #define FAST_WORKING_DIRECTORY 0
37 #else
38 #define FAST_WORKING_DIRECTORY 1
39 #endif
41 static int diff_detect_rename_default;
42 static int diff_indent_heuristic = 1;
43 static int diff_rename_limit_default = 1000;
44 static int diff_suppress_blank_empty;
45 static int diff_use_color_default = -1;
46 static int diff_color_moved_default;
47 static int diff_color_moved_ws_default;
48 static int diff_context_default = 3;
49 static int diff_interhunk_context_default;
50 static const char *diff_word_regex_cfg;
51 static const char *external_diff_cmd_cfg;
52 static const char *diff_order_file_cfg;
53 int diff_auto_refresh_index = 1;
54 static int diff_mnemonic_prefix;
55 static int diff_no_prefix;
56 static int diff_relative;
57 static int diff_stat_graph_width;
58 static int diff_dirstat_permille_default = 30;
59 static struct diff_options default_diff_options;
60 static long diff_algorithm;
61 static unsigned ws_error_highlight_default = WSEH_NEW;
63 static char diff_colors[][COLOR_MAXLEN] = {
64 GIT_COLOR_RESET,
65 GIT_COLOR_NORMAL, /* CONTEXT */
66 GIT_COLOR_BOLD, /* METAINFO */
67 GIT_COLOR_CYAN, /* FRAGINFO */
68 GIT_COLOR_RED, /* OLD */
69 GIT_COLOR_GREEN, /* NEW */
70 GIT_COLOR_YELLOW, /* COMMIT */
71 GIT_COLOR_BG_RED, /* WHITESPACE */
72 GIT_COLOR_NORMAL, /* FUNCINFO */
73 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
74 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
75 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
76 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
77 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
78 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
79 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
80 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
81 GIT_COLOR_FAINT, /* CONTEXT_DIM */
82 GIT_COLOR_FAINT_RED, /* OLD_DIM */
83 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
84 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
85 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
86 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
89 static const char *color_diff_slots[] = {
90 [DIFF_CONTEXT] = "context",
91 [DIFF_METAINFO] = "meta",
92 [DIFF_FRAGINFO] = "frag",
93 [DIFF_FILE_OLD] = "old",
94 [DIFF_FILE_NEW] = "new",
95 [DIFF_COMMIT] = "commit",
96 [DIFF_WHITESPACE] = "whitespace",
97 [DIFF_FUNCINFO] = "func",
98 [DIFF_FILE_OLD_MOVED] = "oldMoved",
99 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
100 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
101 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
102 [DIFF_FILE_NEW_MOVED] = "newMoved",
103 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
104 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
105 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
106 [DIFF_CONTEXT_DIM] = "contextDimmed",
107 [DIFF_FILE_OLD_DIM] = "oldDimmed",
108 [DIFF_FILE_NEW_DIM] = "newDimmed",
109 [DIFF_CONTEXT_BOLD] = "contextBold",
110 [DIFF_FILE_OLD_BOLD] = "oldBold",
111 [DIFF_FILE_NEW_BOLD] = "newBold",
114 define_list_config_array_extra(color_diff_slots, {"plain"});
116 static int parse_diff_color_slot(const char *var)
118 if (!strcasecmp(var, "plain"))
119 return DIFF_CONTEXT;
120 return LOOKUP_CONFIG(color_diff_slots, var);
123 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
124 struct strbuf *errmsg)
126 char *params_copy = xstrdup(params_string);
127 struct string_list params = STRING_LIST_INIT_NODUP;
128 int ret = 0;
129 int i;
131 if (*params_copy)
132 string_list_split_in_place(&params, params_copy, ',', -1);
133 for (i = 0; i < params.nr; i++) {
134 const char *p = params.items[i].string;
135 if (!strcmp(p, "changes")) {
136 options->flags.dirstat_by_line = 0;
137 options->flags.dirstat_by_file = 0;
138 } else if (!strcmp(p, "lines")) {
139 options->flags.dirstat_by_line = 1;
140 options->flags.dirstat_by_file = 0;
141 } else if (!strcmp(p, "files")) {
142 options->flags.dirstat_by_line = 0;
143 options->flags.dirstat_by_file = 1;
144 } else if (!strcmp(p, "noncumulative")) {
145 options->flags.dirstat_cumulative = 0;
146 } else if (!strcmp(p, "cumulative")) {
147 options->flags.dirstat_cumulative = 1;
148 } else if (isdigit(*p)) {
149 char *end;
150 int permille = strtoul(p, &end, 10) * 10;
151 if (*end == '.' && isdigit(*++end)) {
152 /* only use first digit */
153 permille += *end - '0';
154 /* .. and ignore any further digits */
155 while (isdigit(*++end))
156 ; /* nothing */
158 if (!*end)
159 options->dirstat_permille = permille;
160 else {
161 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
163 ret++;
165 } else {
166 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
167 ret++;
171 string_list_clear(&params, 0);
172 free(params_copy);
173 return ret;
176 static int parse_submodule_params(struct diff_options *options, const char *value)
178 if (!strcmp(value, "log"))
179 options->submodule_format = DIFF_SUBMODULE_LOG;
180 else if (!strcmp(value, "short"))
181 options->submodule_format = DIFF_SUBMODULE_SHORT;
182 else if (!strcmp(value, "diff"))
183 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
185 * Please update $__git_diff_submodule_formats in
186 * git-completion.bash when you add new formats.
188 else
189 return -1;
190 return 0;
193 int git_config_rename(const char *var, const char *value)
195 if (!value)
196 return DIFF_DETECT_RENAME;
197 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
198 return DIFF_DETECT_COPY;
199 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
202 long parse_algorithm_value(const char *value)
204 if (!value)
205 return -1;
206 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
207 return 0;
208 else if (!strcasecmp(value, "minimal"))
209 return XDF_NEED_MINIMAL;
210 else if (!strcasecmp(value, "patience"))
211 return XDF_PATIENCE_DIFF;
212 else if (!strcasecmp(value, "histogram"))
213 return XDF_HISTOGRAM_DIFF;
215 * Please update $__git_diff_algorithms in git-completion.bash
216 * when you add new algorithms.
218 return -1;
221 static int parse_one_token(const char **arg, const char *token)
223 const char *rest;
224 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
225 *arg = rest;
226 return 1;
228 return 0;
231 static int parse_ws_error_highlight(const char *arg)
233 const char *orig_arg = arg;
234 unsigned val = 0;
236 while (*arg) {
237 if (parse_one_token(&arg, "none"))
238 val = 0;
239 else if (parse_one_token(&arg, "default"))
240 val = WSEH_NEW;
241 else if (parse_one_token(&arg, "all"))
242 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
243 else if (parse_one_token(&arg, "new"))
244 val |= WSEH_NEW;
245 else if (parse_one_token(&arg, "old"))
246 val |= WSEH_OLD;
247 else if (parse_one_token(&arg, "context"))
248 val |= WSEH_CONTEXT;
249 else {
250 return -1 - (int)(arg - orig_arg);
252 if (*arg)
253 arg++;
255 return val;
259 * These are to give UI layer defaults.
260 * The core-level commands such as git-diff-files should
261 * never be affected by the setting of diff.renames
262 * the user happens to have in the configuration file.
264 void init_diff_ui_defaults(void)
266 diff_detect_rename_default = DIFF_DETECT_RENAME;
269 int git_diff_heuristic_config(const char *var, const char *value,
270 void *cb UNUSED)
272 if (!strcmp(var, "diff.indentheuristic"))
273 diff_indent_heuristic = git_config_bool(var, value);
274 return 0;
277 static int parse_color_moved(const char *arg)
279 switch (git_parse_maybe_bool(arg)) {
280 case 0:
281 return COLOR_MOVED_NO;
282 case 1:
283 return COLOR_MOVED_DEFAULT;
284 default:
285 break;
288 if (!strcmp(arg, "no"))
289 return COLOR_MOVED_NO;
290 else if (!strcmp(arg, "plain"))
291 return COLOR_MOVED_PLAIN;
292 else if (!strcmp(arg, "blocks"))
293 return COLOR_MOVED_BLOCKS;
294 else if (!strcmp(arg, "zebra"))
295 return COLOR_MOVED_ZEBRA;
296 else if (!strcmp(arg, "default"))
297 return COLOR_MOVED_DEFAULT;
298 else if (!strcmp(arg, "dimmed-zebra"))
299 return COLOR_MOVED_ZEBRA_DIM;
300 else if (!strcmp(arg, "dimmed_zebra"))
301 return COLOR_MOVED_ZEBRA_DIM;
302 else
303 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
306 static unsigned parse_color_moved_ws(const char *arg)
308 int ret = 0;
309 struct string_list l = STRING_LIST_INIT_DUP;
310 struct string_list_item *i;
312 string_list_split(&l, arg, ',', -1);
314 for_each_string_list_item(i, &l) {
315 struct strbuf sb = STRBUF_INIT;
316 strbuf_addstr(&sb, i->string);
317 strbuf_trim(&sb);
319 if (!strcmp(sb.buf, "no"))
320 ret = 0;
321 else if (!strcmp(sb.buf, "ignore-space-change"))
322 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
323 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
324 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
325 else if (!strcmp(sb.buf, "ignore-all-space"))
326 ret |= XDF_IGNORE_WHITESPACE;
327 else if (!strcmp(sb.buf, "allow-indentation-change"))
328 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
329 else {
330 ret |= COLOR_MOVED_WS_ERROR;
331 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);
334 strbuf_release(&sb);
337 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
338 (ret & XDF_WHITESPACE_FLAGS)) {
339 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
340 ret |= COLOR_MOVED_WS_ERROR;
343 string_list_clear(&l, 0);
345 return ret;
348 int git_diff_ui_config(const char *var, const char *value, void *cb)
350 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
351 diff_use_color_default = git_config_colorbool(var, value);
352 return 0;
354 if (!strcmp(var, "diff.colormoved")) {
355 int cm = parse_color_moved(value);
356 if (cm < 0)
357 return -1;
358 diff_color_moved_default = cm;
359 return 0;
361 if (!strcmp(var, "diff.colormovedws")) {
362 unsigned cm = parse_color_moved_ws(value);
363 if (cm & COLOR_MOVED_WS_ERROR)
364 return -1;
365 diff_color_moved_ws_default = cm;
366 return 0;
368 if (!strcmp(var, "diff.context")) {
369 diff_context_default = git_config_int(var, value);
370 if (diff_context_default < 0)
371 return -1;
372 return 0;
374 if (!strcmp(var, "diff.interhunkcontext")) {
375 diff_interhunk_context_default = git_config_int(var, value);
376 if (diff_interhunk_context_default < 0)
377 return -1;
378 return 0;
380 if (!strcmp(var, "diff.renames")) {
381 diff_detect_rename_default = git_config_rename(var, value);
382 return 0;
384 if (!strcmp(var, "diff.autorefreshindex")) {
385 diff_auto_refresh_index = git_config_bool(var, value);
386 return 0;
388 if (!strcmp(var, "diff.mnemonicprefix")) {
389 diff_mnemonic_prefix = git_config_bool(var, value);
390 return 0;
392 if (!strcmp(var, "diff.noprefix")) {
393 diff_no_prefix = git_config_bool(var, value);
394 return 0;
396 if (!strcmp(var, "diff.relative")) {
397 diff_relative = git_config_bool(var, value);
398 return 0;
400 if (!strcmp(var, "diff.statgraphwidth")) {
401 diff_stat_graph_width = git_config_int(var, value);
402 return 0;
404 if (!strcmp(var, "diff.external"))
405 return git_config_string(&external_diff_cmd_cfg, var, value);
406 if (!strcmp(var, "diff.wordregex"))
407 return git_config_string(&diff_word_regex_cfg, var, value);
408 if (!strcmp(var, "diff.orderfile"))
409 return git_config_pathname(&diff_order_file_cfg, var, value);
411 if (!strcmp(var, "diff.ignoresubmodules"))
412 handle_ignore_submodules_arg(&default_diff_options, value);
414 if (!strcmp(var, "diff.submodule")) {
415 if (parse_submodule_params(&default_diff_options, value))
416 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
417 value);
418 return 0;
421 if (!strcmp(var, "diff.algorithm")) {
422 diff_algorithm = parse_algorithm_value(value);
423 if (diff_algorithm < 0)
424 return -1;
425 return 0;
428 if (git_color_config(var, value, cb) < 0)
429 return -1;
431 return git_diff_basic_config(var, value, cb);
434 int git_diff_basic_config(const char *var, const char *value, void *cb)
436 const char *name;
438 if (!strcmp(var, "diff.renamelimit")) {
439 diff_rename_limit_default = git_config_int(var, value);
440 return 0;
443 if (userdiff_config(var, value) < 0)
444 return -1;
446 if (skip_prefix(var, "diff.color.", &name) ||
447 skip_prefix(var, "color.diff.", &name)) {
448 int slot = parse_diff_color_slot(name);
449 if (slot < 0)
450 return 0;
451 if (!value)
452 return config_error_nonbool(var);
453 return color_parse(value, diff_colors[slot]);
456 if (!strcmp(var, "diff.wserrorhighlight")) {
457 int val = parse_ws_error_highlight(value);
458 if (val < 0)
459 return -1;
460 ws_error_highlight_default = val;
461 return 0;
464 /* like GNU diff's --suppress-blank-empty option */
465 if (!strcmp(var, "diff.suppressblankempty") ||
466 /* for backwards compatibility */
467 !strcmp(var, "diff.suppress-blank-empty")) {
468 diff_suppress_blank_empty = git_config_bool(var, value);
469 return 0;
472 if (!strcmp(var, "diff.dirstat")) {
473 struct strbuf errmsg = STRBUF_INIT;
474 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
475 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
476 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
477 errmsg.buf);
478 strbuf_release(&errmsg);
479 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
480 return 0;
483 if (git_diff_heuristic_config(var, value, cb) < 0)
484 return -1;
486 return git_default_config(var, value, cb);
489 static char *quote_two(const char *one, const char *two)
491 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
492 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
493 struct strbuf res = STRBUF_INIT;
495 if (need_one + need_two) {
496 strbuf_addch(&res, '"');
497 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
498 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
499 strbuf_addch(&res, '"');
500 } else {
501 strbuf_addstr(&res, one);
502 strbuf_addstr(&res, two);
504 return strbuf_detach(&res, NULL);
507 static const char *external_diff(void)
509 static const char *external_diff_cmd = NULL;
510 static int done_preparing = 0;
512 if (done_preparing)
513 return external_diff_cmd;
514 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
515 if (!external_diff_cmd)
516 external_diff_cmd = external_diff_cmd_cfg;
517 done_preparing = 1;
518 return external_diff_cmd;
522 * Keep track of files used for diffing. Sometimes such an entry
523 * refers to a temporary file, sometimes to an existing file, and
524 * sometimes to "/dev/null".
526 static struct diff_tempfile {
528 * filename external diff should read from, or NULL if this
529 * entry is currently not in use:
531 const char *name;
533 char hex[GIT_MAX_HEXSZ + 1];
534 char mode[10];
537 * If this diff_tempfile instance refers to a temporary file,
538 * this tempfile object is used to manage its lifetime.
540 struct tempfile *tempfile;
541 } diff_temp[2];
543 struct emit_callback {
544 int color_diff;
545 unsigned ws_rule;
546 int blank_at_eof_in_preimage;
547 int blank_at_eof_in_postimage;
548 int lno_in_preimage;
549 int lno_in_postimage;
550 const char **label_path;
551 struct diff_words_data *diff_words;
552 struct diff_options *opt;
553 struct strbuf *header;
556 static int count_lines(const char *data, int size)
558 int count, ch, completely_empty = 1, nl_just_seen = 0;
559 count = 0;
560 while (0 < size--) {
561 ch = *data++;
562 if (ch == '\n') {
563 count++;
564 nl_just_seen = 1;
565 completely_empty = 0;
567 else {
568 nl_just_seen = 0;
569 completely_empty = 0;
572 if (completely_empty)
573 return 0;
574 if (!nl_just_seen)
575 count++; /* no trailing newline */
576 return count;
579 static int fill_mmfile(struct repository *r, mmfile_t *mf,
580 struct diff_filespec *one)
582 if (!DIFF_FILE_VALID(one)) {
583 mf->ptr = (char *)""; /* does not matter */
584 mf->size = 0;
585 return 0;
587 else if (diff_populate_filespec(r, one, NULL))
588 return -1;
590 mf->ptr = one->data;
591 mf->size = one->size;
592 return 0;
595 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
596 static unsigned long diff_filespec_size(struct repository *r,
597 struct diff_filespec *one)
599 struct diff_populate_filespec_options dpf_options = {
600 .check_size_only = 1,
603 if (!DIFF_FILE_VALID(one))
604 return 0;
605 diff_populate_filespec(r, one, &dpf_options);
606 return one->size;
609 static int count_trailing_blank(mmfile_t *mf)
611 char *ptr = mf->ptr;
612 long size = mf->size;
613 int cnt = 0;
615 if (!size)
616 return cnt;
617 ptr += size - 1; /* pointing at the very end */
618 if (*ptr != '\n')
619 ; /* incomplete line */
620 else
621 ptr--; /* skip the last LF */
622 while (mf->ptr < ptr) {
623 char *prev_eol;
624 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
625 if (*prev_eol == '\n')
626 break;
627 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
628 break;
629 cnt++;
630 ptr = prev_eol - 1;
632 return cnt;
635 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
636 struct emit_callback *ecbdata)
638 int l1, l2, at;
639 l1 = count_trailing_blank(mf1);
640 l2 = count_trailing_blank(mf2);
641 if (l2 <= l1) {
642 ecbdata->blank_at_eof_in_preimage = 0;
643 ecbdata->blank_at_eof_in_postimage = 0;
644 return;
646 at = count_lines(mf1->ptr, mf1->size);
647 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
649 at = count_lines(mf2->ptr, mf2->size);
650 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
653 static void emit_line_0(struct diff_options *o,
654 const char *set_sign, const char *set, unsigned reverse, const char *reset,
655 int first, const char *line, int len)
657 int has_trailing_newline, has_trailing_carriage_return;
658 int needs_reset = 0; /* at the end of the line */
659 FILE *file = o->file;
661 fputs(diff_line_prefix(o), file);
663 has_trailing_newline = (len > 0 && line[len-1] == '\n');
664 if (has_trailing_newline)
665 len--;
667 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
668 if (has_trailing_carriage_return)
669 len--;
671 if (!len && !first)
672 goto end_of_line;
674 if (reverse && want_color(o->use_color)) {
675 fputs(GIT_COLOR_REVERSE, file);
676 needs_reset = 1;
679 if (set_sign) {
680 fputs(set_sign, file);
681 needs_reset = 1;
684 if (first)
685 fputc(first, file);
687 if (!len)
688 goto end_of_line;
690 if (set) {
691 if (set_sign && set != set_sign)
692 fputs(reset, file);
693 fputs(set, file);
694 needs_reset = 1;
696 fwrite(line, len, 1, file);
697 needs_reset = 1; /* 'line' may contain color codes. */
699 end_of_line:
700 if (needs_reset)
701 fputs(reset, file);
702 if (has_trailing_carriage_return)
703 fputc('\r', file);
704 if (has_trailing_newline)
705 fputc('\n', file);
708 static void emit_line(struct diff_options *o, const char *set, const char *reset,
709 const char *line, int len)
711 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
714 enum diff_symbol {
715 DIFF_SYMBOL_BINARY_DIFF_HEADER,
716 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
717 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
718 DIFF_SYMBOL_BINARY_DIFF_BODY,
719 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
720 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
721 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
722 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
723 DIFF_SYMBOL_STATS_LINE,
724 DIFF_SYMBOL_WORD_DIFF,
725 DIFF_SYMBOL_STAT_SEP,
726 DIFF_SYMBOL_SUMMARY,
727 DIFF_SYMBOL_SUBMODULE_ADD,
728 DIFF_SYMBOL_SUBMODULE_DEL,
729 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
730 DIFF_SYMBOL_SUBMODULE_MODIFIED,
731 DIFF_SYMBOL_SUBMODULE_HEADER,
732 DIFF_SYMBOL_SUBMODULE_ERROR,
733 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
734 DIFF_SYMBOL_REWRITE_DIFF,
735 DIFF_SYMBOL_BINARY_FILES,
736 DIFF_SYMBOL_HEADER,
737 DIFF_SYMBOL_FILEPAIR_PLUS,
738 DIFF_SYMBOL_FILEPAIR_MINUS,
739 DIFF_SYMBOL_WORDS_PORCELAIN,
740 DIFF_SYMBOL_WORDS,
741 DIFF_SYMBOL_CONTEXT,
742 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
743 DIFF_SYMBOL_PLUS,
744 DIFF_SYMBOL_MINUS,
745 DIFF_SYMBOL_NO_LF_EOF,
746 DIFF_SYMBOL_CONTEXT_FRAGINFO,
747 DIFF_SYMBOL_CONTEXT_MARKER,
748 DIFF_SYMBOL_SEPARATOR
751 * Flags for content lines:
752 * 0..12 are whitespace rules
753 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
754 * 16 is marking if the line is blank at EOF
756 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
757 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
758 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
759 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
760 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
763 * This struct is used when we need to buffer the output of the diff output.
765 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
766 * into the pre/post image file. This pointer could be a union with the
767 * line pointer. By storing an offset into the file instead of the literal line,
768 * we can decrease the memory footprint for the buffered output. At first we
769 * may want to only have indirection for the content lines, but we could also
770 * enhance the state for emitting prefabricated lines, e.g. the similarity
771 * score line or hunk/file headers would only need to store a number or path
772 * and then the output can be constructed later on depending on state.
774 struct emitted_diff_symbol {
775 const char *line;
776 int len;
777 int flags;
778 int indent_off; /* Offset to first non-whitespace character */
779 int indent_width; /* The visual width of the indentation */
780 unsigned id;
781 enum diff_symbol s;
783 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
785 struct emitted_diff_symbols {
786 struct emitted_diff_symbol *buf;
787 int nr, alloc;
789 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
791 static void append_emitted_diff_symbol(struct diff_options *o,
792 struct emitted_diff_symbol *e)
794 struct emitted_diff_symbol *f;
796 ALLOC_GROW(o->emitted_symbols->buf,
797 o->emitted_symbols->nr + 1,
798 o->emitted_symbols->alloc);
799 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
801 memcpy(f, e, sizeof(struct emitted_diff_symbol));
802 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
805 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
807 if (!e)
808 return;
809 free(e->buf);
810 free(e);
813 struct moved_entry {
814 const struct emitted_diff_symbol *es;
815 struct moved_entry *next_line;
816 struct moved_entry *next_match;
819 struct moved_block {
820 struct moved_entry *match;
821 int wsd; /* The whitespace delta of this block */
824 #define INDENT_BLANKLINE INT_MIN
826 static void fill_es_indent_data(struct emitted_diff_symbol *es)
828 unsigned int off = 0, i;
829 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
830 const char *s = es->line;
831 const int len = es->len;
833 /* skip any \v \f \r at start of indentation */
834 while (s[off] == '\f' || s[off] == '\v' ||
835 (s[off] == '\r' && off < len - 1))
836 off++;
838 /* calculate the visual width of indentation */
839 while(1) {
840 if (s[off] == ' ') {
841 width++;
842 off++;
843 } else if (s[off] == '\t') {
844 width += tab_width - (width % tab_width);
845 while (s[++off] == '\t')
846 width += tab_width;
847 } else {
848 break;
852 /* check if this line is blank */
853 for (i = off; i < len; i++)
854 if (!isspace(s[i]))
855 break;
857 if (i == len) {
858 es->indent_width = INDENT_BLANKLINE;
859 es->indent_off = len;
860 } else {
861 es->indent_off = off;
862 es->indent_width = width;
866 static int compute_ws_delta(const struct emitted_diff_symbol *a,
867 const struct emitted_diff_symbol *b)
869 int a_width = a->indent_width,
870 b_width = b->indent_width;
872 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
873 return INDENT_BLANKLINE;
875 return a_width - b_width;
878 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
879 const struct emitted_diff_symbol *l,
880 struct moved_block *pmb)
882 int a_width = cur->es->indent_width, b_width = l->indent_width;
883 int delta;
885 /* The text of each line must match */
886 if (cur->es->id != l->id)
887 return 1;
890 * If 'l' and 'cur' are both blank then we don't need to check the
891 * indent. We only need to check cur as we know the strings match.
892 * */
893 if (a_width == INDENT_BLANKLINE)
894 return 0;
897 * The indent changes of the block are known and stored in pmb->wsd;
898 * however we need to check if the indent changes of the current line
899 * match those of the current block.
901 delta = b_width - a_width;
904 * If the previous lines of this block were all blank then set its
905 * whitespace delta.
907 if (pmb->wsd == INDENT_BLANKLINE)
908 pmb->wsd = delta;
910 return delta != pmb->wsd;
913 struct interned_diff_symbol {
914 struct hashmap_entry ent;
915 struct emitted_diff_symbol *es;
918 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
919 const struct hashmap_entry *eptr,
920 const struct hashmap_entry *entry_or_key,
921 const void *keydata UNUSED)
923 const struct diff_options *diffopt = hashmap_cmp_fn_data;
924 const struct emitted_diff_symbol *a, *b;
925 unsigned flags = diffopt->color_moved_ws_handling
926 & XDF_WHITESPACE_FLAGS;
928 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
929 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
931 return !xdiff_compare_lines(a->line + a->indent_off,
932 a->len - a->indent_off,
933 b->line + b->indent_off,
934 b->len - b->indent_off, flags);
937 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
938 struct interned_diff_symbol *s)
940 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
941 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
942 l->len - l->indent_off, flags);
944 hashmap_entry_init(&s->ent, hash);
945 s->es = l;
948 struct moved_entry_list {
949 struct moved_entry *add, *del;
952 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
953 struct mem_pool *entry_mem_pool)
955 struct moved_entry *prev_line = NULL;
956 struct mem_pool interned_pool;
957 struct hashmap interned_map;
958 struct moved_entry_list *entry_list = NULL;
959 size_t entry_list_alloc = 0;
960 unsigned id = 0;
961 int n;
963 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
964 mem_pool_init(&interned_pool, 1024 * 1024);
966 for (n = 0; n < o->emitted_symbols->nr; n++) {
967 struct interned_diff_symbol key;
968 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
969 struct interned_diff_symbol *s;
970 struct moved_entry *entry;
972 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
973 prev_line = NULL;
974 continue;
977 if (o->color_moved_ws_handling &
978 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
979 fill_es_indent_data(l);
981 prepare_entry(o, l, &key);
982 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
983 if (s) {
984 l->id = s->es->id;
985 } else {
986 l->id = id;
987 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
988 hashmap_add(&interned_map,
989 memcpy(mem_pool_alloc(&interned_pool,
990 sizeof(key)),
991 &key, sizeof(key)));
993 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
994 entry->es = l;
995 entry->next_line = NULL;
996 if (prev_line && prev_line->es->s == l->s)
997 prev_line->next_line = entry;
998 prev_line = entry;
999 if (l->s == DIFF_SYMBOL_PLUS) {
1000 entry->next_match = entry_list[l->id].add;
1001 entry_list[l->id].add = entry;
1002 } else {
1003 entry->next_match = entry_list[l->id].del;
1004 entry_list[l->id].del = entry;
1008 hashmap_clear(&interned_map);
1009 mem_pool_discard(&interned_pool, 0);
1011 return entry_list;
1014 static void pmb_advance_or_null(struct diff_options *o,
1015 struct emitted_diff_symbol *l,
1016 struct moved_block *pmb,
1017 int *pmb_nr)
1019 int i, j;
1021 for (i = 0, j = 0; i < *pmb_nr; i++) {
1022 int match;
1023 struct moved_entry *prev = pmb[i].match;
1024 struct moved_entry *cur = (prev && prev->next_line) ?
1025 prev->next_line : NULL;
1027 if (o->color_moved_ws_handling &
1028 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1029 match = cur &&
1030 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1031 else
1032 match = cur && cur->es->id == l->id;
1034 if (match) {
1035 pmb[j] = pmb[i];
1036 pmb[j++].match = cur;
1039 *pmb_nr = j;
1042 static void fill_potential_moved_blocks(struct diff_options *o,
1043 struct moved_entry *match,
1044 struct emitted_diff_symbol *l,
1045 struct moved_block **pmb_p,
1046 int *pmb_alloc_p, int *pmb_nr_p)
1049 struct moved_block *pmb = *pmb_p;
1050 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1053 * The current line is the start of a new block.
1054 * Setup the set of potential blocks.
1056 for (; match; match = match->next_match) {
1057 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1058 if (o->color_moved_ws_handling &
1059 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1060 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1061 else
1062 pmb[pmb_nr].wsd = 0;
1063 pmb[pmb_nr++].match = match;
1066 *pmb_p = pmb;
1067 *pmb_alloc_p = pmb_alloc;
1068 *pmb_nr_p = pmb_nr;
1072 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1074 * Otherwise, if the last block has fewer alphanumeric characters than
1075 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1076 * that block.
1078 * The last block consists of the (n - block_length)'th line up to but not
1079 * including the nth line.
1081 * Returns 0 if the last block is empty or is unset by this function, non zero
1082 * otherwise.
1084 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1085 * Think of a way to unify them.
1087 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1088 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1089 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1091 int i, alnum_count = 0;
1092 if (o->color_moved == COLOR_MOVED_PLAIN)
1093 return block_length;
1094 for (i = 1; i < block_length + 1; i++) {
1095 const char *c = o->emitted_symbols->buf[n - i].line;
1096 for (; *c; c++) {
1097 if (!isalnum(*c))
1098 continue;
1099 alnum_count++;
1100 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1101 return 1;
1104 for (i = 1; i < block_length + 1; i++)
1105 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1106 return 0;
1109 /* Find blocks of moved code, delegate actual coloring decision to helper */
1110 static void mark_color_as_moved(struct diff_options *o,
1111 struct moved_entry_list *entry_list)
1113 struct moved_block *pmb = NULL; /* potentially moved blocks */
1114 int pmb_nr = 0, pmb_alloc = 0;
1115 int n, flipped_block = 0, block_length = 0;
1116 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1119 for (n = 0; n < o->emitted_symbols->nr; n++) {
1120 struct moved_entry *match = NULL;
1121 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1123 switch (l->s) {
1124 case DIFF_SYMBOL_PLUS:
1125 match = entry_list[l->id].del;
1126 break;
1127 case DIFF_SYMBOL_MINUS:
1128 match = entry_list[l->id].add;
1129 break;
1130 default:
1131 flipped_block = 0;
1134 if (pmb_nr && (!match || l->s != moved_symbol)) {
1135 if (!adjust_last_block(o, n, block_length) &&
1136 block_length > 1) {
1138 * Rewind in case there is another match
1139 * starting at the second line of the block
1141 match = NULL;
1142 n -= block_length;
1144 pmb_nr = 0;
1145 block_length = 0;
1146 flipped_block = 0;
1148 if (!match) {
1149 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1150 continue;
1153 if (o->color_moved == COLOR_MOVED_PLAIN) {
1154 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1155 continue;
1158 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1160 if (pmb_nr == 0) {
1161 int contiguous = adjust_last_block(o, n, block_length);
1163 if (!contiguous && block_length > 1)
1165 * Rewind in case there is another match
1166 * starting at the second line of the block
1168 n -= block_length;
1169 else
1170 fill_potential_moved_blocks(o, match, l,
1171 &pmb, &pmb_alloc,
1172 &pmb_nr);
1174 if (contiguous && pmb_nr && moved_symbol == l->s)
1175 flipped_block = (flipped_block + 1) % 2;
1176 else
1177 flipped_block = 0;
1179 if (pmb_nr)
1180 moved_symbol = l->s;
1181 else
1182 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1184 block_length = 0;
1187 if (pmb_nr) {
1188 block_length++;
1189 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1190 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1191 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1194 adjust_last_block(o, n, block_length);
1196 free(pmb);
1199 static void dim_moved_lines(struct diff_options *o)
1201 int n;
1202 for (n = 0; n < o->emitted_symbols->nr; n++) {
1203 struct emitted_diff_symbol *prev = (n != 0) ?
1204 &o->emitted_symbols->buf[n - 1] : NULL;
1205 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1206 struct emitted_diff_symbol *next =
1207 (n < o->emitted_symbols->nr - 1) ?
1208 &o->emitted_symbols->buf[n + 1] : NULL;
1210 /* Not a plus or minus line? */
1211 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1212 continue;
1214 /* Not a moved line? */
1215 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1216 continue;
1219 * If prev or next are not a plus or minus line,
1220 * pretend they don't exist
1222 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1223 prev->s != DIFF_SYMBOL_MINUS)
1224 prev = NULL;
1225 if (next && next->s != DIFF_SYMBOL_PLUS &&
1226 next->s != DIFF_SYMBOL_MINUS)
1227 next = NULL;
1229 /* Inside a block? */
1230 if ((prev &&
1231 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1232 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1233 (next &&
1234 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1235 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1236 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1237 continue;
1240 /* Check if we are at an interesting bound: */
1241 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1242 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1243 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1244 continue;
1245 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1246 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1247 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1248 continue;
1251 * The boundary to prev and next are not interesting,
1252 * so this line is not interesting as a whole
1254 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1258 static void emit_line_ws_markup(struct diff_options *o,
1259 const char *set_sign, const char *set,
1260 const char *reset,
1261 int sign_index, const char *line, int len,
1262 unsigned ws_rule, int blank_at_eof)
1264 const char *ws = NULL;
1265 int sign = o->output_indicators[sign_index];
1267 if (o->ws_error_highlight & ws_rule) {
1268 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1269 if (!*ws)
1270 ws = NULL;
1273 if (!ws && !set_sign)
1274 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1275 else if (!ws) {
1276 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1277 } else if (blank_at_eof)
1278 /* Blank line at EOF - paint '+' as well */
1279 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1280 else {
1281 /* Emit just the prefix, then the rest. */
1282 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1283 sign, "", 0);
1284 ws_check_emit(line, len, ws_rule,
1285 o->file, set, reset, ws);
1289 static void emit_diff_symbol_from_struct(struct diff_options *o,
1290 struct emitted_diff_symbol *eds)
1292 static const char *nneof = " No newline at end of file\n";
1293 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1295 enum diff_symbol s = eds->s;
1296 const char *line = eds->line;
1297 int len = eds->len;
1298 unsigned flags = eds->flags;
1300 switch (s) {
1301 case DIFF_SYMBOL_NO_LF_EOF:
1302 context = diff_get_color_opt(o, DIFF_CONTEXT);
1303 reset = diff_get_color_opt(o, DIFF_RESET);
1304 putc('\n', o->file);
1305 emit_line_0(o, context, NULL, 0, reset, '\\',
1306 nneof, strlen(nneof));
1307 break;
1308 case DIFF_SYMBOL_SUBMODULE_HEADER:
1309 case DIFF_SYMBOL_SUBMODULE_ERROR:
1310 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1311 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1312 case DIFF_SYMBOL_SUMMARY:
1313 case DIFF_SYMBOL_STATS_LINE:
1314 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1315 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1316 emit_line(o, "", "", line, len);
1317 break;
1318 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1319 case DIFF_SYMBOL_CONTEXT_MARKER:
1320 context = diff_get_color_opt(o, DIFF_CONTEXT);
1321 reset = diff_get_color_opt(o, DIFF_RESET);
1322 emit_line(o, context, reset, line, len);
1323 break;
1324 case DIFF_SYMBOL_SEPARATOR:
1325 fprintf(o->file, "%s%c",
1326 diff_line_prefix(o),
1327 o->line_termination);
1328 break;
1329 case DIFF_SYMBOL_CONTEXT:
1330 set = diff_get_color_opt(o, DIFF_CONTEXT);
1331 reset = diff_get_color_opt(o, DIFF_RESET);
1332 set_sign = NULL;
1333 if (o->flags.dual_color_diffed_diffs) {
1334 char c = !len ? 0 : line[0];
1336 if (c == '+')
1337 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1338 else if (c == '@')
1339 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1340 else if (c == '-')
1341 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1343 emit_line_ws_markup(o, set_sign, set, reset,
1344 OUTPUT_INDICATOR_CONTEXT, line, len,
1345 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1346 break;
1347 case DIFF_SYMBOL_PLUS:
1348 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1349 DIFF_SYMBOL_MOVED_LINE_ALT |
1350 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1351 case DIFF_SYMBOL_MOVED_LINE |
1352 DIFF_SYMBOL_MOVED_LINE_ALT |
1353 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1354 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1355 break;
1356 case DIFF_SYMBOL_MOVED_LINE |
1357 DIFF_SYMBOL_MOVED_LINE_ALT:
1358 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1359 break;
1360 case DIFF_SYMBOL_MOVED_LINE |
1361 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1362 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1363 break;
1364 case DIFF_SYMBOL_MOVED_LINE:
1365 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1366 break;
1367 default:
1368 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1370 reset = diff_get_color_opt(o, DIFF_RESET);
1371 if (!o->flags.dual_color_diffed_diffs)
1372 set_sign = NULL;
1373 else {
1374 char c = !len ? 0 : line[0];
1376 set_sign = set;
1377 if (c == '-')
1378 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1379 else if (c == '@')
1380 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1381 else if (c == '+')
1382 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1383 else
1384 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1385 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1387 emit_line_ws_markup(o, set_sign, set, reset,
1388 OUTPUT_INDICATOR_NEW, line, len,
1389 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1390 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1391 break;
1392 case DIFF_SYMBOL_MINUS:
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_OLD_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_OLD_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_OLD_MOVED_DIM);
1408 break;
1409 case DIFF_SYMBOL_MOVED_LINE:
1410 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1411 break;
1412 default:
1413 set = diff_get_color_opt(o, DIFF_FILE_OLD);
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_NEW_DIM);
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_OLD_DIM);
1428 else
1429 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1431 emit_line_ws_markup(o, set_sign, set, reset,
1432 OUTPUT_INDICATOR_OLD, line, len,
1433 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1434 break;
1435 case DIFF_SYMBOL_WORDS_PORCELAIN:
1436 context = diff_get_color_opt(o, DIFF_CONTEXT);
1437 reset = diff_get_color_opt(o, DIFF_RESET);
1438 emit_line(o, context, reset, line, len);
1439 fputs("~\n", o->file);
1440 break;
1441 case DIFF_SYMBOL_WORDS:
1442 context = diff_get_color_opt(o, DIFF_CONTEXT);
1443 reset = diff_get_color_opt(o, DIFF_RESET);
1445 * Skip the prefix character, if any. With
1446 * diff_suppress_blank_empty, there may be
1447 * none.
1449 if (line[0] != '\n') {
1450 line++;
1451 len--;
1453 emit_line(o, context, reset, line, len);
1454 break;
1455 case DIFF_SYMBOL_FILEPAIR_PLUS:
1456 meta = diff_get_color_opt(o, DIFF_METAINFO);
1457 reset = diff_get_color_opt(o, DIFF_RESET);
1458 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1459 line, reset,
1460 strchr(line, ' ') ? "\t" : "");
1461 break;
1462 case DIFF_SYMBOL_FILEPAIR_MINUS:
1463 meta = diff_get_color_opt(o, DIFF_METAINFO);
1464 reset = diff_get_color_opt(o, DIFF_RESET);
1465 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1466 line, reset,
1467 strchr(line, ' ') ? "\t" : "");
1468 break;
1469 case DIFF_SYMBOL_BINARY_FILES:
1470 case DIFF_SYMBOL_HEADER:
1471 fprintf(o->file, "%s", line);
1472 break;
1473 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1474 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1475 break;
1476 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1477 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1478 break;
1479 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1480 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1481 break;
1482 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1483 fputs(diff_line_prefix(o), o->file);
1484 fputc('\n', o->file);
1485 break;
1486 case DIFF_SYMBOL_REWRITE_DIFF:
1487 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1488 reset = diff_get_color_opt(o, DIFF_RESET);
1489 emit_line(o, fraginfo, reset, line, len);
1490 break;
1491 case DIFF_SYMBOL_SUBMODULE_ADD:
1492 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1493 reset = diff_get_color_opt(o, DIFF_RESET);
1494 emit_line(o, set, reset, line, len);
1495 break;
1496 case DIFF_SYMBOL_SUBMODULE_DEL:
1497 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1498 reset = diff_get_color_opt(o, DIFF_RESET);
1499 emit_line(o, set, reset, line, len);
1500 break;
1501 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1502 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1503 diff_line_prefix(o), line);
1504 break;
1505 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1506 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1507 diff_line_prefix(o), line);
1508 break;
1509 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1510 emit_line(o, "", "", " 0 files changed\n",
1511 strlen(" 0 files changed\n"));
1512 break;
1513 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1514 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1515 break;
1516 case DIFF_SYMBOL_WORD_DIFF:
1517 fprintf(o->file, "%.*s", len, line);
1518 break;
1519 case DIFF_SYMBOL_STAT_SEP:
1520 fputs(o->stat_sep, o->file);
1521 break;
1522 default:
1523 BUG("unknown diff symbol");
1527 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1528 const char *line, int len, unsigned flags)
1530 struct emitted_diff_symbol e = {
1531 .line = line, .len = len, .flags = flags, .s = s
1534 if (o->emitted_symbols)
1535 append_emitted_diff_symbol(o, &e);
1536 else
1537 emit_diff_symbol_from_struct(o, &e);
1540 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1542 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1545 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1547 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1550 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1552 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1553 path, strlen(path), 0);
1556 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1558 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1559 path, strlen(path), 0);
1562 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1564 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1565 header, strlen(header), 0);
1568 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1570 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1573 void diff_emit_submodule_pipethrough(struct diff_options *o,
1574 const char *line, int len)
1576 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1579 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1581 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1582 ecbdata->blank_at_eof_in_preimage &&
1583 ecbdata->blank_at_eof_in_postimage &&
1584 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1585 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1586 return 0;
1587 return ws_blank_line(line, len);
1590 static void emit_add_line(struct emit_callback *ecbdata,
1591 const char *line, int len)
1593 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1594 if (new_blank_line_at_eof(ecbdata, line, len))
1595 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1597 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1600 static void emit_del_line(struct emit_callback *ecbdata,
1601 const char *line, int len)
1603 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1604 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1607 static void emit_context_line(struct emit_callback *ecbdata,
1608 const char *line, int len)
1610 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1611 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1614 static void emit_hunk_header(struct emit_callback *ecbdata,
1615 const char *line, int len)
1617 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1618 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1619 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1620 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1621 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1622 static const char atat[2] = { '@', '@' };
1623 const char *cp, *ep;
1624 struct strbuf msgbuf = STRBUF_INIT;
1625 int org_len = len;
1626 int i = 1;
1629 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1630 * it always is at least 10 bytes long.
1632 if (len < 10 ||
1633 memcmp(line, atat, 2) ||
1634 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1635 emit_diff_symbol(ecbdata->opt,
1636 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1637 return;
1639 ep += 2; /* skip over @@ */
1641 /* The hunk header in fraginfo color */
1642 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1643 strbuf_addstr(&msgbuf, reverse);
1644 strbuf_addstr(&msgbuf, frag);
1645 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1646 strbuf_add(&msgbuf, atat, sizeof(atat));
1647 else
1648 strbuf_add(&msgbuf, line, ep - line);
1649 strbuf_addstr(&msgbuf, reset);
1652 * trailing "\r\n"
1654 for ( ; i < 3; i++)
1655 if (line[len - i] == '\r' || line[len - i] == '\n')
1656 len--;
1658 /* blank before the func header */
1659 for (cp = ep; ep - line < len; ep++)
1660 if (*ep != ' ' && *ep != '\t')
1661 break;
1662 if (ep != cp) {
1663 strbuf_addstr(&msgbuf, context);
1664 strbuf_add(&msgbuf, cp, ep - cp);
1665 strbuf_addstr(&msgbuf, reset);
1668 if (ep < line + len) {
1669 strbuf_addstr(&msgbuf, func);
1670 strbuf_add(&msgbuf, ep, line + len - ep);
1671 strbuf_addstr(&msgbuf, reset);
1674 strbuf_add(&msgbuf, line + len, org_len - len);
1675 strbuf_complete_line(&msgbuf);
1676 emit_diff_symbol(ecbdata->opt,
1677 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1678 strbuf_release(&msgbuf);
1681 static struct diff_tempfile *claim_diff_tempfile(void)
1683 int i;
1684 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1685 if (!diff_temp[i].name)
1686 return diff_temp + i;
1687 BUG("diff is failing to clean up its tempfiles");
1690 static void remove_tempfile(void)
1692 int i;
1693 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1694 if (is_tempfile_active(diff_temp[i].tempfile))
1695 delete_tempfile(&diff_temp[i].tempfile);
1696 diff_temp[i].name = NULL;
1700 static void add_line_count(struct strbuf *out, int count)
1702 switch (count) {
1703 case 0:
1704 strbuf_addstr(out, "0,0");
1705 break;
1706 case 1:
1707 strbuf_addstr(out, "1");
1708 break;
1709 default:
1710 strbuf_addf(out, "1,%d", count);
1711 break;
1715 static void emit_rewrite_lines(struct emit_callback *ecb,
1716 int prefix, const char *data, int size)
1718 const char *endp = NULL;
1720 while (0 < size) {
1721 int len;
1723 endp = memchr(data, '\n', size);
1724 len = endp ? (endp - data + 1) : size;
1725 if (prefix != '+') {
1726 ecb->lno_in_preimage++;
1727 emit_del_line(ecb, data, len);
1728 } else {
1729 ecb->lno_in_postimage++;
1730 emit_add_line(ecb, data, len);
1732 size -= len;
1733 data += len;
1735 if (!endp)
1736 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1739 static void emit_rewrite_diff(const char *name_a,
1740 const char *name_b,
1741 struct diff_filespec *one,
1742 struct diff_filespec *two,
1743 struct userdiff_driver *textconv_one,
1744 struct userdiff_driver *textconv_two,
1745 struct diff_options *o)
1747 int lc_a, lc_b;
1748 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1749 const char *a_prefix, *b_prefix;
1750 char *data_one, *data_two;
1751 size_t size_one, size_two;
1752 struct emit_callback ecbdata;
1753 struct strbuf out = STRBUF_INIT;
1755 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1756 a_prefix = o->b_prefix;
1757 b_prefix = o->a_prefix;
1758 } else {
1759 a_prefix = o->a_prefix;
1760 b_prefix = o->b_prefix;
1763 name_a += (*name_a == '/');
1764 name_b += (*name_b == '/');
1766 strbuf_reset(&a_name);
1767 strbuf_reset(&b_name);
1768 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1769 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1771 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1772 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1774 memset(&ecbdata, 0, sizeof(ecbdata));
1775 ecbdata.color_diff = want_color(o->use_color);
1776 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1777 ecbdata.opt = o;
1778 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1779 mmfile_t mf1, mf2;
1780 mf1.ptr = (char *)data_one;
1781 mf2.ptr = (char *)data_two;
1782 mf1.size = size_one;
1783 mf2.size = size_two;
1784 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1786 ecbdata.lno_in_preimage = 1;
1787 ecbdata.lno_in_postimage = 1;
1789 lc_a = count_lines(data_one, size_one);
1790 lc_b = count_lines(data_two, size_two);
1792 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1793 a_name.buf, a_name.len, 0);
1794 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1795 b_name.buf, b_name.len, 0);
1797 strbuf_addstr(&out, "@@ -");
1798 if (!o->irreversible_delete)
1799 add_line_count(&out, lc_a);
1800 else
1801 strbuf_addstr(&out, "?,?");
1802 strbuf_addstr(&out, " +");
1803 add_line_count(&out, lc_b);
1804 strbuf_addstr(&out, " @@\n");
1805 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1806 strbuf_release(&out);
1808 if (lc_a && !o->irreversible_delete)
1809 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1810 if (lc_b)
1811 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1812 if (textconv_one)
1813 free((char *)data_one);
1814 if (textconv_two)
1815 free((char *)data_two);
1818 struct diff_words_buffer {
1819 mmfile_t text;
1820 unsigned long alloc;
1821 struct diff_words_orig {
1822 const char *begin, *end;
1823 } *orig;
1824 int orig_nr, orig_alloc;
1827 static void diff_words_append(char *line, unsigned long len,
1828 struct diff_words_buffer *buffer)
1830 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1831 line++;
1832 len--;
1833 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1834 buffer->text.size += len;
1835 buffer->text.ptr[buffer->text.size] = '\0';
1838 struct diff_words_style_elem {
1839 const char *prefix;
1840 const char *suffix;
1841 const char *color; /* NULL; filled in by the setup code if
1842 * color is enabled */
1845 struct diff_words_style {
1846 enum diff_words_type type;
1847 struct diff_words_style_elem new_word, old_word, ctx;
1848 const char *newline;
1851 static struct diff_words_style diff_words_styles[] = {
1852 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1853 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1854 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1857 struct diff_words_data {
1858 struct diff_words_buffer minus, plus;
1859 const char *current_plus;
1860 int last_minus;
1861 struct diff_options *opt;
1862 regex_t *word_regex;
1863 enum diff_words_type type;
1864 struct diff_words_style *style;
1867 static int fn_out_diff_words_write_helper(struct diff_options *o,
1868 struct diff_words_style_elem *st_el,
1869 const char *newline,
1870 size_t count, const char *buf)
1872 int print = 0;
1873 struct strbuf sb = STRBUF_INIT;
1875 while (count) {
1876 char *p = memchr(buf, '\n', count);
1877 if (print)
1878 strbuf_addstr(&sb, diff_line_prefix(o));
1880 if (p != buf) {
1881 const char *reset = st_el->color && *st_el->color ?
1882 GIT_COLOR_RESET : NULL;
1883 if (st_el->color && *st_el->color)
1884 strbuf_addstr(&sb, st_el->color);
1885 strbuf_addstr(&sb, st_el->prefix);
1886 strbuf_add(&sb, buf, p ? p - buf : count);
1887 strbuf_addstr(&sb, st_el->suffix);
1888 if (reset)
1889 strbuf_addstr(&sb, reset);
1891 if (!p)
1892 goto out;
1894 strbuf_addstr(&sb, newline);
1895 count -= p + 1 - buf;
1896 buf = p + 1;
1897 print = 1;
1898 if (count) {
1899 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1900 sb.buf, sb.len, 0);
1901 strbuf_reset(&sb);
1905 out:
1906 if (sb.len)
1907 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1908 sb.buf, sb.len, 0);
1909 strbuf_release(&sb);
1910 return 0;
1914 * '--color-words' algorithm can be described as:
1916 * 1. collect the minus/plus lines of a diff hunk, divided into
1917 * minus-lines and plus-lines;
1919 * 2. break both minus-lines and plus-lines into words and
1920 * place them into two mmfile_t with one word for each line;
1922 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1924 * And for the common parts of the both file, we output the plus side text.
1925 * diff_words->current_plus is used to trace the current position of the plus file
1926 * which printed. diff_words->last_minus is used to trace the last minus word
1927 * printed.
1929 * For '--graph' to work with '--color-words', we need to output the graph prefix
1930 * on each line of color words output. Generally, there are two conditions on
1931 * which we should output the prefix.
1933 * 1. diff_words->last_minus == 0 &&
1934 * diff_words->current_plus == diff_words->plus.text.ptr
1936 * that is: the plus text must start as a new line, and if there is no minus
1937 * word printed, a graph prefix must be printed.
1939 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1940 * *(diff_words->current_plus - 1) == '\n'
1942 * that is: a graph prefix must be printed following a '\n'
1944 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1946 if ((diff_words->last_minus == 0 &&
1947 diff_words->current_plus == diff_words->plus.text.ptr) ||
1948 (diff_words->current_plus > diff_words->plus.text.ptr &&
1949 *(diff_words->current_plus - 1) == '\n')) {
1950 return 1;
1951 } else {
1952 return 0;
1956 static void fn_out_diff_words_aux(void *priv,
1957 long minus_first, long minus_len,
1958 long plus_first, long plus_len,
1959 const char *func UNUSED, long funclen UNUSED)
1961 struct diff_words_data *diff_words = priv;
1962 struct diff_words_style *style = diff_words->style;
1963 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1964 struct diff_options *opt = diff_words->opt;
1965 const char *line_prefix;
1967 assert(opt);
1968 line_prefix = diff_line_prefix(opt);
1970 /* POSIX requires that first be decremented by one if len == 0... */
1971 if (minus_len) {
1972 minus_begin = diff_words->minus.orig[minus_first].begin;
1973 minus_end =
1974 diff_words->minus.orig[minus_first + minus_len - 1].end;
1975 } else
1976 minus_begin = minus_end =
1977 diff_words->minus.orig[minus_first].end;
1979 if (plus_len) {
1980 plus_begin = diff_words->plus.orig[plus_first].begin;
1981 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1982 } else
1983 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1985 if (color_words_output_graph_prefix(diff_words)) {
1986 fputs(line_prefix, diff_words->opt->file);
1988 if (diff_words->current_plus != plus_begin) {
1989 fn_out_diff_words_write_helper(diff_words->opt,
1990 &style->ctx, style->newline,
1991 plus_begin - diff_words->current_plus,
1992 diff_words->current_plus);
1994 if (minus_begin != minus_end) {
1995 fn_out_diff_words_write_helper(diff_words->opt,
1996 &style->old_word, style->newline,
1997 minus_end - minus_begin, minus_begin);
1999 if (plus_begin != plus_end) {
2000 fn_out_diff_words_write_helper(diff_words->opt,
2001 &style->new_word, style->newline,
2002 plus_end - plus_begin, plus_begin);
2005 diff_words->current_plus = plus_end;
2006 diff_words->last_minus = minus_first;
2009 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2010 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2011 int *begin, int *end)
2013 while (word_regex && *begin < buffer->size) {
2014 regmatch_t match[1];
2015 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2016 buffer->size - *begin, 1, match, 0)) {
2017 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2018 '\n', match[0].rm_eo - match[0].rm_so);
2019 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2020 *begin += match[0].rm_so;
2021 if (*begin == *end)
2022 (*begin)++;
2023 else
2024 return *begin > *end;
2025 } else {
2026 return -1;
2030 /* find the next word */
2031 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2032 (*begin)++;
2033 if (*begin >= buffer->size)
2034 return -1;
2036 /* find the end of the word */
2037 *end = *begin + 1;
2038 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2039 (*end)++;
2041 return 0;
2045 * This function splits the words in buffer->text, stores the list with
2046 * newline separator into out, and saves the offsets of the original words
2047 * in buffer->orig.
2049 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2050 regex_t *word_regex)
2052 int i, j;
2053 long alloc = 0;
2055 out->size = 0;
2056 out->ptr = NULL;
2058 /* fake an empty "0th" word */
2059 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2060 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2061 buffer->orig_nr = 1;
2063 for (i = 0; i < buffer->text.size; i++) {
2064 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2065 return;
2067 /* store original boundaries */
2068 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2069 buffer->orig_alloc);
2070 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2071 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2072 buffer->orig_nr++;
2074 /* store one word */
2075 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2076 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2077 out->ptr[out->size + j - i] = '\n';
2078 out->size += j - i + 1;
2080 i = j - 1;
2084 /* this executes the word diff on the accumulated buffers */
2085 static void diff_words_show(struct diff_words_data *diff_words)
2087 xpparam_t xpp;
2088 xdemitconf_t xecfg;
2089 mmfile_t minus, plus;
2090 struct diff_words_style *style = diff_words->style;
2092 struct diff_options *opt = diff_words->opt;
2093 const char *line_prefix;
2095 assert(opt);
2096 line_prefix = diff_line_prefix(opt);
2098 /* special case: only removal */
2099 if (!diff_words->plus.text.size) {
2100 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2101 line_prefix, strlen(line_prefix), 0);
2102 fn_out_diff_words_write_helper(diff_words->opt,
2103 &style->old_word, style->newline,
2104 diff_words->minus.text.size,
2105 diff_words->minus.text.ptr);
2106 diff_words->minus.text.size = 0;
2107 return;
2110 diff_words->current_plus = diff_words->plus.text.ptr;
2111 diff_words->last_minus = 0;
2113 memset(&xpp, 0, sizeof(xpp));
2114 memset(&xecfg, 0, sizeof(xecfg));
2115 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2116 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2117 xpp.flags = 0;
2118 /* as only the hunk header will be parsed, we need a 0-context */
2119 xecfg.ctxlen = 0;
2120 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2121 diff_words, &xpp, &xecfg))
2122 die("unable to generate word diff");
2123 free(minus.ptr);
2124 free(plus.ptr);
2125 if (diff_words->current_plus != diff_words->plus.text.ptr +
2126 diff_words->plus.text.size) {
2127 if (color_words_output_graph_prefix(diff_words))
2128 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2129 line_prefix, strlen(line_prefix), 0);
2130 fn_out_diff_words_write_helper(diff_words->opt,
2131 &style->ctx, style->newline,
2132 diff_words->plus.text.ptr + diff_words->plus.text.size
2133 - diff_words->current_plus, diff_words->current_plus);
2135 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2138 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2139 static void diff_words_flush(struct emit_callback *ecbdata)
2141 struct diff_options *wo = ecbdata->diff_words->opt;
2143 if (ecbdata->diff_words->minus.text.size ||
2144 ecbdata->diff_words->plus.text.size)
2145 diff_words_show(ecbdata->diff_words);
2147 if (wo->emitted_symbols) {
2148 struct diff_options *o = ecbdata->opt;
2149 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2150 int i;
2153 * NEEDSWORK:
2154 * Instead of appending each, concat all words to a line?
2156 for (i = 0; i < wol->nr; i++)
2157 append_emitted_diff_symbol(o, &wol->buf[i]);
2159 for (i = 0; i < wol->nr; i++)
2160 free((void *)wol->buf[i].line);
2162 wol->nr = 0;
2166 static void diff_filespec_load_driver(struct diff_filespec *one,
2167 struct index_state *istate)
2169 /* Use already-loaded driver */
2170 if (one->driver)
2171 return;
2173 if (S_ISREG(one->mode))
2174 one->driver = userdiff_find_by_path(istate, one->path);
2176 /* Fallback to default settings */
2177 if (!one->driver)
2178 one->driver = userdiff_find_by_name("default");
2181 static const char *userdiff_word_regex(struct diff_filespec *one,
2182 struct index_state *istate)
2184 diff_filespec_load_driver(one, istate);
2185 return one->driver->word_regex;
2188 static void init_diff_words_data(struct emit_callback *ecbdata,
2189 struct diff_options *orig_opts,
2190 struct diff_filespec *one,
2191 struct diff_filespec *two)
2193 int i;
2194 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2195 memcpy(o, orig_opts, sizeof(struct diff_options));
2197 CALLOC_ARRAY(ecbdata->diff_words, 1);
2198 ecbdata->diff_words->type = o->word_diff;
2199 ecbdata->diff_words->opt = o;
2201 if (orig_opts->emitted_symbols)
2202 CALLOC_ARRAY(o->emitted_symbols, 1);
2204 if (!o->word_regex)
2205 o->word_regex = userdiff_word_regex(one, o->repo->index);
2206 if (!o->word_regex)
2207 o->word_regex = userdiff_word_regex(two, o->repo->index);
2208 if (!o->word_regex)
2209 o->word_regex = diff_word_regex_cfg;
2210 if (o->word_regex) {
2211 ecbdata->diff_words->word_regex = (regex_t *)
2212 xmalloc(sizeof(regex_t));
2213 if (regcomp(ecbdata->diff_words->word_regex,
2214 o->word_regex,
2215 REG_EXTENDED | REG_NEWLINE))
2216 die("invalid regular expression: %s",
2217 o->word_regex);
2219 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2220 if (o->word_diff == diff_words_styles[i].type) {
2221 ecbdata->diff_words->style =
2222 &diff_words_styles[i];
2223 break;
2226 if (want_color(o->use_color)) {
2227 struct diff_words_style *st = ecbdata->diff_words->style;
2228 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2229 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2230 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2234 static void free_diff_words_data(struct emit_callback *ecbdata)
2236 if (ecbdata->diff_words) {
2237 diff_words_flush(ecbdata);
2238 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2239 free (ecbdata->diff_words->opt);
2240 free (ecbdata->diff_words->minus.text.ptr);
2241 free (ecbdata->diff_words->minus.orig);
2242 free (ecbdata->diff_words->plus.text.ptr);
2243 free (ecbdata->diff_words->plus.orig);
2244 if (ecbdata->diff_words->word_regex) {
2245 regfree(ecbdata->diff_words->word_regex);
2246 free(ecbdata->diff_words->word_regex);
2248 FREE_AND_NULL(ecbdata->diff_words);
2252 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2254 if (want_color(diff_use_color))
2255 return diff_colors[ix];
2256 return "";
2259 const char *diff_line_prefix(struct diff_options *opt)
2261 struct strbuf *msgbuf;
2262 if (!opt->output_prefix)
2263 return "";
2265 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2266 return msgbuf->buf;
2269 static unsigned long sane_truncate_line(char *line, unsigned long len)
2271 const char *cp;
2272 unsigned long allot;
2273 size_t l = len;
2275 cp = line;
2276 allot = l;
2277 while (0 < l) {
2278 (void) utf8_width(&cp, &l);
2279 if (!cp)
2280 break; /* truncated in the middle? */
2282 return allot - l;
2285 static void find_lno(const char *line, struct emit_callback *ecbdata)
2287 const char *p;
2288 ecbdata->lno_in_preimage = 0;
2289 ecbdata->lno_in_postimage = 0;
2290 p = strchr(line, '-');
2291 if (!p)
2292 return; /* cannot happen */
2293 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2294 p = strchr(p, '+');
2295 if (!p)
2296 return; /* cannot happen */
2297 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2300 static int fn_out_consume(void *priv, char *line, unsigned long len)
2302 struct emit_callback *ecbdata = priv;
2303 struct diff_options *o = ecbdata->opt;
2305 o->found_changes = 1;
2307 if (ecbdata->header) {
2308 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2309 ecbdata->header->buf, ecbdata->header->len, 0);
2310 strbuf_reset(ecbdata->header);
2311 ecbdata->header = NULL;
2314 if (ecbdata->label_path[0]) {
2315 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2316 ecbdata->label_path[0],
2317 strlen(ecbdata->label_path[0]), 0);
2318 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2319 ecbdata->label_path[1],
2320 strlen(ecbdata->label_path[1]), 0);
2321 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2324 if (diff_suppress_blank_empty
2325 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2326 line[0] = '\n';
2327 len = 1;
2330 if (line[0] == '@') {
2331 if (ecbdata->diff_words)
2332 diff_words_flush(ecbdata);
2333 len = sane_truncate_line(line, len);
2334 find_lno(line, ecbdata);
2335 emit_hunk_header(ecbdata, line, len);
2336 return 0;
2339 if (ecbdata->diff_words) {
2340 enum diff_symbol s =
2341 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2342 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2343 if (line[0] == '-') {
2344 diff_words_append(line, len,
2345 &ecbdata->diff_words->minus);
2346 return 0;
2347 } else if (line[0] == '+') {
2348 diff_words_append(line, len,
2349 &ecbdata->diff_words->plus);
2350 return 0;
2351 } else if (starts_with(line, "\\ ")) {
2353 * Eat the "no newline at eof" marker as if we
2354 * saw a "+" or "-" line with nothing on it,
2355 * and return without diff_words_flush() to
2356 * defer processing. If this is the end of
2357 * preimage, more "+" lines may come after it.
2359 return 0;
2361 diff_words_flush(ecbdata);
2362 emit_diff_symbol(o, s, line, len, 0);
2363 return 0;
2366 switch (line[0]) {
2367 case '+':
2368 ecbdata->lno_in_postimage++;
2369 emit_add_line(ecbdata, line + 1, len - 1);
2370 break;
2371 case '-':
2372 ecbdata->lno_in_preimage++;
2373 emit_del_line(ecbdata, line + 1, len - 1);
2374 break;
2375 case ' ':
2376 ecbdata->lno_in_postimage++;
2377 ecbdata->lno_in_preimage++;
2378 emit_context_line(ecbdata, line + 1, len - 1);
2379 break;
2380 default:
2381 /* incomplete line at the end */
2382 ecbdata->lno_in_preimage++;
2383 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2384 line, len, 0);
2385 break;
2387 return 0;
2390 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2392 const char *old_name = a;
2393 const char *new_name = b;
2394 int pfx_length, sfx_length;
2395 int pfx_adjust_for_slash;
2396 int len_a = strlen(a);
2397 int len_b = strlen(b);
2398 int a_midlen, b_midlen;
2399 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2400 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2402 if (qlen_a || qlen_b) {
2403 quote_c_style(a, name, NULL, 0);
2404 strbuf_addstr(name, " => ");
2405 quote_c_style(b, name, NULL, 0);
2406 return;
2409 /* Find common prefix */
2410 pfx_length = 0;
2411 while (*old_name && *new_name && *old_name == *new_name) {
2412 if (*old_name == '/')
2413 pfx_length = old_name - a + 1;
2414 old_name++;
2415 new_name++;
2418 /* Find common suffix */
2419 old_name = a + len_a;
2420 new_name = b + len_b;
2421 sfx_length = 0;
2423 * If there is a common prefix, it must end in a slash. In
2424 * that case we let this loop run 1 into the prefix to see the
2425 * same slash.
2427 * If there is no common prefix, we cannot do this as it would
2428 * underrun the input strings.
2430 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2431 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2432 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2433 *old_name == *new_name) {
2434 if (*old_name == '/')
2435 sfx_length = len_a - (old_name - a);
2436 old_name--;
2437 new_name--;
2441 * pfx{mid-a => mid-b}sfx
2442 * {pfx-a => pfx-b}sfx
2443 * pfx{sfx-a => sfx-b}
2444 * name-a => name-b
2446 a_midlen = len_a - pfx_length - sfx_length;
2447 b_midlen = len_b - pfx_length - sfx_length;
2448 if (a_midlen < 0)
2449 a_midlen = 0;
2450 if (b_midlen < 0)
2451 b_midlen = 0;
2453 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2454 if (pfx_length + sfx_length) {
2455 strbuf_add(name, a, pfx_length);
2456 strbuf_addch(name, '{');
2458 strbuf_add(name, a + pfx_length, a_midlen);
2459 strbuf_addstr(name, " => ");
2460 strbuf_add(name, b + pfx_length, b_midlen);
2461 if (pfx_length + sfx_length) {
2462 strbuf_addch(name, '}');
2463 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2467 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2468 const char *name_a,
2469 const char *name_b)
2471 struct diffstat_file *x;
2472 CALLOC_ARRAY(x, 1);
2473 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2474 diffstat->files[diffstat->nr++] = x;
2475 if (name_b) {
2476 x->from_name = xstrdup(name_a);
2477 x->name = xstrdup(name_b);
2478 x->is_renamed = 1;
2480 else {
2481 x->from_name = NULL;
2482 x->name = xstrdup(name_a);
2484 return x;
2487 static int diffstat_consume(void *priv, char *line, unsigned long len)
2489 struct diffstat_t *diffstat = priv;
2490 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2492 if (!len)
2493 BUG("xdiff fed us an empty line");
2495 if (line[0] == '+')
2496 x->added++;
2497 else if (line[0] == '-')
2498 x->deleted++;
2499 return 0;
2502 const char mime_boundary_leader[] = "------------";
2504 static int scale_linear(int it, int width, int max_change)
2506 if (!it)
2507 return 0;
2509 * make sure that at least one '-' or '+' is printed if
2510 * there is any change to this path. The easiest way is to
2511 * scale linearly as if the allotted width is one column shorter
2512 * than it is, and then add 1 to the result.
2514 return 1 + (it * (width - 1) / max_change);
2517 static void show_graph(struct strbuf *out, char ch, int cnt,
2518 const char *set, const char *reset)
2520 if (cnt <= 0)
2521 return;
2522 strbuf_addstr(out, set);
2523 strbuf_addchars(out, ch, cnt);
2524 strbuf_addstr(out, reset);
2527 static void fill_print_name(struct diffstat_file *file)
2529 struct strbuf pname = STRBUF_INIT;
2531 if (file->print_name)
2532 return;
2534 if (file->is_renamed)
2535 pprint_rename(&pname, file->from_name, file->name);
2536 else
2537 quote_c_style(file->name, &pname, NULL, 0);
2539 if (file->comments)
2540 strbuf_addf(&pname, " (%s)", file->comments);
2542 file->print_name = strbuf_detach(&pname, NULL);
2545 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2546 int files, int insertions, int deletions)
2548 struct strbuf sb = STRBUF_INIT;
2550 if (!files) {
2551 assert(insertions == 0 && deletions == 0);
2552 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2553 NULL, 0, 0);
2554 return;
2557 strbuf_addf(&sb,
2558 (files == 1) ? " %d file changed" : " %d files changed",
2559 files);
2562 * For binary diff, the caller may want to print "x files
2563 * changed" with insertions == 0 && deletions == 0.
2565 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2566 * is probably less confusing (i.e skip over "2 files changed
2567 * but nothing about added/removed lines? Is this a bug in Git?").
2569 if (insertions || deletions == 0) {
2570 strbuf_addf(&sb,
2571 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2572 insertions);
2575 if (deletions || insertions == 0) {
2576 strbuf_addf(&sb,
2577 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2578 deletions);
2580 strbuf_addch(&sb, '\n');
2581 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2582 sb.buf, sb.len, 0);
2583 strbuf_release(&sb);
2586 void print_stat_summary(FILE *fp, int files,
2587 int insertions, int deletions)
2589 struct diff_options o;
2590 memset(&o, 0, sizeof(o));
2591 o.file = fp;
2593 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2596 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2598 int i, len, add, del, adds = 0, dels = 0;
2599 uintmax_t max_change = 0, max_len = 0;
2600 int total_files = data->nr, count;
2601 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2602 const char *reset, *add_c, *del_c;
2603 int extra_shown = 0;
2604 const char *line_prefix = diff_line_prefix(options);
2605 struct strbuf out = STRBUF_INIT;
2607 if (data->nr == 0)
2608 return;
2610 count = options->stat_count ? options->stat_count : data->nr;
2612 reset = diff_get_color_opt(options, DIFF_RESET);
2613 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2614 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2617 * Find the longest filename and max number of changes
2619 for (i = 0; (i < count) && (i < data->nr); i++) {
2620 struct diffstat_file *file = data->files[i];
2621 uintmax_t change = file->added + file->deleted;
2623 if (!file->is_interesting && (change == 0)) {
2624 count++; /* not shown == room for one more */
2625 continue;
2627 fill_print_name(file);
2628 len = utf8_strwidth(file->print_name);
2629 if (max_len < len)
2630 max_len = len;
2632 if (file->is_unmerged) {
2633 /* "Unmerged" is 8 characters */
2634 bin_width = bin_width < 8 ? 8 : bin_width;
2635 continue;
2637 if (file->is_binary) {
2638 /* "Bin XXX -> YYY bytes" */
2639 int w = 14 + decimal_width(file->added)
2640 + decimal_width(file->deleted);
2641 bin_width = bin_width < w ? w : bin_width;
2642 /* Display change counts aligned with "Bin" */
2643 number_width = 3;
2644 continue;
2647 if (max_change < change)
2648 max_change = change;
2650 count = i; /* where we can stop scanning in data->files[] */
2653 * We have width = stat_width or term_columns() columns total.
2654 * We want a maximum of min(max_len, stat_name_width) for the name part.
2655 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2656 * We also need 1 for " " and 4 + decimal_width(max_change)
2657 * for " | NNNN " and one the empty column at the end, altogether
2658 * 6 + decimal_width(max_change).
2660 * If there's not enough space, we will use the smaller of
2661 * stat_name_width (if set) and 5/8*width for the filename,
2662 * and the rest for constant elements + graph part, but no more
2663 * than stat_graph_width for the graph part.
2664 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2665 * for the standard terminal size).
2667 * In other words: stat_width limits the maximum width, and
2668 * stat_name_width fixes the maximum width of the filename,
2669 * and is also used to divide available columns if there
2670 * aren't enough.
2672 * Binary files are displayed with "Bin XXX -> YYY bytes"
2673 * instead of the change count and graph. This part is treated
2674 * similarly to the graph part, except that it is not
2675 * "scaled". If total width is too small to accommodate the
2676 * guaranteed minimum width of the filename part and the
2677 * separators and this message, this message will "overflow"
2678 * making the line longer than the maximum width.
2682 * NEEDSWORK: line_prefix is often used for "log --graph" output
2683 * and contains ANSI-colored string. utf8_strnwidth() should be
2684 * used to correctly count the display width instead of strlen().
2686 if (options->stat_width == -1)
2687 width = term_columns() - strlen(line_prefix);
2688 else
2689 width = options->stat_width ? options->stat_width : 80;
2690 number_width = decimal_width(max_change) > number_width ?
2691 decimal_width(max_change) : number_width;
2693 if (options->stat_graph_width == -1)
2694 options->stat_graph_width = diff_stat_graph_width;
2697 * Guarantee 3/8*16==6 for the graph part
2698 * and 5/8*16==10 for the filename part
2700 if (width < 16 + 6 + number_width)
2701 width = 16 + 6 + number_width;
2704 * First assign sizes that are wanted, ignoring available width.
2705 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2706 * starting from "XXX" should fit in graph_width.
2708 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2709 if (options->stat_graph_width &&
2710 options->stat_graph_width < graph_width)
2711 graph_width = options->stat_graph_width;
2713 name_width = (options->stat_name_width > 0 &&
2714 options->stat_name_width < max_len) ?
2715 options->stat_name_width : max_len;
2718 * Adjust adjustable widths not to exceed maximum width
2720 if (name_width + number_width + 6 + graph_width > width) {
2721 if (graph_width > width * 3/8 - number_width - 6) {
2722 graph_width = width * 3/8 - number_width - 6;
2723 if (graph_width < 6)
2724 graph_width = 6;
2727 if (options->stat_graph_width &&
2728 graph_width > options->stat_graph_width)
2729 graph_width = options->stat_graph_width;
2730 if (name_width > width - number_width - 6 - graph_width)
2731 name_width = width - number_width - 6 - graph_width;
2732 else
2733 graph_width = width - number_width - 6 - name_width;
2737 * From here name_width is the width of the name area,
2738 * and graph_width is the width of the graph area.
2739 * max_change is used to scale graph properly.
2741 for (i = 0; i < count; i++) {
2742 const char *prefix = "";
2743 struct diffstat_file *file = data->files[i];
2744 char *name = file->print_name;
2745 uintmax_t added = file->added;
2746 uintmax_t deleted = file->deleted;
2747 int name_len, padding;
2749 if (!file->is_interesting && (added + deleted == 0))
2750 continue;
2753 * "scale" the filename
2755 len = name_width;
2756 name_len = utf8_strwidth(name);
2757 if (name_width < name_len) {
2758 char *slash;
2759 prefix = "...";
2760 len -= 3;
2762 * NEEDSWORK: (name_len - len) counts the display
2763 * width, which would be shorter than the byte
2764 * length of the corresponding substring.
2765 * Advancing "name" by that number of bytes does
2766 * *NOT* skip over that many columns, so it is
2767 * very likely that chomping the pathname at the
2768 * slash we will find starting from "name" will
2769 * leave the resulting string still too long.
2771 name += name_len - len;
2772 slash = strchr(name, '/');
2773 if (slash)
2774 name = slash;
2776 padding = len - utf8_strwidth(name);
2777 if (padding < 0)
2778 padding = 0;
2780 if (file->is_binary) {
2781 strbuf_addf(&out, " %s%s%*s | %*s",
2782 prefix, name, padding, "",
2783 number_width, "Bin");
2784 if (!added && !deleted) {
2785 strbuf_addch(&out, '\n');
2786 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2787 out.buf, out.len, 0);
2788 strbuf_reset(&out);
2789 continue;
2791 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2792 del_c, deleted, reset);
2793 strbuf_addstr(&out, " -> ");
2794 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2795 add_c, added, reset);
2796 strbuf_addstr(&out, " bytes\n");
2797 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2798 out.buf, out.len, 0);
2799 strbuf_reset(&out);
2800 continue;
2802 else if (file->is_unmerged) {
2803 strbuf_addf(&out, " %s%s%*s | %*s",
2804 prefix, name, padding, "",
2805 number_width, "Unmerged\n");
2806 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2807 out.buf, out.len, 0);
2808 strbuf_reset(&out);
2809 continue;
2813 * scale the add/delete
2815 add = added;
2816 del = deleted;
2818 if (graph_width <= max_change) {
2819 int total = scale_linear(add + del, graph_width, max_change);
2820 if (total < 2 && add && del)
2821 /* width >= 2 due to the sanity check */
2822 total = 2;
2823 if (add < del) {
2824 add = scale_linear(add, graph_width, max_change);
2825 del = total - add;
2826 } else {
2827 del = scale_linear(del, graph_width, max_change);
2828 add = total - del;
2831 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2832 prefix, name, padding, "",
2833 number_width, added + deleted,
2834 added + deleted ? " " : "");
2835 show_graph(&out, '+', add, add_c, reset);
2836 show_graph(&out, '-', del, del_c, reset);
2837 strbuf_addch(&out, '\n');
2838 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2839 out.buf, out.len, 0);
2840 strbuf_reset(&out);
2843 for (i = 0; i < data->nr; i++) {
2844 struct diffstat_file *file = data->files[i];
2845 uintmax_t added = file->added;
2846 uintmax_t deleted = file->deleted;
2848 if (file->is_unmerged ||
2849 (!file->is_interesting && (added + deleted == 0))) {
2850 total_files--;
2851 continue;
2854 if (!file->is_binary) {
2855 adds += added;
2856 dels += deleted;
2858 if (i < count)
2859 continue;
2860 if (!extra_shown)
2861 emit_diff_symbol(options,
2862 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2863 NULL, 0, 0);
2864 extra_shown = 1;
2867 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2868 strbuf_release(&out);
2871 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2873 int i, adds = 0, dels = 0, total_files = data->nr;
2875 if (data->nr == 0)
2876 return;
2878 for (i = 0; i < data->nr; i++) {
2879 int added = data->files[i]->added;
2880 int deleted = data->files[i]->deleted;
2882 if (data->files[i]->is_unmerged ||
2883 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2884 total_files--;
2885 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2886 adds += added;
2887 dels += deleted;
2890 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2893 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2895 int i;
2897 if (data->nr == 0)
2898 return;
2900 for (i = 0; i < data->nr; i++) {
2901 struct diffstat_file *file = data->files[i];
2903 fprintf(options->file, "%s", diff_line_prefix(options));
2905 if (file->is_binary)
2906 fprintf(options->file, "-\t-\t");
2907 else
2908 fprintf(options->file,
2909 "%"PRIuMAX"\t%"PRIuMAX"\t",
2910 file->added, file->deleted);
2911 if (options->line_termination) {
2912 fill_print_name(file);
2913 if (!file->is_renamed)
2914 write_name_quoted(file->name, options->file,
2915 options->line_termination);
2916 else {
2917 fputs(file->print_name, options->file);
2918 putc(options->line_termination, options->file);
2920 } else {
2921 if (file->is_renamed) {
2922 putc('\0', options->file);
2923 write_name_quoted(file->from_name, options->file, '\0');
2925 write_name_quoted(file->name, options->file, '\0');
2930 struct dirstat_file {
2931 const char *name;
2932 unsigned long changed;
2935 struct dirstat_dir {
2936 struct dirstat_file *files;
2937 int alloc, nr, permille, cumulative;
2940 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2941 unsigned long changed, const char *base, int baselen)
2943 unsigned long sum_changes = 0;
2944 unsigned int sources = 0;
2945 const char *line_prefix = diff_line_prefix(opt);
2947 while (dir->nr) {
2948 struct dirstat_file *f = dir->files;
2949 int namelen = strlen(f->name);
2950 unsigned long changes;
2951 char *slash;
2953 if (namelen < baselen)
2954 break;
2955 if (memcmp(f->name, base, baselen))
2956 break;
2957 slash = strchr(f->name + baselen, '/');
2958 if (slash) {
2959 int newbaselen = slash + 1 - f->name;
2960 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2961 sources++;
2962 } else {
2963 changes = f->changed;
2964 dir->files++;
2965 dir->nr--;
2966 sources += 2;
2968 sum_changes += changes;
2972 * We don't report dirstat's for
2973 * - the top level
2974 * - or cases where everything came from a single directory
2975 * under this directory (sources == 1).
2977 if (baselen && sources != 1) {
2978 if (sum_changes) {
2979 int permille = sum_changes * 1000 / changed;
2980 if (permille >= dir->permille) {
2981 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2982 permille / 10, permille % 10, baselen, base);
2983 if (!dir->cumulative)
2984 return 0;
2988 return sum_changes;
2991 static int dirstat_compare(const void *_a, const void *_b)
2993 const struct dirstat_file *a = _a;
2994 const struct dirstat_file *b = _b;
2995 return strcmp(a->name, b->name);
2998 static void show_dirstat(struct diff_options *options)
3000 int i;
3001 unsigned long changed;
3002 struct dirstat_dir dir;
3003 struct diff_queue_struct *q = &diff_queued_diff;
3005 dir.files = NULL;
3006 dir.alloc = 0;
3007 dir.nr = 0;
3008 dir.permille = options->dirstat_permille;
3009 dir.cumulative = options->flags.dirstat_cumulative;
3011 changed = 0;
3012 for (i = 0; i < q->nr; i++) {
3013 struct diff_filepair *p = q->queue[i];
3014 const char *name;
3015 unsigned long copied, added, damage;
3016 struct diff_populate_filespec_options dpf_options = {
3017 .check_size_only = 1,
3020 name = p->two->path ? p->two->path : p->one->path;
3022 if (p->one->oid_valid && p->two->oid_valid &&
3023 oideq(&p->one->oid, &p->two->oid)) {
3025 * The SHA1 has not changed, so pre-/post-content is
3026 * identical. We can therefore skip looking at the
3027 * file contents altogether.
3029 damage = 0;
3030 goto found_damage;
3033 if (options->flags.dirstat_by_file) {
3035 * In --dirstat-by-file mode, we don't really need to
3036 * look at the actual file contents at all.
3037 * The fact that the SHA1 changed is enough for us to
3038 * add this file to the list of results
3039 * (with each file contributing equal damage).
3041 damage = 1;
3042 goto found_damage;
3045 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3046 diff_populate_filespec(options->repo, p->one, NULL);
3047 diff_populate_filespec(options->repo, p->two, NULL);
3048 diffcore_count_changes(options->repo,
3049 p->one, p->two, NULL, NULL,
3050 &copied, &added);
3051 diff_free_filespec_data(p->one);
3052 diff_free_filespec_data(p->two);
3053 } else if (DIFF_FILE_VALID(p->one)) {
3054 diff_populate_filespec(options->repo, p->one, &dpf_options);
3055 copied = added = 0;
3056 diff_free_filespec_data(p->one);
3057 } else if (DIFF_FILE_VALID(p->two)) {
3058 diff_populate_filespec(options->repo, p->two, &dpf_options);
3059 copied = 0;
3060 added = p->two->size;
3061 diff_free_filespec_data(p->two);
3062 } else
3063 continue;
3066 * Original minus copied is the removed material,
3067 * added is the new material. They are both damages
3068 * made to the preimage.
3069 * If the resulting damage is zero, we know that
3070 * diffcore_count_changes() considers the two entries to
3071 * be identical, but since the oid changed, we
3072 * know that there must have been _some_ kind of change,
3073 * so we force all entries to have damage > 0.
3075 damage = (p->one->size - copied) + added;
3076 if (!damage)
3077 damage = 1;
3079 found_damage:
3080 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3081 dir.files[dir.nr].name = name;
3082 dir.files[dir.nr].changed = damage;
3083 changed += damage;
3084 dir.nr++;
3087 /* This can happen even with many files, if everything was renames */
3088 if (!changed)
3089 return;
3091 /* Show all directories with more than x% of the changes */
3092 QSORT(dir.files, dir.nr, dirstat_compare);
3093 gather_dirstat(options, &dir, changed, "", 0);
3096 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3098 int i;
3099 unsigned long changed;
3100 struct dirstat_dir dir;
3102 if (data->nr == 0)
3103 return;
3105 dir.files = NULL;
3106 dir.alloc = 0;
3107 dir.nr = 0;
3108 dir.permille = options->dirstat_permille;
3109 dir.cumulative = options->flags.dirstat_cumulative;
3111 changed = 0;
3112 for (i = 0; i < data->nr; i++) {
3113 struct diffstat_file *file = data->files[i];
3114 unsigned long damage = file->added + file->deleted;
3115 if (file->is_binary)
3117 * binary files counts bytes, not lines. Must find some
3118 * way to normalize binary bytes vs. textual lines.
3119 * The following heuristic assumes that there are 64
3120 * bytes per "line".
3121 * This is stupid and ugly, but very cheap...
3123 damage = DIV_ROUND_UP(damage, 64);
3124 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3125 dir.files[dir.nr].name = file->name;
3126 dir.files[dir.nr].changed = damage;
3127 changed += damage;
3128 dir.nr++;
3131 /* This can happen even with many files, if everything was renames */
3132 if (!changed)
3133 return;
3135 /* Show all directories with more than x% of the changes */
3136 QSORT(dir.files, dir.nr, dirstat_compare);
3137 gather_dirstat(options, &dir, changed, "", 0);
3140 static void free_diffstat_file(struct diffstat_file *f)
3142 free(f->print_name);
3143 free(f->name);
3144 free(f->from_name);
3145 free(f);
3148 void free_diffstat_info(struct diffstat_t *diffstat)
3150 int i;
3151 for (i = 0; i < diffstat->nr; i++)
3152 free_diffstat_file(diffstat->files[i]);
3153 free(diffstat->files);
3156 struct checkdiff_t {
3157 const char *filename;
3158 int lineno;
3159 int conflict_marker_size;
3160 struct diff_options *o;
3161 unsigned ws_rule;
3162 unsigned status;
3165 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3167 char firstchar;
3168 int cnt;
3170 if (len < marker_size + 1)
3171 return 0;
3172 firstchar = line[0];
3173 switch (firstchar) {
3174 case '=': case '>': case '<': case '|':
3175 break;
3176 default:
3177 return 0;
3179 for (cnt = 1; cnt < marker_size; cnt++)
3180 if (line[cnt] != firstchar)
3181 return 0;
3182 /* line[1] through line[marker_size-1] are same as firstchar */
3183 if (len < marker_size + 1 || !isspace(line[marker_size]))
3184 return 0;
3185 return 1;
3188 static void checkdiff_consume_hunk(void *priv,
3189 long ob UNUSED, long on UNUSED,
3190 long nb, long nn UNUSED,
3191 const char *func UNUSED, long funclen UNUSED)
3194 struct checkdiff_t *data = priv;
3195 data->lineno = nb - 1;
3198 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3200 struct checkdiff_t *data = priv;
3201 int marker_size = data->conflict_marker_size;
3202 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3203 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3204 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3205 char *err;
3206 const char *line_prefix;
3208 assert(data->o);
3209 line_prefix = diff_line_prefix(data->o);
3211 if (line[0] == '+') {
3212 unsigned bad;
3213 data->lineno++;
3214 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3215 data->status |= 1;
3216 fprintf(data->o->file,
3217 "%s%s:%d: leftover conflict marker\n",
3218 line_prefix, data->filename, data->lineno);
3220 bad = ws_check(line + 1, len - 1, data->ws_rule);
3221 if (!bad)
3222 return 0;
3223 data->status |= bad;
3224 err = whitespace_error_string(bad);
3225 fprintf(data->o->file, "%s%s:%d: %s.\n",
3226 line_prefix, data->filename, data->lineno, err);
3227 free(err);
3228 emit_line(data->o, set, reset, line, 1);
3229 ws_check_emit(line + 1, len - 1, data->ws_rule,
3230 data->o->file, set, reset, ws);
3231 } else if (line[0] == ' ') {
3232 data->lineno++;
3234 return 0;
3237 static unsigned char *deflate_it(char *data,
3238 unsigned long size,
3239 unsigned long *result_size)
3241 int bound;
3242 unsigned char *deflated;
3243 git_zstream stream;
3245 git_deflate_init(&stream, zlib_compression_level);
3246 bound = git_deflate_bound(&stream, size);
3247 deflated = xmalloc(bound);
3248 stream.next_out = deflated;
3249 stream.avail_out = bound;
3251 stream.next_in = (unsigned char *)data;
3252 stream.avail_in = size;
3253 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3254 ; /* nothing */
3255 git_deflate_end(&stream);
3256 *result_size = stream.total_out;
3257 return deflated;
3260 static void emit_binary_diff_body(struct diff_options *o,
3261 mmfile_t *one, mmfile_t *two)
3263 void *cp;
3264 void *delta;
3265 void *deflated;
3266 void *data;
3267 unsigned long orig_size;
3268 unsigned long delta_size;
3269 unsigned long deflate_size;
3270 unsigned long data_size;
3272 /* We could do deflated delta, or we could do just deflated two,
3273 * whichever is smaller.
3275 delta = NULL;
3276 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3277 if (one->size && two->size) {
3278 delta = diff_delta(one->ptr, one->size,
3279 two->ptr, two->size,
3280 &delta_size, deflate_size);
3281 if (delta) {
3282 void *to_free = delta;
3283 orig_size = delta_size;
3284 delta = deflate_it(delta, delta_size, &delta_size);
3285 free(to_free);
3289 if (delta && delta_size < deflate_size) {
3290 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3291 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3292 s, strlen(s), 0);
3293 free(s);
3294 free(deflated);
3295 data = delta;
3296 data_size = delta_size;
3297 } else {
3298 char *s = xstrfmt("%lu", two->size);
3299 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3300 s, strlen(s), 0);
3301 free(s);
3302 free(delta);
3303 data = deflated;
3304 data_size = deflate_size;
3307 /* emit data encoded in base85 */
3308 cp = data;
3309 while (data_size) {
3310 int len;
3311 int bytes = (52 < data_size) ? 52 : data_size;
3312 char line[71];
3313 data_size -= bytes;
3314 if (bytes <= 26)
3315 line[0] = bytes + 'A' - 1;
3316 else
3317 line[0] = bytes - 26 + 'a' - 1;
3318 encode_85(line + 1, cp, bytes);
3319 cp = (char *) cp + bytes;
3321 len = strlen(line);
3322 line[len++] = '\n';
3323 line[len] = '\0';
3325 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3326 line, len, 0);
3328 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3329 free(data);
3332 static void emit_binary_diff(struct diff_options *o,
3333 mmfile_t *one, mmfile_t *two)
3335 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3336 emit_binary_diff_body(o, one, two);
3337 emit_binary_diff_body(o, two, one);
3340 int diff_filespec_is_binary(struct repository *r,
3341 struct diff_filespec *one)
3343 struct diff_populate_filespec_options dpf_options = {
3344 .check_binary = 1,
3347 if (one->is_binary == -1) {
3348 diff_filespec_load_driver(one, r->index);
3349 if (one->driver->binary != -1)
3350 one->is_binary = one->driver->binary;
3351 else {
3352 if (!one->data && DIFF_FILE_VALID(one))
3353 diff_populate_filespec(r, one, &dpf_options);
3354 if (one->is_binary == -1 && one->data)
3355 one->is_binary = buffer_is_binary(one->data,
3356 one->size);
3357 if (one->is_binary == -1)
3358 one->is_binary = 0;
3361 return one->is_binary;
3364 static const struct userdiff_funcname *
3365 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3367 diff_filespec_load_driver(one, o->repo->index);
3368 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3371 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3373 if (!options->a_prefix)
3374 options->a_prefix = a;
3375 if (!options->b_prefix)
3376 options->b_prefix = b;
3379 struct userdiff_driver *get_textconv(struct repository *r,
3380 struct diff_filespec *one)
3382 if (!DIFF_FILE_VALID(one))
3383 return NULL;
3385 diff_filespec_load_driver(one, r->index);
3386 return userdiff_get_textconv(r, one->driver);
3389 static struct string_list *additional_headers(struct diff_options *o,
3390 const char *path)
3392 if (!o->additional_path_headers)
3393 return NULL;
3394 return strmap_get(o->additional_path_headers, path);
3397 static void add_formatted_header(struct strbuf *msg,
3398 const char *header,
3399 const char *line_prefix,
3400 const char *meta,
3401 const char *reset)
3403 const char *next, *newline;
3405 for (next = header; *next; next = newline) {
3406 newline = strchrnul(next, '\n');
3407 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3408 (int)(newline - next), next, reset);
3409 if (*newline)
3410 newline++;
3414 static void add_formatted_headers(struct strbuf *msg,
3415 struct string_list *more_headers,
3416 const char *line_prefix,
3417 const char *meta,
3418 const char *reset)
3420 int i;
3422 for (i = 0; i < more_headers->nr; i++)
3423 add_formatted_header(msg, more_headers->items[i].string,
3424 line_prefix, meta, reset);
3427 static int diff_filepair_is_phoney(struct diff_filespec *one,
3428 struct diff_filespec *two)
3431 * This function specifically looks for pairs injected by
3432 * create_filepairs_for_header_only_notifications(). Such
3433 * pairs are "phoney" in that they do not represent any
3434 * content or even mode difference, but were inserted because
3435 * diff_queued_diff previously had no pair associated with
3436 * that path but we needed some pair to avoid losing the
3437 * "remerge CONFLICT" header associated with the path.
3439 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3442 static void builtin_diff(const char *name_a,
3443 const char *name_b,
3444 struct diff_filespec *one,
3445 struct diff_filespec *two,
3446 const char *xfrm_msg,
3447 int must_show_header,
3448 struct diff_options *o,
3449 int complete_rewrite)
3451 mmfile_t mf1, mf2;
3452 const char *lbl[2];
3453 char *a_one, *b_two;
3454 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3455 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3456 const char *a_prefix, *b_prefix;
3457 struct userdiff_driver *textconv_one = NULL;
3458 struct userdiff_driver *textconv_two = NULL;
3459 struct strbuf header = STRBUF_INIT;
3460 const char *line_prefix = diff_line_prefix(o);
3462 diff_set_mnemonic_prefix(o, "a/", "b/");
3463 if (o->flags.reverse_diff) {
3464 a_prefix = o->b_prefix;
3465 b_prefix = o->a_prefix;
3466 } else {
3467 a_prefix = o->a_prefix;
3468 b_prefix = o->b_prefix;
3471 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3472 (!one->mode || S_ISGITLINK(one->mode)) &&
3473 (!two->mode || S_ISGITLINK(two->mode)) &&
3474 (!diff_filepair_is_phoney(one, two))) {
3475 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3476 &one->oid, &two->oid,
3477 two->dirty_submodule);
3478 return;
3479 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3480 (!one->mode || S_ISGITLINK(one->mode)) &&
3481 (!two->mode || S_ISGITLINK(two->mode)) &&
3482 (!diff_filepair_is_phoney(one, two))) {
3483 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3484 &one->oid, &two->oid,
3485 two->dirty_submodule);
3486 return;
3489 if (o->flags.allow_textconv) {
3490 textconv_one = get_textconv(o->repo, one);
3491 textconv_two = get_textconv(o->repo, two);
3494 /* Never use a non-valid filename anywhere if at all possible */
3495 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3496 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3498 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3499 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3500 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3501 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3502 if (diff_filepair_is_phoney(one, two)) {
3504 * We should only reach this point for pairs generated from
3505 * create_filepairs_for_header_only_notifications(). For
3506 * these, we want to avoid the "/dev/null" special casing
3507 * above, because we do not want such pairs shown as either
3508 * "new file" or "deleted file" below.
3510 lbl[0] = a_one;
3511 lbl[1] = b_two;
3513 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3514 if (lbl[0][0] == '/') {
3515 /* /dev/null */
3516 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3517 if (xfrm_msg)
3518 strbuf_addstr(&header, xfrm_msg);
3519 must_show_header = 1;
3521 else if (lbl[1][0] == '/') {
3522 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3523 if (xfrm_msg)
3524 strbuf_addstr(&header, xfrm_msg);
3525 must_show_header = 1;
3527 else {
3528 if (one->mode != two->mode) {
3529 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3530 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3531 must_show_header = 1;
3533 if (xfrm_msg)
3534 strbuf_addstr(&header, xfrm_msg);
3537 * we do not run diff between different kind
3538 * of objects.
3540 if ((one->mode ^ two->mode) & S_IFMT)
3541 goto free_ab_and_return;
3542 if (complete_rewrite &&
3543 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3544 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3545 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3546 header.buf, header.len, 0);
3547 strbuf_reset(&header);
3548 emit_rewrite_diff(name_a, name_b, one, two,
3549 textconv_one, textconv_two, o);
3550 o->found_changes = 1;
3551 goto free_ab_and_return;
3555 if (o->irreversible_delete && lbl[1][0] == '/') {
3556 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3557 header.len, 0);
3558 strbuf_reset(&header);
3559 goto free_ab_and_return;
3560 } else if (!o->flags.text &&
3561 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3562 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3563 struct strbuf sb = STRBUF_INIT;
3564 if (!one->data && !two->data &&
3565 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3566 !o->flags.binary) {
3567 if (oideq(&one->oid, &two->oid)) {
3568 if (must_show_header)
3569 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3570 header.buf, header.len,
3572 goto free_ab_and_return;
3574 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3575 header.buf, header.len, 0);
3576 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3577 diff_line_prefix(o), lbl[0], lbl[1]);
3578 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3579 sb.buf, sb.len, 0);
3580 strbuf_release(&sb);
3581 goto free_ab_and_return;
3583 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3584 fill_mmfile(o->repo, &mf2, two) < 0)
3585 die("unable to read files to diff");
3586 /* Quite common confusing case */
3587 if (mf1.size == mf2.size &&
3588 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3589 if (must_show_header)
3590 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3591 header.buf, header.len, 0);
3592 goto free_ab_and_return;
3594 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3595 strbuf_reset(&header);
3596 if (o->flags.binary)
3597 emit_binary_diff(o, &mf1, &mf2);
3598 else {
3599 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3600 diff_line_prefix(o), lbl[0], lbl[1]);
3601 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3602 sb.buf, sb.len, 0);
3603 strbuf_release(&sb);
3605 o->found_changes = 1;
3606 } else {
3607 /* Crazy xdl interfaces.. */
3608 const char *diffopts;
3609 const char *v;
3610 xpparam_t xpp;
3611 xdemitconf_t xecfg;
3612 struct emit_callback ecbdata;
3613 const struct userdiff_funcname *pe;
3615 if (must_show_header) {
3616 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3617 header.buf, header.len, 0);
3618 strbuf_reset(&header);
3621 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3622 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3624 pe = diff_funcname_pattern(o, one);
3625 if (!pe)
3626 pe = diff_funcname_pattern(o, two);
3628 memset(&xpp, 0, sizeof(xpp));
3629 memset(&xecfg, 0, sizeof(xecfg));
3630 memset(&ecbdata, 0, sizeof(ecbdata));
3631 if (o->flags.suppress_diff_headers)
3632 lbl[0] = NULL;
3633 ecbdata.label_path = lbl;
3634 ecbdata.color_diff = want_color(o->use_color);
3635 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3636 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3637 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3638 ecbdata.opt = o;
3639 if (header.len && !o->flags.suppress_diff_headers)
3640 ecbdata.header = &header;
3641 xpp.flags = o->xdl_opts;
3642 xpp.ignore_regex = o->ignore_regex;
3643 xpp.ignore_regex_nr = o->ignore_regex_nr;
3644 xpp.anchors = o->anchors;
3645 xpp.anchors_nr = o->anchors_nr;
3646 xecfg.ctxlen = o->context;
3647 xecfg.interhunkctxlen = o->interhunkcontext;
3648 xecfg.flags = XDL_EMIT_FUNCNAMES;
3649 if (o->flags.funccontext)
3650 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3651 if (pe)
3652 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3654 diffopts = getenv("GIT_DIFF_OPTS");
3655 if (!diffopts)
3657 else if (skip_prefix(diffopts, "--unified=", &v))
3658 xecfg.ctxlen = strtoul(v, NULL, 10);
3659 else if (skip_prefix(diffopts, "-u", &v))
3660 xecfg.ctxlen = strtoul(v, NULL, 10);
3662 if (o->word_diff)
3663 init_diff_words_data(&ecbdata, o, one, two);
3664 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3665 &ecbdata, &xpp, &xecfg))
3666 die("unable to generate diff for %s", one->path);
3667 if (o->word_diff)
3668 free_diff_words_data(&ecbdata);
3669 if (textconv_one)
3670 free(mf1.ptr);
3671 if (textconv_two)
3672 free(mf2.ptr);
3673 xdiff_clear_find_func(&xecfg);
3676 free_ab_and_return:
3677 strbuf_release(&header);
3678 diff_free_filespec_data(one);
3679 diff_free_filespec_data(two);
3680 free(a_one);
3681 free(b_two);
3682 return;
3685 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3687 if (!is_renamed) {
3688 if (p->status == DIFF_STATUS_ADDED) {
3689 if (S_ISLNK(p->two->mode))
3690 return "new +l";
3691 else if ((p->two->mode & 0777) == 0755)
3692 return "new +x";
3693 else
3694 return "new";
3695 } else if (p->status == DIFF_STATUS_DELETED)
3696 return "gone";
3698 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3699 return "mode -l";
3700 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3701 return "mode +l";
3702 else if ((p->one->mode & 0777) == 0644 &&
3703 (p->two->mode & 0777) == 0755)
3704 return "mode +x";
3705 else if ((p->one->mode & 0777) == 0755 &&
3706 (p->two->mode & 0777) == 0644)
3707 return "mode -x";
3708 return NULL;
3711 static void builtin_diffstat(const char *name_a, const char *name_b,
3712 struct diff_filespec *one,
3713 struct diff_filespec *two,
3714 struct diffstat_t *diffstat,
3715 struct diff_options *o,
3716 struct diff_filepair *p)
3718 mmfile_t mf1, mf2;
3719 struct diffstat_file *data;
3720 int may_differ;
3721 int complete_rewrite = 0;
3723 if (!DIFF_PAIR_UNMERGED(p)) {
3724 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3725 complete_rewrite = 1;
3728 data = diffstat_add(diffstat, name_a, name_b);
3729 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3730 if (o->flags.stat_with_summary)
3731 data->comments = get_compact_summary(p, data->is_renamed);
3733 if (!one || !two) {
3734 data->is_unmerged = 1;
3735 return;
3738 /* saves some reads if true, not a guarantee of diff outcome */
3739 may_differ = !(one->oid_valid && two->oid_valid &&
3740 oideq(&one->oid, &two->oid));
3742 if (diff_filespec_is_binary(o->repo, one) ||
3743 diff_filespec_is_binary(o->repo, two)) {
3744 data->is_binary = 1;
3745 if (!may_differ) {
3746 data->added = 0;
3747 data->deleted = 0;
3748 } else {
3749 data->added = diff_filespec_size(o->repo, two);
3750 data->deleted = diff_filespec_size(o->repo, one);
3754 else if (complete_rewrite) {
3755 diff_populate_filespec(o->repo, one, NULL);
3756 diff_populate_filespec(o->repo, two, NULL);
3757 data->deleted = count_lines(one->data, one->size);
3758 data->added = count_lines(two->data, two->size);
3761 else if (may_differ) {
3762 /* Crazy xdl interfaces.. */
3763 xpparam_t xpp;
3764 xdemitconf_t xecfg;
3766 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3767 fill_mmfile(o->repo, &mf2, two) < 0)
3768 die("unable to read files to diff");
3770 memset(&xpp, 0, sizeof(xpp));
3771 memset(&xecfg, 0, sizeof(xecfg));
3772 xpp.flags = o->xdl_opts;
3773 xpp.ignore_regex = o->ignore_regex;
3774 xpp.ignore_regex_nr = o->ignore_regex_nr;
3775 xpp.anchors = o->anchors;
3776 xpp.anchors_nr = o->anchors_nr;
3777 xecfg.ctxlen = o->context;
3778 xecfg.interhunkctxlen = o->interhunkcontext;
3779 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3780 if (xdi_diff_outf(&mf1, &mf2, NULL,
3781 diffstat_consume, diffstat, &xpp, &xecfg))
3782 die("unable to generate diffstat for %s", one->path);
3784 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3785 struct diffstat_file *file =
3786 diffstat->files[diffstat->nr - 1];
3788 * Omit diffstats of modified files where nothing changed.
3789 * Even if may_differ, this might be the case due to
3790 * ignoring whitespace changes, etc.
3792 * But note that we special-case additions, deletions,
3793 * renames, and mode changes as adding an empty file,
3794 * for example is still of interest.
3796 if ((p->status == DIFF_STATUS_MODIFIED)
3797 && !file->added
3798 && !file->deleted
3799 && one->mode == two->mode) {
3800 free_diffstat_file(file);
3801 diffstat->nr--;
3806 diff_free_filespec_data(one);
3807 diff_free_filespec_data(two);
3810 static void builtin_checkdiff(const char *name_a, const char *name_b,
3811 const char *attr_path,
3812 struct diff_filespec *one,
3813 struct diff_filespec *two,
3814 struct diff_options *o)
3816 mmfile_t mf1, mf2;
3817 struct checkdiff_t data;
3819 if (!two)
3820 return;
3822 memset(&data, 0, sizeof(data));
3823 data.filename = name_b ? name_b : name_a;
3824 data.lineno = 0;
3825 data.o = o;
3826 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3827 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3829 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3830 fill_mmfile(o->repo, &mf2, two) < 0)
3831 die("unable to read files to diff");
3834 * All the other codepaths check both sides, but not checking
3835 * the "old" side here is deliberate. We are checking the newly
3836 * introduced changes, and as long as the "new" side is text, we
3837 * can and should check what it introduces.
3839 if (diff_filespec_is_binary(o->repo, two))
3840 goto free_and_return;
3841 else {
3842 /* Crazy xdl interfaces.. */
3843 xpparam_t xpp;
3844 xdemitconf_t xecfg;
3846 memset(&xpp, 0, sizeof(xpp));
3847 memset(&xecfg, 0, sizeof(xecfg));
3848 xecfg.ctxlen = 1; /* at least one context line */
3849 xpp.flags = 0;
3850 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3851 checkdiff_consume, &data,
3852 &xpp, &xecfg))
3853 die("unable to generate checkdiff for %s", one->path);
3855 if (data.ws_rule & WS_BLANK_AT_EOF) {
3856 struct emit_callback ecbdata;
3857 int blank_at_eof;
3859 ecbdata.ws_rule = data.ws_rule;
3860 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3861 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3863 if (blank_at_eof) {
3864 static char *err;
3865 if (!err)
3866 err = whitespace_error_string(WS_BLANK_AT_EOF);
3867 fprintf(o->file, "%s:%d: %s.\n",
3868 data.filename, blank_at_eof, err);
3869 data.status = 1; /* report errors */
3873 free_and_return:
3874 diff_free_filespec_data(one);
3875 diff_free_filespec_data(two);
3876 if (data.status)
3877 o->flags.check_failed = 1;
3880 struct diff_filespec *alloc_filespec(const char *path)
3882 struct diff_filespec *spec;
3884 FLEXPTR_ALLOC_STR(spec, path, path);
3885 spec->count = 1;
3886 spec->is_binary = -1;
3887 return spec;
3890 void free_filespec(struct diff_filespec *spec)
3892 if (!--spec->count) {
3893 diff_free_filespec_data(spec);
3894 free(spec);
3898 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3899 int oid_valid, unsigned short mode)
3901 if (mode) {
3902 spec->mode = canon_mode(mode);
3903 oidcpy(&spec->oid, oid);
3904 spec->oid_valid = oid_valid;
3909 * Given a name and sha1 pair, if the index tells us the file in
3910 * the work tree has that object contents, return true, so that
3911 * prepare_temp_file() does not have to inflate and extract.
3913 static int reuse_worktree_file(struct index_state *istate,
3914 const char *name,
3915 const struct object_id *oid,
3916 int want_file)
3918 const struct cache_entry *ce;
3919 struct stat st;
3920 int pos, len;
3923 * We do not read the cache ourselves here, because the
3924 * benchmark with my previous version that always reads cache
3925 * shows that it makes things worse for diff-tree comparing
3926 * two linux-2.6 kernel trees in an already checked out work
3927 * tree. This is because most diff-tree comparisons deal with
3928 * only a small number of files, while reading the cache is
3929 * expensive for a large project, and its cost outweighs the
3930 * savings we get by not inflating the object to a temporary
3931 * file. Practically, this code only helps when we are used
3932 * by diff-cache --cached, which does read the cache before
3933 * calling us.
3935 if (!istate->cache)
3936 return 0;
3938 /* We want to avoid the working directory if our caller
3939 * doesn't need the data in a normal file, this system
3940 * is rather slow with its stat/open/mmap/close syscalls,
3941 * and the object is contained in a pack file. The pack
3942 * is probably already open and will be faster to obtain
3943 * the data through than the working directory. Loose
3944 * objects however would tend to be slower as they need
3945 * to be individually opened and inflated.
3947 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3948 return 0;
3951 * Similarly, if we'd have to convert the file contents anyway, that
3952 * makes the optimization not worthwhile.
3954 if (!want_file && would_convert_to_git(istate, name))
3955 return 0;
3958 * If this path does not match our sparse-checkout definition,
3959 * then the file will not be in the working directory.
3961 if (!path_in_sparse_checkout(name, istate))
3962 return 0;
3964 len = strlen(name);
3965 pos = index_name_pos(istate, name, len);
3966 if (pos < 0)
3967 return 0;
3968 ce = istate->cache[pos];
3971 * This is not the sha1 we are looking for, or
3972 * unreusable because it is not a regular file.
3974 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3975 return 0;
3978 * If ce is marked as "assume unchanged", there is no
3979 * guarantee that work tree matches what we are looking for.
3981 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3982 return 0;
3985 * If ce matches the file in the work tree, we can reuse it.
3987 if (ce_uptodate(ce) ||
3988 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3989 return 1;
3991 return 0;
3994 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3996 struct strbuf buf = STRBUF_INIT;
3997 char *dirty = "";
3999 /* Are we looking at the work tree? */
4000 if (s->dirty_submodule)
4001 dirty = "-dirty";
4003 strbuf_addf(&buf, "Subproject commit %s%s\n",
4004 oid_to_hex(&s->oid), dirty);
4005 s->size = buf.len;
4006 if (size_only) {
4007 s->data = NULL;
4008 strbuf_release(&buf);
4009 } else {
4010 s->data = strbuf_detach(&buf, NULL);
4011 s->should_free = 1;
4013 return 0;
4017 * While doing rename detection and pickaxe operation, we may need to
4018 * grab the data for the blob (or file) for our own in-core comparison.
4019 * diff_filespec has data and size fields for this purpose.
4021 int diff_populate_filespec(struct repository *r,
4022 struct diff_filespec *s,
4023 const struct diff_populate_filespec_options *options)
4025 int size_only = options ? options->check_size_only : 0;
4026 int check_binary = options ? options->check_binary : 0;
4027 int err = 0;
4028 int conv_flags = global_conv_flags_eol;
4030 * demote FAIL to WARN to allow inspecting the situation
4031 * instead of refusing.
4033 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4034 conv_flags = CONV_EOL_RNDTRP_WARN;
4036 if (!DIFF_FILE_VALID(s))
4037 die("internal error: asking to populate invalid file.");
4038 if (S_ISDIR(s->mode))
4039 return -1;
4041 if (s->data)
4042 return 0;
4044 if (size_only && 0 < s->size)
4045 return 0;
4047 if (S_ISGITLINK(s->mode))
4048 return diff_populate_gitlink(s, size_only);
4050 if (!s->oid_valid ||
4051 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4052 struct strbuf buf = STRBUF_INIT;
4053 struct stat st;
4054 int fd;
4056 if (lstat(s->path, &st) < 0) {
4057 err_empty:
4058 err = -1;
4059 empty:
4060 s->data = (char *)"";
4061 s->size = 0;
4062 return err;
4064 s->size = xsize_t(st.st_size);
4065 if (!s->size)
4066 goto empty;
4067 if (S_ISLNK(st.st_mode)) {
4068 struct strbuf sb = STRBUF_INIT;
4070 if (strbuf_readlink(&sb, s->path, s->size))
4071 goto err_empty;
4072 s->size = sb.len;
4073 s->data = strbuf_detach(&sb, NULL);
4074 s->should_free = 1;
4075 return 0;
4079 * Even if the caller would be happy with getting
4080 * only the size, we cannot return early at this
4081 * point if the path requires us to run the content
4082 * conversion.
4084 if (size_only && !would_convert_to_git(r->index, s->path))
4085 return 0;
4088 * Note: this check uses xsize_t(st.st_size) that may
4089 * not be the true size of the blob after it goes
4090 * through convert_to_git(). This may not strictly be
4091 * correct, but the whole point of big_file_threshold
4092 * and is_binary check being that we want to avoid
4093 * opening the file and inspecting the contents, this
4094 * is probably fine.
4096 if (check_binary &&
4097 s->size > big_file_threshold && s->is_binary == -1) {
4098 s->is_binary = 1;
4099 return 0;
4101 fd = open(s->path, O_RDONLY);
4102 if (fd < 0)
4103 goto err_empty;
4104 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4105 close(fd);
4106 s->should_munmap = 1;
4109 * Convert from working tree format to canonical git format
4111 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4112 size_t size = 0;
4113 munmap(s->data, s->size);
4114 s->should_munmap = 0;
4115 s->data = strbuf_detach(&buf, &size);
4116 s->size = size;
4117 s->should_free = 1;
4120 else {
4121 struct object_info info = {
4122 .sizep = &s->size
4125 if (!(size_only || check_binary))
4127 * Set contentp, since there is no chance that merely
4128 * the size is sufficient.
4130 info.contentp = &s->data;
4132 if (options && options->missing_object_cb) {
4133 if (!oid_object_info_extended(r, &s->oid, &info,
4134 OBJECT_INFO_LOOKUP_REPLACE |
4135 OBJECT_INFO_SKIP_FETCH_OBJECT))
4136 goto object_read;
4137 options->missing_object_cb(options->missing_object_data);
4139 if (oid_object_info_extended(r, &s->oid, &info,
4140 OBJECT_INFO_LOOKUP_REPLACE))
4141 die("unable to read %s", oid_to_hex(&s->oid));
4143 object_read:
4144 if (size_only || check_binary) {
4145 if (size_only)
4146 return 0;
4147 if (s->size > big_file_threshold && s->is_binary == -1) {
4148 s->is_binary = 1;
4149 return 0;
4152 if (!info.contentp) {
4153 info.contentp = &s->data;
4154 if (oid_object_info_extended(r, &s->oid, &info,
4155 OBJECT_INFO_LOOKUP_REPLACE))
4156 die("unable to read %s", oid_to_hex(&s->oid));
4158 s->should_free = 1;
4160 return 0;
4163 void diff_free_filespec_blob(struct diff_filespec *s)
4165 if (s->should_free)
4166 free(s->data);
4167 else if (s->should_munmap)
4168 munmap(s->data, s->size);
4170 if (s->should_free || s->should_munmap) {
4171 s->should_free = s->should_munmap = 0;
4172 s->data = NULL;
4176 void diff_free_filespec_data(struct diff_filespec *s)
4178 if (!s)
4179 return;
4181 diff_free_filespec_blob(s);
4182 FREE_AND_NULL(s->cnt_data);
4185 static void prep_temp_blob(struct index_state *istate,
4186 const char *path, struct diff_tempfile *temp,
4187 void *blob,
4188 unsigned long size,
4189 const struct object_id *oid,
4190 int mode)
4192 struct strbuf buf = STRBUF_INIT;
4193 char *path_dup = xstrdup(path);
4194 const char *base = basename(path_dup);
4195 struct checkout_metadata meta;
4197 init_checkout_metadata(&meta, NULL, NULL, oid);
4199 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4200 if (!temp->tempfile)
4201 die_errno("unable to create temp-file");
4202 if (convert_to_working_tree(istate, path,
4203 (const char *)blob, (size_t)size, &buf, &meta)) {
4204 blob = buf.buf;
4205 size = buf.len;
4207 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4208 close_tempfile_gently(temp->tempfile))
4209 die_errno("unable to write temp-file");
4210 temp->name = get_tempfile_path(temp->tempfile);
4211 oid_to_hex_r(temp->hex, oid);
4212 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4213 strbuf_release(&buf);
4214 free(path_dup);
4217 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4218 struct diff_filespec *one)
4220 struct diff_tempfile *temp = claim_diff_tempfile();
4222 if (!DIFF_FILE_VALID(one)) {
4223 not_a_valid_file:
4224 /* A '-' entry produces this for file-2, and
4225 * a '+' entry produces this for file-1.
4227 temp->name = "/dev/null";
4228 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4229 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4230 return temp;
4233 if (!S_ISGITLINK(one->mode) &&
4234 (!one->oid_valid ||
4235 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4236 struct stat st;
4237 if (lstat(one->path, &st) < 0) {
4238 if (errno == ENOENT)
4239 goto not_a_valid_file;
4240 die_errno("stat(%s)", one->path);
4242 if (S_ISLNK(st.st_mode)) {
4243 struct strbuf sb = STRBUF_INIT;
4244 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4245 die_errno("readlink(%s)", one->path);
4246 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4247 (one->oid_valid ?
4248 &one->oid : null_oid()),
4249 (one->oid_valid ?
4250 one->mode : S_IFLNK));
4251 strbuf_release(&sb);
4253 else {
4254 /* we can borrow from the file in the work tree */
4255 temp->name = one->path;
4256 if (!one->oid_valid)
4257 oid_to_hex_r(temp->hex, null_oid());
4258 else
4259 oid_to_hex_r(temp->hex, &one->oid);
4260 /* Even though we may sometimes borrow the
4261 * contents from the work tree, we always want
4262 * one->mode. mode is trustworthy even when
4263 * !(one->oid_valid), as long as
4264 * DIFF_FILE_VALID(one).
4266 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4268 return temp;
4270 else {
4271 if (diff_populate_filespec(r, one, NULL))
4272 die("cannot read data blob for %s", one->path);
4273 prep_temp_blob(r->index, one->path, temp,
4274 one->data, one->size,
4275 &one->oid, one->mode);
4277 return temp;
4280 static void add_external_diff_name(struct repository *r,
4281 struct strvec *argv,
4282 struct diff_filespec *df)
4284 struct diff_tempfile *temp = prepare_temp_file(r, df);
4285 strvec_push(argv, temp->name);
4286 strvec_push(argv, temp->hex);
4287 strvec_push(argv, temp->mode);
4290 /* An external diff command takes:
4292 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4293 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4296 static void run_external_diff(const char *pgm,
4297 const char *name,
4298 const char *other,
4299 struct diff_filespec *one,
4300 struct diff_filespec *two,
4301 const char *xfrm_msg,
4302 struct diff_options *o)
4304 struct child_process cmd = CHILD_PROCESS_INIT;
4305 struct diff_queue_struct *q = &diff_queued_diff;
4307 strvec_push(&cmd.args, pgm);
4308 strvec_push(&cmd.args, name);
4310 if (one && two) {
4311 add_external_diff_name(o->repo, &cmd.args, one);
4312 add_external_diff_name(o->repo, &cmd.args, two);
4313 if (other) {
4314 strvec_push(&cmd.args, other);
4315 strvec_push(&cmd.args, xfrm_msg);
4319 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4320 ++o->diff_path_counter);
4321 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4323 diff_free_filespec_data(one);
4324 diff_free_filespec_data(two);
4325 cmd.use_shell = 1;
4326 if (run_command(&cmd))
4327 die(_("external diff died, stopping at %s"), name);
4329 remove_tempfile();
4332 static int similarity_index(struct diff_filepair *p)
4334 return p->score * 100 / MAX_SCORE;
4337 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4339 if (startup_info->have_repository)
4340 return find_unique_abbrev(oid, abbrev);
4341 else {
4342 char *hex = oid_to_hex(oid);
4343 if (abbrev < 0)
4344 abbrev = FALLBACK_DEFAULT_ABBREV;
4345 if (abbrev > the_hash_algo->hexsz)
4346 BUG("oid abbreviation out of range: %d", abbrev);
4347 if (abbrev)
4348 hex[abbrev] = '\0';
4349 return hex;
4353 static void fill_metainfo(struct strbuf *msg,
4354 const char *name,
4355 const char *other,
4356 struct diff_filespec *one,
4357 struct diff_filespec *two,
4358 struct diff_options *o,
4359 struct diff_filepair *p,
4360 int *must_show_header,
4361 int use_color)
4363 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4364 const char *reset = diff_get_color(use_color, DIFF_RESET);
4365 const char *line_prefix = diff_line_prefix(o);
4366 struct string_list *more_headers = NULL;
4368 *must_show_header = 1;
4369 strbuf_init(msg, PATH_MAX * 2 + 300);
4370 switch (p->status) {
4371 case DIFF_STATUS_COPIED:
4372 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4373 line_prefix, set, similarity_index(p));
4374 strbuf_addf(msg, "%s\n%s%scopy from ",
4375 reset, line_prefix, set);
4376 quote_c_style(name, msg, NULL, 0);
4377 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4378 quote_c_style(other, msg, NULL, 0);
4379 strbuf_addf(msg, "%s\n", reset);
4380 break;
4381 case DIFF_STATUS_RENAMED:
4382 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4383 line_prefix, set, similarity_index(p));
4384 strbuf_addf(msg, "%s\n%s%srename from ",
4385 reset, line_prefix, set);
4386 quote_c_style(name, msg, NULL, 0);
4387 strbuf_addf(msg, "%s\n%s%srename to ",
4388 reset, line_prefix, set);
4389 quote_c_style(other, msg, NULL, 0);
4390 strbuf_addf(msg, "%s\n", reset);
4391 break;
4392 case DIFF_STATUS_MODIFIED:
4393 if (p->score) {
4394 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4395 line_prefix,
4396 set, similarity_index(p), reset);
4397 break;
4399 /* fallthru */
4400 default:
4401 *must_show_header = 0;
4403 if ((more_headers = additional_headers(o, name))) {
4404 add_formatted_headers(msg, more_headers,
4405 line_prefix, set, reset);
4406 *must_show_header = 1;
4408 if (one && two && !oideq(&one->oid, &two->oid)) {
4409 const unsigned hexsz = the_hash_algo->hexsz;
4410 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4412 if (o->flags.full_index)
4413 abbrev = hexsz;
4415 if (o->flags.binary) {
4416 mmfile_t mf;
4417 if ((!fill_mmfile(o->repo, &mf, one) &&
4418 diff_filespec_is_binary(o->repo, one)) ||
4419 (!fill_mmfile(o->repo, &mf, two) &&
4420 diff_filespec_is_binary(o->repo, two)))
4421 abbrev = hexsz;
4423 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4424 diff_abbrev_oid(&one->oid, abbrev),
4425 diff_abbrev_oid(&two->oid, abbrev));
4426 if (one->mode == two->mode)
4427 strbuf_addf(msg, " %06o", one->mode);
4428 strbuf_addf(msg, "%s\n", reset);
4432 static void run_diff_cmd(const char *pgm,
4433 const char *name,
4434 const char *other,
4435 const char *attr_path,
4436 struct diff_filespec *one,
4437 struct diff_filespec *two,
4438 struct strbuf *msg,
4439 struct diff_options *o,
4440 struct diff_filepair *p)
4442 const char *xfrm_msg = NULL;
4443 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4444 int must_show_header = 0;
4447 if (o->flags.allow_external) {
4448 struct userdiff_driver *drv;
4450 drv = userdiff_find_by_path(o->repo->index, attr_path);
4451 if (drv && drv->external)
4452 pgm = drv->external;
4455 if (msg) {
4457 * don't use colors when the header is intended for an
4458 * external diff driver
4460 fill_metainfo(msg, name, other, one, two, o, p,
4461 &must_show_header,
4462 want_color(o->use_color) && !pgm);
4463 xfrm_msg = msg->len ? msg->buf : NULL;
4466 if (pgm) {
4467 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4468 return;
4470 if (one && two)
4471 builtin_diff(name, other ? other : name,
4472 one, two, xfrm_msg, must_show_header,
4473 o, complete_rewrite);
4474 else
4475 fprintf(o->file, "* Unmerged path %s\n", name);
4478 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4480 if (DIFF_FILE_VALID(one)) {
4481 if (!one->oid_valid) {
4482 struct stat st;
4483 if (one->is_stdin) {
4484 oidclr(&one->oid);
4485 return;
4487 if (lstat(one->path, &st) < 0)
4488 die_errno("stat '%s'", one->path);
4489 if (index_path(istate, &one->oid, one->path, &st, 0))
4490 die("cannot hash %s", one->path);
4493 else
4494 oidclr(&one->oid);
4497 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4499 /* Strip the prefix but do not molest /dev/null and absolute paths */
4500 if (*namep && !is_absolute_path(*namep)) {
4501 *namep += prefix_length;
4502 if (**namep == '/')
4503 ++*namep;
4505 if (*otherp && !is_absolute_path(*otherp)) {
4506 *otherp += prefix_length;
4507 if (**otherp == '/')
4508 ++*otherp;
4512 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4514 const char *pgm = external_diff();
4515 struct strbuf msg;
4516 struct diff_filespec *one = p->one;
4517 struct diff_filespec *two = p->two;
4518 const char *name;
4519 const char *other;
4520 const char *attr_path;
4522 name = one->path;
4523 other = (strcmp(name, two->path) ? two->path : NULL);
4524 attr_path = name;
4525 if (o->prefix_length)
4526 strip_prefix(o->prefix_length, &name, &other);
4528 if (!o->flags.allow_external)
4529 pgm = NULL;
4531 if (DIFF_PAIR_UNMERGED(p)) {
4532 run_diff_cmd(pgm, name, NULL, attr_path,
4533 NULL, NULL, NULL, o, p);
4534 return;
4537 diff_fill_oid_info(one, o->repo->index);
4538 diff_fill_oid_info(two, o->repo->index);
4540 if (!pgm &&
4541 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4542 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4544 * a filepair that changes between file and symlink
4545 * needs to be split into deletion and creation.
4547 struct diff_filespec *null = alloc_filespec(two->path);
4548 run_diff_cmd(NULL, name, other, attr_path,
4549 one, null, &msg,
4550 o, p);
4551 free(null);
4552 strbuf_release(&msg);
4554 null = alloc_filespec(one->path);
4555 run_diff_cmd(NULL, name, other, attr_path,
4556 null, two, &msg, o, p);
4557 free(null);
4559 else
4560 run_diff_cmd(pgm, name, other, attr_path,
4561 one, two, &msg, o, p);
4563 strbuf_release(&msg);
4566 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4567 struct diffstat_t *diffstat)
4569 const char *name;
4570 const char *other;
4572 if (DIFF_PAIR_UNMERGED(p)) {
4573 /* unmerged */
4574 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4575 diffstat, o, p);
4576 return;
4579 name = p->one->path;
4580 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4582 if (o->prefix_length)
4583 strip_prefix(o->prefix_length, &name, &other);
4585 diff_fill_oid_info(p->one, o->repo->index);
4586 diff_fill_oid_info(p->two, o->repo->index);
4588 builtin_diffstat(name, other, p->one, p->two,
4589 diffstat, o, p);
4592 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4594 const char *name;
4595 const char *other;
4596 const char *attr_path;
4598 if (DIFF_PAIR_UNMERGED(p)) {
4599 /* unmerged */
4600 return;
4603 name = p->one->path;
4604 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4605 attr_path = other ? other : name;
4607 if (o->prefix_length)
4608 strip_prefix(o->prefix_length, &name, &other);
4610 diff_fill_oid_info(p->one, o->repo->index);
4611 diff_fill_oid_info(p->two, o->repo->index);
4613 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4616 void repo_diff_setup(struct repository *r, struct diff_options *options)
4618 memcpy(options, &default_diff_options, sizeof(*options));
4620 options->file = stdout;
4621 options->repo = r;
4623 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4624 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4625 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4626 options->abbrev = DEFAULT_ABBREV;
4627 options->line_termination = '\n';
4628 options->break_opt = -1;
4629 options->rename_limit = -1;
4630 options->dirstat_permille = diff_dirstat_permille_default;
4631 options->context = diff_context_default;
4632 options->interhunkcontext = diff_interhunk_context_default;
4633 options->ws_error_highlight = ws_error_highlight_default;
4634 options->flags.rename_empty = 1;
4635 options->flags.relative_name = diff_relative;
4636 options->objfind = NULL;
4638 /* pathchange left =NULL by default */
4639 options->change = diff_change;
4640 options->add_remove = diff_addremove;
4641 options->use_color = diff_use_color_default;
4642 options->detect_rename = diff_detect_rename_default;
4643 options->xdl_opts |= diff_algorithm;
4644 if (diff_indent_heuristic)
4645 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4647 options->orderfile = diff_order_file_cfg;
4649 if (!options->flags.ignore_submodule_set)
4650 options->flags.ignore_untracked_in_submodules = 1;
4652 if (diff_no_prefix) {
4653 options->a_prefix = options->b_prefix = "";
4654 } else if (!diff_mnemonic_prefix) {
4655 options->a_prefix = "a/";
4656 options->b_prefix = "b/";
4659 options->color_moved = diff_color_moved_default;
4660 options->color_moved_ws_handling = diff_color_moved_ws_default;
4663 static const char diff_status_letters[] = {
4664 DIFF_STATUS_ADDED,
4665 DIFF_STATUS_COPIED,
4666 DIFF_STATUS_DELETED,
4667 DIFF_STATUS_MODIFIED,
4668 DIFF_STATUS_RENAMED,
4669 DIFF_STATUS_TYPE_CHANGED,
4670 DIFF_STATUS_UNKNOWN,
4671 DIFF_STATUS_UNMERGED,
4672 DIFF_STATUS_FILTER_AON,
4673 DIFF_STATUS_FILTER_BROKEN,
4674 '\0',
4677 static unsigned int filter_bit['Z' + 1];
4679 static void prepare_filter_bits(void)
4681 int i;
4683 if (!filter_bit[DIFF_STATUS_ADDED]) {
4684 for (i = 0; diff_status_letters[i]; i++)
4685 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4689 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4691 return opt->filter & filter_bit[(int) status];
4694 unsigned diff_filter_bit(char status)
4696 prepare_filter_bits();
4697 return filter_bit[(int) status];
4700 void diff_setup_done(struct diff_options *options)
4702 unsigned check_mask = DIFF_FORMAT_NAME |
4703 DIFF_FORMAT_NAME_STATUS |
4704 DIFF_FORMAT_CHECKDIFF |
4705 DIFF_FORMAT_NO_OUTPUT;
4707 * This must be signed because we're comparing against a potentially
4708 * negative value.
4710 const int hexsz = the_hash_algo->hexsz;
4712 if (options->set_default)
4713 options->set_default(options);
4715 if (HAS_MULTI_BITS(options->output_format & check_mask))
4716 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4717 "--name-only", "--name-status", "--check", "-s");
4719 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4720 die(_("options '%s', '%s', and '%s' cannot be used together"),
4721 "-G", "-S", "--find-object");
4723 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4724 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4725 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4727 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4728 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4729 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4732 * Most of the time we can say "there are changes"
4733 * only by checking if there are changed paths, but
4734 * --ignore-whitespace* options force us to look
4735 * inside contents.
4738 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4739 options->ignore_regex_nr)
4740 options->flags.diff_from_contents = 1;
4741 else
4742 options->flags.diff_from_contents = 0;
4744 if (options->flags.find_copies_harder)
4745 options->detect_rename = DIFF_DETECT_COPY;
4747 if (!options->flags.relative_name)
4748 options->prefix = NULL;
4749 if (options->prefix)
4750 options->prefix_length = strlen(options->prefix);
4751 else
4752 options->prefix_length = 0;
4754 if (options->output_format & (DIFF_FORMAT_NAME |
4755 DIFF_FORMAT_NAME_STATUS |
4756 DIFF_FORMAT_CHECKDIFF |
4757 DIFF_FORMAT_NO_OUTPUT))
4758 options->output_format &= ~(DIFF_FORMAT_RAW |
4759 DIFF_FORMAT_NUMSTAT |
4760 DIFF_FORMAT_DIFFSTAT |
4761 DIFF_FORMAT_SHORTSTAT |
4762 DIFF_FORMAT_DIRSTAT |
4763 DIFF_FORMAT_SUMMARY |
4764 DIFF_FORMAT_PATCH);
4767 * These cases always need recursive; we do not drop caller-supplied
4768 * recursive bits for other formats here.
4770 if (options->output_format & (DIFF_FORMAT_PATCH |
4771 DIFF_FORMAT_NUMSTAT |
4772 DIFF_FORMAT_DIFFSTAT |
4773 DIFF_FORMAT_SHORTSTAT |
4774 DIFF_FORMAT_DIRSTAT |
4775 DIFF_FORMAT_SUMMARY |
4776 DIFF_FORMAT_CHECKDIFF))
4777 options->flags.recursive = 1;
4779 * Also pickaxe would not work very well if you do not say recursive
4781 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4782 options->flags.recursive = 1;
4784 * When patches are generated, submodules diffed against the work tree
4785 * must be checked for dirtiness too so it can be shown in the output
4787 if (options->output_format & DIFF_FORMAT_PATCH)
4788 options->flags.dirty_submodules = 1;
4790 if (options->detect_rename && options->rename_limit < 0)
4791 options->rename_limit = diff_rename_limit_default;
4792 if (hexsz < options->abbrev)
4793 options->abbrev = hexsz; /* full */
4796 * It does not make sense to show the first hit we happened
4797 * to have found. It does not make sense not to return with
4798 * exit code in such a case either.
4800 if (options->flags.quick) {
4801 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4802 options->flags.exit_with_status = 1;
4805 options->diff_path_counter = 0;
4807 if (options->flags.follow_renames && options->pathspec.nr != 1)
4808 die(_("--follow requires exactly one pathspec"));
4810 if (!options->use_color || external_diff())
4811 options->color_moved = 0;
4813 if (options->filter_not) {
4814 if (!options->filter)
4815 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4816 options->filter &= ~options->filter_not;
4820 int parse_long_opt(const char *opt, const char **argv,
4821 const char **optarg)
4823 const char *arg = argv[0];
4824 if (!skip_prefix(arg, "--", &arg))
4825 return 0;
4826 if (!skip_prefix(arg, opt, &arg))
4827 return 0;
4828 if (*arg == '=') { /* stuck form: --option=value */
4829 *optarg = arg + 1;
4830 return 1;
4832 if (*arg != '\0')
4833 return 0;
4834 /* separate form: --option value */
4835 if (!argv[1])
4836 die("Option '--%s' requires a value", opt);
4837 *optarg = argv[1];
4838 return 2;
4841 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4843 struct diff_options *options = opt->value;
4844 int width = options->stat_width;
4845 int name_width = options->stat_name_width;
4846 int graph_width = options->stat_graph_width;
4847 int count = options->stat_count;
4848 char *end;
4850 BUG_ON_OPT_NEG(unset);
4852 if (!strcmp(opt->long_name, "stat")) {
4853 if (value) {
4854 width = strtoul(value, &end, 10);
4855 if (*end == ',')
4856 name_width = strtoul(end+1, &end, 10);
4857 if (*end == ',')
4858 count = strtoul(end+1, &end, 10);
4859 if (*end)
4860 return error(_("invalid --stat value: %s"), value);
4862 } else if (!strcmp(opt->long_name, "stat-width")) {
4863 width = strtoul(value, &end, 10);
4864 if (*end)
4865 return error(_("%s expects a numerical value"),
4866 opt->long_name);
4867 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4868 name_width = strtoul(value, &end, 10);
4869 if (*end)
4870 return error(_("%s expects a numerical value"),
4871 opt->long_name);
4872 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4873 graph_width = strtoul(value, &end, 10);
4874 if (*end)
4875 return error(_("%s expects a numerical value"),
4876 opt->long_name);
4877 } else if (!strcmp(opt->long_name, "stat-count")) {
4878 count = strtoul(value, &end, 10);
4879 if (*end)
4880 return error(_("%s expects a numerical value"),
4881 opt->long_name);
4882 } else
4883 BUG("%s should not get here", opt->long_name);
4885 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4886 options->stat_name_width = name_width;
4887 options->stat_graph_width = graph_width;
4888 options->stat_width = width;
4889 options->stat_count = count;
4890 return 0;
4893 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4895 struct strbuf errmsg = STRBUF_INIT;
4896 if (parse_dirstat_params(options, params, &errmsg))
4897 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4898 errmsg.buf);
4899 strbuf_release(&errmsg);
4901 * The caller knows a dirstat-related option is given from the command
4902 * line; allow it to say "return this_function();"
4904 options->output_format |= DIFF_FORMAT_DIRSTAT;
4905 return 1;
4908 static int diff_opt_diff_filter(const struct option *option,
4909 const char *optarg, int unset)
4911 struct diff_options *opt = option->value;
4912 int i, optch;
4914 BUG_ON_OPT_NEG(unset);
4915 prepare_filter_bits();
4917 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4918 unsigned int bit;
4919 int negate;
4921 if ('a' <= optch && optch <= 'z') {
4922 negate = 1;
4923 optch = toupper(optch);
4924 } else {
4925 negate = 0;
4928 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4929 if (!bit)
4930 return error(_("unknown change class '%c' in --diff-filter=%s"),
4931 optarg[i], optarg);
4932 if (negate)
4933 opt->filter_not |= bit;
4934 else
4935 opt->filter |= bit;
4937 return 0;
4940 static void enable_patch_output(int *fmt)
4942 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4943 *fmt |= DIFF_FORMAT_PATCH;
4946 static int diff_opt_ws_error_highlight(const struct option *option,
4947 const char *arg, int unset)
4949 struct diff_options *opt = option->value;
4950 int val = parse_ws_error_highlight(arg);
4952 BUG_ON_OPT_NEG(unset);
4953 if (val < 0)
4954 return error(_("unknown value after ws-error-highlight=%.*s"),
4955 -1 - val, arg);
4956 opt->ws_error_highlight = val;
4957 return 0;
4960 static int diff_opt_find_object(const struct option *option,
4961 const char *arg, int unset)
4963 struct diff_options *opt = option->value;
4964 struct object_id oid;
4966 BUG_ON_OPT_NEG(unset);
4967 if (get_oid(arg, &oid))
4968 return error(_("unable to resolve '%s'"), arg);
4970 if (!opt->objfind)
4971 CALLOC_ARRAY(opt->objfind, 1);
4973 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4974 opt->flags.recursive = 1;
4975 opt->flags.tree_in_recursive = 1;
4976 oidset_insert(opt->objfind, &oid);
4977 return 0;
4980 static int diff_opt_anchored(const struct option *opt,
4981 const char *arg, int unset)
4983 struct diff_options *options = opt->value;
4985 BUG_ON_OPT_NEG(unset);
4986 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4987 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4988 options->anchors_alloc);
4989 options->anchors[options->anchors_nr++] = xstrdup(arg);
4990 return 0;
4993 static int diff_opt_binary(const struct option *opt,
4994 const char *arg, int unset)
4996 struct diff_options *options = opt->value;
4998 BUG_ON_OPT_NEG(unset);
4999 BUG_ON_OPT_ARG(arg);
5000 enable_patch_output(&options->output_format);
5001 options->flags.binary = 1;
5002 return 0;
5005 static int diff_opt_break_rewrites(const struct option *opt,
5006 const char *arg, int unset)
5008 int *break_opt = opt->value;
5009 int opt1, opt2;
5011 BUG_ON_OPT_NEG(unset);
5012 if (!arg)
5013 arg = "";
5014 opt1 = parse_rename_score(&arg);
5015 if (*arg == 0)
5016 opt2 = 0;
5017 else if (*arg != '/')
5018 return error(_("%s expects <n>/<m> form"), opt->long_name);
5019 else {
5020 arg++;
5021 opt2 = parse_rename_score(&arg);
5023 if (*arg != 0)
5024 return error(_("%s expects <n>/<m> form"), opt->long_name);
5025 *break_opt = opt1 | (opt2 << 16);
5026 return 0;
5029 static int diff_opt_char(const struct option *opt,
5030 const char *arg, int unset)
5032 char *value = opt->value;
5034 BUG_ON_OPT_NEG(unset);
5035 if (arg[1])
5036 return error(_("%s expects a character, got '%s'"),
5037 opt->long_name, arg);
5038 *value = arg[0];
5039 return 0;
5042 static int diff_opt_color_moved(const struct option *opt,
5043 const char *arg, int unset)
5045 struct diff_options *options = opt->value;
5047 if (unset) {
5048 options->color_moved = COLOR_MOVED_NO;
5049 } else if (!arg) {
5050 if (diff_color_moved_default)
5051 options->color_moved = diff_color_moved_default;
5052 if (options->color_moved == COLOR_MOVED_NO)
5053 options->color_moved = COLOR_MOVED_DEFAULT;
5054 } else {
5055 int cm = parse_color_moved(arg);
5056 if (cm < 0)
5057 return error(_("bad --color-moved argument: %s"), arg);
5058 options->color_moved = cm;
5060 return 0;
5063 static int diff_opt_color_moved_ws(const struct option *opt,
5064 const char *arg, int unset)
5066 struct diff_options *options = opt->value;
5067 unsigned cm;
5069 if (unset) {
5070 options->color_moved_ws_handling = 0;
5071 return 0;
5074 cm = parse_color_moved_ws(arg);
5075 if (cm & COLOR_MOVED_WS_ERROR)
5076 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5077 options->color_moved_ws_handling = cm;
5078 return 0;
5081 static int diff_opt_color_words(const struct option *opt,
5082 const char *arg, int unset)
5084 struct diff_options *options = opt->value;
5086 BUG_ON_OPT_NEG(unset);
5087 options->use_color = 1;
5088 options->word_diff = DIFF_WORDS_COLOR;
5089 options->word_regex = arg;
5090 return 0;
5093 static int diff_opt_compact_summary(const struct option *opt,
5094 const char *arg, int unset)
5096 struct diff_options *options = opt->value;
5098 BUG_ON_OPT_ARG(arg);
5099 if (unset) {
5100 options->flags.stat_with_summary = 0;
5101 } else {
5102 options->flags.stat_with_summary = 1;
5103 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5105 return 0;
5108 static int diff_opt_diff_algorithm(const struct option *opt,
5109 const char *arg, int unset)
5111 struct diff_options *options = opt->value;
5112 long value = parse_algorithm_value(arg);
5114 BUG_ON_OPT_NEG(unset);
5115 if (value < 0)
5116 return error(_("option diff-algorithm accepts \"myers\", "
5117 "\"minimal\", \"patience\" and \"histogram\""));
5119 /* clear out previous settings */
5120 DIFF_XDL_CLR(options, NEED_MINIMAL);
5121 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5122 options->xdl_opts |= value;
5123 return 0;
5126 static int diff_opt_dirstat(const struct option *opt,
5127 const char *arg, int unset)
5129 struct diff_options *options = opt->value;
5131 BUG_ON_OPT_NEG(unset);
5132 if (!strcmp(opt->long_name, "cumulative")) {
5133 if (arg)
5134 BUG("how come --cumulative take a value?");
5135 arg = "cumulative";
5136 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5137 parse_dirstat_opt(options, "files");
5138 parse_dirstat_opt(options, arg ? arg : "");
5139 return 0;
5142 static int diff_opt_find_copies(const struct option *opt,
5143 const char *arg, int unset)
5145 struct diff_options *options = opt->value;
5147 BUG_ON_OPT_NEG(unset);
5148 if (!arg)
5149 arg = "";
5150 options->rename_score = parse_rename_score(&arg);
5151 if (*arg != 0)
5152 return error(_("invalid argument to %s"), opt->long_name);
5154 if (options->detect_rename == DIFF_DETECT_COPY)
5155 options->flags.find_copies_harder = 1;
5156 else
5157 options->detect_rename = DIFF_DETECT_COPY;
5159 return 0;
5162 static int diff_opt_find_renames(const struct option *opt,
5163 const char *arg, int unset)
5165 struct diff_options *options = opt->value;
5167 BUG_ON_OPT_NEG(unset);
5168 if (!arg)
5169 arg = "";
5170 options->rename_score = parse_rename_score(&arg);
5171 if (*arg != 0)
5172 return error(_("invalid argument to %s"), opt->long_name);
5174 options->detect_rename = DIFF_DETECT_RENAME;
5175 return 0;
5178 static int diff_opt_follow(const struct option *opt,
5179 const char *arg, int unset)
5181 struct diff_options *options = opt->value;
5183 BUG_ON_OPT_ARG(arg);
5184 if (unset) {
5185 options->flags.follow_renames = 0;
5186 options->flags.default_follow_renames = 0;
5187 } else {
5188 options->flags.follow_renames = 1;
5190 return 0;
5193 static int diff_opt_ignore_submodules(const struct option *opt,
5194 const char *arg, int unset)
5196 struct diff_options *options = opt->value;
5198 BUG_ON_OPT_NEG(unset);
5199 if (!arg)
5200 arg = "all";
5201 options->flags.override_submodule_config = 1;
5202 handle_ignore_submodules_arg(options, arg);
5203 return 0;
5206 static int diff_opt_line_prefix(const struct option *opt,
5207 const char *optarg, int unset)
5209 struct diff_options *options = opt->value;
5211 BUG_ON_OPT_NEG(unset);
5212 options->line_prefix = optarg;
5213 options->line_prefix_length = strlen(options->line_prefix);
5214 graph_setup_line_prefix(options);
5215 return 0;
5218 static int diff_opt_no_prefix(const struct option *opt,
5219 const char *optarg, int unset)
5221 struct diff_options *options = opt->value;
5223 BUG_ON_OPT_NEG(unset);
5224 BUG_ON_OPT_ARG(optarg);
5225 options->a_prefix = "";
5226 options->b_prefix = "";
5227 return 0;
5230 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5231 const struct option *opt,
5232 const char *arg, int unset)
5234 struct diff_options *options = opt->value;
5235 char *path;
5237 BUG_ON_OPT_NEG(unset);
5238 path = prefix_filename(ctx->prefix, arg);
5239 options->file = xfopen(path, "w");
5240 options->close_file = 1;
5241 if (options->use_color != GIT_COLOR_ALWAYS)
5242 options->use_color = GIT_COLOR_NEVER;
5243 free(path);
5244 return 0;
5247 static int diff_opt_patience(const struct option *opt,
5248 const char *arg, int unset)
5250 struct diff_options *options = opt->value;
5251 int i;
5253 BUG_ON_OPT_NEG(unset);
5254 BUG_ON_OPT_ARG(arg);
5255 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5257 * Both --patience and --anchored use PATIENCE_DIFF
5258 * internally, so remove any anchors previously
5259 * specified.
5261 for (i = 0; i < options->anchors_nr; i++)
5262 free(options->anchors[i]);
5263 options->anchors_nr = 0;
5264 return 0;
5267 static int diff_opt_ignore_regex(const struct option *opt,
5268 const char *arg, int unset)
5270 struct diff_options *options = opt->value;
5271 regex_t *regex;
5273 BUG_ON_OPT_NEG(unset);
5274 regex = xmalloc(sizeof(*regex));
5275 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5276 return error(_("invalid regex given to -I: '%s'"), arg);
5277 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5278 options->ignore_regex_alloc);
5279 options->ignore_regex[options->ignore_regex_nr++] = regex;
5280 return 0;
5283 static int diff_opt_pickaxe_regex(const struct option *opt,
5284 const char *arg, int unset)
5286 struct diff_options *options = opt->value;
5288 BUG_ON_OPT_NEG(unset);
5289 options->pickaxe = arg;
5290 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5291 return 0;
5294 static int diff_opt_pickaxe_string(const struct option *opt,
5295 const char *arg, int unset)
5297 struct diff_options *options = opt->value;
5299 BUG_ON_OPT_NEG(unset);
5300 options->pickaxe = arg;
5301 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5302 return 0;
5305 static int diff_opt_relative(const struct option *opt,
5306 const char *arg, int unset)
5308 struct diff_options *options = opt->value;
5310 options->flags.relative_name = !unset;
5311 if (arg)
5312 options->prefix = arg;
5313 return 0;
5316 static int diff_opt_submodule(const struct option *opt,
5317 const char *arg, int unset)
5319 struct diff_options *options = opt->value;
5321 BUG_ON_OPT_NEG(unset);
5322 if (!arg)
5323 arg = "log";
5324 if (parse_submodule_params(options, arg))
5325 return error(_("failed to parse --submodule option parameter: '%s'"),
5326 arg);
5327 return 0;
5330 static int diff_opt_textconv(const struct option *opt,
5331 const char *arg, int unset)
5333 struct diff_options *options = opt->value;
5335 BUG_ON_OPT_ARG(arg);
5336 if (unset) {
5337 options->flags.allow_textconv = 0;
5338 } else {
5339 options->flags.allow_textconv = 1;
5340 options->flags.textconv_set_via_cmdline = 1;
5342 return 0;
5345 static int diff_opt_unified(const struct option *opt,
5346 const char *arg, int unset)
5348 struct diff_options *options = opt->value;
5349 char *s;
5351 BUG_ON_OPT_NEG(unset);
5353 if (arg) {
5354 options->context = strtol(arg, &s, 10);
5355 if (*s)
5356 return error(_("%s expects a numerical value"), "--unified");
5358 enable_patch_output(&options->output_format);
5360 return 0;
5363 static int diff_opt_word_diff(const struct option *opt,
5364 const char *arg, int unset)
5366 struct diff_options *options = opt->value;
5368 BUG_ON_OPT_NEG(unset);
5369 if (arg) {
5370 if (!strcmp(arg, "plain"))
5371 options->word_diff = DIFF_WORDS_PLAIN;
5372 else if (!strcmp(arg, "color")) {
5373 options->use_color = 1;
5374 options->word_diff = DIFF_WORDS_COLOR;
5376 else if (!strcmp(arg, "porcelain"))
5377 options->word_diff = DIFF_WORDS_PORCELAIN;
5378 else if (!strcmp(arg, "none"))
5379 options->word_diff = DIFF_WORDS_NONE;
5380 else
5381 return error(_("bad --word-diff argument: %s"), arg);
5382 } else {
5383 if (options->word_diff == DIFF_WORDS_NONE)
5384 options->word_diff = DIFF_WORDS_PLAIN;
5386 return 0;
5389 static int diff_opt_word_diff_regex(const struct option *opt,
5390 const char *arg, int unset)
5392 struct diff_options *options = opt->value;
5394 BUG_ON_OPT_NEG(unset);
5395 if (options->word_diff == DIFF_WORDS_NONE)
5396 options->word_diff = DIFF_WORDS_PLAIN;
5397 options->word_regex = arg;
5398 return 0;
5401 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5403 struct diff_options *options = opt->value;
5405 BUG_ON_OPT_NEG(unset);
5406 if (!strcmp(opt->long_name, "skip-to"))
5407 options->skip_instead_of_rotate = 1;
5408 else
5409 options->skip_instead_of_rotate = 0;
5410 options->rotate_to = arg;
5411 return 0;
5414 struct option *add_diff_options(const struct option *opts,
5415 struct diff_options *options)
5417 struct option parseopts[] = {
5418 OPT_GROUP(N_("Diff output format options")),
5419 OPT_BITOP('p', "patch", &options->output_format,
5420 N_("generate patch"),
5421 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5422 OPT_BIT_F('s', "no-patch", &options->output_format,
5423 N_("suppress diff output"),
5424 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5425 OPT_BITOP('u', NULL, &options->output_format,
5426 N_("generate patch"),
5427 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5428 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5429 N_("generate diffs with <n> lines context"),
5430 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5431 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5432 N_("generate diffs with <n> lines context")),
5433 OPT_BIT_F(0, "raw", &options->output_format,
5434 N_("generate the diff in raw format"),
5435 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5436 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5437 N_("synonym for '-p --raw'"),
5438 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5439 DIFF_FORMAT_NO_OUTPUT),
5440 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5441 N_("synonym for '-p --stat'"),
5442 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5443 DIFF_FORMAT_NO_OUTPUT),
5444 OPT_BIT_F(0, "numstat", &options->output_format,
5445 N_("machine friendly --stat"),
5446 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5447 OPT_BIT_F(0, "shortstat", &options->output_format,
5448 N_("output only the last line of --stat"),
5449 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5450 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5451 N_("output the distribution of relative amount of changes for each sub-directory"),
5452 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5453 diff_opt_dirstat),
5454 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5455 N_("synonym for --dirstat=cumulative"),
5456 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5457 diff_opt_dirstat),
5458 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5459 N_("synonym for --dirstat=files,param1,param2..."),
5460 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5461 diff_opt_dirstat),
5462 OPT_BIT_F(0, "check", &options->output_format,
5463 N_("warn if changes introduce conflict markers or whitespace errors"),
5464 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5465 OPT_BIT_F(0, "summary", &options->output_format,
5466 N_("condensed summary such as creations, renames and mode changes"),
5467 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5468 OPT_BIT_F(0, "name-only", &options->output_format,
5469 N_("show only names of changed files"),
5470 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5471 OPT_BIT_F(0, "name-status", &options->output_format,
5472 N_("show only names and status of changed files"),
5473 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5474 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5475 N_("generate diffstat"),
5476 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5477 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5478 N_("generate diffstat with a given width"),
5479 PARSE_OPT_NONEG, diff_opt_stat),
5480 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5481 N_("generate diffstat with a given name width"),
5482 PARSE_OPT_NONEG, diff_opt_stat),
5483 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5484 N_("generate diffstat with a given graph width"),
5485 PARSE_OPT_NONEG, diff_opt_stat),
5486 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5487 N_("generate diffstat with limited lines"),
5488 PARSE_OPT_NONEG, diff_opt_stat),
5489 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5490 N_("generate compact summary in diffstat"),
5491 PARSE_OPT_NOARG, diff_opt_compact_summary),
5492 OPT_CALLBACK_F(0, "binary", options, NULL,
5493 N_("output a binary diff that can be applied"),
5494 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5495 OPT_BOOL(0, "full-index", &options->flags.full_index,
5496 N_("show full pre- and post-image object names on the \"index\" lines")),
5497 OPT_COLOR_FLAG(0, "color", &options->use_color,
5498 N_("show colored diff")),
5499 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5500 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5501 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5502 OPT_SET_INT('z', NULL, &options->line_termination,
5503 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5505 OPT__ABBREV(&options->abbrev),
5506 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5507 N_("show the given source prefix instead of \"a/\""),
5508 PARSE_OPT_NONEG),
5509 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5510 N_("show the given destination prefix instead of \"b/\""),
5511 PARSE_OPT_NONEG),
5512 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5513 N_("prepend an additional prefix to every line of output"),
5514 PARSE_OPT_NONEG, diff_opt_line_prefix),
5515 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5516 N_("do not show any source or destination prefix"),
5517 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5518 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5519 N_("show context between diff hunks up to the specified number of lines"),
5520 PARSE_OPT_NONEG),
5521 OPT_CALLBACK_F(0, "output-indicator-new",
5522 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5523 N_("<char>"),
5524 N_("specify the character to indicate a new line instead of '+'"),
5525 PARSE_OPT_NONEG, diff_opt_char),
5526 OPT_CALLBACK_F(0, "output-indicator-old",
5527 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5528 N_("<char>"),
5529 N_("specify the character to indicate an old line instead of '-'"),
5530 PARSE_OPT_NONEG, diff_opt_char),
5531 OPT_CALLBACK_F(0, "output-indicator-context",
5532 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5533 N_("<char>"),
5534 N_("specify the character to indicate a context instead of ' '"),
5535 PARSE_OPT_NONEG, diff_opt_char),
5537 OPT_GROUP(N_("Diff rename options")),
5538 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5539 N_("break complete rewrite changes into pairs of delete and create"),
5540 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5541 diff_opt_break_rewrites),
5542 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5543 N_("detect renames"),
5544 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5545 diff_opt_find_renames),
5546 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5547 N_("omit the preimage for deletes"),
5548 1, PARSE_OPT_NONEG),
5549 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5550 N_("detect copies"),
5551 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5552 diff_opt_find_copies),
5553 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5554 N_("use unmodified files as source to find copies")),
5555 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5556 N_("disable rename detection"),
5557 0, PARSE_OPT_NONEG),
5558 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5559 N_("use empty blobs as rename source")),
5560 OPT_CALLBACK_F(0, "follow", options, NULL,
5561 N_("continue listing the history of a file beyond renames"),
5562 PARSE_OPT_NOARG, diff_opt_follow),
5563 OPT_INTEGER('l', NULL, &options->rename_limit,
5564 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5566 OPT_GROUP(N_("Diff algorithm options")),
5567 OPT_BIT(0, "minimal", &options->xdl_opts,
5568 N_("produce the smallest possible diff"),
5569 XDF_NEED_MINIMAL),
5570 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5571 N_("ignore whitespace when comparing lines"),
5572 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5573 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5574 N_("ignore changes in amount of whitespace"),
5575 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5576 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5577 N_("ignore changes in whitespace at EOL"),
5578 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5579 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5580 N_("ignore carrier-return at the end of line"),
5581 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5582 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5583 N_("ignore changes whose lines are all blank"),
5584 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5585 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5586 N_("ignore changes whose all lines match <regex>"),
5587 0, diff_opt_ignore_regex),
5588 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5589 N_("heuristic to shift diff hunk boundaries for easy reading"),
5590 XDF_INDENT_HEURISTIC),
5591 OPT_CALLBACK_F(0, "patience", options, NULL,
5592 N_("generate diff using the \"patience diff\" algorithm"),
5593 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5594 diff_opt_patience),
5595 OPT_BITOP(0, "histogram", &options->xdl_opts,
5596 N_("generate diff using the \"histogram diff\" algorithm"),
5597 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5598 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5599 N_("choose a diff algorithm"),
5600 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5601 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5602 N_("generate diff using the \"anchored diff\" algorithm"),
5603 PARSE_OPT_NONEG, diff_opt_anchored),
5604 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5605 N_("show word diff, using <mode> to delimit changed words"),
5606 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5607 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5608 N_("use <regex> to decide what a word is"),
5609 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5610 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5611 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5612 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5613 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5614 N_("moved lines of code are colored differently"),
5615 PARSE_OPT_OPTARG, diff_opt_color_moved),
5616 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5617 N_("how white spaces are ignored in --color-moved"),
5618 0, diff_opt_color_moved_ws),
5620 OPT_GROUP(N_("Other diff options")),
5621 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5622 N_("when run from subdir, exclude changes outside and show relative paths"),
5623 PARSE_OPT_OPTARG,
5624 diff_opt_relative),
5625 OPT_BOOL('a', "text", &options->flags.text,
5626 N_("treat all files as text")),
5627 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5628 N_("swap two inputs, reverse the diff")),
5629 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5630 N_("exit with 1 if there were differences, 0 otherwise")),
5631 OPT_BOOL(0, "quiet", &options->flags.quick,
5632 N_("disable all output of the program")),
5633 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5634 N_("allow an external diff helper to be executed")),
5635 OPT_CALLBACK_F(0, "textconv", options, NULL,
5636 N_("run external text conversion filters when comparing binary files"),
5637 PARSE_OPT_NOARG, diff_opt_textconv),
5638 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5639 N_("ignore changes to submodules in the diff generation"),
5640 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5641 diff_opt_ignore_submodules),
5642 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5643 N_("specify how differences in submodules are shown"),
5644 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5645 diff_opt_submodule),
5646 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5647 N_("hide 'git add -N' entries from the index"),
5648 1, PARSE_OPT_NONEG),
5649 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5650 N_("treat 'git add -N' entries as real in the index"),
5651 0, PARSE_OPT_NONEG),
5652 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5653 N_("look for differences that change the number of occurrences of the specified string"),
5654 0, diff_opt_pickaxe_string),
5655 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5656 N_("look for differences that change the number of occurrences of the specified regex"),
5657 0, diff_opt_pickaxe_regex),
5658 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5659 N_("show all changes in the changeset with -S or -G"),
5660 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5661 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5662 N_("treat <string> in -S as extended POSIX regular expression"),
5663 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5664 OPT_FILENAME('O', NULL, &options->orderfile,
5665 N_("control the order in which files appear in the output")),
5666 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5667 N_("show the change in the specified path first"),
5668 PARSE_OPT_NONEG, diff_opt_rotate_to),
5669 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5670 N_("skip the output to the specified path"),
5671 PARSE_OPT_NONEG, diff_opt_rotate_to),
5672 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5673 N_("look for differences that change the number of occurrences of the specified object"),
5674 PARSE_OPT_NONEG, diff_opt_find_object),
5675 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5676 N_("select files by diff type"),
5677 PARSE_OPT_NONEG, diff_opt_diff_filter),
5678 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5679 N_("output to a specific file"),
5680 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5682 OPT_END()
5685 return parse_options_concat(opts, parseopts);
5688 int diff_opt_parse(struct diff_options *options,
5689 const char **av, int ac, const char *prefix)
5691 struct option no_options[] = { OPT_END() };
5692 struct option *parseopts = add_diff_options(no_options, options);
5694 if (!prefix)
5695 prefix = "";
5697 ac = parse_options(ac, av, prefix, parseopts, NULL,
5698 PARSE_OPT_KEEP_DASHDASH |
5699 PARSE_OPT_KEEP_UNKNOWN_OPT |
5700 PARSE_OPT_NO_INTERNAL_HELP |
5701 PARSE_OPT_ONE_SHOT |
5702 PARSE_OPT_STOP_AT_NON_OPTION);
5703 free(parseopts);
5705 return ac;
5708 int parse_rename_score(const char **cp_p)
5710 unsigned long num, scale;
5711 int ch, dot;
5712 const char *cp = *cp_p;
5714 num = 0;
5715 scale = 1;
5716 dot = 0;
5717 for (;;) {
5718 ch = *cp;
5719 if ( !dot && ch == '.' ) {
5720 scale = 1;
5721 dot = 1;
5722 } else if ( ch == '%' ) {
5723 scale = dot ? scale*100 : 100;
5724 cp++; /* % is always at the end */
5725 break;
5726 } else if ( ch >= '0' && ch <= '9' ) {
5727 if ( scale < 100000 ) {
5728 scale *= 10;
5729 num = (num*10) + (ch-'0');
5731 } else {
5732 break;
5734 cp++;
5736 *cp_p = cp;
5738 /* user says num divided by scale and we say internally that
5739 * is MAX_SCORE * num / scale.
5741 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5744 struct diff_queue_struct diff_queued_diff;
5746 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5748 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5749 queue->queue[queue->nr++] = dp;
5752 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5753 struct diff_filespec *one,
5754 struct diff_filespec *two)
5756 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5757 dp->one = one;
5758 dp->two = two;
5759 if (queue)
5760 diff_q(queue, dp);
5761 return dp;
5764 void diff_free_filepair(struct diff_filepair *p)
5766 free_filespec(p->one);
5767 free_filespec(p->two);
5768 free(p);
5771 void diff_free_queue(struct diff_queue_struct *q)
5773 for (int i = 0; i < q->nr; i++)
5774 diff_free_filepair(q->queue[i]);
5775 free(q->queue);
5778 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5780 int abblen;
5781 const char *abbrev;
5783 /* Do we want all 40 hex characters? */
5784 if (len == the_hash_algo->hexsz)
5785 return oid_to_hex(oid);
5787 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5788 abbrev = diff_abbrev_oid(oid, len);
5790 if (!print_sha1_ellipsis())
5791 return abbrev;
5793 abblen = strlen(abbrev);
5796 * In well-behaved cases, where the abbreviated result is the
5797 * same as the requested length, append three dots after the
5798 * abbreviation (hence the whole logic is limited to the case
5799 * where abblen < 37); when the actual abbreviated result is a
5800 * bit longer than the requested length, we reduce the number
5801 * of dots so that they match the well-behaved ones. However,
5802 * if the actual abbreviation is longer than the requested
5803 * length by more than three, we give up on aligning, and add
5804 * three dots anyway, to indicate that the output is not the
5805 * full object name. Yes, this may be suboptimal, but this
5806 * appears only in "diff --raw --abbrev" output and it is not
5807 * worth the effort to change it now. Note that this would
5808 * likely to work fine when the automatic sizing of default
5809 * abbreviation length is used--we would be fed -1 in "len" in
5810 * that case, and will end up always appending three-dots, but
5811 * the automatic sizing is supposed to give abblen that ensures
5812 * uniqueness across all objects (statistically speaking).
5814 if (abblen < the_hash_algo->hexsz - 3) {
5815 static char hex[GIT_MAX_HEXSZ + 1];
5816 if (len < abblen && abblen <= len + 2)
5817 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5818 else
5819 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5820 return hex;
5823 return oid_to_hex(oid);
5826 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5828 int line_termination = opt->line_termination;
5829 int inter_name_termination = line_termination ? '\t' : '\0';
5831 fprintf(opt->file, "%s", diff_line_prefix(opt));
5832 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5833 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5834 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5835 fprintf(opt->file, "%s ",
5836 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5838 if (p->score) {
5839 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5840 inter_name_termination);
5841 } else {
5842 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5845 if (p->status == DIFF_STATUS_COPIED ||
5846 p->status == DIFF_STATUS_RENAMED) {
5847 const char *name_a, *name_b;
5848 name_a = p->one->path;
5849 name_b = p->two->path;
5850 strip_prefix(opt->prefix_length, &name_a, &name_b);
5851 write_name_quoted(name_a, opt->file, inter_name_termination);
5852 write_name_quoted(name_b, opt->file, line_termination);
5853 } else {
5854 const char *name_a, *name_b;
5855 name_a = p->one->mode ? p->one->path : p->two->path;
5856 name_b = NULL;
5857 strip_prefix(opt->prefix_length, &name_a, &name_b);
5858 write_name_quoted(name_a, opt->file, line_termination);
5862 int diff_unmodified_pair(struct diff_filepair *p)
5864 /* This function is written stricter than necessary to support
5865 * the currently implemented transformers, but the idea is to
5866 * let transformers to produce diff_filepairs any way they want,
5867 * and filter and clean them up here before producing the output.
5869 struct diff_filespec *one = p->one, *two = p->two;
5871 if (DIFF_PAIR_UNMERGED(p))
5872 return 0; /* unmerged is interesting */
5874 /* deletion, addition, mode or type change
5875 * and rename are all interesting.
5877 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5878 DIFF_PAIR_MODE_CHANGED(p) ||
5879 strcmp(one->path, two->path))
5880 return 0;
5882 /* both are valid and point at the same path. that is, we are
5883 * dealing with a change.
5885 if (one->oid_valid && two->oid_valid &&
5886 oideq(&one->oid, &two->oid) &&
5887 !one->dirty_submodule && !two->dirty_submodule)
5888 return 1; /* no change */
5889 if (!one->oid_valid && !two->oid_valid)
5890 return 1; /* both look at the same file on the filesystem. */
5891 return 0;
5894 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5896 int include_conflict_headers =
5897 (additional_headers(o, p->one->path) &&
5898 !o->pickaxe_opts &&
5899 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5902 * Check if we can return early without showing a diff. Note that
5903 * diff_filepair only stores {oid, path, mode, is_valid}
5904 * information for each path, and thus diff_unmodified_pair() only
5905 * considers those bits of info. However, we do not want pairs
5906 * created by create_filepairs_for_header_only_notifications()
5907 * (which always look like unmodified pairs) to be ignored, so
5908 * return early if both p is unmodified AND we don't want to
5909 * include_conflict_headers.
5911 if (diff_unmodified_pair(p) && !include_conflict_headers)
5912 return;
5914 /* Actually, we can also return early to avoid showing tree diffs */
5915 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5916 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5917 return;
5919 run_diff(p, o);
5922 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5923 struct diffstat_t *diffstat)
5925 if (diff_unmodified_pair(p))
5926 return;
5928 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5929 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5930 return; /* no useful stat for tree diffs */
5932 run_diffstat(p, o, diffstat);
5935 static void diff_flush_checkdiff(struct diff_filepair *p,
5936 struct diff_options *o)
5938 if (diff_unmodified_pair(p))
5939 return;
5941 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5942 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5943 return; /* nothing to check in tree diffs */
5945 run_checkdiff(p, o);
5948 int diff_queue_is_empty(struct diff_options *o)
5950 struct diff_queue_struct *q = &diff_queued_diff;
5951 int i;
5952 int include_conflict_headers =
5953 (o->additional_path_headers &&
5954 strmap_get_size(o->additional_path_headers) &&
5955 !o->pickaxe_opts &&
5956 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5958 if (include_conflict_headers)
5959 return 0;
5961 for (i = 0; i < q->nr; i++)
5962 if (!diff_unmodified_pair(q->queue[i]))
5963 return 0;
5964 return 1;
5967 #if DIFF_DEBUG
5968 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5970 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5971 x, one ? one : "",
5972 s->path,
5973 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5974 s->mode,
5975 s->oid_valid ? oid_to_hex(&s->oid) : "");
5976 fprintf(stderr, "queue[%d] %s size %lu\n",
5977 x, one ? one : "",
5978 s->size);
5981 void diff_debug_filepair(const struct diff_filepair *p, int i)
5983 diff_debug_filespec(p->one, i, "one");
5984 diff_debug_filespec(p->two, i, "two");
5985 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5986 p->score, p->status ? p->status : '?',
5987 p->one->rename_used, p->broken_pair);
5990 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5992 int i;
5993 if (msg)
5994 fprintf(stderr, "%s\n", msg);
5995 fprintf(stderr, "q->nr = %d\n", q->nr);
5996 for (i = 0; i < q->nr; i++) {
5997 struct diff_filepair *p = q->queue[i];
5998 diff_debug_filepair(p, i);
6001 #endif
6003 static void diff_resolve_rename_copy(void)
6005 int i;
6006 struct diff_filepair *p;
6007 struct diff_queue_struct *q = &diff_queued_diff;
6009 diff_debug_queue("resolve-rename-copy", q);
6011 for (i = 0; i < q->nr; i++) {
6012 p = q->queue[i];
6013 p->status = 0; /* undecided */
6014 if (DIFF_PAIR_UNMERGED(p))
6015 p->status = DIFF_STATUS_UNMERGED;
6016 else if (!DIFF_FILE_VALID(p->one))
6017 p->status = DIFF_STATUS_ADDED;
6018 else if (!DIFF_FILE_VALID(p->two))
6019 p->status = DIFF_STATUS_DELETED;
6020 else if (DIFF_PAIR_TYPE_CHANGED(p))
6021 p->status = DIFF_STATUS_TYPE_CHANGED;
6023 /* from this point on, we are dealing with a pair
6024 * whose both sides are valid and of the same type, i.e.
6025 * either in-place edit or rename/copy edit.
6027 else if (DIFF_PAIR_RENAME(p)) {
6029 * A rename might have re-connected a broken
6030 * pair up, causing the pathnames to be the
6031 * same again. If so, that's not a rename at
6032 * all, just a modification..
6034 * Otherwise, see if this source was used for
6035 * multiple renames, in which case we decrement
6036 * the count, and call it a copy.
6038 if (!strcmp(p->one->path, p->two->path))
6039 p->status = DIFF_STATUS_MODIFIED;
6040 else if (--p->one->rename_used > 0)
6041 p->status = DIFF_STATUS_COPIED;
6042 else
6043 p->status = DIFF_STATUS_RENAMED;
6045 else if (!oideq(&p->one->oid, &p->two->oid) ||
6046 p->one->mode != p->two->mode ||
6047 p->one->dirty_submodule ||
6048 p->two->dirty_submodule ||
6049 is_null_oid(&p->one->oid))
6050 p->status = DIFF_STATUS_MODIFIED;
6051 else {
6052 /* This is a "no-change" entry and should not
6053 * happen anymore, but prepare for broken callers.
6055 error("feeding unmodified %s to diffcore",
6056 p->one->path);
6057 p->status = DIFF_STATUS_UNKNOWN;
6060 diff_debug_queue("resolve-rename-copy done", q);
6063 static int check_pair_status(struct diff_filepair *p)
6065 switch (p->status) {
6066 case DIFF_STATUS_UNKNOWN:
6067 return 0;
6068 case 0:
6069 die("internal error in diff-resolve-rename-copy");
6070 default:
6071 return 1;
6075 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6077 int fmt = opt->output_format;
6079 if (fmt & DIFF_FORMAT_CHECKDIFF)
6080 diff_flush_checkdiff(p, opt);
6081 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6082 diff_flush_raw(p, opt);
6083 else if (fmt & DIFF_FORMAT_NAME) {
6084 const char *name_a, *name_b;
6085 name_a = p->two->path;
6086 name_b = NULL;
6087 strip_prefix(opt->prefix_length, &name_a, &name_b);
6088 fprintf(opt->file, "%s", diff_line_prefix(opt));
6089 write_name_quoted(name_a, opt->file, opt->line_termination);
6093 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6095 struct strbuf sb = STRBUF_INIT;
6096 if (fs->mode)
6097 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6098 else
6099 strbuf_addf(&sb, " %s ", newdelete);
6101 quote_c_style(fs->path, &sb, NULL, 0);
6102 strbuf_addch(&sb, '\n');
6103 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6104 sb.buf, sb.len, 0);
6105 strbuf_release(&sb);
6108 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6109 int show_name)
6111 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6112 struct strbuf sb = STRBUF_INIT;
6113 strbuf_addf(&sb, " mode change %06o => %06o",
6114 p->one->mode, p->two->mode);
6115 if (show_name) {
6116 strbuf_addch(&sb, ' ');
6117 quote_c_style(p->two->path, &sb, NULL, 0);
6119 strbuf_addch(&sb, '\n');
6120 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6121 sb.buf, sb.len, 0);
6122 strbuf_release(&sb);
6126 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6127 struct diff_filepair *p)
6129 struct strbuf sb = STRBUF_INIT;
6130 struct strbuf names = STRBUF_INIT;
6132 pprint_rename(&names, p->one->path, p->two->path);
6133 strbuf_addf(&sb, " %s %s (%d%%)\n",
6134 renamecopy, names.buf, similarity_index(p));
6135 strbuf_release(&names);
6136 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6137 sb.buf, sb.len, 0);
6138 show_mode_change(opt, p, 0);
6139 strbuf_release(&sb);
6142 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6144 switch(p->status) {
6145 case DIFF_STATUS_DELETED:
6146 show_file_mode_name(opt, "delete", p->one);
6147 break;
6148 case DIFF_STATUS_ADDED:
6149 show_file_mode_name(opt, "create", p->two);
6150 break;
6151 case DIFF_STATUS_COPIED:
6152 show_rename_copy(opt, "copy", p);
6153 break;
6154 case DIFF_STATUS_RENAMED:
6155 show_rename_copy(opt, "rename", p);
6156 break;
6157 default:
6158 if (p->score) {
6159 struct strbuf sb = STRBUF_INIT;
6160 strbuf_addstr(&sb, " rewrite ");
6161 quote_c_style(p->two->path, &sb, NULL, 0);
6162 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6163 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6164 sb.buf, sb.len, 0);
6165 strbuf_release(&sb);
6167 show_mode_change(opt, p, !p->score);
6168 break;
6172 struct patch_id_t {
6173 git_hash_ctx *ctx;
6174 int patchlen;
6177 static int remove_space(char *line, int len)
6179 int i;
6180 char *dst = line;
6181 unsigned char c;
6183 for (i = 0; i < len; i++)
6184 if (!isspace((c = line[i])))
6185 *dst++ = c;
6187 return dst - line;
6190 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6192 unsigned char hash[GIT_MAX_RAWSZ];
6193 unsigned short carry = 0;
6194 int i;
6196 the_hash_algo->final_fn(hash, ctx);
6197 the_hash_algo->init_fn(ctx);
6198 /* 20-byte sum, with carry */
6199 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6200 carry += result->hash[i] + hash[i];
6201 result->hash[i] = carry;
6202 carry >>= 8;
6206 static int patch_id_consume(void *priv, char *line, unsigned long len)
6208 struct patch_id_t *data = priv;
6209 int new_len;
6211 if (len > 12 && starts_with(line, "\\ "))
6212 return 0;
6213 new_len = remove_space(line, len);
6215 the_hash_algo->update_fn(data->ctx, line, new_len);
6216 data->patchlen += new_len;
6217 return 0;
6220 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6222 the_hash_algo->update_fn(ctx, str, strlen(str));
6225 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6227 /* large enough for 2^32 in octal */
6228 char buf[12];
6229 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6230 the_hash_algo->update_fn(ctx, buf, len);
6233 /* returns 0 upon success, and writes result into oid */
6234 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6236 struct diff_queue_struct *q = &diff_queued_diff;
6237 int i;
6238 git_hash_ctx ctx;
6239 struct patch_id_t data;
6241 the_hash_algo->init_fn(&ctx);
6242 memset(&data, 0, sizeof(struct patch_id_t));
6243 data.ctx = &ctx;
6244 oidclr(oid);
6246 for (i = 0; i < q->nr; i++) {
6247 xpparam_t xpp;
6248 xdemitconf_t xecfg;
6249 mmfile_t mf1, mf2;
6250 struct diff_filepair *p = q->queue[i];
6251 int len1, len2;
6253 memset(&xpp, 0, sizeof(xpp));
6254 memset(&xecfg, 0, sizeof(xecfg));
6255 if (p->status == 0)
6256 return error("internal diff status error");
6257 if (p->status == DIFF_STATUS_UNKNOWN)
6258 continue;
6259 if (diff_unmodified_pair(p))
6260 continue;
6261 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6262 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6263 continue;
6264 if (DIFF_PAIR_UNMERGED(p))
6265 continue;
6267 diff_fill_oid_info(p->one, options->repo->index);
6268 diff_fill_oid_info(p->two, options->repo->index);
6270 len1 = remove_space(p->one->path, strlen(p->one->path));
6271 len2 = remove_space(p->two->path, strlen(p->two->path));
6272 patch_id_add_string(&ctx, "diff--git");
6273 patch_id_add_string(&ctx, "a/");
6274 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6275 patch_id_add_string(&ctx, "b/");
6276 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6278 if (p->one->mode == 0) {
6279 patch_id_add_string(&ctx, "newfilemode");
6280 patch_id_add_mode(&ctx, p->two->mode);
6281 } else if (p->two->mode == 0) {
6282 patch_id_add_string(&ctx, "deletedfilemode");
6283 patch_id_add_mode(&ctx, p->one->mode);
6284 } else if (p->one->mode != p->two->mode) {
6285 patch_id_add_string(&ctx, "oldmode");
6286 patch_id_add_mode(&ctx, p->one->mode);
6287 patch_id_add_string(&ctx, "newmode");
6288 patch_id_add_mode(&ctx, p->two->mode);
6291 if (diff_header_only) {
6292 /* don't do anything since we're only populating header info */
6293 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6294 diff_filespec_is_binary(options->repo, p->two)) {
6295 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6296 the_hash_algo->hexsz);
6297 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6298 the_hash_algo->hexsz);
6299 } else {
6300 if (p->one->mode == 0) {
6301 patch_id_add_string(&ctx, "---/dev/null");
6302 patch_id_add_string(&ctx, "+++b/");
6303 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6304 } else if (p->two->mode == 0) {
6305 patch_id_add_string(&ctx, "---a/");
6306 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6307 patch_id_add_string(&ctx, "+++/dev/null");
6308 } else {
6309 patch_id_add_string(&ctx, "---a/");
6310 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6311 patch_id_add_string(&ctx, "+++b/");
6312 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6315 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6316 fill_mmfile(options->repo, &mf2, p->two) < 0)
6317 return error("unable to read files to diff");
6318 xpp.flags = 0;
6319 xecfg.ctxlen = 3;
6320 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6321 if (xdi_diff_outf(&mf1, &mf2, NULL,
6322 patch_id_consume, &data, &xpp, &xecfg))
6323 return error("unable to generate patch-id diff for %s",
6324 p->one->path);
6326 flush_one_hunk(oid, &ctx);
6329 return 0;
6332 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6334 struct diff_queue_struct *q = &diff_queued_diff;
6335 int result = diff_get_patch_id(options, oid, diff_header_only);
6337 diff_free_queue(q);
6338 DIFF_QUEUE_CLEAR(q);
6340 return result;
6343 static int is_summary_empty(const struct diff_queue_struct *q)
6345 int i;
6347 for (i = 0; i < q->nr; i++) {
6348 const struct diff_filepair *p = q->queue[i];
6350 switch (p->status) {
6351 case DIFF_STATUS_DELETED:
6352 case DIFF_STATUS_ADDED:
6353 case DIFF_STATUS_COPIED:
6354 case DIFF_STATUS_RENAMED:
6355 return 0;
6356 default:
6357 if (p->score)
6358 return 0;
6359 if (p->one->mode && p->two->mode &&
6360 p->one->mode != p->two->mode)
6361 return 0;
6362 break;
6365 return 1;
6368 static const char rename_limit_warning[] =
6369 N_("exhaustive rename detection was skipped due to too many files.");
6371 static const char degrade_cc_to_c_warning[] =
6372 N_("only found copies from modified paths due to too many files.");
6374 static const char rename_limit_advice[] =
6375 N_("you may want to set your %s variable to at least "
6376 "%d and retry the command.");
6378 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6380 fflush(stdout);
6381 if (degraded_cc)
6382 warning(_(degrade_cc_to_c_warning));
6383 else if (needed)
6384 warning(_(rename_limit_warning));
6385 else
6386 return;
6387 if (0 < needed)
6388 warning(_(rename_limit_advice), varname, needed);
6391 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6393 struct strset present;
6394 struct diff_queue_struct *q = &diff_queued_diff;
6395 struct hashmap_iter iter;
6396 struct strmap_entry *e;
6397 int i;
6399 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6402 * Find out which paths exist in diff_queued_diff, preferring
6403 * one->path for any pair that has multiple paths.
6405 for (i = 0; i < q->nr; i++) {
6406 struct diff_filepair *p = q->queue[i];
6407 char *path = p->one->path ? p->one->path : p->two->path;
6409 if (strmap_contains(o->additional_path_headers, path))
6410 strset_add(&present, path);
6414 * Loop over paths in additional_path_headers; for each NOT already
6415 * in diff_queued_diff, create a synthetic filepair and insert that
6416 * into diff_queued_diff.
6418 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6419 if (!strset_contains(&present, e->key)) {
6420 struct diff_filespec *one, *two;
6421 struct diff_filepair *p;
6423 one = alloc_filespec(e->key);
6424 two = alloc_filespec(e->key);
6425 fill_filespec(one, null_oid(), 0, 0);
6426 fill_filespec(two, null_oid(), 0, 0);
6427 p = diff_queue(q, one, two);
6428 p->status = DIFF_STATUS_MODIFIED;
6432 /* Re-sort the filepairs */
6433 diffcore_fix_diff_index();
6435 /* Cleanup */
6436 strset_clear(&present);
6439 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6441 int i;
6442 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6443 struct diff_queue_struct *q = &diff_queued_diff;
6445 if (WSEH_NEW & WS_RULE_MASK)
6446 BUG("WS rules bit mask overlaps with diff symbol flags");
6448 if (o->color_moved)
6449 o->emitted_symbols = &esm;
6451 if (o->additional_path_headers)
6452 create_filepairs_for_header_only_notifications(o);
6454 for (i = 0; i < q->nr; i++) {
6455 struct diff_filepair *p = q->queue[i];
6456 if (check_pair_status(p))
6457 diff_flush_patch(p, o);
6460 if (o->emitted_symbols) {
6461 if (o->color_moved) {
6462 struct mem_pool entry_pool;
6463 struct moved_entry_list *entry_list;
6465 mem_pool_init(&entry_pool, 1024 * 1024);
6466 entry_list = add_lines_to_move_detection(o,
6467 &entry_pool);
6468 mark_color_as_moved(o, entry_list);
6469 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6470 dim_moved_lines(o);
6472 mem_pool_discard(&entry_pool, 0);
6473 free(entry_list);
6476 for (i = 0; i < esm.nr; i++)
6477 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6479 for (i = 0; i < esm.nr; i++)
6480 free((void *)esm.buf[i].line);
6481 esm.nr = 0;
6483 o->emitted_symbols = NULL;
6487 static void diff_free_file(struct diff_options *options)
6489 if (options->close_file)
6490 fclose(options->file);
6493 static void diff_free_ignore_regex(struct diff_options *options)
6495 int i;
6497 for (i = 0; i < options->ignore_regex_nr; i++) {
6498 regfree(options->ignore_regex[i]);
6499 free(options->ignore_regex[i]);
6501 free(options->ignore_regex);
6504 void diff_free(struct diff_options *options)
6506 if (options->no_free)
6507 return;
6509 diff_free_file(options);
6510 diff_free_ignore_regex(options);
6511 clear_pathspec(&options->pathspec);
6514 void diff_flush(struct diff_options *options)
6516 struct diff_queue_struct *q = &diff_queued_diff;
6517 int i, output_format = options->output_format;
6518 int separator = 0;
6519 int dirstat_by_line = 0;
6522 * Order: raw, stat, summary, patch
6523 * or: name/name-status/checkdiff (other bits clear)
6525 if (!q->nr && !options->additional_path_headers)
6526 goto free_queue;
6528 if (output_format & (DIFF_FORMAT_RAW |
6529 DIFF_FORMAT_NAME |
6530 DIFF_FORMAT_NAME_STATUS |
6531 DIFF_FORMAT_CHECKDIFF)) {
6532 for (i = 0; i < q->nr; i++) {
6533 struct diff_filepair *p = q->queue[i];
6534 if (check_pair_status(p))
6535 flush_one_pair(p, options);
6537 separator++;
6540 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6541 dirstat_by_line = 1;
6543 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6544 dirstat_by_line) {
6545 struct diffstat_t diffstat;
6547 compute_diffstat(options, &diffstat, q);
6548 if (output_format & DIFF_FORMAT_NUMSTAT)
6549 show_numstat(&diffstat, options);
6550 if (output_format & DIFF_FORMAT_DIFFSTAT)
6551 show_stats(&diffstat, options);
6552 if (output_format & DIFF_FORMAT_SHORTSTAT)
6553 show_shortstats(&diffstat, options);
6554 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6555 show_dirstat_by_line(&diffstat, options);
6556 free_diffstat_info(&diffstat);
6557 separator++;
6559 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6560 show_dirstat(options);
6562 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6563 for (i = 0; i < q->nr; i++) {
6564 diff_summary(options, q->queue[i]);
6566 separator++;
6569 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6570 options->flags.exit_with_status &&
6571 options->flags.diff_from_contents) {
6573 * run diff_flush_patch for the exit status. setting
6574 * options->file to /dev/null should be safe, because we
6575 * aren't supposed to produce any output anyway.
6577 diff_free_file(options);
6578 options->file = xfopen("/dev/null", "w");
6579 options->close_file = 1;
6580 options->color_moved = 0;
6581 for (i = 0; i < q->nr; i++) {
6582 struct diff_filepair *p = q->queue[i];
6583 if (check_pair_status(p))
6584 diff_flush_patch(p, options);
6585 if (options->found_changes)
6586 break;
6590 if (output_format & DIFF_FORMAT_PATCH) {
6591 if (separator) {
6592 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6593 if (options->stat_sep)
6594 /* attach patch instead of inline */
6595 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6596 NULL, 0, 0);
6599 diff_flush_patch_all_file_pairs(options);
6602 if (output_format & DIFF_FORMAT_CALLBACK)
6603 options->format_callback(q, options, options->format_callback_data);
6605 free_queue:
6606 diff_free_queue(q);
6607 DIFF_QUEUE_CLEAR(q);
6608 diff_free(options);
6611 * Report the content-level differences with HAS_CHANGES;
6612 * diff_addremove/diff_change does not set the bit when
6613 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6615 if (options->flags.diff_from_contents) {
6616 if (options->found_changes)
6617 options->flags.has_changes = 1;
6618 else
6619 options->flags.has_changes = 0;
6623 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6625 return (((p->status == DIFF_STATUS_MODIFIED) &&
6626 ((p->score &&
6627 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6628 (!p->score &&
6629 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6630 ((p->status != DIFF_STATUS_MODIFIED) &&
6631 filter_bit_tst(p->status, options)));
6634 static void diffcore_apply_filter(struct diff_options *options)
6636 int i;
6637 struct diff_queue_struct *q = &diff_queued_diff;
6638 struct diff_queue_struct outq;
6640 DIFF_QUEUE_CLEAR(&outq);
6642 if (!options->filter)
6643 return;
6645 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6646 int found;
6647 for (i = found = 0; !found && i < q->nr; i++) {
6648 if (match_filter(options, q->queue[i]))
6649 found++;
6651 if (found)
6652 return;
6654 /* otherwise we will clear the whole queue
6655 * by copying the empty outq at the end of this
6656 * function, but first clear the current entries
6657 * in the queue.
6659 for (i = 0; i < q->nr; i++)
6660 diff_free_filepair(q->queue[i]);
6662 else {
6663 /* Only the matching ones */
6664 for (i = 0; i < q->nr; i++) {
6665 struct diff_filepair *p = q->queue[i];
6666 if (match_filter(options, p))
6667 diff_q(&outq, p);
6668 else
6669 diff_free_filepair(p);
6672 free(q->queue);
6673 *q = outq;
6676 /* Check whether two filespecs with the same mode and size are identical */
6677 static int diff_filespec_is_identical(struct repository *r,
6678 struct diff_filespec *one,
6679 struct diff_filespec *two)
6681 if (S_ISGITLINK(one->mode))
6682 return 0;
6683 if (diff_populate_filespec(r, one, NULL))
6684 return 0;
6685 if (diff_populate_filespec(r, two, NULL))
6686 return 0;
6687 return !memcmp(one->data, two->data, one->size);
6690 static int diff_filespec_check_stat_unmatch(struct repository *r,
6691 struct diff_filepair *p)
6693 struct diff_populate_filespec_options dpf_options = {
6694 .check_size_only = 1,
6695 .missing_object_cb = diff_queued_diff_prefetch,
6696 .missing_object_data = r,
6699 if (p->done_skip_stat_unmatch)
6700 return p->skip_stat_unmatch_result;
6702 p->done_skip_stat_unmatch = 1;
6703 p->skip_stat_unmatch_result = 0;
6705 * 1. Entries that come from stat info dirtiness
6706 * always have both sides (iow, not create/delete),
6707 * one side of the object name is unknown, with
6708 * the same mode and size. Keep the ones that
6709 * do not match these criteria. They have real
6710 * differences.
6712 * 2. At this point, the file is known to be modified,
6713 * with the same mode and size, and the object
6714 * name of one side is unknown. Need to inspect
6715 * the identical contents.
6717 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6718 !DIFF_FILE_VALID(p->two) ||
6719 (p->one->oid_valid && p->two->oid_valid) ||
6720 (p->one->mode != p->two->mode) ||
6721 diff_populate_filespec(r, p->one, &dpf_options) ||
6722 diff_populate_filespec(r, p->two, &dpf_options) ||
6723 (p->one->size != p->two->size) ||
6724 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6725 p->skip_stat_unmatch_result = 1;
6726 return p->skip_stat_unmatch_result;
6729 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6731 int i;
6732 struct diff_queue_struct *q = &diff_queued_diff;
6733 struct diff_queue_struct outq;
6734 DIFF_QUEUE_CLEAR(&outq);
6736 for (i = 0; i < q->nr; i++) {
6737 struct diff_filepair *p = q->queue[i];
6739 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6740 diff_q(&outq, p);
6741 else {
6743 * The caller can subtract 1 from skip_stat_unmatch
6744 * to determine how many paths were dirty only
6745 * due to stat info mismatch.
6747 if (!diffopt->flags.no_index)
6748 diffopt->skip_stat_unmatch++;
6749 diff_free_filepair(p);
6752 free(q->queue);
6753 *q = outq;
6756 static int diffnamecmp(const void *a_, const void *b_)
6758 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6759 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6760 const char *name_a, *name_b;
6762 name_a = a->one ? a->one->path : a->two->path;
6763 name_b = b->one ? b->one->path : b->two->path;
6764 return strcmp(name_a, name_b);
6767 void diffcore_fix_diff_index(void)
6769 struct diff_queue_struct *q = &diff_queued_diff;
6770 QSORT(q->queue, q->nr, diffnamecmp);
6773 void diff_add_if_missing(struct repository *r,
6774 struct oid_array *to_fetch,
6775 const struct diff_filespec *filespec)
6777 if (filespec && filespec->oid_valid &&
6778 !S_ISGITLINK(filespec->mode) &&
6779 oid_object_info_extended(r, &filespec->oid, NULL,
6780 OBJECT_INFO_FOR_PREFETCH))
6781 oid_array_append(to_fetch, &filespec->oid);
6784 void diff_queued_diff_prefetch(void *repository)
6786 struct repository *repo = repository;
6787 int i;
6788 struct diff_queue_struct *q = &diff_queued_diff;
6789 struct oid_array to_fetch = OID_ARRAY_INIT;
6791 for (i = 0; i < q->nr; i++) {
6792 struct diff_filepair *p = q->queue[i];
6793 diff_add_if_missing(repo, &to_fetch, p->one);
6794 diff_add_if_missing(repo, &to_fetch, p->two);
6798 * NEEDSWORK: Consider deduplicating the OIDs sent.
6800 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6802 oid_array_clear(&to_fetch);
6805 void diffcore_std(struct diff_options *options)
6807 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6808 DIFF_FORMAT_NUMSTAT |
6809 DIFF_FORMAT_PATCH |
6810 DIFF_FORMAT_SHORTSTAT |
6811 DIFF_FORMAT_DIRSTAT;
6814 * Check if the user requested a blob-data-requiring diff output and/or
6815 * break-rewrite detection (which requires blob data). If yes, prefetch
6816 * the diff pairs.
6818 * If no prefetching occurs, diffcore_rename() will prefetch if it
6819 * decides that it needs inexact rename detection.
6821 if (options->repo == the_repository && has_promisor_remote() &&
6822 (options->output_format & output_formats_to_prefetch ||
6823 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6824 diff_queued_diff_prefetch(options->repo);
6826 /* NOTE please keep the following in sync with diff_tree_combined() */
6827 if (options->skip_stat_unmatch)
6828 diffcore_skip_stat_unmatch(options);
6829 if (!options->found_follow) {
6830 /* See try_to_follow_renames() in tree-diff.c */
6831 if (options->break_opt != -1)
6832 diffcore_break(options->repo,
6833 options->break_opt);
6834 if (options->detect_rename)
6835 diffcore_rename(options);
6836 if (options->break_opt != -1)
6837 diffcore_merge_broken();
6839 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6840 diffcore_pickaxe(options);
6841 if (options->orderfile)
6842 diffcore_order(options->orderfile);
6843 if (options->rotate_to)
6844 diffcore_rotate(options);
6845 if (!options->found_follow)
6846 /* See try_to_follow_renames() in tree-diff.c */
6847 diff_resolve_rename_copy();
6848 diffcore_apply_filter(options);
6850 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6851 options->flags.has_changes = 1;
6852 else
6853 options->flags.has_changes = 0;
6855 options->found_follow = 0;
6858 int diff_result_code(struct diff_options *opt, int status)
6860 int result = 0;
6862 diff_warn_rename_limit("diff.renameLimit",
6863 opt->needed_rename_limit,
6864 opt->degraded_cc_to_c);
6865 if (!opt->flags.exit_with_status &&
6866 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6867 return status;
6868 if (opt->flags.exit_with_status &&
6869 opt->flags.has_changes)
6870 result |= 01;
6871 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6872 opt->flags.check_failed)
6873 result |= 02;
6874 return result;
6877 int diff_can_quit_early(struct diff_options *opt)
6879 return (opt->flags.quick &&
6880 !opt->filter &&
6881 opt->flags.has_changes);
6885 * Shall changes to this submodule be ignored?
6887 * Submodule changes can be configured to be ignored separately for each path,
6888 * but that configuration can be overridden from the command line.
6890 static int is_submodule_ignored(const char *path, struct diff_options *options)
6892 int ignored = 0;
6893 struct diff_flags orig_flags = options->flags;
6894 if (!options->flags.override_submodule_config)
6895 set_diffopt_flags_from_submodule_config(options, path);
6896 if (options->flags.ignore_submodules)
6897 ignored = 1;
6898 options->flags = orig_flags;
6899 return ignored;
6902 void compute_diffstat(struct diff_options *options,
6903 struct diffstat_t *diffstat,
6904 struct diff_queue_struct *q)
6906 int i;
6908 memset(diffstat, 0, sizeof(struct diffstat_t));
6909 for (i = 0; i < q->nr; i++) {
6910 struct diff_filepair *p = q->queue[i];
6911 if (check_pair_status(p))
6912 diff_flush_stat(p, options, diffstat);
6916 void diff_addremove(struct diff_options *options,
6917 int addremove, unsigned mode,
6918 const struct object_id *oid,
6919 int oid_valid,
6920 const char *concatpath, unsigned dirty_submodule)
6922 struct diff_filespec *one, *two;
6924 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6925 return;
6927 /* This may look odd, but it is a preparation for
6928 * feeding "there are unchanged files which should
6929 * not produce diffs, but when you are doing copy
6930 * detection you would need them, so here they are"
6931 * entries to the diff-core. They will be prefixed
6932 * with something like '=' or '*' (I haven't decided
6933 * which but should not make any difference).
6934 * Feeding the same new and old to diff_change()
6935 * also has the same effect.
6936 * Before the final output happens, they are pruned after
6937 * merged into rename/copy pairs as appropriate.
6939 if (options->flags.reverse_diff)
6940 addremove = (addremove == '+' ? '-' :
6941 addremove == '-' ? '+' : addremove);
6943 if (options->prefix &&
6944 strncmp(concatpath, options->prefix, options->prefix_length))
6945 return;
6947 one = alloc_filespec(concatpath);
6948 two = alloc_filespec(concatpath);
6950 if (addremove != '+')
6951 fill_filespec(one, oid, oid_valid, mode);
6952 if (addremove != '-') {
6953 fill_filespec(two, oid, oid_valid, mode);
6954 two->dirty_submodule = dirty_submodule;
6957 diff_queue(&diff_queued_diff, one, two);
6958 if (!options->flags.diff_from_contents)
6959 options->flags.has_changes = 1;
6962 void diff_change(struct diff_options *options,
6963 unsigned old_mode, unsigned new_mode,
6964 const struct object_id *old_oid,
6965 const struct object_id *new_oid,
6966 int old_oid_valid, int new_oid_valid,
6967 const char *concatpath,
6968 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6970 struct diff_filespec *one, *two;
6971 struct diff_filepair *p;
6973 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6974 is_submodule_ignored(concatpath, options))
6975 return;
6977 if (options->flags.reverse_diff) {
6978 SWAP(old_mode, new_mode);
6979 SWAP(old_oid, new_oid);
6980 SWAP(old_oid_valid, new_oid_valid);
6981 SWAP(old_dirty_submodule, new_dirty_submodule);
6984 if (options->prefix &&
6985 strncmp(concatpath, options->prefix, options->prefix_length))
6986 return;
6988 one = alloc_filespec(concatpath);
6989 two = alloc_filespec(concatpath);
6990 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6991 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6992 one->dirty_submodule = old_dirty_submodule;
6993 two->dirty_submodule = new_dirty_submodule;
6994 p = diff_queue(&diff_queued_diff, one, two);
6996 if (options->flags.diff_from_contents)
6997 return;
6999 if (options->flags.quick && options->skip_stat_unmatch &&
7000 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7001 diff_free_filespec_data(p->one);
7002 diff_free_filespec_data(p->two);
7003 return;
7006 options->flags.has_changes = 1;
7009 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7011 struct diff_filepair *pair;
7012 struct diff_filespec *one, *two;
7014 if (options->prefix &&
7015 strncmp(path, options->prefix, options->prefix_length))
7016 return NULL;
7018 one = alloc_filespec(path);
7019 two = alloc_filespec(path);
7020 pair = diff_queue(&diff_queued_diff, one, two);
7021 pair->is_unmerged = 1;
7022 return pair;
7025 static char *run_textconv(struct repository *r,
7026 const char *pgm,
7027 struct diff_filespec *spec,
7028 size_t *outsize)
7030 struct diff_tempfile *temp;
7031 struct child_process child = CHILD_PROCESS_INIT;
7032 struct strbuf buf = STRBUF_INIT;
7033 int err = 0;
7035 temp = prepare_temp_file(r, spec);
7036 strvec_push(&child.args, pgm);
7037 strvec_push(&child.args, temp->name);
7039 child.use_shell = 1;
7040 child.out = -1;
7041 if (start_command(&child)) {
7042 remove_tempfile();
7043 return NULL;
7046 if (strbuf_read(&buf, child.out, 0) < 0)
7047 err = error("error reading from textconv command '%s'", pgm);
7048 close(child.out);
7050 if (finish_command(&child) || err) {
7051 strbuf_release(&buf);
7052 remove_tempfile();
7053 return NULL;
7055 remove_tempfile();
7057 return strbuf_detach(&buf, outsize);
7060 size_t fill_textconv(struct repository *r,
7061 struct userdiff_driver *driver,
7062 struct diff_filespec *df,
7063 char **outbuf)
7065 size_t size;
7067 if (!driver) {
7068 if (!DIFF_FILE_VALID(df)) {
7069 *outbuf = "";
7070 return 0;
7072 if (diff_populate_filespec(r, df, NULL))
7073 die("unable to read files to diff");
7074 *outbuf = df->data;
7075 return df->size;
7078 if (!driver->textconv)
7079 BUG("fill_textconv called with non-textconv driver");
7081 if (driver->textconv_cache && df->oid_valid) {
7082 *outbuf = notes_cache_get(driver->textconv_cache,
7083 &df->oid,
7084 &size);
7085 if (*outbuf)
7086 return size;
7089 *outbuf = run_textconv(r, driver->textconv, df, &size);
7090 if (!*outbuf)
7091 die("unable to read files to diff");
7093 if (driver->textconv_cache && df->oid_valid) {
7094 /* ignore errors, as we might be in a readonly repository */
7095 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7096 size);
7098 * we could save up changes and flush them all at the end,
7099 * but we would need an extra call after all diffing is done.
7100 * Since generating a cache entry is the slow path anyway,
7101 * this extra overhead probably isn't a big deal.
7103 notes_cache_write(driver->textconv_cache);
7106 return size;
7109 int textconv_object(struct repository *r,
7110 const char *path,
7111 unsigned mode,
7112 const struct object_id *oid,
7113 int oid_valid,
7114 char **buf,
7115 unsigned long *buf_size)
7117 struct diff_filespec *df;
7118 struct userdiff_driver *textconv;
7120 df = alloc_filespec(path);
7121 fill_filespec(df, oid, oid_valid, mode);
7122 textconv = get_textconv(r, df);
7123 if (!textconv) {
7124 free_filespec(df);
7125 return 0;
7128 *buf_size = fill_textconv(r, textconv, df, buf);
7129 free_filespec(df);
7130 return 1;
7133 void setup_diff_pager(struct diff_options *opt)
7136 * If the user asked for our exit code, then either they want --quiet
7137 * or --exit-code. We should definitely not bother with a pager in the
7138 * former case, as we will generate no output. Since we still properly
7139 * report our exit code even when a pager is run, we _could_ run a
7140 * pager with --exit-code. But since we have not done so historically,
7141 * and because it is easy to find people oneline advising "git diff
7142 * --exit-code" in hooks and other scripts, we do not do so.
7144 if (!opt->flags.exit_with_status &&
7145 check_pager_config("diff") != 0)
7146 setup_pager();