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