Merge branch 'fc/completion-colors-do-not-need-prompt-command'
[git.git] / diff.c
blob1617aa50a983fdfe2421566efdf192d2ce87fbb3
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 void diff_set_noprefix(struct diff_options *options)
3381 options->a_prefix = options->b_prefix = "";
3384 void diff_set_default_prefix(struct diff_options *options)
3386 options->a_prefix = "a/";
3387 options->b_prefix = "b/";
3390 struct userdiff_driver *get_textconv(struct repository *r,
3391 struct diff_filespec *one)
3393 if (!DIFF_FILE_VALID(one))
3394 return NULL;
3396 diff_filespec_load_driver(one, r->index);
3397 return userdiff_get_textconv(r, one->driver);
3400 static struct string_list *additional_headers(struct diff_options *o,
3401 const char *path)
3403 if (!o->additional_path_headers)
3404 return NULL;
3405 return strmap_get(o->additional_path_headers, path);
3408 static void add_formatted_header(struct strbuf *msg,
3409 const char *header,
3410 const char *line_prefix,
3411 const char *meta,
3412 const char *reset)
3414 const char *next, *newline;
3416 for (next = header; *next; next = newline) {
3417 newline = strchrnul(next, '\n');
3418 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3419 (int)(newline - next), next, reset);
3420 if (*newline)
3421 newline++;
3425 static void add_formatted_headers(struct strbuf *msg,
3426 struct string_list *more_headers,
3427 const char *line_prefix,
3428 const char *meta,
3429 const char *reset)
3431 int i;
3433 for (i = 0; i < more_headers->nr; i++)
3434 add_formatted_header(msg, more_headers->items[i].string,
3435 line_prefix, meta, reset);
3438 static int diff_filepair_is_phoney(struct diff_filespec *one,
3439 struct diff_filespec *two)
3442 * This function specifically looks for pairs injected by
3443 * create_filepairs_for_header_only_notifications(). Such
3444 * pairs are "phoney" in that they do not represent any
3445 * content or even mode difference, but were inserted because
3446 * diff_queued_diff previously had no pair associated with
3447 * that path but we needed some pair to avoid losing the
3448 * "remerge CONFLICT" header associated with the path.
3450 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3453 static int set_diff_algorithm(struct diff_options *opts,
3454 const char *alg)
3456 long value = parse_algorithm_value(alg);
3458 if (value < 0)
3459 return -1;
3461 /* clear out previous settings */
3462 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3463 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3464 opts->xdl_opts |= value;
3466 return 0;
3469 static void builtin_diff(const char *name_a,
3470 const char *name_b,
3471 struct diff_filespec *one,
3472 struct diff_filespec *two,
3473 const char *xfrm_msg,
3474 int must_show_header,
3475 struct diff_options *o,
3476 int complete_rewrite)
3478 mmfile_t mf1, mf2;
3479 const char *lbl[2];
3480 char *a_one, *b_two;
3481 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3482 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3483 const char *a_prefix, *b_prefix;
3484 struct userdiff_driver *textconv_one = NULL;
3485 struct userdiff_driver *textconv_two = NULL;
3486 struct strbuf header = STRBUF_INIT;
3487 const char *line_prefix = diff_line_prefix(o);
3489 diff_set_mnemonic_prefix(o, "a/", "b/");
3490 if (o->flags.reverse_diff) {
3491 a_prefix = o->b_prefix;
3492 b_prefix = o->a_prefix;
3493 } else {
3494 a_prefix = o->a_prefix;
3495 b_prefix = o->b_prefix;
3498 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3499 (!one->mode || S_ISGITLINK(one->mode)) &&
3500 (!two->mode || S_ISGITLINK(two->mode)) &&
3501 (!diff_filepair_is_phoney(one, two))) {
3502 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3503 &one->oid, &two->oid,
3504 two->dirty_submodule);
3505 return;
3506 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3507 (!one->mode || S_ISGITLINK(one->mode)) &&
3508 (!two->mode || S_ISGITLINK(two->mode)) &&
3509 (!diff_filepair_is_phoney(one, two))) {
3510 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3511 &one->oid, &two->oid,
3512 two->dirty_submodule);
3513 return;
3516 if (o->flags.allow_textconv) {
3517 textconv_one = get_textconv(o->repo, one);
3518 textconv_two = get_textconv(o->repo, two);
3521 /* Never use a non-valid filename anywhere if at all possible */
3522 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3523 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3525 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3526 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3527 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3528 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3529 if (diff_filepair_is_phoney(one, two)) {
3531 * We should only reach this point for pairs generated from
3532 * create_filepairs_for_header_only_notifications(). For
3533 * these, we want to avoid the "/dev/null" special casing
3534 * above, because we do not want such pairs shown as either
3535 * "new file" or "deleted file" below.
3537 lbl[0] = a_one;
3538 lbl[1] = b_two;
3540 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3541 if (lbl[0][0] == '/') {
3542 /* /dev/null */
3543 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3544 if (xfrm_msg)
3545 strbuf_addstr(&header, xfrm_msg);
3546 must_show_header = 1;
3548 else if (lbl[1][0] == '/') {
3549 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3550 if (xfrm_msg)
3551 strbuf_addstr(&header, xfrm_msg);
3552 must_show_header = 1;
3554 else {
3555 if (one->mode != two->mode) {
3556 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3557 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3558 must_show_header = 1;
3560 if (xfrm_msg)
3561 strbuf_addstr(&header, xfrm_msg);
3564 * we do not run diff between different kind
3565 * of objects.
3567 if ((one->mode ^ two->mode) & S_IFMT)
3568 goto free_ab_and_return;
3569 if (complete_rewrite &&
3570 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3571 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3572 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3573 header.buf, header.len, 0);
3574 strbuf_reset(&header);
3575 emit_rewrite_diff(name_a, name_b, one, two,
3576 textconv_one, textconv_two, o);
3577 o->found_changes = 1;
3578 goto free_ab_and_return;
3582 if (o->irreversible_delete && lbl[1][0] == '/') {
3583 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3584 header.len, 0);
3585 strbuf_reset(&header);
3586 goto free_ab_and_return;
3587 } else if (!o->flags.text &&
3588 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3589 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3590 struct strbuf sb = STRBUF_INIT;
3591 if (!one->data && !two->data &&
3592 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3593 !o->flags.binary) {
3594 if (oideq(&one->oid, &two->oid)) {
3595 if (must_show_header)
3596 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3597 header.buf, header.len,
3599 goto free_ab_and_return;
3601 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3602 header.buf, header.len, 0);
3603 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3604 diff_line_prefix(o), lbl[0], lbl[1]);
3605 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3606 sb.buf, sb.len, 0);
3607 strbuf_release(&sb);
3608 goto free_ab_and_return;
3610 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3611 fill_mmfile(o->repo, &mf2, two) < 0)
3612 die("unable to read files to diff");
3613 /* Quite common confusing case */
3614 if (mf1.size == mf2.size &&
3615 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3616 if (must_show_header)
3617 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3618 header.buf, header.len, 0);
3619 goto free_ab_and_return;
3621 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3622 strbuf_reset(&header);
3623 if (o->flags.binary)
3624 emit_binary_diff(o, &mf1, &mf2);
3625 else {
3626 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3627 diff_line_prefix(o), lbl[0], lbl[1]);
3628 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3629 sb.buf, sb.len, 0);
3630 strbuf_release(&sb);
3632 o->found_changes = 1;
3633 } else {
3634 /* Crazy xdl interfaces.. */
3635 const char *diffopts;
3636 const char *v;
3637 xpparam_t xpp;
3638 xdemitconf_t xecfg;
3639 struct emit_callback ecbdata;
3640 const struct userdiff_funcname *pe;
3642 if (must_show_header) {
3643 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3644 header.buf, header.len, 0);
3645 strbuf_reset(&header);
3648 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3649 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3651 pe = diff_funcname_pattern(o, one);
3652 if (!pe)
3653 pe = diff_funcname_pattern(o, two);
3655 memset(&xpp, 0, sizeof(xpp));
3656 memset(&xecfg, 0, sizeof(xecfg));
3657 memset(&ecbdata, 0, sizeof(ecbdata));
3658 if (o->flags.suppress_diff_headers)
3659 lbl[0] = NULL;
3660 ecbdata.label_path = lbl;
3661 ecbdata.color_diff = want_color(o->use_color);
3662 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3663 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3664 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3665 ecbdata.opt = o;
3666 if (header.len && !o->flags.suppress_diff_headers)
3667 ecbdata.header = &header;
3668 xpp.flags = o->xdl_opts;
3669 xpp.ignore_regex = o->ignore_regex;
3670 xpp.ignore_regex_nr = o->ignore_regex_nr;
3671 xpp.anchors = o->anchors;
3672 xpp.anchors_nr = o->anchors_nr;
3673 xecfg.ctxlen = o->context;
3674 xecfg.interhunkctxlen = o->interhunkcontext;
3675 xecfg.flags = XDL_EMIT_FUNCNAMES;
3676 if (o->flags.funccontext)
3677 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3678 if (pe)
3679 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3681 diffopts = getenv("GIT_DIFF_OPTS");
3682 if (!diffopts)
3684 else if (skip_prefix(diffopts, "--unified=", &v))
3685 xecfg.ctxlen = strtoul(v, NULL, 10);
3686 else if (skip_prefix(diffopts, "-u", &v))
3687 xecfg.ctxlen = strtoul(v, NULL, 10);
3689 if (o->word_diff)
3690 init_diff_words_data(&ecbdata, o, one, two);
3691 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3692 &ecbdata, &xpp, &xecfg))
3693 die("unable to generate diff for %s", one->path);
3694 if (o->word_diff)
3695 free_diff_words_data(&ecbdata);
3696 if (textconv_one)
3697 free(mf1.ptr);
3698 if (textconv_two)
3699 free(mf2.ptr);
3700 xdiff_clear_find_func(&xecfg);
3703 free_ab_and_return:
3704 strbuf_release(&header);
3705 diff_free_filespec_data(one);
3706 diff_free_filespec_data(two);
3707 free(a_one);
3708 free(b_two);
3709 return;
3712 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3714 if (!is_renamed) {
3715 if (p->status == DIFF_STATUS_ADDED) {
3716 if (S_ISLNK(p->two->mode))
3717 return "new +l";
3718 else if ((p->two->mode & 0777) == 0755)
3719 return "new +x";
3720 else
3721 return "new";
3722 } else if (p->status == DIFF_STATUS_DELETED)
3723 return "gone";
3725 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3726 return "mode -l";
3727 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3728 return "mode +l";
3729 else if ((p->one->mode & 0777) == 0644 &&
3730 (p->two->mode & 0777) == 0755)
3731 return "mode +x";
3732 else if ((p->one->mode & 0777) == 0755 &&
3733 (p->two->mode & 0777) == 0644)
3734 return "mode -x";
3735 return NULL;
3738 static void builtin_diffstat(const char *name_a, const char *name_b,
3739 struct diff_filespec *one,
3740 struct diff_filespec *two,
3741 struct diffstat_t *diffstat,
3742 struct diff_options *o,
3743 struct diff_filepair *p)
3745 mmfile_t mf1, mf2;
3746 struct diffstat_file *data;
3747 int may_differ;
3748 int complete_rewrite = 0;
3750 if (!DIFF_PAIR_UNMERGED(p)) {
3751 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3752 complete_rewrite = 1;
3755 data = diffstat_add(diffstat, name_a, name_b);
3756 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3757 if (o->flags.stat_with_summary)
3758 data->comments = get_compact_summary(p, data->is_renamed);
3760 if (!one || !two) {
3761 data->is_unmerged = 1;
3762 return;
3765 /* saves some reads if true, not a guarantee of diff outcome */
3766 may_differ = !(one->oid_valid && two->oid_valid &&
3767 oideq(&one->oid, &two->oid));
3769 if (diff_filespec_is_binary(o->repo, one) ||
3770 diff_filespec_is_binary(o->repo, two)) {
3771 data->is_binary = 1;
3772 if (!may_differ) {
3773 data->added = 0;
3774 data->deleted = 0;
3775 } else {
3776 data->added = diff_filespec_size(o->repo, two);
3777 data->deleted = diff_filespec_size(o->repo, one);
3781 else if (complete_rewrite) {
3782 diff_populate_filespec(o->repo, one, NULL);
3783 diff_populate_filespec(o->repo, two, NULL);
3784 data->deleted = count_lines(one->data, one->size);
3785 data->added = count_lines(two->data, two->size);
3788 else if (may_differ) {
3789 /* Crazy xdl interfaces.. */
3790 xpparam_t xpp;
3791 xdemitconf_t xecfg;
3793 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3794 fill_mmfile(o->repo, &mf2, two) < 0)
3795 die("unable to read files to diff");
3797 memset(&xpp, 0, sizeof(xpp));
3798 memset(&xecfg, 0, sizeof(xecfg));
3799 xpp.flags = o->xdl_opts;
3800 xpp.ignore_regex = o->ignore_regex;
3801 xpp.ignore_regex_nr = o->ignore_regex_nr;
3802 xpp.anchors = o->anchors;
3803 xpp.anchors_nr = o->anchors_nr;
3804 xecfg.ctxlen = o->context;
3805 xecfg.interhunkctxlen = o->interhunkcontext;
3806 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3807 if (xdi_diff_outf(&mf1, &mf2, NULL,
3808 diffstat_consume, diffstat, &xpp, &xecfg))
3809 die("unable to generate diffstat for %s", one->path);
3811 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3812 struct diffstat_file *file =
3813 diffstat->files[diffstat->nr - 1];
3815 * Omit diffstats of modified files where nothing changed.
3816 * Even if may_differ, this might be the case due to
3817 * ignoring whitespace changes, etc.
3819 * But note that we special-case additions, deletions,
3820 * renames, and mode changes as adding an empty file,
3821 * for example is still of interest.
3823 if ((p->status == DIFF_STATUS_MODIFIED)
3824 && !file->added
3825 && !file->deleted
3826 && one->mode == two->mode) {
3827 free_diffstat_file(file);
3828 diffstat->nr--;
3833 diff_free_filespec_data(one);
3834 diff_free_filespec_data(two);
3837 static void builtin_checkdiff(const char *name_a, const char *name_b,
3838 const char *attr_path,
3839 struct diff_filespec *one,
3840 struct diff_filespec *two,
3841 struct diff_options *o)
3843 mmfile_t mf1, mf2;
3844 struct checkdiff_t data;
3846 if (!two)
3847 return;
3849 memset(&data, 0, sizeof(data));
3850 data.filename = name_b ? name_b : name_a;
3851 data.lineno = 0;
3852 data.o = o;
3853 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3854 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3856 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3857 fill_mmfile(o->repo, &mf2, two) < 0)
3858 die("unable to read files to diff");
3861 * All the other codepaths check both sides, but not checking
3862 * the "old" side here is deliberate. We are checking the newly
3863 * introduced changes, and as long as the "new" side is text, we
3864 * can and should check what it introduces.
3866 if (diff_filespec_is_binary(o->repo, two))
3867 goto free_and_return;
3868 else {
3869 /* Crazy xdl interfaces.. */
3870 xpparam_t xpp;
3871 xdemitconf_t xecfg;
3873 memset(&xpp, 0, sizeof(xpp));
3874 memset(&xecfg, 0, sizeof(xecfg));
3875 xecfg.ctxlen = 1; /* at least one context line */
3876 xpp.flags = 0;
3877 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3878 checkdiff_consume, &data,
3879 &xpp, &xecfg))
3880 die("unable to generate checkdiff for %s", one->path);
3882 if (data.ws_rule & WS_BLANK_AT_EOF) {
3883 struct emit_callback ecbdata;
3884 int blank_at_eof;
3886 ecbdata.ws_rule = data.ws_rule;
3887 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3888 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3890 if (blank_at_eof) {
3891 static char *err;
3892 if (!err)
3893 err = whitespace_error_string(WS_BLANK_AT_EOF);
3894 fprintf(o->file, "%s:%d: %s.\n",
3895 data.filename, blank_at_eof, err);
3896 data.status = 1; /* report errors */
3900 free_and_return:
3901 diff_free_filespec_data(one);
3902 diff_free_filespec_data(two);
3903 if (data.status)
3904 o->flags.check_failed = 1;
3907 struct diff_filespec *alloc_filespec(const char *path)
3909 struct diff_filespec *spec;
3911 FLEXPTR_ALLOC_STR(spec, path, path);
3912 spec->count = 1;
3913 spec->is_binary = -1;
3914 return spec;
3917 void free_filespec(struct diff_filespec *spec)
3919 if (!--spec->count) {
3920 diff_free_filespec_data(spec);
3921 free(spec);
3925 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3926 int oid_valid, unsigned short mode)
3928 if (mode) {
3929 spec->mode = canon_mode(mode);
3930 oidcpy(&spec->oid, oid);
3931 spec->oid_valid = oid_valid;
3936 * Given a name and sha1 pair, if the index tells us the file in
3937 * the work tree has that object contents, return true, so that
3938 * prepare_temp_file() does not have to inflate and extract.
3940 static int reuse_worktree_file(struct index_state *istate,
3941 const char *name,
3942 const struct object_id *oid,
3943 int want_file)
3945 const struct cache_entry *ce;
3946 struct stat st;
3947 int pos, len;
3950 * We do not read the cache ourselves here, because the
3951 * benchmark with my previous version that always reads cache
3952 * shows that it makes things worse for diff-tree comparing
3953 * two linux-2.6 kernel trees in an already checked out work
3954 * tree. This is because most diff-tree comparisons deal with
3955 * only a small number of files, while reading the cache is
3956 * expensive for a large project, and its cost outweighs the
3957 * savings we get by not inflating the object to a temporary
3958 * file. Practically, this code only helps when we are used
3959 * by diff-cache --cached, which does read the cache before
3960 * calling us.
3962 if (!istate->cache)
3963 return 0;
3965 /* We want to avoid the working directory if our caller
3966 * doesn't need the data in a normal file, this system
3967 * is rather slow with its stat/open/mmap/close syscalls,
3968 * and the object is contained in a pack file. The pack
3969 * is probably already open and will be faster to obtain
3970 * the data through than the working directory. Loose
3971 * objects however would tend to be slower as they need
3972 * to be individually opened and inflated.
3974 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3975 return 0;
3978 * Similarly, if we'd have to convert the file contents anyway, that
3979 * makes the optimization not worthwhile.
3981 if (!want_file && would_convert_to_git(istate, name))
3982 return 0;
3985 * If this path does not match our sparse-checkout definition,
3986 * then the file will not be in the working directory.
3988 if (!path_in_sparse_checkout(name, istate))
3989 return 0;
3991 len = strlen(name);
3992 pos = index_name_pos(istate, name, len);
3993 if (pos < 0)
3994 return 0;
3995 ce = istate->cache[pos];
3998 * This is not the sha1 we are looking for, or
3999 * unreusable because it is not a regular file.
4001 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4002 return 0;
4005 * If ce is marked as "assume unchanged", there is no
4006 * guarantee that work tree matches what we are looking for.
4008 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4009 return 0;
4012 * If ce matches the file in the work tree, we can reuse it.
4014 if (ce_uptodate(ce) ||
4015 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4016 return 1;
4018 return 0;
4021 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4023 struct strbuf buf = STRBUF_INIT;
4024 char *dirty = "";
4026 /* Are we looking at the work tree? */
4027 if (s->dirty_submodule)
4028 dirty = "-dirty";
4030 strbuf_addf(&buf, "Subproject commit %s%s\n",
4031 oid_to_hex(&s->oid), dirty);
4032 s->size = buf.len;
4033 if (size_only) {
4034 s->data = NULL;
4035 strbuf_release(&buf);
4036 } else {
4037 s->data = strbuf_detach(&buf, NULL);
4038 s->should_free = 1;
4040 return 0;
4044 * While doing rename detection and pickaxe operation, we may need to
4045 * grab the data for the blob (or file) for our own in-core comparison.
4046 * diff_filespec has data and size fields for this purpose.
4048 int diff_populate_filespec(struct repository *r,
4049 struct diff_filespec *s,
4050 const struct diff_populate_filespec_options *options)
4052 int size_only = options ? options->check_size_only : 0;
4053 int check_binary = options ? options->check_binary : 0;
4054 int err = 0;
4055 int conv_flags = global_conv_flags_eol;
4057 * demote FAIL to WARN to allow inspecting the situation
4058 * instead of refusing.
4060 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4061 conv_flags = CONV_EOL_RNDTRP_WARN;
4063 if (!DIFF_FILE_VALID(s))
4064 die("internal error: asking to populate invalid file.");
4065 if (S_ISDIR(s->mode))
4066 return -1;
4068 if (s->data)
4069 return 0;
4071 if (size_only && 0 < s->size)
4072 return 0;
4074 if (S_ISGITLINK(s->mode))
4075 return diff_populate_gitlink(s, size_only);
4077 if (!s->oid_valid ||
4078 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4079 struct strbuf buf = STRBUF_INIT;
4080 struct stat st;
4081 int fd;
4083 if (lstat(s->path, &st) < 0) {
4084 err_empty:
4085 err = -1;
4086 empty:
4087 s->data = (char *)"";
4088 s->size = 0;
4089 return err;
4091 s->size = xsize_t(st.st_size);
4092 if (!s->size)
4093 goto empty;
4094 if (S_ISLNK(st.st_mode)) {
4095 struct strbuf sb = STRBUF_INIT;
4097 if (strbuf_readlink(&sb, s->path, s->size))
4098 goto err_empty;
4099 s->size = sb.len;
4100 s->data = strbuf_detach(&sb, NULL);
4101 s->should_free = 1;
4102 return 0;
4106 * Even if the caller would be happy with getting
4107 * only the size, we cannot return early at this
4108 * point if the path requires us to run the content
4109 * conversion.
4111 if (size_only && !would_convert_to_git(r->index, s->path))
4112 return 0;
4115 * Note: this check uses xsize_t(st.st_size) that may
4116 * not be the true size of the blob after it goes
4117 * through convert_to_git(). This may not strictly be
4118 * correct, but the whole point of big_file_threshold
4119 * and is_binary check being that we want to avoid
4120 * opening the file and inspecting the contents, this
4121 * is probably fine.
4123 if (check_binary &&
4124 s->size > big_file_threshold && s->is_binary == -1) {
4125 s->is_binary = 1;
4126 return 0;
4128 fd = open(s->path, O_RDONLY);
4129 if (fd < 0)
4130 goto err_empty;
4131 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4132 close(fd);
4133 s->should_munmap = 1;
4136 * Convert from working tree format to canonical git format
4138 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4139 size_t size = 0;
4140 munmap(s->data, s->size);
4141 s->should_munmap = 0;
4142 s->data = strbuf_detach(&buf, &size);
4143 s->size = size;
4144 s->should_free = 1;
4147 else {
4148 struct object_info info = {
4149 .sizep = &s->size
4152 if (!(size_only || check_binary))
4154 * Set contentp, since there is no chance that merely
4155 * the size is sufficient.
4157 info.contentp = &s->data;
4159 if (options && options->missing_object_cb) {
4160 if (!oid_object_info_extended(r, &s->oid, &info,
4161 OBJECT_INFO_LOOKUP_REPLACE |
4162 OBJECT_INFO_SKIP_FETCH_OBJECT))
4163 goto object_read;
4164 options->missing_object_cb(options->missing_object_data);
4166 if (oid_object_info_extended(r, &s->oid, &info,
4167 OBJECT_INFO_LOOKUP_REPLACE))
4168 die("unable to read %s", oid_to_hex(&s->oid));
4170 object_read:
4171 if (size_only || check_binary) {
4172 if (size_only)
4173 return 0;
4174 if (s->size > big_file_threshold && s->is_binary == -1) {
4175 s->is_binary = 1;
4176 return 0;
4179 if (!info.contentp) {
4180 info.contentp = &s->data;
4181 if (oid_object_info_extended(r, &s->oid, &info,
4182 OBJECT_INFO_LOOKUP_REPLACE))
4183 die("unable to read %s", oid_to_hex(&s->oid));
4185 s->should_free = 1;
4187 return 0;
4190 void diff_free_filespec_blob(struct diff_filespec *s)
4192 if (s->should_free)
4193 free(s->data);
4194 else if (s->should_munmap)
4195 munmap(s->data, s->size);
4197 if (s->should_free || s->should_munmap) {
4198 s->should_free = s->should_munmap = 0;
4199 s->data = NULL;
4203 void diff_free_filespec_data(struct diff_filespec *s)
4205 if (!s)
4206 return;
4208 diff_free_filespec_blob(s);
4209 FREE_AND_NULL(s->cnt_data);
4212 static void prep_temp_blob(struct index_state *istate,
4213 const char *path, struct diff_tempfile *temp,
4214 void *blob,
4215 unsigned long size,
4216 const struct object_id *oid,
4217 int mode)
4219 struct strbuf buf = STRBUF_INIT;
4220 char *path_dup = xstrdup(path);
4221 const char *base = basename(path_dup);
4222 struct checkout_metadata meta;
4224 init_checkout_metadata(&meta, NULL, NULL, oid);
4226 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4227 if (!temp->tempfile)
4228 die_errno("unable to create temp-file");
4229 if (convert_to_working_tree(istate, path,
4230 (const char *)blob, (size_t)size, &buf, &meta)) {
4231 blob = buf.buf;
4232 size = buf.len;
4234 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4235 close_tempfile_gently(temp->tempfile))
4236 die_errno("unable to write temp-file");
4237 temp->name = get_tempfile_path(temp->tempfile);
4238 oid_to_hex_r(temp->hex, oid);
4239 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4240 strbuf_release(&buf);
4241 free(path_dup);
4244 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4245 struct diff_filespec *one)
4247 struct diff_tempfile *temp = claim_diff_tempfile();
4249 if (!DIFF_FILE_VALID(one)) {
4250 not_a_valid_file:
4251 /* A '-' entry produces this for file-2, and
4252 * a '+' entry produces this for file-1.
4254 temp->name = "/dev/null";
4255 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4256 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4257 return temp;
4260 if (!S_ISGITLINK(one->mode) &&
4261 (!one->oid_valid ||
4262 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4263 struct stat st;
4264 if (lstat(one->path, &st) < 0) {
4265 if (errno == ENOENT)
4266 goto not_a_valid_file;
4267 die_errno("stat(%s)", one->path);
4269 if (S_ISLNK(st.st_mode)) {
4270 struct strbuf sb = STRBUF_INIT;
4271 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4272 die_errno("readlink(%s)", one->path);
4273 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4274 (one->oid_valid ?
4275 &one->oid : null_oid()),
4276 (one->oid_valid ?
4277 one->mode : S_IFLNK));
4278 strbuf_release(&sb);
4280 else {
4281 /* we can borrow from the file in the work tree */
4282 temp->name = one->path;
4283 if (!one->oid_valid)
4284 oid_to_hex_r(temp->hex, null_oid());
4285 else
4286 oid_to_hex_r(temp->hex, &one->oid);
4287 /* Even though we may sometimes borrow the
4288 * contents from the work tree, we always want
4289 * one->mode. mode is trustworthy even when
4290 * !(one->oid_valid), as long as
4291 * DIFF_FILE_VALID(one).
4293 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4295 return temp;
4297 else {
4298 if (diff_populate_filespec(r, one, NULL))
4299 die("cannot read data blob for %s", one->path);
4300 prep_temp_blob(r->index, one->path, temp,
4301 one->data, one->size,
4302 &one->oid, one->mode);
4304 return temp;
4307 static void add_external_diff_name(struct repository *r,
4308 struct strvec *argv,
4309 struct diff_filespec *df)
4311 struct diff_tempfile *temp = prepare_temp_file(r, df);
4312 strvec_push(argv, temp->name);
4313 strvec_push(argv, temp->hex);
4314 strvec_push(argv, temp->mode);
4317 /* An external diff command takes:
4319 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4320 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4323 static void run_external_diff(const char *pgm,
4324 const char *name,
4325 const char *other,
4326 struct diff_filespec *one,
4327 struct diff_filespec *two,
4328 const char *xfrm_msg,
4329 struct diff_options *o)
4331 struct child_process cmd = CHILD_PROCESS_INIT;
4332 struct diff_queue_struct *q = &diff_queued_diff;
4334 strvec_push(&cmd.args, pgm);
4335 strvec_push(&cmd.args, name);
4337 if (one && two) {
4338 add_external_diff_name(o->repo, &cmd.args, one);
4339 add_external_diff_name(o->repo, &cmd.args, two);
4340 if (other) {
4341 strvec_push(&cmd.args, other);
4342 strvec_push(&cmd.args, xfrm_msg);
4346 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4347 ++o->diff_path_counter);
4348 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4350 diff_free_filespec_data(one);
4351 diff_free_filespec_data(two);
4352 cmd.use_shell = 1;
4353 if (run_command(&cmd))
4354 die(_("external diff died, stopping at %s"), name);
4356 remove_tempfile();
4359 static int similarity_index(struct diff_filepair *p)
4361 return p->score * 100 / MAX_SCORE;
4364 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4366 if (startup_info->have_repository)
4367 return find_unique_abbrev(oid, abbrev);
4368 else {
4369 char *hex = oid_to_hex(oid);
4370 if (abbrev < 0)
4371 abbrev = FALLBACK_DEFAULT_ABBREV;
4372 if (abbrev > the_hash_algo->hexsz)
4373 BUG("oid abbreviation out of range: %d", abbrev);
4374 if (abbrev)
4375 hex[abbrev] = '\0';
4376 return hex;
4380 static void fill_metainfo(struct strbuf *msg,
4381 const char *name,
4382 const char *other,
4383 struct diff_filespec *one,
4384 struct diff_filespec *two,
4385 struct diff_options *o,
4386 struct diff_filepair *p,
4387 int *must_show_header,
4388 int use_color)
4390 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4391 const char *reset = diff_get_color(use_color, DIFF_RESET);
4392 const char *line_prefix = diff_line_prefix(o);
4393 struct string_list *more_headers = NULL;
4395 *must_show_header = 1;
4396 strbuf_init(msg, PATH_MAX * 2 + 300);
4397 switch (p->status) {
4398 case DIFF_STATUS_COPIED:
4399 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4400 line_prefix, set, similarity_index(p));
4401 strbuf_addf(msg, "%s\n%s%scopy from ",
4402 reset, line_prefix, set);
4403 quote_c_style(name, msg, NULL, 0);
4404 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4405 quote_c_style(other, msg, NULL, 0);
4406 strbuf_addf(msg, "%s\n", reset);
4407 break;
4408 case DIFF_STATUS_RENAMED:
4409 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4410 line_prefix, set, similarity_index(p));
4411 strbuf_addf(msg, "%s\n%s%srename from ",
4412 reset, line_prefix, set);
4413 quote_c_style(name, msg, NULL, 0);
4414 strbuf_addf(msg, "%s\n%s%srename to ",
4415 reset, line_prefix, set);
4416 quote_c_style(other, msg, NULL, 0);
4417 strbuf_addf(msg, "%s\n", reset);
4418 break;
4419 case DIFF_STATUS_MODIFIED:
4420 if (p->score) {
4421 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4422 line_prefix,
4423 set, similarity_index(p), reset);
4424 break;
4426 /* fallthru */
4427 default:
4428 *must_show_header = 0;
4430 if ((more_headers = additional_headers(o, name))) {
4431 add_formatted_headers(msg, more_headers,
4432 line_prefix, set, reset);
4433 *must_show_header = 1;
4435 if (one && two && !oideq(&one->oid, &two->oid)) {
4436 const unsigned hexsz = the_hash_algo->hexsz;
4437 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4439 if (o->flags.full_index)
4440 abbrev = hexsz;
4442 if (o->flags.binary) {
4443 mmfile_t mf;
4444 if ((!fill_mmfile(o->repo, &mf, one) &&
4445 diff_filespec_is_binary(o->repo, one)) ||
4446 (!fill_mmfile(o->repo, &mf, two) &&
4447 diff_filespec_is_binary(o->repo, two)))
4448 abbrev = hexsz;
4450 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4451 diff_abbrev_oid(&one->oid, abbrev),
4452 diff_abbrev_oid(&two->oid, abbrev));
4453 if (one->mode == two->mode)
4454 strbuf_addf(msg, " %06o", one->mode);
4455 strbuf_addf(msg, "%s\n", reset);
4459 static void run_diff_cmd(const char *pgm,
4460 const char *name,
4461 const char *other,
4462 const char *attr_path,
4463 struct diff_filespec *one,
4464 struct diff_filespec *two,
4465 struct strbuf *msg,
4466 struct diff_options *o,
4467 struct diff_filepair *p)
4469 const char *xfrm_msg = NULL;
4470 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4471 int must_show_header = 0;
4472 struct userdiff_driver *drv = NULL;
4474 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4475 drv = userdiff_find_by_path(o->repo->index, attr_path);
4477 if (o->flags.allow_external && drv && drv->external)
4478 pgm = drv->external;
4480 if (msg) {
4482 * don't use colors when the header is intended for an
4483 * external diff driver
4485 fill_metainfo(msg, name, other, one, two, o, p,
4486 &must_show_header,
4487 want_color(o->use_color) && !pgm);
4488 xfrm_msg = msg->len ? msg->buf : NULL;
4491 if (pgm) {
4492 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4493 return;
4495 if (one && two) {
4496 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4497 set_diff_algorithm(o, drv->algorithm);
4499 builtin_diff(name, other ? other : name,
4500 one, two, xfrm_msg, must_show_header,
4501 o, complete_rewrite);
4502 } else {
4503 fprintf(o->file, "* Unmerged path %s\n", name);
4507 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4509 if (DIFF_FILE_VALID(one)) {
4510 if (!one->oid_valid) {
4511 struct stat st;
4512 if (one->is_stdin) {
4513 oidclr(&one->oid);
4514 return;
4516 if (lstat(one->path, &st) < 0)
4517 die_errno("stat '%s'", one->path);
4518 if (index_path(istate, &one->oid, one->path, &st, 0))
4519 die("cannot hash %s", one->path);
4522 else
4523 oidclr(&one->oid);
4526 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4528 /* Strip the prefix but do not molest /dev/null and absolute paths */
4529 if (*namep && !is_absolute_path(*namep)) {
4530 *namep += prefix_length;
4531 if (**namep == '/')
4532 ++*namep;
4534 if (*otherp && !is_absolute_path(*otherp)) {
4535 *otherp += prefix_length;
4536 if (**otherp == '/')
4537 ++*otherp;
4541 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4543 const char *pgm = external_diff();
4544 struct strbuf msg;
4545 struct diff_filespec *one = p->one;
4546 struct diff_filespec *two = p->two;
4547 const char *name;
4548 const char *other;
4549 const char *attr_path;
4551 name = one->path;
4552 other = (strcmp(name, two->path) ? two->path : NULL);
4553 attr_path = name;
4554 if (o->prefix_length)
4555 strip_prefix(o->prefix_length, &name, &other);
4557 if (!o->flags.allow_external)
4558 pgm = NULL;
4560 if (DIFF_PAIR_UNMERGED(p)) {
4561 run_diff_cmd(pgm, name, NULL, attr_path,
4562 NULL, NULL, NULL, o, p);
4563 return;
4566 diff_fill_oid_info(one, o->repo->index);
4567 diff_fill_oid_info(two, o->repo->index);
4569 if (!pgm &&
4570 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4571 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4573 * a filepair that changes between file and symlink
4574 * needs to be split into deletion and creation.
4576 struct diff_filespec *null = alloc_filespec(two->path);
4577 run_diff_cmd(NULL, name, other, attr_path,
4578 one, null, &msg,
4579 o, p);
4580 free(null);
4581 strbuf_release(&msg);
4583 null = alloc_filespec(one->path);
4584 run_diff_cmd(NULL, name, other, attr_path,
4585 null, two, &msg, o, p);
4586 free(null);
4588 else
4589 run_diff_cmd(pgm, name, other, attr_path,
4590 one, two, &msg, o, p);
4592 strbuf_release(&msg);
4595 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4596 struct diffstat_t *diffstat)
4598 const char *name;
4599 const char *other;
4601 if (!o->ignore_driver_algorithm) {
4602 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4603 p->one->path);
4605 if (drv && drv->algorithm)
4606 set_diff_algorithm(o, drv->algorithm);
4609 if (DIFF_PAIR_UNMERGED(p)) {
4610 /* unmerged */
4611 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4612 diffstat, o, p);
4613 return;
4616 name = p->one->path;
4617 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4619 if (o->prefix_length)
4620 strip_prefix(o->prefix_length, &name, &other);
4622 diff_fill_oid_info(p->one, o->repo->index);
4623 diff_fill_oid_info(p->two, o->repo->index);
4625 builtin_diffstat(name, other, p->one, p->two,
4626 diffstat, o, p);
4629 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4631 const char *name;
4632 const char *other;
4633 const char *attr_path;
4635 if (DIFF_PAIR_UNMERGED(p)) {
4636 /* unmerged */
4637 return;
4640 name = p->one->path;
4641 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4642 attr_path = other ? other : name;
4644 if (o->prefix_length)
4645 strip_prefix(o->prefix_length, &name, &other);
4647 diff_fill_oid_info(p->one, o->repo->index);
4648 diff_fill_oid_info(p->two, o->repo->index);
4650 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4653 void repo_diff_setup(struct repository *r, struct diff_options *options)
4655 memcpy(options, &default_diff_options, sizeof(*options));
4657 options->file = stdout;
4658 options->repo = r;
4660 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4661 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4662 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4663 options->abbrev = DEFAULT_ABBREV;
4664 options->line_termination = '\n';
4665 options->break_opt = -1;
4666 options->rename_limit = -1;
4667 options->dirstat_permille = diff_dirstat_permille_default;
4668 options->context = diff_context_default;
4669 options->interhunkcontext = diff_interhunk_context_default;
4670 options->ws_error_highlight = ws_error_highlight_default;
4671 options->flags.rename_empty = 1;
4672 options->flags.relative_name = diff_relative;
4673 options->objfind = NULL;
4675 /* pathchange left =NULL by default */
4676 options->change = diff_change;
4677 options->add_remove = diff_addremove;
4678 options->use_color = diff_use_color_default;
4679 options->detect_rename = diff_detect_rename_default;
4680 options->xdl_opts |= diff_algorithm;
4681 if (diff_indent_heuristic)
4682 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4684 options->orderfile = diff_order_file_cfg;
4686 if (!options->flags.ignore_submodule_set)
4687 options->flags.ignore_untracked_in_submodules = 1;
4689 if (diff_no_prefix) {
4690 diff_set_noprefix(options);
4691 } else if (!diff_mnemonic_prefix) {
4692 diff_set_default_prefix(options);
4695 options->color_moved = diff_color_moved_default;
4696 options->color_moved_ws_handling = diff_color_moved_ws_default;
4699 static const char diff_status_letters[] = {
4700 DIFF_STATUS_ADDED,
4701 DIFF_STATUS_COPIED,
4702 DIFF_STATUS_DELETED,
4703 DIFF_STATUS_MODIFIED,
4704 DIFF_STATUS_RENAMED,
4705 DIFF_STATUS_TYPE_CHANGED,
4706 DIFF_STATUS_UNKNOWN,
4707 DIFF_STATUS_UNMERGED,
4708 DIFF_STATUS_FILTER_AON,
4709 DIFF_STATUS_FILTER_BROKEN,
4710 '\0',
4713 static unsigned int filter_bit['Z' + 1];
4715 static void prepare_filter_bits(void)
4717 int i;
4719 if (!filter_bit[DIFF_STATUS_ADDED]) {
4720 for (i = 0; diff_status_letters[i]; i++)
4721 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4725 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4727 return opt->filter & filter_bit[(int) status];
4730 unsigned diff_filter_bit(char status)
4732 prepare_filter_bits();
4733 return filter_bit[(int) status];
4736 void diff_setup_done(struct diff_options *options)
4738 unsigned check_mask = DIFF_FORMAT_NAME |
4739 DIFF_FORMAT_NAME_STATUS |
4740 DIFF_FORMAT_CHECKDIFF |
4741 DIFF_FORMAT_NO_OUTPUT;
4743 * This must be signed because we're comparing against a potentially
4744 * negative value.
4746 const int hexsz = the_hash_algo->hexsz;
4748 if (options->set_default)
4749 options->set_default(options);
4751 if (HAS_MULTI_BITS(options->output_format & check_mask))
4752 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4753 "--name-only", "--name-status", "--check", "-s");
4755 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4756 die(_("options '%s', '%s', and '%s' cannot be used together"),
4757 "-G", "-S", "--find-object");
4759 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4760 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4761 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4763 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4764 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4765 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4768 * Most of the time we can say "there are changes"
4769 * only by checking if there are changed paths, but
4770 * --ignore-whitespace* options force us to look
4771 * inside contents.
4774 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4775 options->ignore_regex_nr)
4776 options->flags.diff_from_contents = 1;
4777 else
4778 options->flags.diff_from_contents = 0;
4780 if (options->flags.find_copies_harder)
4781 options->detect_rename = DIFF_DETECT_COPY;
4783 if (!options->flags.relative_name)
4784 options->prefix = NULL;
4785 if (options->prefix)
4786 options->prefix_length = strlen(options->prefix);
4787 else
4788 options->prefix_length = 0;
4790 if (options->output_format & (DIFF_FORMAT_NAME |
4791 DIFF_FORMAT_NAME_STATUS |
4792 DIFF_FORMAT_CHECKDIFF |
4793 DIFF_FORMAT_NO_OUTPUT))
4794 options->output_format &= ~(DIFF_FORMAT_RAW |
4795 DIFF_FORMAT_NUMSTAT |
4796 DIFF_FORMAT_DIFFSTAT |
4797 DIFF_FORMAT_SHORTSTAT |
4798 DIFF_FORMAT_DIRSTAT |
4799 DIFF_FORMAT_SUMMARY |
4800 DIFF_FORMAT_PATCH);
4803 * These cases always need recursive; we do not drop caller-supplied
4804 * recursive bits for other formats here.
4806 if (options->output_format & (DIFF_FORMAT_PATCH |
4807 DIFF_FORMAT_NUMSTAT |
4808 DIFF_FORMAT_DIFFSTAT |
4809 DIFF_FORMAT_SHORTSTAT |
4810 DIFF_FORMAT_DIRSTAT |
4811 DIFF_FORMAT_SUMMARY |
4812 DIFF_FORMAT_CHECKDIFF))
4813 options->flags.recursive = 1;
4815 * Also pickaxe would not work very well if you do not say recursive
4817 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4818 options->flags.recursive = 1;
4820 * When patches are generated, submodules diffed against the work tree
4821 * must be checked for dirtiness too so it can be shown in the output
4823 if (options->output_format & DIFF_FORMAT_PATCH)
4824 options->flags.dirty_submodules = 1;
4826 if (options->detect_rename && options->rename_limit < 0)
4827 options->rename_limit = diff_rename_limit_default;
4828 if (hexsz < options->abbrev)
4829 options->abbrev = hexsz; /* full */
4832 * It does not make sense to show the first hit we happened
4833 * to have found. It does not make sense not to return with
4834 * exit code in such a case either.
4836 if (options->flags.quick) {
4837 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4838 options->flags.exit_with_status = 1;
4841 options->diff_path_counter = 0;
4843 if (options->flags.follow_renames && options->pathspec.nr != 1)
4844 die(_("--follow requires exactly one pathspec"));
4846 if (!options->use_color || external_diff())
4847 options->color_moved = 0;
4849 if (options->filter_not) {
4850 if (!options->filter)
4851 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4852 options->filter &= ~options->filter_not;
4856 int parse_long_opt(const char *opt, const char **argv,
4857 const char **optarg)
4859 const char *arg = argv[0];
4860 if (!skip_prefix(arg, "--", &arg))
4861 return 0;
4862 if (!skip_prefix(arg, opt, &arg))
4863 return 0;
4864 if (*arg == '=') { /* stuck form: --option=value */
4865 *optarg = arg + 1;
4866 return 1;
4868 if (*arg != '\0')
4869 return 0;
4870 /* separate form: --option value */
4871 if (!argv[1])
4872 die("Option '--%s' requires a value", opt);
4873 *optarg = argv[1];
4874 return 2;
4877 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4879 struct diff_options *options = opt->value;
4880 int width = options->stat_width;
4881 int name_width = options->stat_name_width;
4882 int graph_width = options->stat_graph_width;
4883 int count = options->stat_count;
4884 char *end;
4886 BUG_ON_OPT_NEG(unset);
4888 if (!strcmp(opt->long_name, "stat")) {
4889 if (value) {
4890 width = strtoul(value, &end, 10);
4891 if (*end == ',')
4892 name_width = strtoul(end+1, &end, 10);
4893 if (*end == ',')
4894 count = strtoul(end+1, &end, 10);
4895 if (*end)
4896 return error(_("invalid --stat value: %s"), value);
4898 } else if (!strcmp(opt->long_name, "stat-width")) {
4899 width = strtoul(value, &end, 10);
4900 if (*end)
4901 return error(_("%s expects a numerical value"),
4902 opt->long_name);
4903 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4904 name_width = strtoul(value, &end, 10);
4905 if (*end)
4906 return error(_("%s expects a numerical value"),
4907 opt->long_name);
4908 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4909 graph_width = strtoul(value, &end, 10);
4910 if (*end)
4911 return error(_("%s expects a numerical value"),
4912 opt->long_name);
4913 } else if (!strcmp(opt->long_name, "stat-count")) {
4914 count = strtoul(value, &end, 10);
4915 if (*end)
4916 return error(_("%s expects a numerical value"),
4917 opt->long_name);
4918 } else
4919 BUG("%s should not get here", opt->long_name);
4921 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4922 options->stat_name_width = name_width;
4923 options->stat_graph_width = graph_width;
4924 options->stat_width = width;
4925 options->stat_count = count;
4926 return 0;
4929 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4931 struct strbuf errmsg = STRBUF_INIT;
4932 if (parse_dirstat_params(options, params, &errmsg))
4933 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4934 errmsg.buf);
4935 strbuf_release(&errmsg);
4937 * The caller knows a dirstat-related option is given from the command
4938 * line; allow it to say "return this_function();"
4940 options->output_format |= DIFF_FORMAT_DIRSTAT;
4941 return 1;
4944 static int diff_opt_diff_filter(const struct option *option,
4945 const char *optarg, int unset)
4947 struct diff_options *opt = option->value;
4948 int i, optch;
4950 BUG_ON_OPT_NEG(unset);
4951 prepare_filter_bits();
4953 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4954 unsigned int bit;
4955 int negate;
4957 if ('a' <= optch && optch <= 'z') {
4958 negate = 1;
4959 optch = toupper(optch);
4960 } else {
4961 negate = 0;
4964 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4965 if (!bit)
4966 return error(_("unknown change class '%c' in --diff-filter=%s"),
4967 optarg[i], optarg);
4968 if (negate)
4969 opt->filter_not |= bit;
4970 else
4971 opt->filter |= bit;
4973 return 0;
4976 static void enable_patch_output(int *fmt)
4978 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4979 *fmt |= DIFF_FORMAT_PATCH;
4982 static int diff_opt_ws_error_highlight(const struct option *option,
4983 const char *arg, int unset)
4985 struct diff_options *opt = option->value;
4986 int val = parse_ws_error_highlight(arg);
4988 BUG_ON_OPT_NEG(unset);
4989 if (val < 0)
4990 return error(_("unknown value after ws-error-highlight=%.*s"),
4991 -1 - val, arg);
4992 opt->ws_error_highlight = val;
4993 return 0;
4996 static int diff_opt_find_object(const struct option *option,
4997 const char *arg, int unset)
4999 struct diff_options *opt = option->value;
5000 struct object_id oid;
5002 BUG_ON_OPT_NEG(unset);
5003 if (get_oid(arg, &oid))
5004 return error(_("unable to resolve '%s'"), arg);
5006 if (!opt->objfind)
5007 CALLOC_ARRAY(opt->objfind, 1);
5009 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5010 opt->flags.recursive = 1;
5011 opt->flags.tree_in_recursive = 1;
5012 oidset_insert(opt->objfind, &oid);
5013 return 0;
5016 static int diff_opt_anchored(const struct option *opt,
5017 const char *arg, int unset)
5019 struct diff_options *options = opt->value;
5021 BUG_ON_OPT_NEG(unset);
5022 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5023 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5024 options->anchors_alloc);
5025 options->anchors[options->anchors_nr++] = xstrdup(arg);
5026 return 0;
5029 static int diff_opt_binary(const struct option *opt,
5030 const char *arg, int unset)
5032 struct diff_options *options = opt->value;
5034 BUG_ON_OPT_NEG(unset);
5035 BUG_ON_OPT_ARG(arg);
5036 enable_patch_output(&options->output_format);
5037 options->flags.binary = 1;
5038 return 0;
5041 static int diff_opt_break_rewrites(const struct option *opt,
5042 const char *arg, int unset)
5044 int *break_opt = opt->value;
5045 int opt1, opt2;
5047 BUG_ON_OPT_NEG(unset);
5048 if (!arg)
5049 arg = "";
5050 opt1 = parse_rename_score(&arg);
5051 if (*arg == 0)
5052 opt2 = 0;
5053 else if (*arg != '/')
5054 return error(_("%s expects <n>/<m> form"), opt->long_name);
5055 else {
5056 arg++;
5057 opt2 = parse_rename_score(&arg);
5059 if (*arg != 0)
5060 return error(_("%s expects <n>/<m> form"), opt->long_name);
5061 *break_opt = opt1 | (opt2 << 16);
5062 return 0;
5065 static int diff_opt_char(const struct option *opt,
5066 const char *arg, int unset)
5068 char *value = opt->value;
5070 BUG_ON_OPT_NEG(unset);
5071 if (arg[1])
5072 return error(_("%s expects a character, got '%s'"),
5073 opt->long_name, arg);
5074 *value = arg[0];
5075 return 0;
5078 static int diff_opt_color_moved(const struct option *opt,
5079 const char *arg, int unset)
5081 struct diff_options *options = opt->value;
5083 if (unset) {
5084 options->color_moved = COLOR_MOVED_NO;
5085 } else if (!arg) {
5086 if (diff_color_moved_default)
5087 options->color_moved = diff_color_moved_default;
5088 if (options->color_moved == COLOR_MOVED_NO)
5089 options->color_moved = COLOR_MOVED_DEFAULT;
5090 } else {
5091 int cm = parse_color_moved(arg);
5092 if (cm < 0)
5093 return error(_("bad --color-moved argument: %s"), arg);
5094 options->color_moved = cm;
5096 return 0;
5099 static int diff_opt_color_moved_ws(const struct option *opt,
5100 const char *arg, int unset)
5102 struct diff_options *options = opt->value;
5103 unsigned cm;
5105 if (unset) {
5106 options->color_moved_ws_handling = 0;
5107 return 0;
5110 cm = parse_color_moved_ws(arg);
5111 if (cm & COLOR_MOVED_WS_ERROR)
5112 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5113 options->color_moved_ws_handling = cm;
5114 return 0;
5117 static int diff_opt_color_words(const struct option *opt,
5118 const char *arg, int unset)
5120 struct diff_options *options = opt->value;
5122 BUG_ON_OPT_NEG(unset);
5123 options->use_color = 1;
5124 options->word_diff = DIFF_WORDS_COLOR;
5125 options->word_regex = arg;
5126 return 0;
5129 static int diff_opt_compact_summary(const struct option *opt,
5130 const char *arg, int unset)
5132 struct diff_options *options = opt->value;
5134 BUG_ON_OPT_ARG(arg);
5135 if (unset) {
5136 options->flags.stat_with_summary = 0;
5137 } else {
5138 options->flags.stat_with_summary = 1;
5139 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5141 return 0;
5144 static int diff_opt_diff_algorithm(const struct option *opt,
5145 const char *arg, int unset)
5147 struct diff_options *options = opt->value;
5149 BUG_ON_OPT_NEG(unset);
5151 if (set_diff_algorithm(options, arg))
5152 return error(_("option diff-algorithm accepts \"myers\", "
5153 "\"minimal\", \"patience\" and \"histogram\""));
5155 options->ignore_driver_algorithm = 1;
5157 return 0;
5160 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5161 const char *arg, int unset)
5163 struct diff_options *options = opt->value;
5165 BUG_ON_OPT_NEG(unset);
5166 BUG_ON_OPT_ARG(arg);
5168 if (set_diff_algorithm(options, opt->long_name))
5169 BUG("available diff algorithms include \"myers\", "
5170 "\"minimal\", \"patience\" and \"histogram\"");
5172 options->ignore_driver_algorithm = 1;
5174 return 0;
5177 static int diff_opt_dirstat(const struct option *opt,
5178 const char *arg, int unset)
5180 struct diff_options *options = opt->value;
5182 BUG_ON_OPT_NEG(unset);
5183 if (!strcmp(opt->long_name, "cumulative")) {
5184 if (arg)
5185 BUG("how come --cumulative take a value?");
5186 arg = "cumulative";
5187 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5188 parse_dirstat_opt(options, "files");
5189 parse_dirstat_opt(options, arg ? arg : "");
5190 return 0;
5193 static int diff_opt_find_copies(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 = "";
5201 options->rename_score = parse_rename_score(&arg);
5202 if (*arg != 0)
5203 return error(_("invalid argument to %s"), opt->long_name);
5205 if (options->detect_rename == DIFF_DETECT_COPY)
5206 options->flags.find_copies_harder = 1;
5207 else
5208 options->detect_rename = DIFF_DETECT_COPY;
5210 return 0;
5213 static int diff_opt_find_renames(const struct option *opt,
5214 const char *arg, int unset)
5216 struct diff_options *options = opt->value;
5218 BUG_ON_OPT_NEG(unset);
5219 if (!arg)
5220 arg = "";
5221 options->rename_score = parse_rename_score(&arg);
5222 if (*arg != 0)
5223 return error(_("invalid argument to %s"), opt->long_name);
5225 options->detect_rename = DIFF_DETECT_RENAME;
5226 return 0;
5229 static int diff_opt_follow(const struct option *opt,
5230 const char *arg, int unset)
5232 struct diff_options *options = opt->value;
5234 BUG_ON_OPT_ARG(arg);
5235 if (unset) {
5236 options->flags.follow_renames = 0;
5237 options->flags.default_follow_renames = 0;
5238 } else {
5239 options->flags.follow_renames = 1;
5241 return 0;
5244 static int diff_opt_ignore_submodules(const struct option *opt,
5245 const char *arg, int unset)
5247 struct diff_options *options = opt->value;
5249 BUG_ON_OPT_NEG(unset);
5250 if (!arg)
5251 arg = "all";
5252 options->flags.override_submodule_config = 1;
5253 handle_ignore_submodules_arg(options, arg);
5254 return 0;
5257 static int diff_opt_line_prefix(const struct option *opt,
5258 const char *optarg, int unset)
5260 struct diff_options *options = opt->value;
5262 BUG_ON_OPT_NEG(unset);
5263 options->line_prefix = optarg;
5264 options->line_prefix_length = strlen(options->line_prefix);
5265 graph_setup_line_prefix(options);
5266 return 0;
5269 static int diff_opt_no_prefix(const struct option *opt,
5270 const char *optarg, int unset)
5272 struct diff_options *options = opt->value;
5274 BUG_ON_OPT_NEG(unset);
5275 BUG_ON_OPT_ARG(optarg);
5276 diff_set_noprefix(options);
5277 return 0;
5280 static int diff_opt_default_prefix(const struct option *opt,
5281 const char *optarg, int unset)
5283 struct diff_options *options = opt->value;
5285 BUG_ON_OPT_NEG(unset);
5286 BUG_ON_OPT_ARG(optarg);
5287 diff_set_default_prefix(options);
5288 return 0;
5291 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5292 const struct option *opt,
5293 const char *arg, int unset)
5295 struct diff_options *options = opt->value;
5296 char *path;
5298 BUG_ON_OPT_NEG(unset);
5299 path = prefix_filename(ctx->prefix, arg);
5300 options->file = xfopen(path, "w");
5301 options->close_file = 1;
5302 if (options->use_color != GIT_COLOR_ALWAYS)
5303 options->use_color = GIT_COLOR_NEVER;
5304 free(path);
5305 return 0;
5308 static int diff_opt_patience(const struct option *opt,
5309 const char *arg, int unset)
5311 struct diff_options *options = opt->value;
5312 int i;
5314 BUG_ON_OPT_NEG(unset);
5315 BUG_ON_OPT_ARG(arg);
5317 * Both --patience and --anchored use PATIENCE_DIFF
5318 * internally, so remove any anchors previously
5319 * specified.
5321 for (i = 0; i < options->anchors_nr; i++)
5322 free(options->anchors[i]);
5323 options->anchors_nr = 0;
5324 options->ignore_driver_algorithm = 1;
5326 return set_diff_algorithm(options, "patience");
5329 static int diff_opt_ignore_regex(const struct option *opt,
5330 const char *arg, int unset)
5332 struct diff_options *options = opt->value;
5333 regex_t *regex;
5335 BUG_ON_OPT_NEG(unset);
5336 regex = xmalloc(sizeof(*regex));
5337 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5338 return error(_("invalid regex given to -I: '%s'"), arg);
5339 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5340 options->ignore_regex_alloc);
5341 options->ignore_regex[options->ignore_regex_nr++] = regex;
5342 return 0;
5345 static int diff_opt_pickaxe_regex(const struct option *opt,
5346 const char *arg, int unset)
5348 struct diff_options *options = opt->value;
5350 BUG_ON_OPT_NEG(unset);
5351 options->pickaxe = arg;
5352 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5353 return 0;
5356 static int diff_opt_pickaxe_string(const struct option *opt,
5357 const char *arg, int unset)
5359 struct diff_options *options = opt->value;
5361 BUG_ON_OPT_NEG(unset);
5362 options->pickaxe = arg;
5363 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5364 return 0;
5367 static int diff_opt_relative(const struct option *opt,
5368 const char *arg, int unset)
5370 struct diff_options *options = opt->value;
5372 options->flags.relative_name = !unset;
5373 if (arg)
5374 options->prefix = arg;
5375 return 0;
5378 static int diff_opt_submodule(const struct option *opt,
5379 const char *arg, int unset)
5381 struct diff_options *options = opt->value;
5383 BUG_ON_OPT_NEG(unset);
5384 if (!arg)
5385 arg = "log";
5386 if (parse_submodule_params(options, arg))
5387 return error(_("failed to parse --submodule option parameter: '%s'"),
5388 arg);
5389 return 0;
5392 static int diff_opt_textconv(const struct option *opt,
5393 const char *arg, int unset)
5395 struct diff_options *options = opt->value;
5397 BUG_ON_OPT_ARG(arg);
5398 if (unset) {
5399 options->flags.allow_textconv = 0;
5400 } else {
5401 options->flags.allow_textconv = 1;
5402 options->flags.textconv_set_via_cmdline = 1;
5404 return 0;
5407 static int diff_opt_unified(const struct option *opt,
5408 const char *arg, int unset)
5410 struct diff_options *options = opt->value;
5411 char *s;
5413 BUG_ON_OPT_NEG(unset);
5415 if (arg) {
5416 options->context = strtol(arg, &s, 10);
5417 if (*s)
5418 return error(_("%s expects a numerical value"), "--unified");
5420 enable_patch_output(&options->output_format);
5422 return 0;
5425 static int diff_opt_word_diff(const struct option *opt,
5426 const char *arg, int unset)
5428 struct diff_options *options = opt->value;
5430 BUG_ON_OPT_NEG(unset);
5431 if (arg) {
5432 if (!strcmp(arg, "plain"))
5433 options->word_diff = DIFF_WORDS_PLAIN;
5434 else if (!strcmp(arg, "color")) {
5435 options->use_color = 1;
5436 options->word_diff = DIFF_WORDS_COLOR;
5438 else if (!strcmp(arg, "porcelain"))
5439 options->word_diff = DIFF_WORDS_PORCELAIN;
5440 else if (!strcmp(arg, "none"))
5441 options->word_diff = DIFF_WORDS_NONE;
5442 else
5443 return error(_("bad --word-diff argument: %s"), arg);
5444 } else {
5445 if (options->word_diff == DIFF_WORDS_NONE)
5446 options->word_diff = DIFF_WORDS_PLAIN;
5448 return 0;
5451 static int diff_opt_word_diff_regex(const struct option *opt,
5452 const char *arg, int unset)
5454 struct diff_options *options = opt->value;
5456 BUG_ON_OPT_NEG(unset);
5457 if (options->word_diff == DIFF_WORDS_NONE)
5458 options->word_diff = DIFF_WORDS_PLAIN;
5459 options->word_regex = arg;
5460 return 0;
5463 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5465 struct diff_options *options = opt->value;
5467 BUG_ON_OPT_NEG(unset);
5468 if (!strcmp(opt->long_name, "skip-to"))
5469 options->skip_instead_of_rotate = 1;
5470 else
5471 options->skip_instead_of_rotate = 0;
5472 options->rotate_to = arg;
5473 return 0;
5476 struct option *add_diff_options(const struct option *opts,
5477 struct diff_options *options)
5479 struct option parseopts[] = {
5480 OPT_GROUP(N_("Diff output format options")),
5481 OPT_BITOP('p', "patch", &options->output_format,
5482 N_("generate patch"),
5483 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5484 OPT_BIT_F('s', "no-patch", &options->output_format,
5485 N_("suppress diff output"),
5486 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5487 OPT_BITOP('u', NULL, &options->output_format,
5488 N_("generate patch"),
5489 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5490 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5491 N_("generate diffs with <n> lines context"),
5492 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5493 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5494 N_("generate diffs with <n> lines context")),
5495 OPT_BIT_F(0, "raw", &options->output_format,
5496 N_("generate the diff in raw format"),
5497 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5498 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5499 N_("synonym for '-p --raw'"),
5500 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5501 DIFF_FORMAT_NO_OUTPUT),
5502 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5503 N_("synonym for '-p --stat'"),
5504 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5505 DIFF_FORMAT_NO_OUTPUT),
5506 OPT_BIT_F(0, "numstat", &options->output_format,
5507 N_("machine friendly --stat"),
5508 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5509 OPT_BIT_F(0, "shortstat", &options->output_format,
5510 N_("output only the last line of --stat"),
5511 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5512 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5513 N_("output the distribution of relative amount of changes for each sub-directory"),
5514 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5515 diff_opt_dirstat),
5516 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5517 N_("synonym for --dirstat=cumulative"),
5518 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5519 diff_opt_dirstat),
5520 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5521 N_("synonym for --dirstat=files,param1,param2..."),
5522 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5523 diff_opt_dirstat),
5524 OPT_BIT_F(0, "check", &options->output_format,
5525 N_("warn if changes introduce conflict markers or whitespace errors"),
5526 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5527 OPT_BIT_F(0, "summary", &options->output_format,
5528 N_("condensed summary such as creations, renames and mode changes"),
5529 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5530 OPT_BIT_F(0, "name-only", &options->output_format,
5531 N_("show only names of changed files"),
5532 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5533 OPT_BIT_F(0, "name-status", &options->output_format,
5534 N_("show only names and status of changed files"),
5535 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5536 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5537 N_("generate diffstat"),
5538 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5539 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5540 N_("generate diffstat with a given width"),
5541 PARSE_OPT_NONEG, diff_opt_stat),
5542 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5543 N_("generate diffstat with a given name width"),
5544 PARSE_OPT_NONEG, diff_opt_stat),
5545 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5546 N_("generate diffstat with a given graph width"),
5547 PARSE_OPT_NONEG, diff_opt_stat),
5548 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5549 N_("generate diffstat with limited lines"),
5550 PARSE_OPT_NONEG, diff_opt_stat),
5551 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5552 N_("generate compact summary in diffstat"),
5553 PARSE_OPT_NOARG, diff_opt_compact_summary),
5554 OPT_CALLBACK_F(0, "binary", options, NULL,
5555 N_("output a binary diff that can be applied"),
5556 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5557 OPT_BOOL(0, "full-index", &options->flags.full_index,
5558 N_("show full pre- and post-image object names on the \"index\" lines")),
5559 OPT_COLOR_FLAG(0, "color", &options->use_color,
5560 N_("show colored diff")),
5561 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5562 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5563 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5564 OPT_SET_INT('z', NULL, &options->line_termination,
5565 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5567 OPT__ABBREV(&options->abbrev),
5568 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5569 N_("show the given source prefix instead of \"a/\""),
5570 PARSE_OPT_NONEG),
5571 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5572 N_("show the given destination prefix instead of \"b/\""),
5573 PARSE_OPT_NONEG),
5574 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5575 N_("prepend an additional prefix to every line of output"),
5576 PARSE_OPT_NONEG, diff_opt_line_prefix),
5577 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5578 N_("do not show any source or destination prefix"),
5579 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5580 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5581 N_("use default prefixes a/ and b/"),
5582 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5583 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5584 N_("show context between diff hunks up to the specified number of lines"),
5585 PARSE_OPT_NONEG),
5586 OPT_CALLBACK_F(0, "output-indicator-new",
5587 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5588 N_("<char>"),
5589 N_("specify the character to indicate a new line instead of '+'"),
5590 PARSE_OPT_NONEG, diff_opt_char),
5591 OPT_CALLBACK_F(0, "output-indicator-old",
5592 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5593 N_("<char>"),
5594 N_("specify the character to indicate an old line instead of '-'"),
5595 PARSE_OPT_NONEG, diff_opt_char),
5596 OPT_CALLBACK_F(0, "output-indicator-context",
5597 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5598 N_("<char>"),
5599 N_("specify the character to indicate a context instead of ' '"),
5600 PARSE_OPT_NONEG, diff_opt_char),
5602 OPT_GROUP(N_("Diff rename options")),
5603 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5604 N_("break complete rewrite changes into pairs of delete and create"),
5605 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5606 diff_opt_break_rewrites),
5607 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5608 N_("detect renames"),
5609 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5610 diff_opt_find_renames),
5611 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5612 N_("omit the preimage for deletes"),
5613 1, PARSE_OPT_NONEG),
5614 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5615 N_("detect copies"),
5616 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5617 diff_opt_find_copies),
5618 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5619 N_("use unmodified files as source to find copies")),
5620 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5621 N_("disable rename detection"),
5622 0, PARSE_OPT_NONEG),
5623 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5624 N_("use empty blobs as rename source")),
5625 OPT_CALLBACK_F(0, "follow", options, NULL,
5626 N_("continue listing the history of a file beyond renames"),
5627 PARSE_OPT_NOARG, diff_opt_follow),
5628 OPT_INTEGER('l', NULL, &options->rename_limit,
5629 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5631 OPT_GROUP(N_("Diff algorithm options")),
5632 OPT_CALLBACK_F(0, "minimal", options, NULL,
5633 N_("produce the smallest possible diff"),
5634 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5635 diff_opt_diff_algorithm_no_arg),
5636 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5637 N_("ignore whitespace when comparing lines"),
5638 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5639 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5640 N_("ignore changes in amount of whitespace"),
5641 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5642 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5643 N_("ignore changes in whitespace at EOL"),
5644 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5645 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5646 N_("ignore carrier-return at the end of line"),
5647 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5648 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5649 N_("ignore changes whose lines are all blank"),
5650 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5651 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5652 N_("ignore changes whose all lines match <regex>"),
5653 0, diff_opt_ignore_regex),
5654 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5655 N_("heuristic to shift diff hunk boundaries for easy reading"),
5656 XDF_INDENT_HEURISTIC),
5657 OPT_CALLBACK_F(0, "patience", options, NULL,
5658 N_("generate diff using the \"patience diff\" algorithm"),
5659 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5660 diff_opt_patience),
5661 OPT_CALLBACK_F(0, "histogram", options, NULL,
5662 N_("generate diff using the \"histogram diff\" algorithm"),
5663 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5664 diff_opt_diff_algorithm_no_arg),
5665 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5666 N_("choose a diff algorithm"),
5667 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5668 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5669 N_("generate diff using the \"anchored diff\" algorithm"),
5670 PARSE_OPT_NONEG, diff_opt_anchored),
5671 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5672 N_("show word diff, using <mode> to delimit changed words"),
5673 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5674 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5675 N_("use <regex> to decide what a word is"),
5676 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5677 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5678 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5679 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5680 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5681 N_("moved lines of code are colored differently"),
5682 PARSE_OPT_OPTARG, diff_opt_color_moved),
5683 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5684 N_("how white spaces are ignored in --color-moved"),
5685 0, diff_opt_color_moved_ws),
5687 OPT_GROUP(N_("Other diff options")),
5688 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5689 N_("when run from subdir, exclude changes outside and show relative paths"),
5690 PARSE_OPT_OPTARG,
5691 diff_opt_relative),
5692 OPT_BOOL('a', "text", &options->flags.text,
5693 N_("treat all files as text")),
5694 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5695 N_("swap two inputs, reverse the diff")),
5696 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5697 N_("exit with 1 if there were differences, 0 otherwise")),
5698 OPT_BOOL(0, "quiet", &options->flags.quick,
5699 N_("disable all output of the program")),
5700 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5701 N_("allow an external diff helper to be executed")),
5702 OPT_CALLBACK_F(0, "textconv", options, NULL,
5703 N_("run external text conversion filters when comparing binary files"),
5704 PARSE_OPT_NOARG, diff_opt_textconv),
5705 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5706 N_("ignore changes to submodules in the diff generation"),
5707 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5708 diff_opt_ignore_submodules),
5709 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5710 N_("specify how differences in submodules are shown"),
5711 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5712 diff_opt_submodule),
5713 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5714 N_("hide 'git add -N' entries from the index"),
5715 1, PARSE_OPT_NONEG),
5716 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5717 N_("treat 'git add -N' entries as real in the index"),
5718 0, PARSE_OPT_NONEG),
5719 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5720 N_("look for differences that change the number of occurrences of the specified string"),
5721 0, diff_opt_pickaxe_string),
5722 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5723 N_("look for differences that change the number of occurrences of the specified regex"),
5724 0, diff_opt_pickaxe_regex),
5725 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5726 N_("show all changes in the changeset with -S or -G"),
5727 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5728 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5729 N_("treat <string> in -S as extended POSIX regular expression"),
5730 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5731 OPT_FILENAME('O', NULL, &options->orderfile,
5732 N_("control the order in which files appear in the output")),
5733 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5734 N_("show the change in the specified path first"),
5735 PARSE_OPT_NONEG, diff_opt_rotate_to),
5736 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5737 N_("skip the output to the specified path"),
5738 PARSE_OPT_NONEG, diff_opt_rotate_to),
5739 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5740 N_("look for differences that change the number of occurrences of the specified object"),
5741 PARSE_OPT_NONEG, diff_opt_find_object),
5742 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5743 N_("select files by diff type"),
5744 PARSE_OPT_NONEG, diff_opt_diff_filter),
5745 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5746 N_("output to a specific file"),
5747 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5749 OPT_END()
5752 return parse_options_concat(opts, parseopts);
5755 int diff_opt_parse(struct diff_options *options,
5756 const char **av, int ac, const char *prefix)
5758 struct option no_options[] = { OPT_END() };
5759 struct option *parseopts = add_diff_options(no_options, options);
5761 if (!prefix)
5762 prefix = "";
5764 ac = parse_options(ac, av, prefix, parseopts, NULL,
5765 PARSE_OPT_KEEP_DASHDASH |
5766 PARSE_OPT_KEEP_UNKNOWN_OPT |
5767 PARSE_OPT_NO_INTERNAL_HELP |
5768 PARSE_OPT_ONE_SHOT |
5769 PARSE_OPT_STOP_AT_NON_OPTION);
5770 free(parseopts);
5772 return ac;
5775 int parse_rename_score(const char **cp_p)
5777 unsigned long num, scale;
5778 int ch, dot;
5779 const char *cp = *cp_p;
5781 num = 0;
5782 scale = 1;
5783 dot = 0;
5784 for (;;) {
5785 ch = *cp;
5786 if ( !dot && ch == '.' ) {
5787 scale = 1;
5788 dot = 1;
5789 } else if ( ch == '%' ) {
5790 scale = dot ? scale*100 : 100;
5791 cp++; /* % is always at the end */
5792 break;
5793 } else if ( ch >= '0' && ch <= '9' ) {
5794 if ( scale < 100000 ) {
5795 scale *= 10;
5796 num = (num*10) + (ch-'0');
5798 } else {
5799 break;
5801 cp++;
5803 *cp_p = cp;
5805 /* user says num divided by scale and we say internally that
5806 * is MAX_SCORE * num / scale.
5808 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5811 struct diff_queue_struct diff_queued_diff;
5813 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5815 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5816 queue->queue[queue->nr++] = dp;
5819 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5820 struct diff_filespec *one,
5821 struct diff_filespec *two)
5823 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5824 dp->one = one;
5825 dp->two = two;
5826 if (queue)
5827 diff_q(queue, dp);
5828 return dp;
5831 void diff_free_filepair(struct diff_filepair *p)
5833 free_filespec(p->one);
5834 free_filespec(p->two);
5835 free(p);
5838 void diff_free_queue(struct diff_queue_struct *q)
5840 for (int i = 0; i < q->nr; i++)
5841 diff_free_filepair(q->queue[i]);
5842 free(q->queue);
5845 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5847 int abblen;
5848 const char *abbrev;
5850 /* Do we want all 40 hex characters? */
5851 if (len == the_hash_algo->hexsz)
5852 return oid_to_hex(oid);
5854 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5855 abbrev = diff_abbrev_oid(oid, len);
5857 if (!print_sha1_ellipsis())
5858 return abbrev;
5860 abblen = strlen(abbrev);
5863 * In well-behaved cases, where the abbreviated result is the
5864 * same as the requested length, append three dots after the
5865 * abbreviation (hence the whole logic is limited to the case
5866 * where abblen < 37); when the actual abbreviated result is a
5867 * bit longer than the requested length, we reduce the number
5868 * of dots so that they match the well-behaved ones. However,
5869 * if the actual abbreviation is longer than the requested
5870 * length by more than three, we give up on aligning, and add
5871 * three dots anyway, to indicate that the output is not the
5872 * full object name. Yes, this may be suboptimal, but this
5873 * appears only in "diff --raw --abbrev" output and it is not
5874 * worth the effort to change it now. Note that this would
5875 * likely to work fine when the automatic sizing of default
5876 * abbreviation length is used--we would be fed -1 in "len" in
5877 * that case, and will end up always appending three-dots, but
5878 * the automatic sizing is supposed to give abblen that ensures
5879 * uniqueness across all objects (statistically speaking).
5881 if (abblen < the_hash_algo->hexsz - 3) {
5882 static char hex[GIT_MAX_HEXSZ + 1];
5883 if (len < abblen && abblen <= len + 2)
5884 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5885 else
5886 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5887 return hex;
5890 return oid_to_hex(oid);
5893 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5895 int line_termination = opt->line_termination;
5896 int inter_name_termination = line_termination ? '\t' : '\0';
5898 fprintf(opt->file, "%s", diff_line_prefix(opt));
5899 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5900 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5901 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5902 fprintf(opt->file, "%s ",
5903 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5905 if (p->score) {
5906 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5907 inter_name_termination);
5908 } else {
5909 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5912 if (p->status == DIFF_STATUS_COPIED ||
5913 p->status == DIFF_STATUS_RENAMED) {
5914 const char *name_a, *name_b;
5915 name_a = p->one->path;
5916 name_b = p->two->path;
5917 strip_prefix(opt->prefix_length, &name_a, &name_b);
5918 write_name_quoted(name_a, opt->file, inter_name_termination);
5919 write_name_quoted(name_b, opt->file, line_termination);
5920 } else {
5921 const char *name_a, *name_b;
5922 name_a = p->one->mode ? p->one->path : p->two->path;
5923 name_b = NULL;
5924 strip_prefix(opt->prefix_length, &name_a, &name_b);
5925 write_name_quoted(name_a, opt->file, line_termination);
5929 int diff_unmodified_pair(struct diff_filepair *p)
5931 /* This function is written stricter than necessary to support
5932 * the currently implemented transformers, but the idea is to
5933 * let transformers to produce diff_filepairs any way they want,
5934 * and filter and clean them up here before producing the output.
5936 struct diff_filespec *one = p->one, *two = p->two;
5938 if (DIFF_PAIR_UNMERGED(p))
5939 return 0; /* unmerged is interesting */
5941 /* deletion, addition, mode or type change
5942 * and rename are all interesting.
5944 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5945 DIFF_PAIR_MODE_CHANGED(p) ||
5946 strcmp(one->path, two->path))
5947 return 0;
5949 /* both are valid and point at the same path. that is, we are
5950 * dealing with a change.
5952 if (one->oid_valid && two->oid_valid &&
5953 oideq(&one->oid, &two->oid) &&
5954 !one->dirty_submodule && !two->dirty_submodule)
5955 return 1; /* no change */
5956 if (!one->oid_valid && !two->oid_valid)
5957 return 1; /* both look at the same file on the filesystem. */
5958 return 0;
5961 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5963 int include_conflict_headers =
5964 (additional_headers(o, p->one->path) &&
5965 !o->pickaxe_opts &&
5966 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5969 * Check if we can return early without showing a diff. Note that
5970 * diff_filepair only stores {oid, path, mode, is_valid}
5971 * information for each path, and thus diff_unmodified_pair() only
5972 * considers those bits of info. However, we do not want pairs
5973 * created by create_filepairs_for_header_only_notifications()
5974 * (which always look like unmodified pairs) to be ignored, so
5975 * return early if both p is unmodified AND we don't want to
5976 * include_conflict_headers.
5978 if (diff_unmodified_pair(p) && !include_conflict_headers)
5979 return;
5981 /* Actually, we can also return early to avoid showing tree diffs */
5982 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5983 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5984 return;
5986 run_diff(p, o);
5989 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5990 struct diffstat_t *diffstat)
5992 if (diff_unmodified_pair(p))
5993 return;
5995 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5996 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5997 return; /* no useful stat for tree diffs */
5999 run_diffstat(p, o, diffstat);
6002 static void diff_flush_checkdiff(struct diff_filepair *p,
6003 struct diff_options *o)
6005 if (diff_unmodified_pair(p))
6006 return;
6008 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6009 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6010 return; /* nothing to check in tree diffs */
6012 run_checkdiff(p, o);
6015 int diff_queue_is_empty(struct diff_options *o)
6017 struct diff_queue_struct *q = &diff_queued_diff;
6018 int i;
6019 int include_conflict_headers =
6020 (o->additional_path_headers &&
6021 strmap_get_size(o->additional_path_headers) &&
6022 !o->pickaxe_opts &&
6023 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6025 if (include_conflict_headers)
6026 return 0;
6028 for (i = 0; i < q->nr; i++)
6029 if (!diff_unmodified_pair(q->queue[i]))
6030 return 0;
6031 return 1;
6034 #if DIFF_DEBUG
6035 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6037 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6038 x, one ? one : "",
6039 s->path,
6040 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6041 s->mode,
6042 s->oid_valid ? oid_to_hex(&s->oid) : "");
6043 fprintf(stderr, "queue[%d] %s size %lu\n",
6044 x, one ? one : "",
6045 s->size);
6048 void diff_debug_filepair(const struct diff_filepair *p, int i)
6050 diff_debug_filespec(p->one, i, "one");
6051 diff_debug_filespec(p->two, i, "two");
6052 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6053 p->score, p->status ? p->status : '?',
6054 p->one->rename_used, p->broken_pair);
6057 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6059 int i;
6060 if (msg)
6061 fprintf(stderr, "%s\n", msg);
6062 fprintf(stderr, "q->nr = %d\n", q->nr);
6063 for (i = 0; i < q->nr; i++) {
6064 struct diff_filepair *p = q->queue[i];
6065 diff_debug_filepair(p, i);
6068 #endif
6070 static void diff_resolve_rename_copy(void)
6072 int i;
6073 struct diff_filepair *p;
6074 struct diff_queue_struct *q = &diff_queued_diff;
6076 diff_debug_queue("resolve-rename-copy", q);
6078 for (i = 0; i < q->nr; i++) {
6079 p = q->queue[i];
6080 p->status = 0; /* undecided */
6081 if (DIFF_PAIR_UNMERGED(p))
6082 p->status = DIFF_STATUS_UNMERGED;
6083 else if (!DIFF_FILE_VALID(p->one))
6084 p->status = DIFF_STATUS_ADDED;
6085 else if (!DIFF_FILE_VALID(p->two))
6086 p->status = DIFF_STATUS_DELETED;
6087 else if (DIFF_PAIR_TYPE_CHANGED(p))
6088 p->status = DIFF_STATUS_TYPE_CHANGED;
6090 /* from this point on, we are dealing with a pair
6091 * whose both sides are valid and of the same type, i.e.
6092 * either in-place edit or rename/copy edit.
6094 else if (DIFF_PAIR_RENAME(p)) {
6096 * A rename might have re-connected a broken
6097 * pair up, causing the pathnames to be the
6098 * same again. If so, that's not a rename at
6099 * all, just a modification..
6101 * Otherwise, see if this source was used for
6102 * multiple renames, in which case we decrement
6103 * the count, and call it a copy.
6105 if (!strcmp(p->one->path, p->two->path))
6106 p->status = DIFF_STATUS_MODIFIED;
6107 else if (--p->one->rename_used > 0)
6108 p->status = DIFF_STATUS_COPIED;
6109 else
6110 p->status = DIFF_STATUS_RENAMED;
6112 else if (!oideq(&p->one->oid, &p->two->oid) ||
6113 p->one->mode != p->two->mode ||
6114 p->one->dirty_submodule ||
6115 p->two->dirty_submodule ||
6116 is_null_oid(&p->one->oid))
6117 p->status = DIFF_STATUS_MODIFIED;
6118 else {
6119 /* This is a "no-change" entry and should not
6120 * happen anymore, but prepare for broken callers.
6122 error("feeding unmodified %s to diffcore",
6123 p->one->path);
6124 p->status = DIFF_STATUS_UNKNOWN;
6127 diff_debug_queue("resolve-rename-copy done", q);
6130 static int check_pair_status(struct diff_filepair *p)
6132 switch (p->status) {
6133 case DIFF_STATUS_UNKNOWN:
6134 return 0;
6135 case 0:
6136 die("internal error in diff-resolve-rename-copy");
6137 default:
6138 return 1;
6142 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6144 int fmt = opt->output_format;
6146 if (fmt & DIFF_FORMAT_CHECKDIFF)
6147 diff_flush_checkdiff(p, opt);
6148 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6149 diff_flush_raw(p, opt);
6150 else if (fmt & DIFF_FORMAT_NAME) {
6151 const char *name_a, *name_b;
6152 name_a = p->two->path;
6153 name_b = NULL;
6154 strip_prefix(opt->prefix_length, &name_a, &name_b);
6155 fprintf(opt->file, "%s", diff_line_prefix(opt));
6156 write_name_quoted(name_a, opt->file, opt->line_termination);
6160 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6162 struct strbuf sb = STRBUF_INIT;
6163 if (fs->mode)
6164 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6165 else
6166 strbuf_addf(&sb, " %s ", newdelete);
6168 quote_c_style(fs->path, &sb, NULL, 0);
6169 strbuf_addch(&sb, '\n');
6170 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6171 sb.buf, sb.len, 0);
6172 strbuf_release(&sb);
6175 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6176 int show_name)
6178 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6179 struct strbuf sb = STRBUF_INIT;
6180 strbuf_addf(&sb, " mode change %06o => %06o",
6181 p->one->mode, p->two->mode);
6182 if (show_name) {
6183 strbuf_addch(&sb, ' ');
6184 quote_c_style(p->two->path, &sb, NULL, 0);
6186 strbuf_addch(&sb, '\n');
6187 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6188 sb.buf, sb.len, 0);
6189 strbuf_release(&sb);
6193 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6194 struct diff_filepair *p)
6196 struct strbuf sb = STRBUF_INIT;
6197 struct strbuf names = STRBUF_INIT;
6199 pprint_rename(&names, p->one->path, p->two->path);
6200 strbuf_addf(&sb, " %s %s (%d%%)\n",
6201 renamecopy, names.buf, similarity_index(p));
6202 strbuf_release(&names);
6203 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6204 sb.buf, sb.len, 0);
6205 show_mode_change(opt, p, 0);
6206 strbuf_release(&sb);
6209 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6211 switch(p->status) {
6212 case DIFF_STATUS_DELETED:
6213 show_file_mode_name(opt, "delete", p->one);
6214 break;
6215 case DIFF_STATUS_ADDED:
6216 show_file_mode_name(opt, "create", p->two);
6217 break;
6218 case DIFF_STATUS_COPIED:
6219 show_rename_copy(opt, "copy", p);
6220 break;
6221 case DIFF_STATUS_RENAMED:
6222 show_rename_copy(opt, "rename", p);
6223 break;
6224 default:
6225 if (p->score) {
6226 struct strbuf sb = STRBUF_INIT;
6227 strbuf_addstr(&sb, " rewrite ");
6228 quote_c_style(p->two->path, &sb, NULL, 0);
6229 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6230 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6231 sb.buf, sb.len, 0);
6232 strbuf_release(&sb);
6234 show_mode_change(opt, p, !p->score);
6235 break;
6239 struct patch_id_t {
6240 git_hash_ctx *ctx;
6241 int patchlen;
6244 static int remove_space(char *line, int len)
6246 int i;
6247 char *dst = line;
6248 unsigned char c;
6250 for (i = 0; i < len; i++)
6251 if (!isspace((c = line[i])))
6252 *dst++ = c;
6254 return dst - line;
6257 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6259 unsigned char hash[GIT_MAX_RAWSZ];
6260 unsigned short carry = 0;
6261 int i;
6263 the_hash_algo->final_fn(hash, ctx);
6264 the_hash_algo->init_fn(ctx);
6265 /* 20-byte sum, with carry */
6266 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6267 carry += result->hash[i] + hash[i];
6268 result->hash[i] = carry;
6269 carry >>= 8;
6273 static int patch_id_consume(void *priv, char *line, unsigned long len)
6275 struct patch_id_t *data = priv;
6276 int new_len;
6278 if (len > 12 && starts_with(line, "\\ "))
6279 return 0;
6280 new_len = remove_space(line, len);
6282 the_hash_algo->update_fn(data->ctx, line, new_len);
6283 data->patchlen += new_len;
6284 return 0;
6287 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6289 the_hash_algo->update_fn(ctx, str, strlen(str));
6292 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6294 /* large enough for 2^32 in octal */
6295 char buf[12];
6296 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6297 the_hash_algo->update_fn(ctx, buf, len);
6300 /* returns 0 upon success, and writes result into oid */
6301 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6303 struct diff_queue_struct *q = &diff_queued_diff;
6304 int i;
6305 git_hash_ctx ctx;
6306 struct patch_id_t data;
6308 the_hash_algo->init_fn(&ctx);
6309 memset(&data, 0, sizeof(struct patch_id_t));
6310 data.ctx = &ctx;
6311 oidclr(oid);
6313 for (i = 0; i < q->nr; i++) {
6314 xpparam_t xpp;
6315 xdemitconf_t xecfg;
6316 mmfile_t mf1, mf2;
6317 struct diff_filepair *p = q->queue[i];
6318 int len1, len2;
6320 memset(&xpp, 0, sizeof(xpp));
6321 memset(&xecfg, 0, sizeof(xecfg));
6322 if (p->status == 0)
6323 return error("internal diff status error");
6324 if (p->status == DIFF_STATUS_UNKNOWN)
6325 continue;
6326 if (diff_unmodified_pair(p))
6327 continue;
6328 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6329 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6330 continue;
6331 if (DIFF_PAIR_UNMERGED(p))
6332 continue;
6334 diff_fill_oid_info(p->one, options->repo->index);
6335 diff_fill_oid_info(p->two, options->repo->index);
6337 len1 = remove_space(p->one->path, strlen(p->one->path));
6338 len2 = remove_space(p->two->path, strlen(p->two->path));
6339 patch_id_add_string(&ctx, "diff--git");
6340 patch_id_add_string(&ctx, "a/");
6341 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6342 patch_id_add_string(&ctx, "b/");
6343 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6345 if (p->one->mode == 0) {
6346 patch_id_add_string(&ctx, "newfilemode");
6347 patch_id_add_mode(&ctx, p->two->mode);
6348 } else if (p->two->mode == 0) {
6349 patch_id_add_string(&ctx, "deletedfilemode");
6350 patch_id_add_mode(&ctx, p->one->mode);
6351 } else if (p->one->mode != p->two->mode) {
6352 patch_id_add_string(&ctx, "oldmode");
6353 patch_id_add_mode(&ctx, p->one->mode);
6354 patch_id_add_string(&ctx, "newmode");
6355 patch_id_add_mode(&ctx, p->two->mode);
6358 if (diff_header_only) {
6359 /* don't do anything since we're only populating header info */
6360 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6361 diff_filespec_is_binary(options->repo, p->two)) {
6362 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6363 the_hash_algo->hexsz);
6364 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6365 the_hash_algo->hexsz);
6366 } else {
6367 if (p->one->mode == 0) {
6368 patch_id_add_string(&ctx, "---/dev/null");
6369 patch_id_add_string(&ctx, "+++b/");
6370 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6371 } else if (p->two->mode == 0) {
6372 patch_id_add_string(&ctx, "---a/");
6373 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6374 patch_id_add_string(&ctx, "+++/dev/null");
6375 } else {
6376 patch_id_add_string(&ctx, "---a/");
6377 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6378 patch_id_add_string(&ctx, "+++b/");
6379 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6382 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6383 fill_mmfile(options->repo, &mf2, p->two) < 0)
6384 return error("unable to read files to diff");
6385 xpp.flags = 0;
6386 xecfg.ctxlen = 3;
6387 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6388 if (xdi_diff_outf(&mf1, &mf2, NULL,
6389 patch_id_consume, &data, &xpp, &xecfg))
6390 return error("unable to generate patch-id diff for %s",
6391 p->one->path);
6393 flush_one_hunk(oid, &ctx);
6396 return 0;
6399 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6401 struct diff_queue_struct *q = &diff_queued_diff;
6402 int result = diff_get_patch_id(options, oid, diff_header_only);
6404 diff_free_queue(q);
6405 DIFF_QUEUE_CLEAR(q);
6407 return result;
6410 static int is_summary_empty(const struct diff_queue_struct *q)
6412 int i;
6414 for (i = 0; i < q->nr; i++) {
6415 const struct diff_filepair *p = q->queue[i];
6417 switch (p->status) {
6418 case DIFF_STATUS_DELETED:
6419 case DIFF_STATUS_ADDED:
6420 case DIFF_STATUS_COPIED:
6421 case DIFF_STATUS_RENAMED:
6422 return 0;
6423 default:
6424 if (p->score)
6425 return 0;
6426 if (p->one->mode && p->two->mode &&
6427 p->one->mode != p->two->mode)
6428 return 0;
6429 break;
6432 return 1;
6435 static const char rename_limit_warning[] =
6436 N_("exhaustive rename detection was skipped due to too many files.");
6438 static const char degrade_cc_to_c_warning[] =
6439 N_("only found copies from modified paths due to too many files.");
6441 static const char rename_limit_advice[] =
6442 N_("you may want to set your %s variable to at least "
6443 "%d and retry the command.");
6445 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6447 fflush(stdout);
6448 if (degraded_cc)
6449 warning(_(degrade_cc_to_c_warning));
6450 else if (needed)
6451 warning(_(rename_limit_warning));
6452 else
6453 return;
6454 if (0 < needed)
6455 warning(_(rename_limit_advice), varname, needed);
6458 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6460 struct strset present;
6461 struct diff_queue_struct *q = &diff_queued_diff;
6462 struct hashmap_iter iter;
6463 struct strmap_entry *e;
6464 int i;
6466 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6469 * Find out which paths exist in diff_queued_diff, preferring
6470 * one->path for any pair that has multiple paths.
6472 for (i = 0; i < q->nr; i++) {
6473 struct diff_filepair *p = q->queue[i];
6474 char *path = p->one->path ? p->one->path : p->two->path;
6476 if (strmap_contains(o->additional_path_headers, path))
6477 strset_add(&present, path);
6481 * Loop over paths in additional_path_headers; for each NOT already
6482 * in diff_queued_diff, create a synthetic filepair and insert that
6483 * into diff_queued_diff.
6485 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6486 if (!strset_contains(&present, e->key)) {
6487 struct diff_filespec *one, *two;
6488 struct diff_filepair *p;
6490 one = alloc_filespec(e->key);
6491 two = alloc_filespec(e->key);
6492 fill_filespec(one, null_oid(), 0, 0);
6493 fill_filespec(two, null_oid(), 0, 0);
6494 p = diff_queue(q, one, two);
6495 p->status = DIFF_STATUS_MODIFIED;
6499 /* Re-sort the filepairs */
6500 diffcore_fix_diff_index();
6502 /* Cleanup */
6503 strset_clear(&present);
6506 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6508 int i;
6509 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6510 struct diff_queue_struct *q = &diff_queued_diff;
6512 if (WSEH_NEW & WS_RULE_MASK)
6513 BUG("WS rules bit mask overlaps with diff symbol flags");
6515 if (o->color_moved)
6516 o->emitted_symbols = &esm;
6518 if (o->additional_path_headers)
6519 create_filepairs_for_header_only_notifications(o);
6521 for (i = 0; i < q->nr; i++) {
6522 struct diff_filepair *p = q->queue[i];
6523 if (check_pair_status(p))
6524 diff_flush_patch(p, o);
6527 if (o->emitted_symbols) {
6528 if (o->color_moved) {
6529 struct mem_pool entry_pool;
6530 struct moved_entry_list *entry_list;
6532 mem_pool_init(&entry_pool, 1024 * 1024);
6533 entry_list = add_lines_to_move_detection(o,
6534 &entry_pool);
6535 mark_color_as_moved(o, entry_list);
6536 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6537 dim_moved_lines(o);
6539 mem_pool_discard(&entry_pool, 0);
6540 free(entry_list);
6543 for (i = 0; i < esm.nr; i++)
6544 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6546 for (i = 0; i < esm.nr; i++)
6547 free((void *)esm.buf[i].line);
6548 esm.nr = 0;
6550 o->emitted_symbols = NULL;
6554 static void diff_free_file(struct diff_options *options)
6556 if (options->close_file)
6557 fclose(options->file);
6560 static void diff_free_ignore_regex(struct diff_options *options)
6562 int i;
6564 for (i = 0; i < options->ignore_regex_nr; i++) {
6565 regfree(options->ignore_regex[i]);
6566 free(options->ignore_regex[i]);
6568 free(options->ignore_regex);
6571 void diff_free(struct diff_options *options)
6573 if (options->no_free)
6574 return;
6576 diff_free_file(options);
6577 diff_free_ignore_regex(options);
6578 clear_pathspec(&options->pathspec);
6581 void diff_flush(struct diff_options *options)
6583 struct diff_queue_struct *q = &diff_queued_diff;
6584 int i, output_format = options->output_format;
6585 int separator = 0;
6586 int dirstat_by_line = 0;
6589 * Order: raw, stat, summary, patch
6590 * or: name/name-status/checkdiff (other bits clear)
6592 if (!q->nr && !options->additional_path_headers)
6593 goto free_queue;
6595 if (output_format & (DIFF_FORMAT_RAW |
6596 DIFF_FORMAT_NAME |
6597 DIFF_FORMAT_NAME_STATUS |
6598 DIFF_FORMAT_CHECKDIFF)) {
6599 for (i = 0; i < q->nr; i++) {
6600 struct diff_filepair *p = q->queue[i];
6601 if (check_pair_status(p))
6602 flush_one_pair(p, options);
6604 separator++;
6607 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6608 dirstat_by_line = 1;
6610 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6611 dirstat_by_line) {
6612 struct diffstat_t diffstat;
6614 compute_diffstat(options, &diffstat, q);
6615 if (output_format & DIFF_FORMAT_NUMSTAT)
6616 show_numstat(&diffstat, options);
6617 if (output_format & DIFF_FORMAT_DIFFSTAT)
6618 show_stats(&diffstat, options);
6619 if (output_format & DIFF_FORMAT_SHORTSTAT)
6620 show_shortstats(&diffstat, options);
6621 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6622 show_dirstat_by_line(&diffstat, options);
6623 free_diffstat_info(&diffstat);
6624 separator++;
6626 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6627 show_dirstat(options);
6629 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6630 for (i = 0; i < q->nr; i++) {
6631 diff_summary(options, q->queue[i]);
6633 separator++;
6636 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6637 options->flags.exit_with_status &&
6638 options->flags.diff_from_contents) {
6640 * run diff_flush_patch for the exit status. setting
6641 * options->file to /dev/null should be safe, because we
6642 * aren't supposed to produce any output anyway.
6644 diff_free_file(options);
6645 options->file = xfopen("/dev/null", "w");
6646 options->close_file = 1;
6647 options->color_moved = 0;
6648 for (i = 0; i < q->nr; i++) {
6649 struct diff_filepair *p = q->queue[i];
6650 if (check_pair_status(p))
6651 diff_flush_patch(p, options);
6652 if (options->found_changes)
6653 break;
6657 if (output_format & DIFF_FORMAT_PATCH) {
6658 if (separator) {
6659 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6660 if (options->stat_sep)
6661 /* attach patch instead of inline */
6662 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6663 NULL, 0, 0);
6666 diff_flush_patch_all_file_pairs(options);
6669 if (output_format & DIFF_FORMAT_CALLBACK)
6670 options->format_callback(q, options, options->format_callback_data);
6672 free_queue:
6673 diff_free_queue(q);
6674 DIFF_QUEUE_CLEAR(q);
6675 diff_free(options);
6678 * Report the content-level differences with HAS_CHANGES;
6679 * diff_addremove/diff_change does not set the bit when
6680 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6682 if (options->flags.diff_from_contents) {
6683 if (options->found_changes)
6684 options->flags.has_changes = 1;
6685 else
6686 options->flags.has_changes = 0;
6690 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6692 return (((p->status == DIFF_STATUS_MODIFIED) &&
6693 ((p->score &&
6694 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6695 (!p->score &&
6696 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6697 ((p->status != DIFF_STATUS_MODIFIED) &&
6698 filter_bit_tst(p->status, options)));
6701 static void diffcore_apply_filter(struct diff_options *options)
6703 int i;
6704 struct diff_queue_struct *q = &diff_queued_diff;
6705 struct diff_queue_struct outq;
6707 DIFF_QUEUE_CLEAR(&outq);
6709 if (!options->filter)
6710 return;
6712 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6713 int found;
6714 for (i = found = 0; !found && i < q->nr; i++) {
6715 if (match_filter(options, q->queue[i]))
6716 found++;
6718 if (found)
6719 return;
6721 /* otherwise we will clear the whole queue
6722 * by copying the empty outq at the end of this
6723 * function, but first clear the current entries
6724 * in the queue.
6726 for (i = 0; i < q->nr; i++)
6727 diff_free_filepair(q->queue[i]);
6729 else {
6730 /* Only the matching ones */
6731 for (i = 0; i < q->nr; i++) {
6732 struct diff_filepair *p = q->queue[i];
6733 if (match_filter(options, p))
6734 diff_q(&outq, p);
6735 else
6736 diff_free_filepair(p);
6739 free(q->queue);
6740 *q = outq;
6743 /* Check whether two filespecs with the same mode and size are identical */
6744 static int diff_filespec_is_identical(struct repository *r,
6745 struct diff_filespec *one,
6746 struct diff_filespec *two)
6748 if (S_ISGITLINK(one->mode))
6749 return 0;
6750 if (diff_populate_filespec(r, one, NULL))
6751 return 0;
6752 if (diff_populate_filespec(r, two, NULL))
6753 return 0;
6754 return !memcmp(one->data, two->data, one->size);
6757 static int diff_filespec_check_stat_unmatch(struct repository *r,
6758 struct diff_filepair *p)
6760 struct diff_populate_filespec_options dpf_options = {
6761 .check_size_only = 1,
6762 .missing_object_cb = diff_queued_diff_prefetch,
6763 .missing_object_data = r,
6766 if (p->done_skip_stat_unmatch)
6767 return p->skip_stat_unmatch_result;
6769 p->done_skip_stat_unmatch = 1;
6770 p->skip_stat_unmatch_result = 0;
6772 * 1. Entries that come from stat info dirtiness
6773 * always have both sides (iow, not create/delete),
6774 * one side of the object name is unknown, with
6775 * the same mode and size. Keep the ones that
6776 * do not match these criteria. They have real
6777 * differences.
6779 * 2. At this point, the file is known to be modified,
6780 * with the same mode and size, and the object
6781 * name of one side is unknown. Need to inspect
6782 * the identical contents.
6784 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6785 !DIFF_FILE_VALID(p->two) ||
6786 (p->one->oid_valid && p->two->oid_valid) ||
6787 (p->one->mode != p->two->mode) ||
6788 diff_populate_filespec(r, p->one, &dpf_options) ||
6789 diff_populate_filespec(r, p->two, &dpf_options) ||
6790 (p->one->size != p->two->size) ||
6791 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6792 p->skip_stat_unmatch_result = 1;
6793 return p->skip_stat_unmatch_result;
6796 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6798 int i;
6799 struct diff_queue_struct *q = &diff_queued_diff;
6800 struct diff_queue_struct outq;
6801 DIFF_QUEUE_CLEAR(&outq);
6803 for (i = 0; i < q->nr; i++) {
6804 struct diff_filepair *p = q->queue[i];
6806 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6807 diff_q(&outq, p);
6808 else {
6810 * The caller can subtract 1 from skip_stat_unmatch
6811 * to determine how many paths were dirty only
6812 * due to stat info mismatch.
6814 if (!diffopt->flags.no_index)
6815 diffopt->skip_stat_unmatch++;
6816 diff_free_filepair(p);
6819 free(q->queue);
6820 *q = outq;
6823 static int diffnamecmp(const void *a_, const void *b_)
6825 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6826 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6827 const char *name_a, *name_b;
6829 name_a = a->one ? a->one->path : a->two->path;
6830 name_b = b->one ? b->one->path : b->two->path;
6831 return strcmp(name_a, name_b);
6834 void diffcore_fix_diff_index(void)
6836 struct diff_queue_struct *q = &diff_queued_diff;
6837 QSORT(q->queue, q->nr, diffnamecmp);
6840 void diff_add_if_missing(struct repository *r,
6841 struct oid_array *to_fetch,
6842 const struct diff_filespec *filespec)
6844 if (filespec && filespec->oid_valid &&
6845 !S_ISGITLINK(filespec->mode) &&
6846 oid_object_info_extended(r, &filespec->oid, NULL,
6847 OBJECT_INFO_FOR_PREFETCH))
6848 oid_array_append(to_fetch, &filespec->oid);
6851 void diff_queued_diff_prefetch(void *repository)
6853 struct repository *repo = repository;
6854 int i;
6855 struct diff_queue_struct *q = &diff_queued_diff;
6856 struct oid_array to_fetch = OID_ARRAY_INIT;
6858 for (i = 0; i < q->nr; i++) {
6859 struct diff_filepair *p = q->queue[i];
6860 diff_add_if_missing(repo, &to_fetch, p->one);
6861 diff_add_if_missing(repo, &to_fetch, p->two);
6865 * NEEDSWORK: Consider deduplicating the OIDs sent.
6867 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6869 oid_array_clear(&to_fetch);
6872 void diffcore_std(struct diff_options *options)
6874 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6875 DIFF_FORMAT_NUMSTAT |
6876 DIFF_FORMAT_PATCH |
6877 DIFF_FORMAT_SHORTSTAT |
6878 DIFF_FORMAT_DIRSTAT;
6881 * Check if the user requested a blob-data-requiring diff output and/or
6882 * break-rewrite detection (which requires blob data). If yes, prefetch
6883 * the diff pairs.
6885 * If no prefetching occurs, diffcore_rename() will prefetch if it
6886 * decides that it needs inexact rename detection.
6888 if (options->repo == the_repository && has_promisor_remote() &&
6889 (options->output_format & output_formats_to_prefetch ||
6890 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6891 diff_queued_diff_prefetch(options->repo);
6893 /* NOTE please keep the following in sync with diff_tree_combined() */
6894 if (options->skip_stat_unmatch)
6895 diffcore_skip_stat_unmatch(options);
6896 if (!options->found_follow) {
6897 /* See try_to_follow_renames() in tree-diff.c */
6898 if (options->break_opt != -1)
6899 diffcore_break(options->repo,
6900 options->break_opt);
6901 if (options->detect_rename)
6902 diffcore_rename(options);
6903 if (options->break_opt != -1)
6904 diffcore_merge_broken();
6906 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6907 diffcore_pickaxe(options);
6908 if (options->orderfile)
6909 diffcore_order(options->orderfile);
6910 if (options->rotate_to)
6911 diffcore_rotate(options);
6912 if (!options->found_follow)
6913 /* See try_to_follow_renames() in tree-diff.c */
6914 diff_resolve_rename_copy();
6915 diffcore_apply_filter(options);
6917 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6918 options->flags.has_changes = 1;
6919 else
6920 options->flags.has_changes = 0;
6922 options->found_follow = 0;
6925 int diff_result_code(struct diff_options *opt, int status)
6927 int result = 0;
6929 diff_warn_rename_limit("diff.renameLimit",
6930 opt->needed_rename_limit,
6931 opt->degraded_cc_to_c);
6932 if (!opt->flags.exit_with_status &&
6933 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6934 return status;
6935 if (opt->flags.exit_with_status &&
6936 opt->flags.has_changes)
6937 result |= 01;
6938 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6939 opt->flags.check_failed)
6940 result |= 02;
6941 return result;
6944 int diff_can_quit_early(struct diff_options *opt)
6946 return (opt->flags.quick &&
6947 !opt->filter &&
6948 opt->flags.has_changes);
6952 * Shall changes to this submodule be ignored?
6954 * Submodule changes can be configured to be ignored separately for each path,
6955 * but that configuration can be overridden from the command line.
6957 static int is_submodule_ignored(const char *path, struct diff_options *options)
6959 int ignored = 0;
6960 struct diff_flags orig_flags = options->flags;
6961 if (!options->flags.override_submodule_config)
6962 set_diffopt_flags_from_submodule_config(options, path);
6963 if (options->flags.ignore_submodules)
6964 ignored = 1;
6965 options->flags = orig_flags;
6966 return ignored;
6969 void compute_diffstat(struct diff_options *options,
6970 struct diffstat_t *diffstat,
6971 struct diff_queue_struct *q)
6973 int i;
6975 memset(diffstat, 0, sizeof(struct diffstat_t));
6976 for (i = 0; i < q->nr; i++) {
6977 struct diff_filepair *p = q->queue[i];
6978 if (check_pair_status(p))
6979 diff_flush_stat(p, options, diffstat);
6983 void diff_addremove(struct diff_options *options,
6984 int addremove, unsigned mode,
6985 const struct object_id *oid,
6986 int oid_valid,
6987 const char *concatpath, unsigned dirty_submodule)
6989 struct diff_filespec *one, *two;
6991 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6992 return;
6994 /* This may look odd, but it is a preparation for
6995 * feeding "there are unchanged files which should
6996 * not produce diffs, but when you are doing copy
6997 * detection you would need them, so here they are"
6998 * entries to the diff-core. They will be prefixed
6999 * with something like '=' or '*' (I haven't decided
7000 * which but should not make any difference).
7001 * Feeding the same new and old to diff_change()
7002 * also has the same effect.
7003 * Before the final output happens, they are pruned after
7004 * merged into rename/copy pairs as appropriate.
7006 if (options->flags.reverse_diff)
7007 addremove = (addremove == '+' ? '-' :
7008 addremove == '-' ? '+' : addremove);
7010 if (options->prefix &&
7011 strncmp(concatpath, options->prefix, options->prefix_length))
7012 return;
7014 one = alloc_filespec(concatpath);
7015 two = alloc_filespec(concatpath);
7017 if (addremove != '+')
7018 fill_filespec(one, oid, oid_valid, mode);
7019 if (addremove != '-') {
7020 fill_filespec(two, oid, oid_valid, mode);
7021 two->dirty_submodule = dirty_submodule;
7024 diff_queue(&diff_queued_diff, one, two);
7025 if (!options->flags.diff_from_contents)
7026 options->flags.has_changes = 1;
7029 void diff_change(struct diff_options *options,
7030 unsigned old_mode, unsigned new_mode,
7031 const struct object_id *old_oid,
7032 const struct object_id *new_oid,
7033 int old_oid_valid, int new_oid_valid,
7034 const char *concatpath,
7035 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7037 struct diff_filespec *one, *two;
7038 struct diff_filepair *p;
7040 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7041 is_submodule_ignored(concatpath, options))
7042 return;
7044 if (options->flags.reverse_diff) {
7045 SWAP(old_mode, new_mode);
7046 SWAP(old_oid, new_oid);
7047 SWAP(old_oid_valid, new_oid_valid);
7048 SWAP(old_dirty_submodule, new_dirty_submodule);
7051 if (options->prefix &&
7052 strncmp(concatpath, options->prefix, options->prefix_length))
7053 return;
7055 one = alloc_filespec(concatpath);
7056 two = alloc_filespec(concatpath);
7057 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7058 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7059 one->dirty_submodule = old_dirty_submodule;
7060 two->dirty_submodule = new_dirty_submodule;
7061 p = diff_queue(&diff_queued_diff, one, two);
7063 if (options->flags.diff_from_contents)
7064 return;
7066 if (options->flags.quick && options->skip_stat_unmatch &&
7067 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7068 diff_free_filespec_data(p->one);
7069 diff_free_filespec_data(p->two);
7070 return;
7073 options->flags.has_changes = 1;
7076 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7078 struct diff_filepair *pair;
7079 struct diff_filespec *one, *two;
7081 if (options->prefix &&
7082 strncmp(path, options->prefix, options->prefix_length))
7083 return NULL;
7085 one = alloc_filespec(path);
7086 two = alloc_filespec(path);
7087 pair = diff_queue(&diff_queued_diff, one, two);
7088 pair->is_unmerged = 1;
7089 return pair;
7092 static char *run_textconv(struct repository *r,
7093 const char *pgm,
7094 struct diff_filespec *spec,
7095 size_t *outsize)
7097 struct diff_tempfile *temp;
7098 struct child_process child = CHILD_PROCESS_INIT;
7099 struct strbuf buf = STRBUF_INIT;
7100 int err = 0;
7102 temp = prepare_temp_file(r, spec);
7103 strvec_push(&child.args, pgm);
7104 strvec_push(&child.args, temp->name);
7106 child.use_shell = 1;
7107 child.out = -1;
7108 if (start_command(&child)) {
7109 remove_tempfile();
7110 return NULL;
7113 if (strbuf_read(&buf, child.out, 0) < 0)
7114 err = error("error reading from textconv command '%s'", pgm);
7115 close(child.out);
7117 if (finish_command(&child) || err) {
7118 strbuf_release(&buf);
7119 remove_tempfile();
7120 return NULL;
7122 remove_tempfile();
7124 return strbuf_detach(&buf, outsize);
7127 size_t fill_textconv(struct repository *r,
7128 struct userdiff_driver *driver,
7129 struct diff_filespec *df,
7130 char **outbuf)
7132 size_t size;
7134 if (!driver) {
7135 if (!DIFF_FILE_VALID(df)) {
7136 *outbuf = "";
7137 return 0;
7139 if (diff_populate_filespec(r, df, NULL))
7140 die("unable to read files to diff");
7141 *outbuf = df->data;
7142 return df->size;
7145 if (!driver->textconv)
7146 BUG("fill_textconv called with non-textconv driver");
7148 if (driver->textconv_cache && df->oid_valid) {
7149 *outbuf = notes_cache_get(driver->textconv_cache,
7150 &df->oid,
7151 &size);
7152 if (*outbuf)
7153 return size;
7156 *outbuf = run_textconv(r, driver->textconv, df, &size);
7157 if (!*outbuf)
7158 die("unable to read files to diff");
7160 if (driver->textconv_cache && df->oid_valid) {
7161 /* ignore errors, as we might be in a readonly repository */
7162 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7163 size);
7165 * we could save up changes and flush them all at the end,
7166 * but we would need an extra call after all diffing is done.
7167 * Since generating a cache entry is the slow path anyway,
7168 * this extra overhead probably isn't a big deal.
7170 notes_cache_write(driver->textconv_cache);
7173 return size;
7176 int textconv_object(struct repository *r,
7177 const char *path,
7178 unsigned mode,
7179 const struct object_id *oid,
7180 int oid_valid,
7181 char **buf,
7182 unsigned long *buf_size)
7184 struct diff_filespec *df;
7185 struct userdiff_driver *textconv;
7187 df = alloc_filespec(path);
7188 fill_filespec(df, oid, oid_valid, mode);
7189 textconv = get_textconv(r, df);
7190 if (!textconv) {
7191 free_filespec(df);
7192 return 0;
7195 *buf_size = fill_textconv(r, textconv, df, buf);
7196 free_filespec(df);
7197 return 1;
7200 void setup_diff_pager(struct diff_options *opt)
7203 * If the user asked for our exit code, then either they want --quiet
7204 * or --exit-code. We should definitely not bother with a pager in the
7205 * former case, as we will generate no output. Since we still properly
7206 * report our exit code even when a pager is run, we _could_ run a
7207 * pager with --exit-code. But since we have not done so historically,
7208 * and because it is easy to find people oneline advising "git diff
7209 * --exit-code" in hooks and other scripts, we do not do so.
7211 if (!opt->flags.exit_with_status &&
7212 check_pager_config("diff") != 0)
7213 setup_pager();