Merge branch 'ps/commit-graph-less-paranoid' into maint-2.43
[alt-git.git] / diff.c
blob2c602df10a372c7e99402ca5a2dc9cf7aa673c09
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "base85.h"
7 #include "config.h"
8 #include "convert.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "tempfile.h"
12 #include "quote.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "delta.h"
16 #include "hex.h"
17 #include "xdiff-interface.h"
18 #include "color.h"
19 #include "attr.h"
20 #include "run-command.h"
21 #include "utf8.h"
22 #include "object-store-ll.h"
23 #include "userdiff.h"
24 #include "submodule-config.h"
25 #include "submodule.h"
26 #include "hashmap.h"
27 #include "mem-pool.h"
28 #include "merge-ll.h"
29 #include "string-list.h"
30 #include "strvec.h"
31 #include "graph.h"
32 #include "oid-array.h"
33 #include "packfile.h"
34 #include "pager.h"
35 #include "parse-options.h"
36 #include "help.h"
37 #include "promisor-remote.h"
38 #include "dir.h"
39 #include "object-file.h"
40 #include "object-name.h"
41 #include "read-cache-ll.h"
42 #include "setup.h"
43 #include "strmap.h"
44 #include "ws.h"
46 #ifdef NO_FAST_WORKING_DIRECTORY
47 #define FAST_WORKING_DIRECTORY 0
48 #else
49 #define FAST_WORKING_DIRECTORY 1
50 #endif
52 static int diff_detect_rename_default;
53 static int diff_indent_heuristic = 1;
54 static int diff_rename_limit_default = 1000;
55 static int diff_suppress_blank_empty;
56 static int diff_use_color_default = -1;
57 static int diff_color_moved_default;
58 static int diff_color_moved_ws_default;
59 static int diff_context_default = 3;
60 static int diff_interhunk_context_default;
61 static const char *diff_word_regex_cfg;
62 static const char *external_diff_cmd_cfg;
63 static const char *diff_order_file_cfg;
64 int diff_auto_refresh_index = 1;
65 static int diff_mnemonic_prefix;
66 static int diff_no_prefix;
67 static int diff_relative;
68 static int diff_stat_name_width;
69 static int diff_stat_graph_width;
70 static int diff_dirstat_permille_default = 30;
71 static struct diff_options default_diff_options;
72 static long diff_algorithm;
73 static unsigned ws_error_highlight_default = WSEH_NEW;
75 static char diff_colors[][COLOR_MAXLEN] = {
76 GIT_COLOR_RESET,
77 GIT_COLOR_NORMAL, /* CONTEXT */
78 GIT_COLOR_BOLD, /* METAINFO */
79 GIT_COLOR_CYAN, /* FRAGINFO */
80 GIT_COLOR_RED, /* OLD */
81 GIT_COLOR_GREEN, /* NEW */
82 GIT_COLOR_YELLOW, /* COMMIT */
83 GIT_COLOR_BG_RED, /* WHITESPACE */
84 GIT_COLOR_NORMAL, /* FUNCINFO */
85 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
86 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
87 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
88 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
89 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
90 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
91 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
92 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
93 GIT_COLOR_FAINT, /* CONTEXT_DIM */
94 GIT_COLOR_FAINT_RED, /* OLD_DIM */
95 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
96 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
97 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
98 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
101 static const char *color_diff_slots[] = {
102 [DIFF_CONTEXT] = "context",
103 [DIFF_METAINFO] = "meta",
104 [DIFF_FRAGINFO] = "frag",
105 [DIFF_FILE_OLD] = "old",
106 [DIFF_FILE_NEW] = "new",
107 [DIFF_COMMIT] = "commit",
108 [DIFF_WHITESPACE] = "whitespace",
109 [DIFF_FUNCINFO] = "func",
110 [DIFF_FILE_OLD_MOVED] = "oldMoved",
111 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
112 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
113 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
114 [DIFF_FILE_NEW_MOVED] = "newMoved",
115 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
116 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
117 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
118 [DIFF_CONTEXT_DIM] = "contextDimmed",
119 [DIFF_FILE_OLD_DIM] = "oldDimmed",
120 [DIFF_FILE_NEW_DIM] = "newDimmed",
121 [DIFF_CONTEXT_BOLD] = "contextBold",
122 [DIFF_FILE_OLD_BOLD] = "oldBold",
123 [DIFF_FILE_NEW_BOLD] = "newBold",
126 define_list_config_array_extra(color_diff_slots, {"plain"});
128 static int parse_diff_color_slot(const char *var)
130 if (!strcasecmp(var, "plain"))
131 return DIFF_CONTEXT;
132 return LOOKUP_CONFIG(color_diff_slots, var);
135 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
136 struct strbuf *errmsg)
138 char *params_copy = xstrdup(params_string);
139 struct string_list params = STRING_LIST_INIT_NODUP;
140 int ret = 0;
141 int i;
143 if (*params_copy)
144 string_list_split_in_place(&params, params_copy, ",", -1);
145 for (i = 0; i < params.nr; i++) {
146 const char *p = params.items[i].string;
147 if (!strcmp(p, "changes")) {
148 options->flags.dirstat_by_line = 0;
149 options->flags.dirstat_by_file = 0;
150 } else if (!strcmp(p, "lines")) {
151 options->flags.dirstat_by_line = 1;
152 options->flags.dirstat_by_file = 0;
153 } else if (!strcmp(p, "files")) {
154 options->flags.dirstat_by_line = 0;
155 options->flags.dirstat_by_file = 1;
156 } else if (!strcmp(p, "noncumulative")) {
157 options->flags.dirstat_cumulative = 0;
158 } else if (!strcmp(p, "cumulative")) {
159 options->flags.dirstat_cumulative = 1;
160 } else if (isdigit(*p)) {
161 char *end;
162 int permille = strtoul(p, &end, 10) * 10;
163 if (*end == '.' && isdigit(*++end)) {
164 /* only use first digit */
165 permille += *end - '0';
166 /* .. and ignore any further digits */
167 while (isdigit(*++end))
168 ; /* nothing */
170 if (!*end)
171 options->dirstat_permille = permille;
172 else {
173 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
175 ret++;
177 } else {
178 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
179 ret++;
183 string_list_clear(&params, 0);
184 free(params_copy);
185 return ret;
188 static int parse_submodule_params(struct diff_options *options, const char *value)
190 if (!strcmp(value, "log"))
191 options->submodule_format = DIFF_SUBMODULE_LOG;
192 else if (!strcmp(value, "short"))
193 options->submodule_format = DIFF_SUBMODULE_SHORT;
194 else if (!strcmp(value, "diff"))
195 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
197 * Please update $__git_diff_submodule_formats in
198 * git-completion.bash when you add new formats.
200 else
201 return -1;
202 return 0;
205 int git_config_rename(const char *var, const char *value)
207 if (!value)
208 return DIFF_DETECT_RENAME;
209 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
210 return DIFF_DETECT_COPY;
211 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
214 long parse_algorithm_value(const char *value)
216 if (!value)
217 return -1;
218 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
219 return 0;
220 else if (!strcasecmp(value, "minimal"))
221 return XDF_NEED_MINIMAL;
222 else if (!strcasecmp(value, "patience"))
223 return XDF_PATIENCE_DIFF;
224 else if (!strcasecmp(value, "histogram"))
225 return XDF_HISTOGRAM_DIFF;
227 * Please update $__git_diff_algorithms in git-completion.bash
228 * when you add new algorithms.
230 return -1;
233 static int parse_one_token(const char **arg, const char *token)
235 const char *rest;
236 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
237 *arg = rest;
238 return 1;
240 return 0;
243 static int parse_ws_error_highlight(const char *arg)
245 const char *orig_arg = arg;
246 unsigned val = 0;
248 while (*arg) {
249 if (parse_one_token(&arg, "none"))
250 val = 0;
251 else if (parse_one_token(&arg, "default"))
252 val = WSEH_NEW;
253 else if (parse_one_token(&arg, "all"))
254 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
255 else if (parse_one_token(&arg, "new"))
256 val |= WSEH_NEW;
257 else if (parse_one_token(&arg, "old"))
258 val |= WSEH_OLD;
259 else if (parse_one_token(&arg, "context"))
260 val |= WSEH_CONTEXT;
261 else {
262 return -1 - (int)(arg - orig_arg);
264 if (*arg)
265 arg++;
267 return val;
271 * These are to give UI layer defaults.
272 * The core-level commands such as git-diff-files should
273 * never be affected by the setting of diff.renames
274 * the user happens to have in the configuration file.
276 void init_diff_ui_defaults(void)
278 diff_detect_rename_default = DIFF_DETECT_RENAME;
281 int git_diff_heuristic_config(const char *var, const char *value,
282 void *cb UNUSED)
284 if (!strcmp(var, "diff.indentheuristic"))
285 diff_indent_heuristic = git_config_bool(var, value);
286 return 0;
289 static int parse_color_moved(const char *arg)
291 switch (git_parse_maybe_bool(arg)) {
292 case 0:
293 return COLOR_MOVED_NO;
294 case 1:
295 return COLOR_MOVED_DEFAULT;
296 default:
297 break;
300 if (!strcmp(arg, "no"))
301 return COLOR_MOVED_NO;
302 else if (!strcmp(arg, "plain"))
303 return COLOR_MOVED_PLAIN;
304 else if (!strcmp(arg, "blocks"))
305 return COLOR_MOVED_BLOCKS;
306 else if (!strcmp(arg, "zebra"))
307 return COLOR_MOVED_ZEBRA;
308 else if (!strcmp(arg, "default"))
309 return COLOR_MOVED_DEFAULT;
310 else if (!strcmp(arg, "dimmed-zebra"))
311 return COLOR_MOVED_ZEBRA_DIM;
312 else if (!strcmp(arg, "dimmed_zebra"))
313 return COLOR_MOVED_ZEBRA_DIM;
314 else
315 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
318 static unsigned parse_color_moved_ws(const char *arg)
320 int ret = 0;
321 struct string_list l = STRING_LIST_INIT_DUP;
322 struct string_list_item *i;
324 string_list_split(&l, arg, ',', -1);
326 for_each_string_list_item(i, &l) {
327 struct strbuf sb = STRBUF_INIT;
328 strbuf_addstr(&sb, i->string);
329 strbuf_trim(&sb);
331 if (!strcmp(sb.buf, "no"))
332 ret = 0;
333 else if (!strcmp(sb.buf, "ignore-space-change"))
334 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
335 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
336 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
337 else if (!strcmp(sb.buf, "ignore-all-space"))
338 ret |= XDF_IGNORE_WHITESPACE;
339 else if (!strcmp(sb.buf, "allow-indentation-change"))
340 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
341 else {
342 ret |= COLOR_MOVED_WS_ERROR;
343 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);
346 strbuf_release(&sb);
349 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
350 (ret & XDF_WHITESPACE_FLAGS)) {
351 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
352 ret |= COLOR_MOVED_WS_ERROR;
355 string_list_clear(&l, 0);
357 return ret;
360 int git_diff_ui_config(const char *var, const char *value,
361 const struct config_context *ctx, void *cb)
363 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
364 diff_use_color_default = git_config_colorbool(var, value);
365 return 0;
367 if (!strcmp(var, "diff.colormoved")) {
368 int cm = parse_color_moved(value);
369 if (cm < 0)
370 return -1;
371 diff_color_moved_default = cm;
372 return 0;
374 if (!strcmp(var, "diff.colormovedws")) {
375 unsigned cm = parse_color_moved_ws(value);
376 if (cm & COLOR_MOVED_WS_ERROR)
377 return -1;
378 diff_color_moved_ws_default = cm;
379 return 0;
381 if (!strcmp(var, "diff.context")) {
382 diff_context_default = git_config_int(var, value, ctx->kvi);
383 if (diff_context_default < 0)
384 return -1;
385 return 0;
387 if (!strcmp(var, "diff.interhunkcontext")) {
388 diff_interhunk_context_default = git_config_int(var, value,
389 ctx->kvi);
390 if (diff_interhunk_context_default < 0)
391 return -1;
392 return 0;
394 if (!strcmp(var, "diff.renames")) {
395 diff_detect_rename_default = git_config_rename(var, value);
396 return 0;
398 if (!strcmp(var, "diff.autorefreshindex")) {
399 diff_auto_refresh_index = git_config_bool(var, value);
400 return 0;
402 if (!strcmp(var, "diff.mnemonicprefix")) {
403 diff_mnemonic_prefix = git_config_bool(var, value);
404 return 0;
406 if (!strcmp(var, "diff.noprefix")) {
407 diff_no_prefix = git_config_bool(var, value);
408 return 0;
410 if (!strcmp(var, "diff.relative")) {
411 diff_relative = git_config_bool(var, value);
412 return 0;
414 if (!strcmp(var, "diff.statnamewidth")) {
415 diff_stat_name_width = git_config_int(var, value, ctx->kvi);
416 return 0;
418 if (!strcmp(var, "diff.statgraphwidth")) {
419 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
420 return 0;
422 if (!strcmp(var, "diff.external"))
423 return git_config_string(&external_diff_cmd_cfg, var, value);
424 if (!strcmp(var, "diff.wordregex"))
425 return git_config_string(&diff_word_regex_cfg, var, value);
426 if (!strcmp(var, "diff.orderfile"))
427 return git_config_pathname(&diff_order_file_cfg, var, value);
429 if (!strcmp(var, "diff.ignoresubmodules"))
430 handle_ignore_submodules_arg(&default_diff_options, value);
432 if (!strcmp(var, "diff.submodule")) {
433 if (parse_submodule_params(&default_diff_options, value))
434 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
435 value);
436 return 0;
439 if (!strcmp(var, "diff.algorithm")) {
440 diff_algorithm = parse_algorithm_value(value);
441 if (diff_algorithm < 0)
442 return -1;
443 return 0;
446 if (git_color_config(var, value, cb) < 0)
447 return -1;
449 return git_diff_basic_config(var, value, ctx, cb);
452 int git_diff_basic_config(const char *var, const char *value,
453 const struct config_context *ctx, void *cb)
455 const char *name;
457 if (!strcmp(var, "diff.renamelimit")) {
458 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
459 return 0;
462 if (userdiff_config(var, value) < 0)
463 return -1;
465 if (skip_prefix(var, "diff.color.", &name) ||
466 skip_prefix(var, "color.diff.", &name)) {
467 int slot = parse_diff_color_slot(name);
468 if (slot < 0)
469 return 0;
470 if (!value)
471 return config_error_nonbool(var);
472 return color_parse(value, diff_colors[slot]);
475 if (!strcmp(var, "diff.wserrorhighlight")) {
476 int val = parse_ws_error_highlight(value);
477 if (val < 0)
478 return -1;
479 ws_error_highlight_default = val;
480 return 0;
483 /* like GNU diff's --suppress-blank-empty option */
484 if (!strcmp(var, "diff.suppressblankempty") ||
485 /* for backwards compatibility */
486 !strcmp(var, "diff.suppress-blank-empty")) {
487 diff_suppress_blank_empty = git_config_bool(var, value);
488 return 0;
491 if (!strcmp(var, "diff.dirstat")) {
492 struct strbuf errmsg = STRBUF_INIT;
493 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
494 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
495 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
496 errmsg.buf);
497 strbuf_release(&errmsg);
498 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
499 return 0;
502 if (git_diff_heuristic_config(var, value, cb) < 0)
503 return -1;
505 return git_default_config(var, value, ctx, cb);
508 static char *quote_two(const char *one, const char *two)
510 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
511 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
512 struct strbuf res = STRBUF_INIT;
514 if (need_one + need_two) {
515 strbuf_addch(&res, '"');
516 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
517 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
518 strbuf_addch(&res, '"');
519 } else {
520 strbuf_addstr(&res, one);
521 strbuf_addstr(&res, two);
523 return strbuf_detach(&res, NULL);
526 static const char *external_diff(void)
528 static const char *external_diff_cmd = NULL;
529 static int done_preparing = 0;
531 if (done_preparing)
532 return external_diff_cmd;
533 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
534 if (!external_diff_cmd)
535 external_diff_cmd = external_diff_cmd_cfg;
536 done_preparing = 1;
537 return external_diff_cmd;
541 * Keep track of files used for diffing. Sometimes such an entry
542 * refers to a temporary file, sometimes to an existing file, and
543 * sometimes to "/dev/null".
545 static struct diff_tempfile {
547 * filename external diff should read from, or NULL if this
548 * entry is currently not in use:
550 const char *name;
552 char hex[GIT_MAX_HEXSZ + 1];
553 char mode[10];
556 * If this diff_tempfile instance refers to a temporary file,
557 * this tempfile object is used to manage its lifetime.
559 struct tempfile *tempfile;
560 } diff_temp[2];
562 struct emit_callback {
563 int color_diff;
564 unsigned ws_rule;
565 int blank_at_eof_in_preimage;
566 int blank_at_eof_in_postimage;
567 int lno_in_preimage;
568 int lno_in_postimage;
569 const char **label_path;
570 struct diff_words_data *diff_words;
571 struct diff_options *opt;
572 struct strbuf *header;
575 static int count_lines(const char *data, int size)
577 int count, ch, completely_empty = 1, nl_just_seen = 0;
578 count = 0;
579 while (0 < size--) {
580 ch = *data++;
581 if (ch == '\n') {
582 count++;
583 nl_just_seen = 1;
584 completely_empty = 0;
586 else {
587 nl_just_seen = 0;
588 completely_empty = 0;
591 if (completely_empty)
592 return 0;
593 if (!nl_just_seen)
594 count++; /* no trailing newline */
595 return count;
598 static int fill_mmfile(struct repository *r, mmfile_t *mf,
599 struct diff_filespec *one)
601 if (!DIFF_FILE_VALID(one)) {
602 mf->ptr = (char *)""; /* does not matter */
603 mf->size = 0;
604 return 0;
606 else if (diff_populate_filespec(r, one, NULL))
607 return -1;
609 mf->ptr = one->data;
610 mf->size = one->size;
611 return 0;
614 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
615 static unsigned long diff_filespec_size(struct repository *r,
616 struct diff_filespec *one)
618 struct diff_populate_filespec_options dpf_options = {
619 .check_size_only = 1,
622 if (!DIFF_FILE_VALID(one))
623 return 0;
624 diff_populate_filespec(r, one, &dpf_options);
625 return one->size;
628 static int count_trailing_blank(mmfile_t *mf)
630 char *ptr = mf->ptr;
631 long size = mf->size;
632 int cnt = 0;
634 if (!size)
635 return cnt;
636 ptr += size - 1; /* pointing at the very end */
637 if (*ptr != '\n')
638 ; /* incomplete line */
639 else
640 ptr--; /* skip the last LF */
641 while (mf->ptr < ptr) {
642 char *prev_eol;
643 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
644 if (*prev_eol == '\n')
645 break;
646 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
647 break;
648 cnt++;
649 ptr = prev_eol - 1;
651 return cnt;
654 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
655 struct emit_callback *ecbdata)
657 int l1, l2, at;
658 l1 = count_trailing_blank(mf1);
659 l2 = count_trailing_blank(mf2);
660 if (l2 <= l1) {
661 ecbdata->blank_at_eof_in_preimage = 0;
662 ecbdata->blank_at_eof_in_postimage = 0;
663 return;
665 at = count_lines(mf1->ptr, mf1->size);
666 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
668 at = count_lines(mf2->ptr, mf2->size);
669 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
672 static void emit_line_0(struct diff_options *o,
673 const char *set_sign, const char *set, unsigned reverse, const char *reset,
674 int first, const char *line, int len)
676 int has_trailing_newline, has_trailing_carriage_return;
677 int needs_reset = 0; /* at the end of the line */
678 FILE *file = o->file;
680 fputs(diff_line_prefix(o), file);
682 has_trailing_newline = (len > 0 && line[len-1] == '\n');
683 if (has_trailing_newline)
684 len--;
686 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
687 if (has_trailing_carriage_return)
688 len--;
690 if (!len && !first)
691 goto end_of_line;
693 if (reverse && want_color(o->use_color)) {
694 fputs(GIT_COLOR_REVERSE, file);
695 needs_reset = 1;
698 if (set_sign) {
699 fputs(set_sign, file);
700 needs_reset = 1;
703 if (first)
704 fputc(first, file);
706 if (!len)
707 goto end_of_line;
709 if (set) {
710 if (set_sign && set != set_sign)
711 fputs(reset, file);
712 fputs(set, file);
713 needs_reset = 1;
715 fwrite(line, len, 1, file);
716 needs_reset = 1; /* 'line' may contain color codes. */
718 end_of_line:
719 if (needs_reset)
720 fputs(reset, file);
721 if (has_trailing_carriage_return)
722 fputc('\r', file);
723 if (has_trailing_newline)
724 fputc('\n', file);
727 static void emit_line(struct diff_options *o, const char *set, const char *reset,
728 const char *line, int len)
730 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
733 enum diff_symbol {
734 DIFF_SYMBOL_BINARY_DIFF_HEADER,
735 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
736 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
737 DIFF_SYMBOL_BINARY_DIFF_BODY,
738 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
739 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
740 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
741 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
742 DIFF_SYMBOL_STATS_LINE,
743 DIFF_SYMBOL_WORD_DIFF,
744 DIFF_SYMBOL_STAT_SEP,
745 DIFF_SYMBOL_SUMMARY,
746 DIFF_SYMBOL_SUBMODULE_ADD,
747 DIFF_SYMBOL_SUBMODULE_DEL,
748 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
749 DIFF_SYMBOL_SUBMODULE_MODIFIED,
750 DIFF_SYMBOL_SUBMODULE_HEADER,
751 DIFF_SYMBOL_SUBMODULE_ERROR,
752 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
753 DIFF_SYMBOL_REWRITE_DIFF,
754 DIFF_SYMBOL_BINARY_FILES,
755 DIFF_SYMBOL_HEADER,
756 DIFF_SYMBOL_FILEPAIR_PLUS,
757 DIFF_SYMBOL_FILEPAIR_MINUS,
758 DIFF_SYMBOL_WORDS_PORCELAIN,
759 DIFF_SYMBOL_WORDS,
760 DIFF_SYMBOL_CONTEXT,
761 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
762 DIFF_SYMBOL_PLUS,
763 DIFF_SYMBOL_MINUS,
764 DIFF_SYMBOL_NO_LF_EOF,
765 DIFF_SYMBOL_CONTEXT_FRAGINFO,
766 DIFF_SYMBOL_CONTEXT_MARKER,
767 DIFF_SYMBOL_SEPARATOR
770 * Flags for content lines:
771 * 0..12 are whitespace rules
772 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
773 * 16 is marking if the line is blank at EOF
775 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
776 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
777 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
778 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
779 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
782 * This struct is used when we need to buffer the output of the diff output.
784 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
785 * into the pre/post image file. This pointer could be a union with the
786 * line pointer. By storing an offset into the file instead of the literal line,
787 * we can decrease the memory footprint for the buffered output. At first we
788 * may want to only have indirection for the content lines, but we could also
789 * enhance the state for emitting prefabricated lines, e.g. the similarity
790 * score line or hunk/file headers would only need to store a number or path
791 * and then the output can be constructed later on depending on state.
793 struct emitted_diff_symbol {
794 const char *line;
795 int len;
796 int flags;
797 int indent_off; /* Offset to first non-whitespace character */
798 int indent_width; /* The visual width of the indentation */
799 unsigned id;
800 enum diff_symbol s;
802 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
804 struct emitted_diff_symbols {
805 struct emitted_diff_symbol *buf;
806 int nr, alloc;
808 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
810 static void append_emitted_diff_symbol(struct diff_options *o,
811 struct emitted_diff_symbol *e)
813 struct emitted_diff_symbol *f;
815 ALLOC_GROW(o->emitted_symbols->buf,
816 o->emitted_symbols->nr + 1,
817 o->emitted_symbols->alloc);
818 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
820 memcpy(f, e, sizeof(struct emitted_diff_symbol));
821 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
824 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
826 if (!e)
827 return;
828 free(e->buf);
829 free(e);
832 struct moved_entry {
833 const struct emitted_diff_symbol *es;
834 struct moved_entry *next_line;
835 struct moved_entry *next_match;
838 struct moved_block {
839 struct moved_entry *match;
840 int wsd; /* The whitespace delta of this block */
843 #define INDENT_BLANKLINE INT_MIN
845 static void fill_es_indent_data(struct emitted_diff_symbol *es)
847 unsigned int off = 0, i;
848 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
849 const char *s = es->line;
850 const int len = es->len;
852 /* skip any \v \f \r at start of indentation */
853 while (s[off] == '\f' || s[off] == '\v' ||
854 (s[off] == '\r' && off < len - 1))
855 off++;
857 /* calculate the visual width of indentation */
858 while(1) {
859 if (s[off] == ' ') {
860 width++;
861 off++;
862 } else if (s[off] == '\t') {
863 width += tab_width - (width % tab_width);
864 while (s[++off] == '\t')
865 width += tab_width;
866 } else {
867 break;
871 /* check if this line is blank */
872 for (i = off; i < len; i++)
873 if (!isspace(s[i]))
874 break;
876 if (i == len) {
877 es->indent_width = INDENT_BLANKLINE;
878 es->indent_off = len;
879 } else {
880 es->indent_off = off;
881 es->indent_width = width;
885 static int compute_ws_delta(const struct emitted_diff_symbol *a,
886 const struct emitted_diff_symbol *b)
888 int a_width = a->indent_width,
889 b_width = b->indent_width;
891 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
892 return INDENT_BLANKLINE;
894 return a_width - b_width;
897 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
898 const struct emitted_diff_symbol *l,
899 struct moved_block *pmb)
901 int a_width = cur->es->indent_width, b_width = l->indent_width;
902 int delta;
904 /* The text of each line must match */
905 if (cur->es->id != l->id)
906 return 1;
909 * If 'l' and 'cur' are both blank then we don't need to check the
910 * indent. We only need to check cur as we know the strings match.
911 * */
912 if (a_width == INDENT_BLANKLINE)
913 return 0;
916 * The indent changes of the block are known and stored in pmb->wsd;
917 * however we need to check if the indent changes of the current line
918 * match those of the current block.
920 delta = b_width - a_width;
923 * If the previous lines of this block were all blank then set its
924 * whitespace delta.
926 if (pmb->wsd == INDENT_BLANKLINE)
927 pmb->wsd = delta;
929 return delta != pmb->wsd;
932 struct interned_diff_symbol {
933 struct hashmap_entry ent;
934 struct emitted_diff_symbol *es;
937 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
938 const struct hashmap_entry *eptr,
939 const struct hashmap_entry *entry_or_key,
940 const void *keydata UNUSED)
942 const struct diff_options *diffopt = hashmap_cmp_fn_data;
943 const struct emitted_diff_symbol *a, *b;
944 unsigned flags = diffopt->color_moved_ws_handling
945 & XDF_WHITESPACE_FLAGS;
947 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
948 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
950 return !xdiff_compare_lines(a->line + a->indent_off,
951 a->len - a->indent_off,
952 b->line + b->indent_off,
953 b->len - b->indent_off, flags);
956 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
957 struct interned_diff_symbol *s)
959 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
960 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
961 l->len - l->indent_off, flags);
963 hashmap_entry_init(&s->ent, hash);
964 s->es = l;
967 struct moved_entry_list {
968 struct moved_entry *add, *del;
971 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
972 struct mem_pool *entry_mem_pool)
974 struct moved_entry *prev_line = NULL;
975 struct mem_pool interned_pool;
976 struct hashmap interned_map;
977 struct moved_entry_list *entry_list = NULL;
978 size_t entry_list_alloc = 0;
979 unsigned id = 0;
980 int n;
982 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
983 mem_pool_init(&interned_pool, 1024 * 1024);
985 for (n = 0; n < o->emitted_symbols->nr; n++) {
986 struct interned_diff_symbol key;
987 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
988 struct interned_diff_symbol *s;
989 struct moved_entry *entry;
991 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
992 prev_line = NULL;
993 continue;
996 if (o->color_moved_ws_handling &
997 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
998 fill_es_indent_data(l);
1000 prepare_entry(o, l, &key);
1001 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1002 if (s) {
1003 l->id = s->es->id;
1004 } else {
1005 l->id = id;
1006 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1007 hashmap_add(&interned_map,
1008 memcpy(mem_pool_alloc(&interned_pool,
1009 sizeof(key)),
1010 &key, sizeof(key)));
1012 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1013 entry->es = l;
1014 entry->next_line = NULL;
1015 if (prev_line && prev_line->es->s == l->s)
1016 prev_line->next_line = entry;
1017 prev_line = entry;
1018 if (l->s == DIFF_SYMBOL_PLUS) {
1019 entry->next_match = entry_list[l->id].add;
1020 entry_list[l->id].add = entry;
1021 } else {
1022 entry->next_match = entry_list[l->id].del;
1023 entry_list[l->id].del = entry;
1027 hashmap_clear(&interned_map);
1028 mem_pool_discard(&interned_pool, 0);
1030 return entry_list;
1033 static void pmb_advance_or_null(struct diff_options *o,
1034 struct emitted_diff_symbol *l,
1035 struct moved_block *pmb,
1036 int *pmb_nr)
1038 int i, j;
1040 for (i = 0, j = 0; i < *pmb_nr; i++) {
1041 int match;
1042 struct moved_entry *prev = pmb[i].match;
1043 struct moved_entry *cur = (prev && prev->next_line) ?
1044 prev->next_line : NULL;
1046 if (o->color_moved_ws_handling &
1047 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1048 match = cur &&
1049 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1050 else
1051 match = cur && cur->es->id == l->id;
1053 if (match) {
1054 pmb[j] = pmb[i];
1055 pmb[j++].match = cur;
1058 *pmb_nr = j;
1061 static void fill_potential_moved_blocks(struct diff_options *o,
1062 struct moved_entry *match,
1063 struct emitted_diff_symbol *l,
1064 struct moved_block **pmb_p,
1065 int *pmb_alloc_p, int *pmb_nr_p)
1068 struct moved_block *pmb = *pmb_p;
1069 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1072 * The current line is the start of a new block.
1073 * Setup the set of potential blocks.
1075 for (; match; match = match->next_match) {
1076 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1077 if (o->color_moved_ws_handling &
1078 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1079 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1080 else
1081 pmb[pmb_nr].wsd = 0;
1082 pmb[pmb_nr++].match = match;
1085 *pmb_p = pmb;
1086 *pmb_alloc_p = pmb_alloc;
1087 *pmb_nr_p = pmb_nr;
1091 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1093 * Otherwise, if the last block has fewer alphanumeric characters than
1094 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1095 * that block.
1097 * The last block consists of the (n - block_length)'th line up to but not
1098 * including the nth line.
1100 * Returns 0 if the last block is empty or is unset by this function, non zero
1101 * otherwise.
1103 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1104 * Think of a way to unify them.
1106 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1107 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1108 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1110 int i, alnum_count = 0;
1111 if (o->color_moved == COLOR_MOVED_PLAIN)
1112 return block_length;
1113 for (i = 1; i < block_length + 1; i++) {
1114 const char *c = o->emitted_symbols->buf[n - i].line;
1115 for (; *c; c++) {
1116 if (!isalnum(*c))
1117 continue;
1118 alnum_count++;
1119 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1120 return 1;
1123 for (i = 1; i < block_length + 1; i++)
1124 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1125 return 0;
1128 /* Find blocks of moved code, delegate actual coloring decision to helper */
1129 static void mark_color_as_moved(struct diff_options *o,
1130 struct moved_entry_list *entry_list)
1132 struct moved_block *pmb = NULL; /* potentially moved blocks */
1133 int pmb_nr = 0, pmb_alloc = 0;
1134 int n, flipped_block = 0, block_length = 0;
1135 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1138 for (n = 0; n < o->emitted_symbols->nr; n++) {
1139 struct moved_entry *match = NULL;
1140 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1142 switch (l->s) {
1143 case DIFF_SYMBOL_PLUS:
1144 match = entry_list[l->id].del;
1145 break;
1146 case DIFF_SYMBOL_MINUS:
1147 match = entry_list[l->id].add;
1148 break;
1149 default:
1150 flipped_block = 0;
1153 if (pmb_nr && (!match || l->s != moved_symbol)) {
1154 if (!adjust_last_block(o, n, block_length) &&
1155 block_length > 1) {
1157 * Rewind in case there is another match
1158 * starting at the second line of the block
1160 match = NULL;
1161 n -= block_length;
1163 pmb_nr = 0;
1164 block_length = 0;
1165 flipped_block = 0;
1167 if (!match) {
1168 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1169 continue;
1172 if (o->color_moved == COLOR_MOVED_PLAIN) {
1173 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1174 continue;
1177 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1179 if (pmb_nr == 0) {
1180 int contiguous = adjust_last_block(o, n, block_length);
1182 if (!contiguous && block_length > 1)
1184 * Rewind in case there is another match
1185 * starting at the second line of the block
1187 n -= block_length;
1188 else
1189 fill_potential_moved_blocks(o, match, l,
1190 &pmb, &pmb_alloc,
1191 &pmb_nr);
1193 if (contiguous && pmb_nr && moved_symbol == l->s)
1194 flipped_block = (flipped_block + 1) % 2;
1195 else
1196 flipped_block = 0;
1198 if (pmb_nr)
1199 moved_symbol = l->s;
1200 else
1201 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1203 block_length = 0;
1206 if (pmb_nr) {
1207 block_length++;
1208 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1209 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1210 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1213 adjust_last_block(o, n, block_length);
1215 free(pmb);
1218 static void dim_moved_lines(struct diff_options *o)
1220 int n;
1221 for (n = 0; n < o->emitted_symbols->nr; n++) {
1222 struct emitted_diff_symbol *prev = (n != 0) ?
1223 &o->emitted_symbols->buf[n - 1] : NULL;
1224 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1225 struct emitted_diff_symbol *next =
1226 (n < o->emitted_symbols->nr - 1) ?
1227 &o->emitted_symbols->buf[n + 1] : NULL;
1229 /* Not a plus or minus line? */
1230 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1231 continue;
1233 /* Not a moved line? */
1234 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1235 continue;
1238 * If prev or next are not a plus or minus line,
1239 * pretend they don't exist
1241 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1242 prev->s != DIFF_SYMBOL_MINUS)
1243 prev = NULL;
1244 if (next && next->s != DIFF_SYMBOL_PLUS &&
1245 next->s != DIFF_SYMBOL_MINUS)
1246 next = NULL;
1248 /* Inside a block? */
1249 if ((prev &&
1250 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1251 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1252 (next &&
1253 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1254 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1255 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1256 continue;
1259 /* Check if we are at an interesting bound: */
1260 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1261 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1262 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1263 continue;
1264 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1265 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1266 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1267 continue;
1270 * The boundary to prev and next are not interesting,
1271 * so this line is not interesting as a whole
1273 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1277 static void emit_line_ws_markup(struct diff_options *o,
1278 const char *set_sign, const char *set,
1279 const char *reset,
1280 int sign_index, const char *line, int len,
1281 unsigned ws_rule, int blank_at_eof)
1283 const char *ws = NULL;
1284 int sign = o->output_indicators[sign_index];
1286 if (o->ws_error_highlight & ws_rule) {
1287 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1288 if (!*ws)
1289 ws = NULL;
1292 if (!ws && !set_sign)
1293 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1294 else if (!ws) {
1295 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1296 } else if (blank_at_eof)
1297 /* Blank line at EOF - paint '+' as well */
1298 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1299 else {
1300 /* Emit just the prefix, then the rest. */
1301 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1302 sign, "", 0);
1303 ws_check_emit(line, len, ws_rule,
1304 o->file, set, reset, ws);
1308 static void emit_diff_symbol_from_struct(struct diff_options *o,
1309 struct emitted_diff_symbol *eds)
1311 static const char *nneof = " No newline at end of file\n";
1312 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1314 enum diff_symbol s = eds->s;
1315 const char *line = eds->line;
1316 int len = eds->len;
1317 unsigned flags = eds->flags;
1319 switch (s) {
1320 case DIFF_SYMBOL_NO_LF_EOF:
1321 context = diff_get_color_opt(o, DIFF_CONTEXT);
1322 reset = diff_get_color_opt(o, DIFF_RESET);
1323 putc('\n', o->file);
1324 emit_line_0(o, context, NULL, 0, reset, '\\',
1325 nneof, strlen(nneof));
1326 break;
1327 case DIFF_SYMBOL_SUBMODULE_HEADER:
1328 case DIFF_SYMBOL_SUBMODULE_ERROR:
1329 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1330 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1331 case DIFF_SYMBOL_SUMMARY:
1332 case DIFF_SYMBOL_STATS_LINE:
1333 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1334 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1335 emit_line(o, "", "", line, len);
1336 break;
1337 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1338 case DIFF_SYMBOL_CONTEXT_MARKER:
1339 context = diff_get_color_opt(o, DIFF_CONTEXT);
1340 reset = diff_get_color_opt(o, DIFF_RESET);
1341 emit_line(o, context, reset, line, len);
1342 break;
1343 case DIFF_SYMBOL_SEPARATOR:
1344 fprintf(o->file, "%s%c",
1345 diff_line_prefix(o),
1346 o->line_termination);
1347 break;
1348 case DIFF_SYMBOL_CONTEXT:
1349 set = diff_get_color_opt(o, DIFF_CONTEXT);
1350 reset = diff_get_color_opt(o, DIFF_RESET);
1351 set_sign = NULL;
1352 if (o->flags.dual_color_diffed_diffs) {
1353 char c = !len ? 0 : line[0];
1355 if (c == '+')
1356 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1357 else if (c == '@')
1358 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1359 else if (c == '-')
1360 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1362 emit_line_ws_markup(o, set_sign, set, reset,
1363 OUTPUT_INDICATOR_CONTEXT, line, len,
1364 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1365 break;
1366 case DIFF_SYMBOL_PLUS:
1367 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1368 DIFF_SYMBOL_MOVED_LINE_ALT |
1369 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1370 case DIFF_SYMBOL_MOVED_LINE |
1371 DIFF_SYMBOL_MOVED_LINE_ALT |
1372 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1373 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1374 break;
1375 case DIFF_SYMBOL_MOVED_LINE |
1376 DIFF_SYMBOL_MOVED_LINE_ALT:
1377 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1378 break;
1379 case DIFF_SYMBOL_MOVED_LINE |
1380 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1381 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1382 break;
1383 case DIFF_SYMBOL_MOVED_LINE:
1384 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1385 break;
1386 default:
1387 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1389 reset = diff_get_color_opt(o, DIFF_RESET);
1390 if (!o->flags.dual_color_diffed_diffs)
1391 set_sign = NULL;
1392 else {
1393 char c = !len ? 0 : line[0];
1395 set_sign = set;
1396 if (c == '-')
1397 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1398 else if (c == '@')
1399 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1400 else if (c == '+')
1401 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1402 else
1403 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1404 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1406 emit_line_ws_markup(o, set_sign, set, reset,
1407 OUTPUT_INDICATOR_NEW, line, len,
1408 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1409 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1410 break;
1411 case DIFF_SYMBOL_MINUS:
1412 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1413 DIFF_SYMBOL_MOVED_LINE_ALT |
1414 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1415 case DIFF_SYMBOL_MOVED_LINE |
1416 DIFF_SYMBOL_MOVED_LINE_ALT |
1417 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1418 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1419 break;
1420 case DIFF_SYMBOL_MOVED_LINE |
1421 DIFF_SYMBOL_MOVED_LINE_ALT:
1422 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1423 break;
1424 case DIFF_SYMBOL_MOVED_LINE |
1425 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1426 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1427 break;
1428 case DIFF_SYMBOL_MOVED_LINE:
1429 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1430 break;
1431 default:
1432 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1434 reset = diff_get_color_opt(o, DIFF_RESET);
1435 if (!o->flags.dual_color_diffed_diffs)
1436 set_sign = NULL;
1437 else {
1438 char c = !len ? 0 : line[0];
1440 set_sign = set;
1441 if (c == '+')
1442 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1443 else if (c == '@')
1444 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1445 else if (c == '-')
1446 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1447 else
1448 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1450 emit_line_ws_markup(o, set_sign, set, reset,
1451 OUTPUT_INDICATOR_OLD, line, len,
1452 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1453 break;
1454 case DIFF_SYMBOL_WORDS_PORCELAIN:
1455 context = diff_get_color_opt(o, DIFF_CONTEXT);
1456 reset = diff_get_color_opt(o, DIFF_RESET);
1457 emit_line(o, context, reset, line, len);
1458 fputs("~\n", o->file);
1459 break;
1460 case DIFF_SYMBOL_WORDS:
1461 context = diff_get_color_opt(o, DIFF_CONTEXT);
1462 reset = diff_get_color_opt(o, DIFF_RESET);
1464 * Skip the prefix character, if any. With
1465 * diff_suppress_blank_empty, there may be
1466 * none.
1468 if (line[0] != '\n') {
1469 line++;
1470 len--;
1472 emit_line(o, context, reset, line, len);
1473 break;
1474 case DIFF_SYMBOL_FILEPAIR_PLUS:
1475 meta = diff_get_color_opt(o, DIFF_METAINFO);
1476 reset = diff_get_color_opt(o, DIFF_RESET);
1477 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1478 line, reset,
1479 strchr(line, ' ') ? "\t" : "");
1480 break;
1481 case DIFF_SYMBOL_FILEPAIR_MINUS:
1482 meta = diff_get_color_opt(o, DIFF_METAINFO);
1483 reset = diff_get_color_opt(o, DIFF_RESET);
1484 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1485 line, reset,
1486 strchr(line, ' ') ? "\t" : "");
1487 break;
1488 case DIFF_SYMBOL_BINARY_FILES:
1489 case DIFF_SYMBOL_HEADER:
1490 fprintf(o->file, "%s", line);
1491 break;
1492 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1493 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1494 break;
1495 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1496 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1497 break;
1498 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1499 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1500 break;
1501 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1502 fputs(diff_line_prefix(o), o->file);
1503 fputc('\n', o->file);
1504 break;
1505 case DIFF_SYMBOL_REWRITE_DIFF:
1506 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1507 reset = diff_get_color_opt(o, DIFF_RESET);
1508 emit_line(o, fraginfo, reset, line, len);
1509 break;
1510 case DIFF_SYMBOL_SUBMODULE_ADD:
1511 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1512 reset = diff_get_color_opt(o, DIFF_RESET);
1513 emit_line(o, set, reset, line, len);
1514 break;
1515 case DIFF_SYMBOL_SUBMODULE_DEL:
1516 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1517 reset = diff_get_color_opt(o, DIFF_RESET);
1518 emit_line(o, set, reset, line, len);
1519 break;
1520 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1521 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1522 diff_line_prefix(o), line);
1523 break;
1524 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1525 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1526 diff_line_prefix(o), line);
1527 break;
1528 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1529 emit_line(o, "", "", " 0 files changed\n",
1530 strlen(" 0 files changed\n"));
1531 break;
1532 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1533 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1534 break;
1535 case DIFF_SYMBOL_WORD_DIFF:
1536 fprintf(o->file, "%.*s", len, line);
1537 break;
1538 case DIFF_SYMBOL_STAT_SEP:
1539 fputs(o->stat_sep, o->file);
1540 break;
1541 default:
1542 BUG("unknown diff symbol");
1546 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1547 const char *line, int len, unsigned flags)
1549 struct emitted_diff_symbol e = {
1550 .line = line, .len = len, .flags = flags, .s = s
1553 if (o->emitted_symbols)
1554 append_emitted_diff_symbol(o, &e);
1555 else
1556 emit_diff_symbol_from_struct(o, &e);
1559 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1561 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1564 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1566 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1569 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1571 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1572 path, strlen(path), 0);
1575 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1577 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1578 path, strlen(path), 0);
1581 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1583 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1584 header, strlen(header), 0);
1587 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1589 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1592 void diff_emit_submodule_pipethrough(struct diff_options *o,
1593 const char *line, int len)
1595 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1598 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1600 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1601 ecbdata->blank_at_eof_in_preimage &&
1602 ecbdata->blank_at_eof_in_postimage &&
1603 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1604 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1605 return 0;
1606 return ws_blank_line(line, len);
1609 static void emit_add_line(struct emit_callback *ecbdata,
1610 const char *line, int len)
1612 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1613 if (new_blank_line_at_eof(ecbdata, line, len))
1614 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1616 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1619 static void emit_del_line(struct emit_callback *ecbdata,
1620 const char *line, int len)
1622 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1623 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1626 static void emit_context_line(struct emit_callback *ecbdata,
1627 const char *line, int len)
1629 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1630 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1633 static void emit_hunk_header(struct emit_callback *ecbdata,
1634 const char *line, int len)
1636 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1637 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1638 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1639 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1640 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1641 static const char atat[2] = { '@', '@' };
1642 const char *cp, *ep;
1643 struct strbuf msgbuf = STRBUF_INIT;
1644 int org_len = len;
1645 int i = 1;
1648 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1649 * it always is at least 10 bytes long.
1651 if (len < 10 ||
1652 memcmp(line, atat, 2) ||
1653 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1654 emit_diff_symbol(ecbdata->opt,
1655 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1656 return;
1658 ep += 2; /* skip over @@ */
1660 /* The hunk header in fraginfo color */
1661 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1662 strbuf_addstr(&msgbuf, reverse);
1663 strbuf_addstr(&msgbuf, frag);
1664 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1665 strbuf_add(&msgbuf, atat, sizeof(atat));
1666 else
1667 strbuf_add(&msgbuf, line, ep - line);
1668 strbuf_addstr(&msgbuf, reset);
1671 * trailing "\r\n"
1673 for ( ; i < 3; i++)
1674 if (line[len - i] == '\r' || line[len - i] == '\n')
1675 len--;
1677 /* blank before the func header */
1678 for (cp = ep; ep - line < len; ep++)
1679 if (*ep != ' ' && *ep != '\t')
1680 break;
1681 if (ep != cp) {
1682 strbuf_addstr(&msgbuf, context);
1683 strbuf_add(&msgbuf, cp, ep - cp);
1684 strbuf_addstr(&msgbuf, reset);
1687 if (ep < line + len) {
1688 strbuf_addstr(&msgbuf, func);
1689 strbuf_add(&msgbuf, ep, line + len - ep);
1690 strbuf_addstr(&msgbuf, reset);
1693 strbuf_add(&msgbuf, line + len, org_len - len);
1694 strbuf_complete_line(&msgbuf);
1695 emit_diff_symbol(ecbdata->opt,
1696 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1697 strbuf_release(&msgbuf);
1700 static struct diff_tempfile *claim_diff_tempfile(void)
1702 int i;
1703 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1704 if (!diff_temp[i].name)
1705 return diff_temp + i;
1706 BUG("diff is failing to clean up its tempfiles");
1709 static void remove_tempfile(void)
1711 int i;
1712 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1713 if (is_tempfile_active(diff_temp[i].tempfile))
1714 delete_tempfile(&diff_temp[i].tempfile);
1715 diff_temp[i].name = NULL;
1719 static void add_line_count(struct strbuf *out, int count)
1721 switch (count) {
1722 case 0:
1723 strbuf_addstr(out, "0,0");
1724 break;
1725 case 1:
1726 strbuf_addstr(out, "1");
1727 break;
1728 default:
1729 strbuf_addf(out, "1,%d", count);
1730 break;
1734 static void emit_rewrite_lines(struct emit_callback *ecb,
1735 int prefix, const char *data, int size)
1737 const char *endp = NULL;
1739 while (0 < size) {
1740 int len;
1742 endp = memchr(data, '\n', size);
1743 len = endp ? (endp - data + 1) : size;
1744 if (prefix != '+') {
1745 ecb->lno_in_preimage++;
1746 emit_del_line(ecb, data, len);
1747 } else {
1748 ecb->lno_in_postimage++;
1749 emit_add_line(ecb, data, len);
1751 size -= len;
1752 data += len;
1754 if (!endp)
1755 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1758 static void emit_rewrite_diff(const char *name_a,
1759 const char *name_b,
1760 struct diff_filespec *one,
1761 struct diff_filespec *two,
1762 struct userdiff_driver *textconv_one,
1763 struct userdiff_driver *textconv_two,
1764 struct diff_options *o)
1766 int lc_a, lc_b;
1767 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1768 const char *a_prefix, *b_prefix;
1769 char *data_one, *data_two;
1770 size_t size_one, size_two;
1771 struct emit_callback ecbdata;
1772 struct strbuf out = STRBUF_INIT;
1774 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1775 a_prefix = o->b_prefix;
1776 b_prefix = o->a_prefix;
1777 } else {
1778 a_prefix = o->a_prefix;
1779 b_prefix = o->b_prefix;
1782 name_a += (*name_a == '/');
1783 name_b += (*name_b == '/');
1785 strbuf_reset(&a_name);
1786 strbuf_reset(&b_name);
1787 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1788 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1790 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1791 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1793 memset(&ecbdata, 0, sizeof(ecbdata));
1794 ecbdata.color_diff = want_color(o->use_color);
1795 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1796 ecbdata.opt = o;
1797 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1798 mmfile_t mf1, mf2;
1799 mf1.ptr = (char *)data_one;
1800 mf2.ptr = (char *)data_two;
1801 mf1.size = size_one;
1802 mf2.size = size_two;
1803 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1805 ecbdata.lno_in_preimage = 1;
1806 ecbdata.lno_in_postimage = 1;
1808 lc_a = count_lines(data_one, size_one);
1809 lc_b = count_lines(data_two, size_two);
1811 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1812 a_name.buf, a_name.len, 0);
1813 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1814 b_name.buf, b_name.len, 0);
1816 strbuf_addstr(&out, "@@ -");
1817 if (!o->irreversible_delete)
1818 add_line_count(&out, lc_a);
1819 else
1820 strbuf_addstr(&out, "?,?");
1821 strbuf_addstr(&out, " +");
1822 add_line_count(&out, lc_b);
1823 strbuf_addstr(&out, " @@\n");
1824 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1825 strbuf_release(&out);
1827 if (lc_a && !o->irreversible_delete)
1828 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1829 if (lc_b)
1830 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1831 if (textconv_one)
1832 free((char *)data_one);
1833 if (textconv_two)
1834 free((char *)data_two);
1837 struct diff_words_buffer {
1838 mmfile_t text;
1839 unsigned long alloc;
1840 struct diff_words_orig {
1841 const char *begin, *end;
1842 } *orig;
1843 int orig_nr, orig_alloc;
1846 static void diff_words_append(char *line, unsigned long len,
1847 struct diff_words_buffer *buffer)
1849 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1850 line++;
1851 len--;
1852 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1853 buffer->text.size += len;
1854 buffer->text.ptr[buffer->text.size] = '\0';
1857 struct diff_words_style_elem {
1858 const char *prefix;
1859 const char *suffix;
1860 const char *color; /* NULL; filled in by the setup code if
1861 * color is enabled */
1864 struct diff_words_style {
1865 enum diff_words_type type;
1866 struct diff_words_style_elem new_word, old_word, ctx;
1867 const char *newline;
1870 static struct diff_words_style diff_words_styles[] = {
1871 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1872 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1873 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1876 struct diff_words_data {
1877 struct diff_words_buffer minus, plus;
1878 const char *current_plus;
1879 int last_minus;
1880 struct diff_options *opt;
1881 regex_t *word_regex;
1882 enum diff_words_type type;
1883 struct diff_words_style *style;
1886 static int fn_out_diff_words_write_helper(struct diff_options *o,
1887 struct diff_words_style_elem *st_el,
1888 const char *newline,
1889 size_t count, const char *buf)
1891 int print = 0;
1892 struct strbuf sb = STRBUF_INIT;
1894 while (count) {
1895 char *p = memchr(buf, '\n', count);
1896 if (print)
1897 strbuf_addstr(&sb, diff_line_prefix(o));
1899 if (p != buf) {
1900 const char *reset = st_el->color && *st_el->color ?
1901 GIT_COLOR_RESET : NULL;
1902 if (st_el->color && *st_el->color)
1903 strbuf_addstr(&sb, st_el->color);
1904 strbuf_addstr(&sb, st_el->prefix);
1905 strbuf_add(&sb, buf, p ? p - buf : count);
1906 strbuf_addstr(&sb, st_el->suffix);
1907 if (reset)
1908 strbuf_addstr(&sb, reset);
1910 if (!p)
1911 goto out;
1913 strbuf_addstr(&sb, newline);
1914 count -= p + 1 - buf;
1915 buf = p + 1;
1916 print = 1;
1917 if (count) {
1918 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1919 sb.buf, sb.len, 0);
1920 strbuf_reset(&sb);
1924 out:
1925 if (sb.len)
1926 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1927 sb.buf, sb.len, 0);
1928 strbuf_release(&sb);
1929 return 0;
1933 * '--color-words' algorithm can be described as:
1935 * 1. collect the minus/plus lines of a diff hunk, divided into
1936 * minus-lines and plus-lines;
1938 * 2. break both minus-lines and plus-lines into words and
1939 * place them into two mmfile_t with one word for each line;
1941 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1943 * And for the common parts of the both file, we output the plus side text.
1944 * diff_words->current_plus is used to trace the current position of the plus file
1945 * which printed. diff_words->last_minus is used to trace the last minus word
1946 * printed.
1948 * For '--graph' to work with '--color-words', we need to output the graph prefix
1949 * on each line of color words output. Generally, there are two conditions on
1950 * which we should output the prefix.
1952 * 1. diff_words->last_minus == 0 &&
1953 * diff_words->current_plus == diff_words->plus.text.ptr
1955 * that is: the plus text must start as a new line, and if there is no minus
1956 * word printed, a graph prefix must be printed.
1958 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1959 * *(diff_words->current_plus - 1) == '\n'
1961 * that is: a graph prefix must be printed following a '\n'
1963 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1965 if ((diff_words->last_minus == 0 &&
1966 diff_words->current_plus == diff_words->plus.text.ptr) ||
1967 (diff_words->current_plus > diff_words->plus.text.ptr &&
1968 *(diff_words->current_plus - 1) == '\n')) {
1969 return 1;
1970 } else {
1971 return 0;
1975 static void fn_out_diff_words_aux(void *priv,
1976 long minus_first, long minus_len,
1977 long plus_first, long plus_len,
1978 const char *func UNUSED, long funclen UNUSED)
1980 struct diff_words_data *diff_words = priv;
1981 struct diff_words_style *style = diff_words->style;
1982 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1983 struct diff_options *opt = diff_words->opt;
1984 const char *line_prefix;
1986 assert(opt);
1987 line_prefix = diff_line_prefix(opt);
1989 /* POSIX requires that first be decremented by one if len == 0... */
1990 if (minus_len) {
1991 minus_begin = diff_words->minus.orig[minus_first].begin;
1992 minus_end =
1993 diff_words->minus.orig[minus_first + minus_len - 1].end;
1994 } else
1995 minus_begin = minus_end =
1996 diff_words->minus.orig[minus_first].end;
1998 if (plus_len) {
1999 plus_begin = diff_words->plus.orig[plus_first].begin;
2000 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2001 } else
2002 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2004 if (color_words_output_graph_prefix(diff_words)) {
2005 fputs(line_prefix, diff_words->opt->file);
2007 if (diff_words->current_plus != plus_begin) {
2008 fn_out_diff_words_write_helper(diff_words->opt,
2009 &style->ctx, style->newline,
2010 plus_begin - diff_words->current_plus,
2011 diff_words->current_plus);
2013 if (minus_begin != minus_end) {
2014 fn_out_diff_words_write_helper(diff_words->opt,
2015 &style->old_word, style->newline,
2016 minus_end - minus_begin, minus_begin);
2018 if (plus_begin != plus_end) {
2019 fn_out_diff_words_write_helper(diff_words->opt,
2020 &style->new_word, style->newline,
2021 plus_end - plus_begin, plus_begin);
2024 diff_words->current_plus = plus_end;
2025 diff_words->last_minus = minus_first;
2028 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2029 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2030 int *begin, int *end)
2032 while (word_regex && *begin < buffer->size) {
2033 regmatch_t match[1];
2034 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2035 buffer->size - *begin, 1, match, 0)) {
2036 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2037 '\n', match[0].rm_eo - match[0].rm_so);
2038 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2039 *begin += match[0].rm_so;
2040 if (*begin == *end)
2041 (*begin)++;
2042 else
2043 return *begin > *end;
2044 } else {
2045 return -1;
2049 /* find the next word */
2050 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2051 (*begin)++;
2052 if (*begin >= buffer->size)
2053 return -1;
2055 /* find the end of the word */
2056 *end = *begin + 1;
2057 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2058 (*end)++;
2060 return 0;
2064 * This function splits the words in buffer->text, stores the list with
2065 * newline separator into out, and saves the offsets of the original words
2066 * in buffer->orig.
2068 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2069 regex_t *word_regex)
2071 int i, j;
2072 long alloc = 0;
2074 out->size = 0;
2075 out->ptr = NULL;
2077 /* fake an empty "0th" word */
2078 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2079 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2080 buffer->orig_nr = 1;
2082 for (i = 0; i < buffer->text.size; i++) {
2083 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2084 return;
2086 /* store original boundaries */
2087 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2088 buffer->orig_alloc);
2089 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2090 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2091 buffer->orig_nr++;
2093 /* store one word */
2094 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2095 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2096 out->ptr[out->size + j - i] = '\n';
2097 out->size += j - i + 1;
2099 i = j - 1;
2103 /* this executes the word diff on the accumulated buffers */
2104 static void diff_words_show(struct diff_words_data *diff_words)
2106 xpparam_t xpp;
2107 xdemitconf_t xecfg;
2108 mmfile_t minus, plus;
2109 struct diff_words_style *style = diff_words->style;
2111 struct diff_options *opt = diff_words->opt;
2112 const char *line_prefix;
2114 assert(opt);
2115 line_prefix = diff_line_prefix(opt);
2117 /* special case: only removal */
2118 if (!diff_words->plus.text.size) {
2119 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2120 line_prefix, strlen(line_prefix), 0);
2121 fn_out_diff_words_write_helper(diff_words->opt,
2122 &style->old_word, style->newline,
2123 diff_words->minus.text.size,
2124 diff_words->minus.text.ptr);
2125 diff_words->minus.text.size = 0;
2126 return;
2129 diff_words->current_plus = diff_words->plus.text.ptr;
2130 diff_words->last_minus = 0;
2132 memset(&xpp, 0, sizeof(xpp));
2133 memset(&xecfg, 0, sizeof(xecfg));
2134 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2135 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2136 xpp.flags = 0;
2137 /* as only the hunk header will be parsed, we need a 0-context */
2138 xecfg.ctxlen = 0;
2139 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2140 diff_words, &xpp, &xecfg))
2141 die("unable to generate word diff");
2142 free(minus.ptr);
2143 free(plus.ptr);
2144 if (diff_words->current_plus != diff_words->plus.text.ptr +
2145 diff_words->plus.text.size) {
2146 if (color_words_output_graph_prefix(diff_words))
2147 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2148 line_prefix, strlen(line_prefix), 0);
2149 fn_out_diff_words_write_helper(diff_words->opt,
2150 &style->ctx, style->newline,
2151 diff_words->plus.text.ptr + diff_words->plus.text.size
2152 - diff_words->current_plus, diff_words->current_plus);
2154 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2157 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2158 static void diff_words_flush(struct emit_callback *ecbdata)
2160 struct diff_options *wo = ecbdata->diff_words->opt;
2162 if (ecbdata->diff_words->minus.text.size ||
2163 ecbdata->diff_words->plus.text.size)
2164 diff_words_show(ecbdata->diff_words);
2166 if (wo->emitted_symbols) {
2167 struct diff_options *o = ecbdata->opt;
2168 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2169 int i;
2172 * NEEDSWORK:
2173 * Instead of appending each, concat all words to a line?
2175 for (i = 0; i < wol->nr; i++)
2176 append_emitted_diff_symbol(o, &wol->buf[i]);
2178 for (i = 0; i < wol->nr; i++)
2179 free((void *)wol->buf[i].line);
2181 wol->nr = 0;
2185 static void diff_filespec_load_driver(struct diff_filespec *one,
2186 struct index_state *istate)
2188 /* Use already-loaded driver */
2189 if (one->driver)
2190 return;
2192 if (S_ISREG(one->mode))
2193 one->driver = userdiff_find_by_path(istate, one->path);
2195 /* Fallback to default settings */
2196 if (!one->driver)
2197 one->driver = userdiff_find_by_name("default");
2200 static const char *userdiff_word_regex(struct diff_filespec *one,
2201 struct index_state *istate)
2203 diff_filespec_load_driver(one, istate);
2204 return one->driver->word_regex;
2207 static void init_diff_words_data(struct emit_callback *ecbdata,
2208 struct diff_options *orig_opts,
2209 struct diff_filespec *one,
2210 struct diff_filespec *two)
2212 int i;
2213 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2214 memcpy(o, orig_opts, sizeof(struct diff_options));
2216 CALLOC_ARRAY(ecbdata->diff_words, 1);
2217 ecbdata->diff_words->type = o->word_diff;
2218 ecbdata->diff_words->opt = o;
2220 if (orig_opts->emitted_symbols)
2221 CALLOC_ARRAY(o->emitted_symbols, 1);
2223 if (!o->word_regex)
2224 o->word_regex = userdiff_word_regex(one, o->repo->index);
2225 if (!o->word_regex)
2226 o->word_regex = userdiff_word_regex(two, o->repo->index);
2227 if (!o->word_regex)
2228 o->word_regex = diff_word_regex_cfg;
2229 if (o->word_regex) {
2230 ecbdata->diff_words->word_regex = (regex_t *)
2231 xmalloc(sizeof(regex_t));
2232 if (regcomp(ecbdata->diff_words->word_regex,
2233 o->word_regex,
2234 REG_EXTENDED | REG_NEWLINE))
2235 die("invalid regular expression: %s",
2236 o->word_regex);
2238 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2239 if (o->word_diff == diff_words_styles[i].type) {
2240 ecbdata->diff_words->style =
2241 &diff_words_styles[i];
2242 break;
2245 if (want_color(o->use_color)) {
2246 struct diff_words_style *st = ecbdata->diff_words->style;
2247 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2248 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2249 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2253 static void free_diff_words_data(struct emit_callback *ecbdata)
2255 if (ecbdata->diff_words) {
2256 diff_words_flush(ecbdata);
2257 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2258 free (ecbdata->diff_words->opt);
2259 free (ecbdata->diff_words->minus.text.ptr);
2260 free (ecbdata->diff_words->minus.orig);
2261 free (ecbdata->diff_words->plus.text.ptr);
2262 free (ecbdata->diff_words->plus.orig);
2263 if (ecbdata->diff_words->word_regex) {
2264 regfree(ecbdata->diff_words->word_regex);
2265 free(ecbdata->diff_words->word_regex);
2267 FREE_AND_NULL(ecbdata->diff_words);
2271 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2273 if (want_color(diff_use_color))
2274 return diff_colors[ix];
2275 return "";
2278 const char *diff_line_prefix(struct diff_options *opt)
2280 struct strbuf *msgbuf;
2281 if (!opt->output_prefix)
2282 return "";
2284 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2285 return msgbuf->buf;
2288 static unsigned long sane_truncate_line(char *line, unsigned long len)
2290 const char *cp;
2291 unsigned long allot;
2292 size_t l = len;
2294 cp = line;
2295 allot = l;
2296 while (0 < l) {
2297 (void) utf8_width(&cp, &l);
2298 if (!cp)
2299 break; /* truncated in the middle? */
2301 return allot - l;
2304 static void find_lno(const char *line, struct emit_callback *ecbdata)
2306 const char *p;
2307 ecbdata->lno_in_preimage = 0;
2308 ecbdata->lno_in_postimage = 0;
2309 p = strchr(line, '-');
2310 if (!p)
2311 return; /* cannot happen */
2312 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2313 p = strchr(p, '+');
2314 if (!p)
2315 return; /* cannot happen */
2316 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2319 static int fn_out_consume(void *priv, char *line, unsigned long len)
2321 struct emit_callback *ecbdata = priv;
2322 struct diff_options *o = ecbdata->opt;
2324 o->found_changes = 1;
2326 if (ecbdata->header) {
2327 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2328 ecbdata->header->buf, ecbdata->header->len, 0);
2329 strbuf_reset(ecbdata->header);
2330 ecbdata->header = NULL;
2333 if (ecbdata->label_path[0]) {
2334 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2335 ecbdata->label_path[0],
2336 strlen(ecbdata->label_path[0]), 0);
2337 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2338 ecbdata->label_path[1],
2339 strlen(ecbdata->label_path[1]), 0);
2340 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2343 if (diff_suppress_blank_empty
2344 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2345 line[0] = '\n';
2346 len = 1;
2349 if (line[0] == '@') {
2350 if (ecbdata->diff_words)
2351 diff_words_flush(ecbdata);
2352 len = sane_truncate_line(line, len);
2353 find_lno(line, ecbdata);
2354 emit_hunk_header(ecbdata, line, len);
2355 return 0;
2358 if (ecbdata->diff_words) {
2359 enum diff_symbol s =
2360 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2361 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2362 if (line[0] == '-') {
2363 diff_words_append(line, len,
2364 &ecbdata->diff_words->minus);
2365 return 0;
2366 } else if (line[0] == '+') {
2367 diff_words_append(line, len,
2368 &ecbdata->diff_words->plus);
2369 return 0;
2370 } else if (starts_with(line, "\\ ")) {
2372 * Eat the "no newline at eof" marker as if we
2373 * saw a "+" or "-" line with nothing on it,
2374 * and return without diff_words_flush() to
2375 * defer processing. If this is the end of
2376 * preimage, more "+" lines may come after it.
2378 return 0;
2380 diff_words_flush(ecbdata);
2381 emit_diff_symbol(o, s, line, len, 0);
2382 return 0;
2385 switch (line[0]) {
2386 case '+':
2387 ecbdata->lno_in_postimage++;
2388 emit_add_line(ecbdata, line + 1, len - 1);
2389 break;
2390 case '-':
2391 ecbdata->lno_in_preimage++;
2392 emit_del_line(ecbdata, line + 1, len - 1);
2393 break;
2394 case ' ':
2395 ecbdata->lno_in_postimage++;
2396 ecbdata->lno_in_preimage++;
2397 emit_context_line(ecbdata, line + 1, len - 1);
2398 break;
2399 default:
2400 /* incomplete line at the end */
2401 ecbdata->lno_in_preimage++;
2402 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2403 line, len, 0);
2404 break;
2406 return 0;
2409 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2411 const char *old_name = a;
2412 const char *new_name = b;
2413 int pfx_length, sfx_length;
2414 int pfx_adjust_for_slash;
2415 int len_a = strlen(a);
2416 int len_b = strlen(b);
2417 int a_midlen, b_midlen;
2418 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2419 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2421 if (qlen_a || qlen_b) {
2422 quote_c_style(a, name, NULL, 0);
2423 strbuf_addstr(name, " => ");
2424 quote_c_style(b, name, NULL, 0);
2425 return;
2428 /* Find common prefix */
2429 pfx_length = 0;
2430 while (*old_name && *new_name && *old_name == *new_name) {
2431 if (*old_name == '/')
2432 pfx_length = old_name - a + 1;
2433 old_name++;
2434 new_name++;
2437 /* Find common suffix */
2438 old_name = a + len_a;
2439 new_name = b + len_b;
2440 sfx_length = 0;
2442 * If there is a common prefix, it must end in a slash. In
2443 * that case we let this loop run 1 into the prefix to see the
2444 * same slash.
2446 * If there is no common prefix, we cannot do this as it would
2447 * underrun the input strings.
2449 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2450 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2451 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2452 *old_name == *new_name) {
2453 if (*old_name == '/')
2454 sfx_length = len_a - (old_name - a);
2455 old_name--;
2456 new_name--;
2460 * pfx{mid-a => mid-b}sfx
2461 * {pfx-a => pfx-b}sfx
2462 * pfx{sfx-a => sfx-b}
2463 * name-a => name-b
2465 a_midlen = len_a - pfx_length - sfx_length;
2466 b_midlen = len_b - pfx_length - sfx_length;
2467 if (a_midlen < 0)
2468 a_midlen = 0;
2469 if (b_midlen < 0)
2470 b_midlen = 0;
2472 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2473 if (pfx_length + sfx_length) {
2474 strbuf_add(name, a, pfx_length);
2475 strbuf_addch(name, '{');
2477 strbuf_add(name, a + pfx_length, a_midlen);
2478 strbuf_addstr(name, " => ");
2479 strbuf_add(name, b + pfx_length, b_midlen);
2480 if (pfx_length + sfx_length) {
2481 strbuf_addch(name, '}');
2482 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2486 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2487 const char *name_a,
2488 const char *name_b)
2490 struct diffstat_file *x;
2491 CALLOC_ARRAY(x, 1);
2492 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2493 diffstat->files[diffstat->nr++] = x;
2494 if (name_b) {
2495 x->from_name = xstrdup(name_a);
2496 x->name = xstrdup(name_b);
2497 x->is_renamed = 1;
2499 else {
2500 x->from_name = NULL;
2501 x->name = xstrdup(name_a);
2503 return x;
2506 static int diffstat_consume(void *priv, char *line, unsigned long len)
2508 struct diffstat_t *diffstat = priv;
2509 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2511 if (!len)
2512 BUG("xdiff fed us an empty line");
2514 if (line[0] == '+')
2515 x->added++;
2516 else if (line[0] == '-')
2517 x->deleted++;
2518 return 0;
2521 const char mime_boundary_leader[] = "------------";
2523 static int scale_linear(int it, int width, int max_change)
2525 if (!it)
2526 return 0;
2528 * make sure that at least one '-' or '+' is printed if
2529 * there is any change to this path. The easiest way is to
2530 * scale linearly as if the allotted width is one column shorter
2531 * than it is, and then add 1 to the result.
2533 return 1 + (it * (width - 1) / max_change);
2536 static void show_graph(struct strbuf *out, char ch, int cnt,
2537 const char *set, const char *reset)
2539 if (cnt <= 0)
2540 return;
2541 strbuf_addstr(out, set);
2542 strbuf_addchars(out, ch, cnt);
2543 strbuf_addstr(out, reset);
2546 static void fill_print_name(struct diffstat_file *file)
2548 struct strbuf pname = STRBUF_INIT;
2550 if (file->print_name)
2551 return;
2553 if (file->is_renamed)
2554 pprint_rename(&pname, file->from_name, file->name);
2555 else
2556 quote_c_style(file->name, &pname, NULL, 0);
2558 if (file->comments)
2559 strbuf_addf(&pname, " (%s)", file->comments);
2561 file->print_name = strbuf_detach(&pname, NULL);
2564 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2565 int files, int insertions, int deletions)
2567 struct strbuf sb = STRBUF_INIT;
2569 if (!files) {
2570 assert(insertions == 0 && deletions == 0);
2571 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2572 NULL, 0, 0);
2573 return;
2576 strbuf_addf(&sb,
2577 (files == 1) ? " %d file changed" : " %d files changed",
2578 files);
2581 * For binary diff, the caller may want to print "x files
2582 * changed" with insertions == 0 && deletions == 0.
2584 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2585 * is probably less confusing (i.e skip over "2 files changed
2586 * but nothing about added/removed lines? Is this a bug in Git?").
2588 if (insertions || deletions == 0) {
2589 strbuf_addf(&sb,
2590 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2591 insertions);
2594 if (deletions || insertions == 0) {
2595 strbuf_addf(&sb,
2596 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2597 deletions);
2599 strbuf_addch(&sb, '\n');
2600 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2601 sb.buf, sb.len, 0);
2602 strbuf_release(&sb);
2605 void print_stat_summary(FILE *fp, int files,
2606 int insertions, int deletions)
2608 struct diff_options o;
2609 memset(&o, 0, sizeof(o));
2610 o.file = fp;
2612 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2615 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2617 int i, len, add, del, adds = 0, dels = 0;
2618 uintmax_t max_change = 0, max_len = 0;
2619 int total_files = data->nr, count;
2620 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2621 const char *reset, *add_c, *del_c;
2622 int extra_shown = 0;
2623 const char *line_prefix = diff_line_prefix(options);
2624 struct strbuf out = STRBUF_INIT;
2626 if (data->nr == 0)
2627 return;
2629 count = options->stat_count ? options->stat_count : data->nr;
2631 reset = diff_get_color_opt(options, DIFF_RESET);
2632 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2633 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2636 * Find the longest filename and max number of changes
2638 for (i = 0; (i < count) && (i < data->nr); i++) {
2639 struct diffstat_file *file = data->files[i];
2640 uintmax_t change = file->added + file->deleted;
2642 if (!file->is_interesting && (change == 0)) {
2643 count++; /* not shown == room for one more */
2644 continue;
2646 fill_print_name(file);
2647 len = utf8_strwidth(file->print_name);
2648 if (max_len < len)
2649 max_len = len;
2651 if (file->is_unmerged) {
2652 /* "Unmerged" is 8 characters */
2653 bin_width = bin_width < 8 ? 8 : bin_width;
2654 continue;
2656 if (file->is_binary) {
2657 /* "Bin XXX -> YYY bytes" */
2658 int w = 14 + decimal_width(file->added)
2659 + decimal_width(file->deleted);
2660 bin_width = bin_width < w ? w : bin_width;
2661 /* Display change counts aligned with "Bin" */
2662 number_width = 3;
2663 continue;
2666 if (max_change < change)
2667 max_change = change;
2669 count = i; /* where we can stop scanning in data->files[] */
2672 * We have width = stat_width or term_columns() columns total.
2673 * We want a maximum of min(max_len, stat_name_width) for the name part.
2674 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2675 * We also need 1 for " " and 4 + decimal_width(max_change)
2676 * for " | NNNN " and one the empty column at the end, altogether
2677 * 6 + decimal_width(max_change).
2679 * If there's not enough space, we will use the smaller of
2680 * stat_name_width (if set) and 5/8*width for the filename,
2681 * and the rest for constant elements + graph part, but no more
2682 * than stat_graph_width for the graph part.
2683 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2684 * for the standard terminal size).
2686 * In other words: stat_width limits the maximum width, and
2687 * stat_name_width fixes the maximum width of the filename,
2688 * and is also used to divide available columns if there
2689 * aren't enough.
2691 * Binary files are displayed with "Bin XXX -> YYY bytes"
2692 * instead of the change count and graph. This part is treated
2693 * similarly to the graph part, except that it is not
2694 * "scaled". If total width is too small to accommodate the
2695 * guaranteed minimum width of the filename part and the
2696 * separators and this message, this message will "overflow"
2697 * making the line longer than the maximum width.
2701 * NEEDSWORK: line_prefix is often used for "log --graph" output
2702 * and contains ANSI-colored string. utf8_strnwidth() should be
2703 * used to correctly count the display width instead of strlen().
2705 if (options->stat_width == -1)
2706 width = term_columns() - strlen(line_prefix);
2707 else
2708 width = options->stat_width ? options->stat_width : 80;
2709 number_width = decimal_width(max_change) > number_width ?
2710 decimal_width(max_change) : number_width;
2712 if (options->stat_name_width == -1)
2713 options->stat_name_width = diff_stat_name_width;
2714 if (options->stat_graph_width == -1)
2715 options->stat_graph_width = diff_stat_graph_width;
2718 * Guarantee 3/8*16 == 6 for the graph part
2719 * and 5/8*16 == 10 for the filename part
2721 if (width < 16 + 6 + number_width)
2722 width = 16 + 6 + number_width;
2725 * First assign sizes that are wanted, ignoring available width.
2726 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2727 * starting from "XXX" should fit in graph_width.
2729 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2730 if (options->stat_graph_width &&
2731 options->stat_graph_width < graph_width)
2732 graph_width = options->stat_graph_width;
2734 name_width = (options->stat_name_width > 0 &&
2735 options->stat_name_width < max_len) ?
2736 options->stat_name_width : max_len;
2739 * Adjust adjustable widths not to exceed maximum width
2741 if (name_width + number_width + 6 + graph_width > width) {
2742 if (graph_width > width * 3/8 - number_width - 6) {
2743 graph_width = width * 3/8 - number_width - 6;
2744 if (graph_width < 6)
2745 graph_width = 6;
2748 if (options->stat_graph_width &&
2749 graph_width > options->stat_graph_width)
2750 graph_width = options->stat_graph_width;
2751 if (name_width > width - number_width - 6 - graph_width)
2752 name_width = width - number_width - 6 - graph_width;
2753 else
2754 graph_width = width - number_width - 6 - name_width;
2758 * From here name_width is the width of the name area,
2759 * and graph_width is the width of the graph area.
2760 * max_change is used to scale graph properly.
2762 for (i = 0; i < count; i++) {
2763 const char *prefix = "";
2764 struct diffstat_file *file = data->files[i];
2765 char *name = file->print_name;
2766 uintmax_t added = file->added;
2767 uintmax_t deleted = file->deleted;
2768 int name_len, padding;
2770 if (!file->is_interesting && (added + deleted == 0))
2771 continue;
2774 * "scale" the filename
2776 len = name_width;
2777 name_len = utf8_strwidth(name);
2778 if (name_width < name_len) {
2779 char *slash;
2780 prefix = "...";
2781 len -= 3;
2783 * NEEDSWORK: (name_len - len) counts the display
2784 * width, which would be shorter than the byte
2785 * length of the corresponding substring.
2786 * Advancing "name" by that number of bytes does
2787 * *NOT* skip over that many columns, so it is
2788 * very likely that chomping the pathname at the
2789 * slash we will find starting from "name" will
2790 * leave the resulting string still too long.
2792 name += name_len - len;
2793 slash = strchr(name, '/');
2794 if (slash)
2795 name = slash;
2797 padding = len - utf8_strwidth(name);
2798 if (padding < 0)
2799 padding = 0;
2801 if (file->is_binary) {
2802 strbuf_addf(&out, " %s%s%*s | %*s",
2803 prefix, name, padding, "",
2804 number_width, "Bin");
2805 if (!added && !deleted) {
2806 strbuf_addch(&out, '\n');
2807 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2808 out.buf, out.len, 0);
2809 strbuf_reset(&out);
2810 continue;
2812 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2813 del_c, deleted, reset);
2814 strbuf_addstr(&out, " -> ");
2815 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2816 add_c, added, reset);
2817 strbuf_addstr(&out, " bytes\n");
2818 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2819 out.buf, out.len, 0);
2820 strbuf_reset(&out);
2821 continue;
2823 else if (file->is_unmerged) {
2824 strbuf_addf(&out, " %s%s%*s | %*s",
2825 prefix, name, padding, "",
2826 number_width, "Unmerged\n");
2827 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2828 out.buf, out.len, 0);
2829 strbuf_reset(&out);
2830 continue;
2834 * scale the add/delete
2836 add = added;
2837 del = deleted;
2839 if (graph_width <= max_change) {
2840 int total = scale_linear(add + del, graph_width, max_change);
2841 if (total < 2 && add && del)
2842 /* width >= 2 due to the sanity check */
2843 total = 2;
2844 if (add < del) {
2845 add = scale_linear(add, graph_width, max_change);
2846 del = total - add;
2847 } else {
2848 del = scale_linear(del, graph_width, max_change);
2849 add = total - del;
2852 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2853 prefix, name, padding, "",
2854 number_width, added + deleted,
2855 added + deleted ? " " : "");
2856 show_graph(&out, '+', add, add_c, reset);
2857 show_graph(&out, '-', del, del_c, reset);
2858 strbuf_addch(&out, '\n');
2859 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2860 out.buf, out.len, 0);
2861 strbuf_reset(&out);
2864 for (i = 0; i < data->nr; i++) {
2865 struct diffstat_file *file = data->files[i];
2866 uintmax_t added = file->added;
2867 uintmax_t deleted = file->deleted;
2869 if (file->is_unmerged ||
2870 (!file->is_interesting && (added + deleted == 0))) {
2871 total_files--;
2872 continue;
2875 if (!file->is_binary) {
2876 adds += added;
2877 dels += deleted;
2879 if (i < count)
2880 continue;
2881 if (!extra_shown)
2882 emit_diff_symbol(options,
2883 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2884 NULL, 0, 0);
2885 extra_shown = 1;
2888 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2889 strbuf_release(&out);
2892 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2894 int i, adds = 0, dels = 0, total_files = data->nr;
2896 if (data->nr == 0)
2897 return;
2899 for (i = 0; i < data->nr; i++) {
2900 int added = data->files[i]->added;
2901 int deleted = data->files[i]->deleted;
2903 if (data->files[i]->is_unmerged ||
2904 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2905 total_files--;
2906 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2907 adds += added;
2908 dels += deleted;
2911 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2914 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2916 int i;
2918 if (data->nr == 0)
2919 return;
2921 for (i = 0; i < data->nr; i++) {
2922 struct diffstat_file *file = data->files[i];
2924 fprintf(options->file, "%s", diff_line_prefix(options));
2926 if (file->is_binary)
2927 fprintf(options->file, "-\t-\t");
2928 else
2929 fprintf(options->file,
2930 "%"PRIuMAX"\t%"PRIuMAX"\t",
2931 file->added, file->deleted);
2932 if (options->line_termination) {
2933 fill_print_name(file);
2934 if (!file->is_renamed)
2935 write_name_quoted(file->name, options->file,
2936 options->line_termination);
2937 else {
2938 fputs(file->print_name, options->file);
2939 putc(options->line_termination, options->file);
2941 } else {
2942 if (file->is_renamed) {
2943 putc('\0', options->file);
2944 write_name_quoted(file->from_name, options->file, '\0');
2946 write_name_quoted(file->name, options->file, '\0');
2951 struct dirstat_file {
2952 const char *name;
2953 unsigned long changed;
2956 struct dirstat_dir {
2957 struct dirstat_file *files;
2958 int alloc, nr, permille, cumulative;
2961 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2962 unsigned long changed, const char *base, int baselen)
2964 unsigned long sum_changes = 0;
2965 unsigned int sources = 0;
2966 const char *line_prefix = diff_line_prefix(opt);
2968 while (dir->nr) {
2969 struct dirstat_file *f = dir->files;
2970 int namelen = strlen(f->name);
2971 unsigned long changes;
2972 char *slash;
2974 if (namelen < baselen)
2975 break;
2976 if (memcmp(f->name, base, baselen))
2977 break;
2978 slash = strchr(f->name + baselen, '/');
2979 if (slash) {
2980 int newbaselen = slash + 1 - f->name;
2981 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2982 sources++;
2983 } else {
2984 changes = f->changed;
2985 dir->files++;
2986 dir->nr--;
2987 sources += 2;
2989 sum_changes += changes;
2993 * We don't report dirstat's for
2994 * - the top level
2995 * - or cases where everything came from a single directory
2996 * under this directory (sources == 1).
2998 if (baselen && sources != 1) {
2999 if (sum_changes) {
3000 int permille = sum_changes * 1000 / changed;
3001 if (permille >= dir->permille) {
3002 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3003 permille / 10, permille % 10, baselen, base);
3004 if (!dir->cumulative)
3005 return 0;
3009 return sum_changes;
3012 static int dirstat_compare(const void *_a, const void *_b)
3014 const struct dirstat_file *a = _a;
3015 const struct dirstat_file *b = _b;
3016 return strcmp(a->name, b->name);
3019 static void conclude_dirstat(struct diff_options *options,
3020 struct dirstat_dir *dir,
3021 unsigned long changed)
3023 struct dirstat_file *to_free = dir->files;
3025 if (!changed) {
3026 /* This can happen even with many files, if everything was renames */
3028 } else {
3029 /* Show all directories with more than x% of the changes */
3030 QSORT(dir->files, dir->nr, dirstat_compare);
3031 gather_dirstat(options, dir, changed, "", 0);
3034 free(to_free);
3037 static void show_dirstat(struct diff_options *options)
3039 int i;
3040 unsigned long changed;
3041 struct dirstat_dir dir;
3042 struct diff_queue_struct *q = &diff_queued_diff;
3044 dir.files = NULL;
3045 dir.alloc = 0;
3046 dir.nr = 0;
3047 dir.permille = options->dirstat_permille;
3048 dir.cumulative = options->flags.dirstat_cumulative;
3050 changed = 0;
3051 for (i = 0; i < q->nr; i++) {
3052 struct diff_filepair *p = q->queue[i];
3053 const char *name;
3054 unsigned long copied, added, damage;
3055 struct diff_populate_filespec_options dpf_options = {
3056 .check_size_only = 1,
3059 name = p->two->path ? p->two->path : p->one->path;
3061 if (p->one->oid_valid && p->two->oid_valid &&
3062 oideq(&p->one->oid, &p->two->oid)) {
3064 * The SHA1 has not changed, so pre-/post-content is
3065 * identical. We can therefore skip looking at the
3066 * file contents altogether.
3068 damage = 0;
3069 goto found_damage;
3072 if (options->flags.dirstat_by_file) {
3074 * In --dirstat-by-file mode, we don't really need to
3075 * look at the actual file contents at all.
3076 * The fact that the SHA1 changed is enough for us to
3077 * add this file to the list of results
3078 * (with each file contributing equal damage).
3080 damage = 1;
3081 goto found_damage;
3084 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3085 diff_populate_filespec(options->repo, p->one, NULL);
3086 diff_populate_filespec(options->repo, p->two, NULL);
3087 diffcore_count_changes(options->repo,
3088 p->one, p->two, NULL, NULL,
3089 &copied, &added);
3090 diff_free_filespec_data(p->one);
3091 diff_free_filespec_data(p->two);
3092 } else if (DIFF_FILE_VALID(p->one)) {
3093 diff_populate_filespec(options->repo, p->one, &dpf_options);
3094 copied = added = 0;
3095 diff_free_filespec_data(p->one);
3096 } else if (DIFF_FILE_VALID(p->two)) {
3097 diff_populate_filespec(options->repo, p->two, &dpf_options);
3098 copied = 0;
3099 added = p->two->size;
3100 diff_free_filespec_data(p->two);
3101 } else
3102 continue;
3105 * Original minus copied is the removed material,
3106 * added is the new material. They are both damages
3107 * made to the preimage.
3108 * If the resulting damage is zero, we know that
3109 * diffcore_count_changes() considers the two entries to
3110 * be identical, but since the oid changed, we
3111 * know that there must have been _some_ kind of change,
3112 * so we force all entries to have damage > 0.
3114 damage = (p->one->size - copied) + added;
3115 if (!damage)
3116 damage = 1;
3118 found_damage:
3119 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3120 dir.files[dir.nr].name = name;
3121 dir.files[dir.nr].changed = damage;
3122 changed += damage;
3123 dir.nr++;
3126 conclude_dirstat(options, &dir, changed);
3129 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3131 int i;
3132 unsigned long changed;
3133 struct dirstat_dir dir;
3135 if (data->nr == 0)
3136 return;
3138 dir.files = NULL;
3139 dir.alloc = 0;
3140 dir.nr = 0;
3141 dir.permille = options->dirstat_permille;
3142 dir.cumulative = options->flags.dirstat_cumulative;
3144 changed = 0;
3145 for (i = 0; i < data->nr; i++) {
3146 struct diffstat_file *file = data->files[i];
3147 unsigned long damage = file->added + file->deleted;
3148 if (file->is_binary)
3150 * binary files counts bytes, not lines. Must find some
3151 * way to normalize binary bytes vs. textual lines.
3152 * The following heuristic assumes that there are 64
3153 * bytes per "line".
3154 * This is stupid and ugly, but very cheap...
3156 damage = DIV_ROUND_UP(damage, 64);
3157 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3158 dir.files[dir.nr].name = file->name;
3159 dir.files[dir.nr].changed = damage;
3160 changed += damage;
3161 dir.nr++;
3164 conclude_dirstat(options, &dir, changed);
3167 static void free_diffstat_file(struct diffstat_file *f)
3169 free(f->print_name);
3170 free(f->name);
3171 free(f->from_name);
3172 free(f);
3175 void free_diffstat_info(struct diffstat_t *diffstat)
3177 int i;
3178 for (i = 0; i < diffstat->nr; i++)
3179 free_diffstat_file(diffstat->files[i]);
3180 free(diffstat->files);
3183 struct checkdiff_t {
3184 const char *filename;
3185 int lineno;
3186 int conflict_marker_size;
3187 struct diff_options *o;
3188 unsigned ws_rule;
3189 unsigned status;
3192 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3194 char firstchar;
3195 int cnt;
3197 if (len < marker_size + 1)
3198 return 0;
3199 firstchar = line[0];
3200 switch (firstchar) {
3201 case '=': case '>': case '<': case '|':
3202 break;
3203 default:
3204 return 0;
3206 for (cnt = 1; cnt < marker_size; cnt++)
3207 if (line[cnt] != firstchar)
3208 return 0;
3209 /* line[1] through line[marker_size-1] are same as firstchar */
3210 if (len < marker_size + 1 || !isspace(line[marker_size]))
3211 return 0;
3212 return 1;
3215 static void checkdiff_consume_hunk(void *priv,
3216 long ob UNUSED, long on UNUSED,
3217 long nb, long nn UNUSED,
3218 const char *func UNUSED, long funclen UNUSED)
3221 struct checkdiff_t *data = priv;
3222 data->lineno = nb - 1;
3225 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3227 struct checkdiff_t *data = priv;
3228 int marker_size = data->conflict_marker_size;
3229 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3230 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3231 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3232 char *err;
3233 const char *line_prefix;
3235 assert(data->o);
3236 line_prefix = diff_line_prefix(data->o);
3238 if (line[0] == '+') {
3239 unsigned bad;
3240 data->lineno++;
3241 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3242 data->status |= 1;
3243 fprintf(data->o->file,
3244 "%s%s:%d: leftover conflict marker\n",
3245 line_prefix, data->filename, data->lineno);
3247 bad = ws_check(line + 1, len - 1, data->ws_rule);
3248 if (!bad)
3249 return 0;
3250 data->status |= bad;
3251 err = whitespace_error_string(bad);
3252 fprintf(data->o->file, "%s%s:%d: %s.\n",
3253 line_prefix, data->filename, data->lineno, err);
3254 free(err);
3255 emit_line(data->o, set, reset, line, 1);
3256 ws_check_emit(line + 1, len - 1, data->ws_rule,
3257 data->o->file, set, reset, ws);
3258 } else if (line[0] == ' ') {
3259 data->lineno++;
3261 return 0;
3264 static unsigned char *deflate_it(char *data,
3265 unsigned long size,
3266 unsigned long *result_size)
3268 int bound;
3269 unsigned char *deflated;
3270 git_zstream stream;
3272 git_deflate_init(&stream, zlib_compression_level);
3273 bound = git_deflate_bound(&stream, size);
3274 deflated = xmalloc(bound);
3275 stream.next_out = deflated;
3276 stream.avail_out = bound;
3278 stream.next_in = (unsigned char *)data;
3279 stream.avail_in = size;
3280 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3281 ; /* nothing */
3282 git_deflate_end(&stream);
3283 *result_size = stream.total_out;
3284 return deflated;
3287 static void emit_binary_diff_body(struct diff_options *o,
3288 mmfile_t *one, mmfile_t *two)
3290 void *cp;
3291 void *delta;
3292 void *deflated;
3293 void *data;
3294 unsigned long orig_size;
3295 unsigned long delta_size;
3296 unsigned long deflate_size;
3297 unsigned long data_size;
3299 /* We could do deflated delta, or we could do just deflated two,
3300 * whichever is smaller.
3302 delta = NULL;
3303 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3304 if (one->size && two->size) {
3305 delta = diff_delta(one->ptr, one->size,
3306 two->ptr, two->size,
3307 &delta_size, deflate_size);
3308 if (delta) {
3309 void *to_free = delta;
3310 orig_size = delta_size;
3311 delta = deflate_it(delta, delta_size, &delta_size);
3312 free(to_free);
3316 if (delta && delta_size < deflate_size) {
3317 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3318 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3319 s, strlen(s), 0);
3320 free(s);
3321 free(deflated);
3322 data = delta;
3323 data_size = delta_size;
3324 } else {
3325 char *s = xstrfmt("%lu", two->size);
3326 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3327 s, strlen(s), 0);
3328 free(s);
3329 free(delta);
3330 data = deflated;
3331 data_size = deflate_size;
3334 /* emit data encoded in base85 */
3335 cp = data;
3336 while (data_size) {
3337 int len;
3338 int bytes = (52 < data_size) ? 52 : data_size;
3339 char line[71];
3340 data_size -= bytes;
3341 if (bytes <= 26)
3342 line[0] = bytes + 'A' - 1;
3343 else
3344 line[0] = bytes - 26 + 'a' - 1;
3345 encode_85(line + 1, cp, bytes);
3346 cp = (char *) cp + bytes;
3348 len = strlen(line);
3349 line[len++] = '\n';
3350 line[len] = '\0';
3352 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3353 line, len, 0);
3355 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3356 free(data);
3359 static void emit_binary_diff(struct diff_options *o,
3360 mmfile_t *one, mmfile_t *two)
3362 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3363 emit_binary_diff_body(o, one, two);
3364 emit_binary_diff_body(o, two, one);
3367 int diff_filespec_is_binary(struct repository *r,
3368 struct diff_filespec *one)
3370 struct diff_populate_filespec_options dpf_options = {
3371 .check_binary = 1,
3374 if (one->is_binary == -1) {
3375 diff_filespec_load_driver(one, r->index);
3376 if (one->driver->binary != -1)
3377 one->is_binary = one->driver->binary;
3378 else {
3379 if (!one->data && DIFF_FILE_VALID(one))
3380 diff_populate_filespec(r, one, &dpf_options);
3381 if (one->is_binary == -1 && one->data)
3382 one->is_binary = buffer_is_binary(one->data,
3383 one->size);
3384 if (one->is_binary == -1)
3385 one->is_binary = 0;
3388 return one->is_binary;
3391 static const struct userdiff_funcname *
3392 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3394 diff_filespec_load_driver(one, o->repo->index);
3395 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3398 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3400 if (!options->a_prefix)
3401 options->a_prefix = a;
3402 if (!options->b_prefix)
3403 options->b_prefix = b;
3406 void diff_set_noprefix(struct diff_options *options)
3408 options->a_prefix = options->b_prefix = "";
3411 void diff_set_default_prefix(struct diff_options *options)
3413 options->a_prefix = "a/";
3414 options->b_prefix = "b/";
3417 struct userdiff_driver *get_textconv(struct repository *r,
3418 struct diff_filespec *one)
3420 if (!DIFF_FILE_VALID(one))
3421 return NULL;
3423 diff_filespec_load_driver(one, r->index);
3424 return userdiff_get_textconv(r, one->driver);
3427 static struct string_list *additional_headers(struct diff_options *o,
3428 const char *path)
3430 if (!o->additional_path_headers)
3431 return NULL;
3432 return strmap_get(o->additional_path_headers, path);
3435 static void add_formatted_header(struct strbuf *msg,
3436 const char *header,
3437 const char *line_prefix,
3438 const char *meta,
3439 const char *reset)
3441 const char *next, *newline;
3443 for (next = header; *next; next = newline) {
3444 newline = strchrnul(next, '\n');
3445 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3446 (int)(newline - next), next, reset);
3447 if (*newline)
3448 newline++;
3452 static void add_formatted_headers(struct strbuf *msg,
3453 struct string_list *more_headers,
3454 const char *line_prefix,
3455 const char *meta,
3456 const char *reset)
3458 int i;
3460 for (i = 0; i < more_headers->nr; i++)
3461 add_formatted_header(msg, more_headers->items[i].string,
3462 line_prefix, meta, reset);
3465 static int diff_filepair_is_phoney(struct diff_filespec *one,
3466 struct diff_filespec *two)
3469 * This function specifically looks for pairs injected by
3470 * create_filepairs_for_header_only_notifications(). Such
3471 * pairs are "phoney" in that they do not represent any
3472 * content or even mode difference, but were inserted because
3473 * diff_queued_diff previously had no pair associated with
3474 * that path but we needed some pair to avoid losing the
3475 * "remerge CONFLICT" header associated with the path.
3477 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3480 static int set_diff_algorithm(struct diff_options *opts,
3481 const char *alg)
3483 long value = parse_algorithm_value(alg);
3485 if (value < 0)
3486 return -1;
3488 /* clear out previous settings */
3489 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3490 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3491 opts->xdl_opts |= value;
3493 return 0;
3496 static void builtin_diff(const char *name_a,
3497 const char *name_b,
3498 struct diff_filespec *one,
3499 struct diff_filespec *two,
3500 const char *xfrm_msg,
3501 int must_show_header,
3502 struct diff_options *o,
3503 int complete_rewrite)
3505 mmfile_t mf1, mf2;
3506 const char *lbl[2];
3507 char *a_one, *b_two;
3508 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3509 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3510 const char *a_prefix, *b_prefix;
3511 struct userdiff_driver *textconv_one = NULL;
3512 struct userdiff_driver *textconv_two = NULL;
3513 struct strbuf header = STRBUF_INIT;
3514 const char *line_prefix = diff_line_prefix(o);
3516 diff_set_mnemonic_prefix(o, "a/", "b/");
3517 if (o->flags.reverse_diff) {
3518 a_prefix = o->b_prefix;
3519 b_prefix = o->a_prefix;
3520 } else {
3521 a_prefix = o->a_prefix;
3522 b_prefix = o->b_prefix;
3525 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3526 (!one->mode || S_ISGITLINK(one->mode)) &&
3527 (!two->mode || S_ISGITLINK(two->mode)) &&
3528 (!diff_filepair_is_phoney(one, two))) {
3529 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3530 &one->oid, &two->oid,
3531 two->dirty_submodule);
3532 return;
3533 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3534 (!one->mode || S_ISGITLINK(one->mode)) &&
3535 (!two->mode || S_ISGITLINK(two->mode)) &&
3536 (!diff_filepair_is_phoney(one, two))) {
3537 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3538 &one->oid, &two->oid,
3539 two->dirty_submodule);
3540 return;
3543 if (o->flags.allow_textconv) {
3544 textconv_one = get_textconv(o->repo, one);
3545 textconv_two = get_textconv(o->repo, two);
3548 /* Never use a non-valid filename anywhere if at all possible */
3549 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3550 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3552 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3553 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3554 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3555 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3556 if (diff_filepair_is_phoney(one, two)) {
3558 * We should only reach this point for pairs generated from
3559 * create_filepairs_for_header_only_notifications(). For
3560 * these, we want to avoid the "/dev/null" special casing
3561 * above, because we do not want such pairs shown as either
3562 * "new file" or "deleted file" below.
3564 lbl[0] = a_one;
3565 lbl[1] = b_two;
3567 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3568 if (lbl[0][0] == '/') {
3569 /* /dev/null */
3570 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3571 if (xfrm_msg)
3572 strbuf_addstr(&header, xfrm_msg);
3573 o->found_changes = 1;
3574 must_show_header = 1;
3576 else if (lbl[1][0] == '/') {
3577 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3578 if (xfrm_msg)
3579 strbuf_addstr(&header, xfrm_msg);
3580 o->found_changes = 1;
3581 must_show_header = 1;
3583 else {
3584 if (one->mode != two->mode) {
3585 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3586 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3587 o->found_changes = 1;
3588 must_show_header = 1;
3590 if (xfrm_msg)
3591 strbuf_addstr(&header, xfrm_msg);
3594 * we do not run diff between different kind
3595 * of objects.
3597 if ((one->mode ^ two->mode) & S_IFMT)
3598 goto free_ab_and_return;
3599 if (complete_rewrite &&
3600 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3601 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3602 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3603 header.buf, header.len, 0);
3604 strbuf_reset(&header);
3605 emit_rewrite_diff(name_a, name_b, one, two,
3606 textconv_one, textconv_two, o);
3607 o->found_changes = 1;
3608 goto free_ab_and_return;
3612 if (o->irreversible_delete && lbl[1][0] == '/') {
3613 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3614 header.len, 0);
3615 strbuf_reset(&header);
3616 goto free_ab_and_return;
3617 } else if (!o->flags.text &&
3618 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3619 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3620 struct strbuf sb = STRBUF_INIT;
3621 if (!one->data && !two->data &&
3622 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3623 !o->flags.binary) {
3624 if (oideq(&one->oid, &two->oid)) {
3625 if (must_show_header)
3626 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3627 header.buf, header.len,
3629 goto free_ab_and_return;
3631 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3632 header.buf, header.len, 0);
3633 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3634 diff_line_prefix(o), lbl[0], lbl[1]);
3635 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3636 sb.buf, sb.len, 0);
3637 strbuf_release(&sb);
3638 goto free_ab_and_return;
3640 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3641 fill_mmfile(o->repo, &mf2, two) < 0)
3642 die("unable to read files to diff");
3643 /* Quite common confusing case */
3644 if (mf1.size == mf2.size &&
3645 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3646 if (must_show_header)
3647 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3648 header.buf, header.len, 0);
3649 goto free_ab_and_return;
3651 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3652 strbuf_reset(&header);
3653 if (o->flags.binary)
3654 emit_binary_diff(o, &mf1, &mf2);
3655 else {
3656 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3657 diff_line_prefix(o), lbl[0], lbl[1]);
3658 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3659 sb.buf, sb.len, 0);
3660 strbuf_release(&sb);
3662 o->found_changes = 1;
3663 } else {
3664 /* Crazy xdl interfaces.. */
3665 const char *diffopts;
3666 const char *v;
3667 xpparam_t xpp;
3668 xdemitconf_t xecfg;
3669 struct emit_callback ecbdata;
3670 const struct userdiff_funcname *pe;
3672 if (must_show_header) {
3673 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3674 header.buf, header.len, 0);
3675 strbuf_reset(&header);
3678 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3679 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3681 pe = diff_funcname_pattern(o, one);
3682 if (!pe)
3683 pe = diff_funcname_pattern(o, two);
3685 memset(&xpp, 0, sizeof(xpp));
3686 memset(&xecfg, 0, sizeof(xecfg));
3687 memset(&ecbdata, 0, sizeof(ecbdata));
3688 if (o->flags.suppress_diff_headers)
3689 lbl[0] = NULL;
3690 ecbdata.label_path = lbl;
3691 ecbdata.color_diff = want_color(o->use_color);
3692 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3693 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3694 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3695 ecbdata.opt = o;
3696 if (header.len && !o->flags.suppress_diff_headers)
3697 ecbdata.header = &header;
3698 xpp.flags = o->xdl_opts;
3699 xpp.ignore_regex = o->ignore_regex;
3700 xpp.ignore_regex_nr = o->ignore_regex_nr;
3701 xpp.anchors = o->anchors;
3702 xpp.anchors_nr = o->anchors_nr;
3703 xecfg.ctxlen = o->context;
3704 xecfg.interhunkctxlen = o->interhunkcontext;
3705 xecfg.flags = XDL_EMIT_FUNCNAMES;
3706 if (o->flags.funccontext)
3707 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3708 if (pe)
3709 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3711 diffopts = getenv("GIT_DIFF_OPTS");
3712 if (!diffopts)
3714 else if (skip_prefix(diffopts, "--unified=", &v))
3715 xecfg.ctxlen = strtoul(v, NULL, 10);
3716 else if (skip_prefix(diffopts, "-u", &v))
3717 xecfg.ctxlen = strtoul(v, NULL, 10);
3719 if (o->word_diff)
3720 init_diff_words_data(&ecbdata, o, one, two);
3721 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3722 &ecbdata, &xpp, &xecfg))
3723 die("unable to generate diff for %s", one->path);
3724 if (o->word_diff)
3725 free_diff_words_data(&ecbdata);
3726 if (textconv_one)
3727 free(mf1.ptr);
3728 if (textconv_two)
3729 free(mf2.ptr);
3730 xdiff_clear_find_func(&xecfg);
3733 free_ab_and_return:
3734 strbuf_release(&header);
3735 diff_free_filespec_data(one);
3736 diff_free_filespec_data(two);
3737 free(a_one);
3738 free(b_two);
3739 return;
3742 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3744 if (!is_renamed) {
3745 if (p->status == DIFF_STATUS_ADDED) {
3746 if (S_ISLNK(p->two->mode))
3747 return "new +l";
3748 else if ((p->two->mode & 0777) == 0755)
3749 return "new +x";
3750 else
3751 return "new";
3752 } else if (p->status == DIFF_STATUS_DELETED)
3753 return "gone";
3755 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3756 return "mode -l";
3757 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3758 return "mode +l";
3759 else if ((p->one->mode & 0777) == 0644 &&
3760 (p->two->mode & 0777) == 0755)
3761 return "mode +x";
3762 else if ((p->one->mode & 0777) == 0755 &&
3763 (p->two->mode & 0777) == 0644)
3764 return "mode -x";
3765 return NULL;
3768 static void builtin_diffstat(const char *name_a, const char *name_b,
3769 struct diff_filespec *one,
3770 struct diff_filespec *two,
3771 struct diffstat_t *diffstat,
3772 struct diff_options *o,
3773 struct diff_filepair *p)
3775 mmfile_t mf1, mf2;
3776 struct diffstat_file *data;
3777 int may_differ;
3778 int complete_rewrite = 0;
3780 if (!DIFF_PAIR_UNMERGED(p)) {
3781 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3782 complete_rewrite = 1;
3785 data = diffstat_add(diffstat, name_a, name_b);
3786 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3787 if (o->flags.stat_with_summary)
3788 data->comments = get_compact_summary(p, data->is_renamed);
3790 if (!one || !two) {
3791 data->is_unmerged = 1;
3792 return;
3795 /* saves some reads if true, not a guarantee of diff outcome */
3796 may_differ = !(one->oid_valid && two->oid_valid &&
3797 oideq(&one->oid, &two->oid));
3799 if (diff_filespec_is_binary(o->repo, one) ||
3800 diff_filespec_is_binary(o->repo, two)) {
3801 data->is_binary = 1;
3802 if (!may_differ) {
3803 data->added = 0;
3804 data->deleted = 0;
3805 } else {
3806 data->added = diff_filespec_size(o->repo, two);
3807 data->deleted = diff_filespec_size(o->repo, one);
3811 else if (complete_rewrite) {
3812 diff_populate_filespec(o->repo, one, NULL);
3813 diff_populate_filespec(o->repo, two, NULL);
3814 data->deleted = count_lines(one->data, one->size);
3815 data->added = count_lines(two->data, two->size);
3818 else if (may_differ) {
3819 /* Crazy xdl interfaces.. */
3820 xpparam_t xpp;
3821 xdemitconf_t xecfg;
3823 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3824 fill_mmfile(o->repo, &mf2, two) < 0)
3825 die("unable to read files to diff");
3827 memset(&xpp, 0, sizeof(xpp));
3828 memset(&xecfg, 0, sizeof(xecfg));
3829 xpp.flags = o->xdl_opts;
3830 xpp.ignore_regex = o->ignore_regex;
3831 xpp.ignore_regex_nr = o->ignore_regex_nr;
3832 xpp.anchors = o->anchors;
3833 xpp.anchors_nr = o->anchors_nr;
3834 xecfg.ctxlen = o->context;
3835 xecfg.interhunkctxlen = o->interhunkcontext;
3836 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3837 if (xdi_diff_outf(&mf1, &mf2, NULL,
3838 diffstat_consume, diffstat, &xpp, &xecfg))
3839 die("unable to generate diffstat for %s", one->path);
3841 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3842 struct diffstat_file *file =
3843 diffstat->files[diffstat->nr - 1];
3845 * Omit diffstats of modified files where nothing changed.
3846 * Even if may_differ, this might be the case due to
3847 * ignoring whitespace changes, etc.
3849 * But note that we special-case additions, deletions,
3850 * renames, and mode changes as adding an empty file,
3851 * for example is still of interest.
3853 if ((p->status == DIFF_STATUS_MODIFIED)
3854 && !file->added
3855 && !file->deleted
3856 && one->mode == two->mode) {
3857 free_diffstat_file(file);
3858 diffstat->nr--;
3863 diff_free_filespec_data(one);
3864 diff_free_filespec_data(two);
3867 static void builtin_checkdiff(const char *name_a, const char *name_b,
3868 const char *attr_path,
3869 struct diff_filespec *one,
3870 struct diff_filespec *two,
3871 struct diff_options *o)
3873 mmfile_t mf1, mf2;
3874 struct checkdiff_t data;
3876 if (!two)
3877 return;
3879 memset(&data, 0, sizeof(data));
3880 data.filename = name_b ? name_b : name_a;
3881 data.lineno = 0;
3882 data.o = o;
3883 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3884 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3886 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3887 fill_mmfile(o->repo, &mf2, two) < 0)
3888 die("unable to read files to diff");
3891 * All the other codepaths check both sides, but not checking
3892 * the "old" side here is deliberate. We are checking the newly
3893 * introduced changes, and as long as the "new" side is text, we
3894 * can and should check what it introduces.
3896 if (diff_filespec_is_binary(o->repo, two))
3897 goto free_and_return;
3898 else {
3899 /* Crazy xdl interfaces.. */
3900 xpparam_t xpp;
3901 xdemitconf_t xecfg;
3903 memset(&xpp, 0, sizeof(xpp));
3904 memset(&xecfg, 0, sizeof(xecfg));
3905 xecfg.ctxlen = 1; /* at least one context line */
3906 xpp.flags = 0;
3907 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3908 checkdiff_consume, &data,
3909 &xpp, &xecfg))
3910 die("unable to generate checkdiff for %s", one->path);
3912 if (data.ws_rule & WS_BLANK_AT_EOF) {
3913 struct emit_callback ecbdata;
3914 int blank_at_eof;
3916 ecbdata.ws_rule = data.ws_rule;
3917 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3918 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3920 if (blank_at_eof) {
3921 static char *err;
3922 if (!err)
3923 err = whitespace_error_string(WS_BLANK_AT_EOF);
3924 fprintf(o->file, "%s:%d: %s.\n",
3925 data.filename, blank_at_eof, err);
3926 data.status = 1; /* report errors */
3930 free_and_return:
3931 diff_free_filespec_data(one);
3932 diff_free_filespec_data(two);
3933 if (data.status)
3934 o->flags.check_failed = 1;
3937 struct diff_filespec *alloc_filespec(const char *path)
3939 struct diff_filespec *spec;
3941 FLEXPTR_ALLOC_STR(spec, path, path);
3942 spec->count = 1;
3943 spec->is_binary = -1;
3944 return spec;
3947 void free_filespec(struct diff_filespec *spec)
3949 if (!--spec->count) {
3950 diff_free_filespec_data(spec);
3951 free(spec);
3955 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3956 int oid_valid, unsigned short mode)
3958 if (mode) {
3959 spec->mode = canon_mode(mode);
3960 oidcpy(&spec->oid, oid);
3961 spec->oid_valid = oid_valid;
3966 * Given a name and sha1 pair, if the index tells us the file in
3967 * the work tree has that object contents, return true, so that
3968 * prepare_temp_file() does not have to inflate and extract.
3970 static int reuse_worktree_file(struct index_state *istate,
3971 const char *name,
3972 const struct object_id *oid,
3973 int want_file)
3975 const struct cache_entry *ce;
3976 struct stat st;
3977 int pos, len;
3980 * We do not read the cache ourselves here, because the
3981 * benchmark with my previous version that always reads cache
3982 * shows that it makes things worse for diff-tree comparing
3983 * two linux-2.6 kernel trees in an already checked out work
3984 * tree. This is because most diff-tree comparisons deal with
3985 * only a small number of files, while reading the cache is
3986 * expensive for a large project, and its cost outweighs the
3987 * savings we get by not inflating the object to a temporary
3988 * file. Practically, this code only helps when we are used
3989 * by diff-cache --cached, which does read the cache before
3990 * calling us.
3992 if (!istate->cache)
3993 return 0;
3995 /* We want to avoid the working directory if our caller
3996 * doesn't need the data in a normal file, this system
3997 * is rather slow with its stat/open/mmap/close syscalls,
3998 * and the object is contained in a pack file. The pack
3999 * is probably already open and will be faster to obtain
4000 * the data through than the working directory. Loose
4001 * objects however would tend to be slower as they need
4002 * to be individually opened and inflated.
4004 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
4005 return 0;
4008 * Similarly, if we'd have to convert the file contents anyway, that
4009 * makes the optimization not worthwhile.
4011 if (!want_file && would_convert_to_git(istate, name))
4012 return 0;
4015 * If this path does not match our sparse-checkout definition,
4016 * then the file will not be in the working directory.
4018 if (!path_in_sparse_checkout(name, istate))
4019 return 0;
4021 len = strlen(name);
4022 pos = index_name_pos(istate, name, len);
4023 if (pos < 0)
4024 return 0;
4025 ce = istate->cache[pos];
4028 * This is not the sha1 we are looking for, or
4029 * unreusable because it is not a regular file.
4031 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4032 return 0;
4035 * If ce is marked as "assume unchanged", there is no
4036 * guarantee that work tree matches what we are looking for.
4038 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4039 return 0;
4042 * If ce matches the file in the work tree, we can reuse it.
4044 if (ce_uptodate(ce) ||
4045 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4046 return 1;
4048 return 0;
4051 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4053 struct strbuf buf = STRBUF_INIT;
4054 char *dirty = "";
4056 /* Are we looking at the work tree? */
4057 if (s->dirty_submodule)
4058 dirty = "-dirty";
4060 strbuf_addf(&buf, "Subproject commit %s%s\n",
4061 oid_to_hex(&s->oid), dirty);
4062 s->size = buf.len;
4063 if (size_only) {
4064 s->data = NULL;
4065 strbuf_release(&buf);
4066 } else {
4067 s->data = strbuf_detach(&buf, NULL);
4068 s->should_free = 1;
4070 return 0;
4074 * While doing rename detection and pickaxe operation, we may need to
4075 * grab the data for the blob (or file) for our own in-core comparison.
4076 * diff_filespec has data and size fields for this purpose.
4078 int diff_populate_filespec(struct repository *r,
4079 struct diff_filespec *s,
4080 const struct diff_populate_filespec_options *options)
4082 int size_only = options ? options->check_size_only : 0;
4083 int check_binary = options ? options->check_binary : 0;
4084 int err = 0;
4085 int conv_flags = global_conv_flags_eol;
4087 * demote FAIL to WARN to allow inspecting the situation
4088 * instead of refusing.
4090 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4091 conv_flags = CONV_EOL_RNDTRP_WARN;
4093 if (!DIFF_FILE_VALID(s))
4094 die("internal error: asking to populate invalid file.");
4095 if (S_ISDIR(s->mode))
4096 return -1;
4098 if (s->data)
4099 return 0;
4101 if (size_only && 0 < s->size)
4102 return 0;
4104 if (S_ISGITLINK(s->mode))
4105 return diff_populate_gitlink(s, size_only);
4107 if (!s->oid_valid ||
4108 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4109 struct strbuf buf = STRBUF_INIT;
4110 struct stat st;
4111 int fd;
4113 if (lstat(s->path, &st) < 0) {
4114 err_empty:
4115 err = -1;
4116 empty:
4117 s->data = (char *)"";
4118 s->size = 0;
4119 return err;
4121 s->size = xsize_t(st.st_size);
4122 if (!s->size)
4123 goto empty;
4124 if (S_ISLNK(st.st_mode)) {
4125 struct strbuf sb = STRBUF_INIT;
4127 if (strbuf_readlink(&sb, s->path, s->size))
4128 goto err_empty;
4129 s->size = sb.len;
4130 s->data = strbuf_detach(&sb, NULL);
4131 s->should_free = 1;
4132 return 0;
4136 * Even if the caller would be happy with getting
4137 * only the size, we cannot return early at this
4138 * point if the path requires us to run the content
4139 * conversion.
4141 if (size_only && !would_convert_to_git(r->index, s->path))
4142 return 0;
4145 * Note: this check uses xsize_t(st.st_size) that may
4146 * not be the true size of the blob after it goes
4147 * through convert_to_git(). This may not strictly be
4148 * correct, but the whole point of big_file_threshold
4149 * and is_binary check being that we want to avoid
4150 * opening the file and inspecting the contents, this
4151 * is probably fine.
4153 if (check_binary &&
4154 s->size > big_file_threshold && s->is_binary == -1) {
4155 s->is_binary = 1;
4156 return 0;
4158 fd = open(s->path, O_RDONLY);
4159 if (fd < 0)
4160 goto err_empty;
4161 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4162 close(fd);
4163 s->should_munmap = 1;
4166 * Convert from working tree format to canonical git format
4168 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4169 size_t size = 0;
4170 munmap(s->data, s->size);
4171 s->should_munmap = 0;
4172 s->data = strbuf_detach(&buf, &size);
4173 s->size = size;
4174 s->should_free = 1;
4177 else {
4178 struct object_info info = {
4179 .sizep = &s->size
4182 if (!(size_only || check_binary))
4184 * Set contentp, since there is no chance that merely
4185 * the size is sufficient.
4187 info.contentp = &s->data;
4189 if (options && options->missing_object_cb) {
4190 if (!oid_object_info_extended(r, &s->oid, &info,
4191 OBJECT_INFO_LOOKUP_REPLACE |
4192 OBJECT_INFO_SKIP_FETCH_OBJECT))
4193 goto object_read;
4194 options->missing_object_cb(options->missing_object_data);
4196 if (oid_object_info_extended(r, &s->oid, &info,
4197 OBJECT_INFO_LOOKUP_REPLACE))
4198 die("unable to read %s", oid_to_hex(&s->oid));
4200 object_read:
4201 if (size_only || check_binary) {
4202 if (size_only)
4203 return 0;
4204 if (s->size > big_file_threshold && s->is_binary == -1) {
4205 s->is_binary = 1;
4206 return 0;
4209 if (!info.contentp) {
4210 info.contentp = &s->data;
4211 if (oid_object_info_extended(r, &s->oid, &info,
4212 OBJECT_INFO_LOOKUP_REPLACE))
4213 die("unable to read %s", oid_to_hex(&s->oid));
4215 s->should_free = 1;
4217 return 0;
4220 void diff_free_filespec_blob(struct diff_filespec *s)
4222 if (s->should_free)
4223 free(s->data);
4224 else if (s->should_munmap)
4225 munmap(s->data, s->size);
4227 if (s->should_free || s->should_munmap) {
4228 s->should_free = s->should_munmap = 0;
4229 s->data = NULL;
4233 void diff_free_filespec_data(struct diff_filespec *s)
4235 if (!s)
4236 return;
4238 diff_free_filespec_blob(s);
4239 FREE_AND_NULL(s->cnt_data);
4242 static void prep_temp_blob(struct index_state *istate,
4243 const char *path, struct diff_tempfile *temp,
4244 void *blob,
4245 unsigned long size,
4246 const struct object_id *oid,
4247 int mode)
4249 struct strbuf buf = STRBUF_INIT;
4250 char *path_dup = xstrdup(path);
4251 const char *base = basename(path_dup);
4252 struct checkout_metadata meta;
4254 init_checkout_metadata(&meta, NULL, NULL, oid);
4256 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4257 if (!temp->tempfile)
4258 die_errno("unable to create temp-file");
4259 if (convert_to_working_tree(istate, path,
4260 (const char *)blob, (size_t)size, &buf, &meta)) {
4261 blob = buf.buf;
4262 size = buf.len;
4264 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4265 close_tempfile_gently(temp->tempfile))
4266 die_errno("unable to write temp-file");
4267 temp->name = get_tempfile_path(temp->tempfile);
4268 oid_to_hex_r(temp->hex, oid);
4269 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4270 strbuf_release(&buf);
4271 free(path_dup);
4274 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4275 struct diff_filespec *one)
4277 struct diff_tempfile *temp = claim_diff_tempfile();
4279 if (!DIFF_FILE_VALID(one)) {
4280 not_a_valid_file:
4281 /* A '-' entry produces this for file-2, and
4282 * a '+' entry produces this for file-1.
4284 temp->name = "/dev/null";
4285 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4286 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4287 return temp;
4290 if (!S_ISGITLINK(one->mode) &&
4291 (!one->oid_valid ||
4292 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4293 struct stat st;
4294 if (lstat(one->path, &st) < 0) {
4295 if (errno == ENOENT)
4296 goto not_a_valid_file;
4297 die_errno("stat(%s)", one->path);
4299 if (S_ISLNK(st.st_mode)) {
4300 struct strbuf sb = STRBUF_INIT;
4301 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4302 die_errno("readlink(%s)", one->path);
4303 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4304 (one->oid_valid ?
4305 &one->oid : null_oid()),
4306 (one->oid_valid ?
4307 one->mode : S_IFLNK));
4308 strbuf_release(&sb);
4310 else {
4311 /* we can borrow from the file in the work tree */
4312 temp->name = one->path;
4313 if (!one->oid_valid)
4314 oid_to_hex_r(temp->hex, null_oid());
4315 else
4316 oid_to_hex_r(temp->hex, &one->oid);
4317 /* Even though we may sometimes borrow the
4318 * contents from the work tree, we always want
4319 * one->mode. mode is trustworthy even when
4320 * !(one->oid_valid), as long as
4321 * DIFF_FILE_VALID(one).
4323 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4325 return temp;
4327 else {
4328 if (diff_populate_filespec(r, one, NULL))
4329 die("cannot read data blob for %s", one->path);
4330 prep_temp_blob(r->index, one->path, temp,
4331 one->data, one->size,
4332 &one->oid, one->mode);
4334 return temp;
4337 static void add_external_diff_name(struct repository *r,
4338 struct strvec *argv,
4339 struct diff_filespec *df)
4341 struct diff_tempfile *temp = prepare_temp_file(r, df);
4342 strvec_push(argv, temp->name);
4343 strvec_push(argv, temp->hex);
4344 strvec_push(argv, temp->mode);
4347 /* An external diff command takes:
4349 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4350 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4353 static void run_external_diff(const char *pgm,
4354 const char *name,
4355 const char *other,
4356 struct diff_filespec *one,
4357 struct diff_filespec *two,
4358 const char *xfrm_msg,
4359 struct diff_options *o)
4361 struct child_process cmd = CHILD_PROCESS_INIT;
4362 struct diff_queue_struct *q = &diff_queued_diff;
4364 strvec_push(&cmd.args, pgm);
4365 strvec_push(&cmd.args, name);
4367 if (one && two) {
4368 add_external_diff_name(o->repo, &cmd.args, one);
4369 add_external_diff_name(o->repo, &cmd.args, two);
4370 if (other) {
4371 strvec_push(&cmd.args, other);
4372 strvec_push(&cmd.args, xfrm_msg);
4376 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4377 ++o->diff_path_counter);
4378 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4380 diff_free_filespec_data(one);
4381 diff_free_filespec_data(two);
4382 cmd.use_shell = 1;
4383 if (run_command(&cmd))
4384 die(_("external diff died, stopping at %s"), name);
4386 remove_tempfile();
4389 static int similarity_index(struct diff_filepair *p)
4391 return p->score * 100 / MAX_SCORE;
4394 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4396 if (startup_info->have_repository)
4397 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4398 else {
4399 char *hex = oid_to_hex(oid);
4400 if (abbrev < 0)
4401 abbrev = FALLBACK_DEFAULT_ABBREV;
4402 if (abbrev > the_hash_algo->hexsz)
4403 BUG("oid abbreviation out of range: %d", abbrev);
4404 if (abbrev)
4405 hex[abbrev] = '\0';
4406 return hex;
4410 static void fill_metainfo(struct strbuf *msg,
4411 const char *name,
4412 const char *other,
4413 struct diff_filespec *one,
4414 struct diff_filespec *two,
4415 struct diff_options *o,
4416 struct diff_filepair *p,
4417 int *must_show_header,
4418 int use_color)
4420 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4421 const char *reset = diff_get_color(use_color, DIFF_RESET);
4422 const char *line_prefix = diff_line_prefix(o);
4423 struct string_list *more_headers = NULL;
4425 *must_show_header = 1;
4426 strbuf_init(msg, PATH_MAX * 2 + 300);
4427 switch (p->status) {
4428 case DIFF_STATUS_COPIED:
4429 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4430 line_prefix, set, similarity_index(p));
4431 strbuf_addf(msg, "%s\n%s%scopy from ",
4432 reset, line_prefix, set);
4433 quote_c_style(name, msg, NULL, 0);
4434 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4435 quote_c_style(other, msg, NULL, 0);
4436 strbuf_addf(msg, "%s\n", reset);
4437 break;
4438 case DIFF_STATUS_RENAMED:
4439 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4440 line_prefix, set, similarity_index(p));
4441 strbuf_addf(msg, "%s\n%s%srename from ",
4442 reset, line_prefix, set);
4443 quote_c_style(name, msg, NULL, 0);
4444 strbuf_addf(msg, "%s\n%s%srename to ",
4445 reset, line_prefix, set);
4446 quote_c_style(other, msg, NULL, 0);
4447 strbuf_addf(msg, "%s\n", reset);
4448 break;
4449 case DIFF_STATUS_MODIFIED:
4450 if (p->score) {
4451 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4452 line_prefix,
4453 set, similarity_index(p), reset);
4454 break;
4456 /* fallthru */
4457 default:
4458 *must_show_header = 0;
4460 if ((more_headers = additional_headers(o, name))) {
4461 add_formatted_headers(msg, more_headers,
4462 line_prefix, set, reset);
4463 *must_show_header = 1;
4465 if (one && two && !oideq(&one->oid, &two->oid)) {
4466 const unsigned hexsz = the_hash_algo->hexsz;
4467 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4469 if (o->flags.full_index)
4470 abbrev = hexsz;
4472 if (o->flags.binary) {
4473 mmfile_t mf;
4474 if ((!fill_mmfile(o->repo, &mf, one) &&
4475 diff_filespec_is_binary(o->repo, one)) ||
4476 (!fill_mmfile(o->repo, &mf, two) &&
4477 diff_filespec_is_binary(o->repo, two)))
4478 abbrev = hexsz;
4480 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4481 diff_abbrev_oid(&one->oid, abbrev),
4482 diff_abbrev_oid(&two->oid, abbrev));
4483 if (one->mode == two->mode)
4484 strbuf_addf(msg, " %06o", one->mode);
4485 strbuf_addf(msg, "%s\n", reset);
4489 static void run_diff_cmd(const char *pgm,
4490 const char *name,
4491 const char *other,
4492 const char *attr_path,
4493 struct diff_filespec *one,
4494 struct diff_filespec *two,
4495 struct strbuf *msg,
4496 struct diff_options *o,
4497 struct diff_filepair *p)
4499 const char *xfrm_msg = NULL;
4500 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4501 int must_show_header = 0;
4502 struct userdiff_driver *drv = NULL;
4504 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4505 drv = userdiff_find_by_path(o->repo->index, attr_path);
4507 if (o->flags.allow_external && drv && drv->external)
4508 pgm = drv->external;
4510 if (msg) {
4512 * don't use colors when the header is intended for an
4513 * external diff driver
4515 fill_metainfo(msg, name, other, one, two, o, p,
4516 &must_show_header,
4517 want_color(o->use_color) && !pgm);
4518 xfrm_msg = msg->len ? msg->buf : NULL;
4521 if (pgm) {
4522 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4523 return;
4525 if (one && two) {
4526 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4527 set_diff_algorithm(o, drv->algorithm);
4529 builtin_diff(name, other ? other : name,
4530 one, two, xfrm_msg, must_show_header,
4531 o, complete_rewrite);
4532 } else {
4533 fprintf(o->file, "* Unmerged path %s\n", name);
4537 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4539 if (DIFF_FILE_VALID(one)) {
4540 if (!one->oid_valid) {
4541 struct stat st;
4542 if (one->is_stdin) {
4543 oidclr(&one->oid);
4544 return;
4546 if (lstat(one->path, &st) < 0)
4547 die_errno("stat '%s'", one->path);
4548 if (index_path(istate, &one->oid, one->path, &st, 0))
4549 die("cannot hash %s", one->path);
4552 else
4553 oidclr(&one->oid);
4556 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4558 /* Strip the prefix but do not molest /dev/null and absolute paths */
4559 if (*namep && !is_absolute_path(*namep)) {
4560 *namep += prefix_length;
4561 if (**namep == '/')
4562 ++*namep;
4564 if (*otherp && !is_absolute_path(*otherp)) {
4565 *otherp += prefix_length;
4566 if (**otherp == '/')
4567 ++*otherp;
4571 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4573 const char *pgm = external_diff();
4574 struct strbuf msg;
4575 struct diff_filespec *one = p->one;
4576 struct diff_filespec *two = p->two;
4577 const char *name;
4578 const char *other;
4579 const char *attr_path;
4581 name = one->path;
4582 other = (strcmp(name, two->path) ? two->path : NULL);
4583 attr_path = name;
4584 if (o->prefix_length)
4585 strip_prefix(o->prefix_length, &name, &other);
4587 if (!o->flags.allow_external)
4588 pgm = NULL;
4590 if (DIFF_PAIR_UNMERGED(p)) {
4591 run_diff_cmd(pgm, name, NULL, attr_path,
4592 NULL, NULL, NULL, o, p);
4593 return;
4596 diff_fill_oid_info(one, o->repo->index);
4597 diff_fill_oid_info(two, o->repo->index);
4599 if (!pgm &&
4600 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4601 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4603 * a filepair that changes between file and symlink
4604 * needs to be split into deletion and creation.
4606 struct diff_filespec *null = alloc_filespec(two->path);
4607 run_diff_cmd(NULL, name, other, attr_path,
4608 one, null, &msg,
4609 o, p);
4610 free(null);
4611 strbuf_release(&msg);
4613 null = alloc_filespec(one->path);
4614 run_diff_cmd(NULL, name, other, attr_path,
4615 null, two, &msg, o, p);
4616 free(null);
4618 else
4619 run_diff_cmd(pgm, name, other, attr_path,
4620 one, two, &msg, o, p);
4622 strbuf_release(&msg);
4625 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4626 struct diffstat_t *diffstat)
4628 const char *name;
4629 const char *other;
4631 if (!o->ignore_driver_algorithm) {
4632 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4633 p->one->path);
4635 if (drv && drv->algorithm)
4636 set_diff_algorithm(o, drv->algorithm);
4639 if (DIFF_PAIR_UNMERGED(p)) {
4640 /* unmerged */
4641 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4642 diffstat, o, p);
4643 return;
4646 name = p->one->path;
4647 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4649 if (o->prefix_length)
4650 strip_prefix(o->prefix_length, &name, &other);
4652 diff_fill_oid_info(p->one, o->repo->index);
4653 diff_fill_oid_info(p->two, o->repo->index);
4655 builtin_diffstat(name, other, p->one, p->two,
4656 diffstat, o, p);
4659 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4661 const char *name;
4662 const char *other;
4663 const char *attr_path;
4665 if (DIFF_PAIR_UNMERGED(p)) {
4666 /* unmerged */
4667 return;
4670 name = p->one->path;
4671 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4672 attr_path = other ? other : name;
4674 if (o->prefix_length)
4675 strip_prefix(o->prefix_length, &name, &other);
4677 diff_fill_oid_info(p->one, o->repo->index);
4678 diff_fill_oid_info(p->two, o->repo->index);
4680 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4683 void repo_diff_setup(struct repository *r, struct diff_options *options)
4685 memcpy(options, &default_diff_options, sizeof(*options));
4687 options->file = stdout;
4688 options->repo = r;
4690 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4691 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4692 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4693 options->abbrev = DEFAULT_ABBREV;
4694 options->line_termination = '\n';
4695 options->break_opt = -1;
4696 options->rename_limit = -1;
4697 options->dirstat_permille = diff_dirstat_permille_default;
4698 options->context = diff_context_default;
4699 options->interhunkcontext = diff_interhunk_context_default;
4700 options->ws_error_highlight = ws_error_highlight_default;
4701 options->flags.rename_empty = 1;
4702 options->flags.relative_name = diff_relative;
4703 options->objfind = NULL;
4705 /* pathchange left =NULL by default */
4706 options->change = diff_change;
4707 options->add_remove = diff_addremove;
4708 options->use_color = diff_use_color_default;
4709 options->detect_rename = diff_detect_rename_default;
4710 options->xdl_opts |= diff_algorithm;
4711 if (diff_indent_heuristic)
4712 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4714 options->orderfile = diff_order_file_cfg;
4716 if (!options->flags.ignore_submodule_set)
4717 options->flags.ignore_untracked_in_submodules = 1;
4719 if (diff_no_prefix) {
4720 diff_set_noprefix(options);
4721 } else if (!diff_mnemonic_prefix) {
4722 diff_set_default_prefix(options);
4725 options->color_moved = diff_color_moved_default;
4726 options->color_moved_ws_handling = diff_color_moved_ws_default;
4729 static const char diff_status_letters[] = {
4730 DIFF_STATUS_ADDED,
4731 DIFF_STATUS_COPIED,
4732 DIFF_STATUS_DELETED,
4733 DIFF_STATUS_MODIFIED,
4734 DIFF_STATUS_RENAMED,
4735 DIFF_STATUS_TYPE_CHANGED,
4736 DIFF_STATUS_UNKNOWN,
4737 DIFF_STATUS_UNMERGED,
4738 DIFF_STATUS_FILTER_AON,
4739 DIFF_STATUS_FILTER_BROKEN,
4740 '\0',
4743 static unsigned int filter_bit['Z' + 1];
4745 static void prepare_filter_bits(void)
4747 int i;
4749 if (!filter_bit[DIFF_STATUS_ADDED]) {
4750 for (i = 0; diff_status_letters[i]; i++)
4751 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4755 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4757 return opt->filter & filter_bit[(int) status];
4760 unsigned diff_filter_bit(char status)
4762 prepare_filter_bits();
4763 return filter_bit[(int) status];
4766 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4768 unsigned forbidden_magic;
4770 if (ps->nr != 1) {
4771 if (die_on_error)
4772 die(_("--follow requires exactly one pathspec"));
4773 return 0;
4776 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4777 PATHSPEC_LITERAL);
4778 if (forbidden_magic) {
4779 if (die_on_error) {
4780 struct strbuf sb = STRBUF_INIT;
4781 pathspec_magic_names(forbidden_magic, &sb);
4782 die(_("pathspec magic not supported by --follow: %s"),
4783 sb.buf);
4785 return 0;
4788 return 1;
4791 void diff_setup_done(struct diff_options *options)
4793 unsigned check_mask = DIFF_FORMAT_NAME |
4794 DIFF_FORMAT_NAME_STATUS |
4795 DIFF_FORMAT_CHECKDIFF |
4796 DIFF_FORMAT_NO_OUTPUT;
4798 * This must be signed because we're comparing against a potentially
4799 * negative value.
4801 const int hexsz = the_hash_algo->hexsz;
4803 if (options->set_default)
4804 options->set_default(options);
4806 if (HAS_MULTI_BITS(options->output_format & check_mask))
4807 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4808 "--name-only", "--name-status", "--check", "-s");
4810 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4811 die(_("options '%s', '%s', and '%s' cannot be used together"),
4812 "-G", "-S", "--find-object");
4814 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4815 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4816 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4818 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4819 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4820 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4823 * Most of the time we can say "there are changes"
4824 * only by checking if there are changed paths, but
4825 * --ignore-whitespace* options force us to look
4826 * inside contents.
4829 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4830 options->ignore_regex_nr)
4831 options->flags.diff_from_contents = 1;
4832 else
4833 options->flags.diff_from_contents = 0;
4835 if (options->flags.find_copies_harder)
4836 options->detect_rename = DIFF_DETECT_COPY;
4838 if (!options->flags.relative_name)
4839 options->prefix = NULL;
4840 if (options->prefix)
4841 options->prefix_length = strlen(options->prefix);
4842 else
4843 options->prefix_length = 0;
4846 * --name-only, --name-status, --checkdiff, and -s
4847 * turn other output format off.
4849 if (options->output_format & (DIFF_FORMAT_NAME |
4850 DIFF_FORMAT_NAME_STATUS |
4851 DIFF_FORMAT_CHECKDIFF |
4852 DIFF_FORMAT_NO_OUTPUT))
4853 options->output_format &= ~(DIFF_FORMAT_RAW |
4854 DIFF_FORMAT_NUMSTAT |
4855 DIFF_FORMAT_DIFFSTAT |
4856 DIFF_FORMAT_SHORTSTAT |
4857 DIFF_FORMAT_DIRSTAT |
4858 DIFF_FORMAT_SUMMARY |
4859 DIFF_FORMAT_PATCH);
4862 * These cases always need recursive; we do not drop caller-supplied
4863 * recursive bits for other formats here.
4865 if (options->output_format & (DIFF_FORMAT_PATCH |
4866 DIFF_FORMAT_NUMSTAT |
4867 DIFF_FORMAT_DIFFSTAT |
4868 DIFF_FORMAT_SHORTSTAT |
4869 DIFF_FORMAT_DIRSTAT |
4870 DIFF_FORMAT_SUMMARY |
4871 DIFF_FORMAT_CHECKDIFF))
4872 options->flags.recursive = 1;
4874 * Also pickaxe would not work very well if you do not say recursive
4876 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4877 options->flags.recursive = 1;
4879 * When patches are generated, submodules diffed against the work tree
4880 * must be checked for dirtiness too so it can be shown in the output
4882 if (options->output_format & DIFF_FORMAT_PATCH)
4883 options->flags.dirty_submodules = 1;
4885 if (options->detect_rename && options->rename_limit < 0)
4886 options->rename_limit = diff_rename_limit_default;
4887 if (hexsz < options->abbrev)
4888 options->abbrev = hexsz; /* full */
4891 * It does not make sense to show the first hit we happened
4892 * to have found. It does not make sense not to return with
4893 * exit code in such a case either.
4895 if (options->flags.quick) {
4896 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4897 options->flags.exit_with_status = 1;
4900 options->diff_path_counter = 0;
4902 if (options->flags.follow_renames)
4903 diff_check_follow_pathspec(&options->pathspec, 1);
4905 if (!options->use_color || external_diff())
4906 options->color_moved = 0;
4908 if (options->filter_not) {
4909 if (!options->filter)
4910 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4911 options->filter &= ~options->filter_not;
4915 int parse_long_opt(const char *opt, const char **argv,
4916 const char **optarg)
4918 const char *arg = argv[0];
4919 if (!skip_prefix(arg, "--", &arg))
4920 return 0;
4921 if (!skip_prefix(arg, opt, &arg))
4922 return 0;
4923 if (*arg == '=') { /* stuck form: --option=value */
4924 *optarg = arg + 1;
4925 return 1;
4927 if (*arg != '\0')
4928 return 0;
4929 /* separate form: --option value */
4930 if (!argv[1])
4931 die("Option '--%s' requires a value", opt);
4932 *optarg = argv[1];
4933 return 2;
4936 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4938 struct diff_options *options = opt->value;
4939 int width = options->stat_width;
4940 int name_width = options->stat_name_width;
4941 int graph_width = options->stat_graph_width;
4942 int count = options->stat_count;
4943 char *end;
4945 BUG_ON_OPT_NEG(unset);
4947 if (!strcmp(opt->long_name, "stat")) {
4948 if (value) {
4949 width = strtoul(value, &end, 10);
4950 if (*end == ',')
4951 name_width = strtoul(end+1, &end, 10);
4952 if (*end == ',')
4953 count = strtoul(end+1, &end, 10);
4954 if (*end)
4955 return error(_("invalid --stat value: %s"), value);
4957 } else if (!strcmp(opt->long_name, "stat-width")) {
4958 width = strtoul(value, &end, 10);
4959 if (*end)
4960 return error(_("%s expects a numerical value"),
4961 opt->long_name);
4962 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4963 name_width = strtoul(value, &end, 10);
4964 if (*end)
4965 return error(_("%s expects a numerical value"),
4966 opt->long_name);
4967 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4968 graph_width = strtoul(value, &end, 10);
4969 if (*end)
4970 return error(_("%s expects a numerical value"),
4971 opt->long_name);
4972 } else if (!strcmp(opt->long_name, "stat-count")) {
4973 count = strtoul(value, &end, 10);
4974 if (*end)
4975 return error(_("%s expects a numerical value"),
4976 opt->long_name);
4977 } else
4978 BUG("%s should not get here", opt->long_name);
4980 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4981 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4982 options->stat_name_width = name_width;
4983 options->stat_graph_width = graph_width;
4984 options->stat_width = width;
4985 options->stat_count = count;
4986 return 0;
4989 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4991 struct strbuf errmsg = STRBUF_INIT;
4992 if (parse_dirstat_params(options, params, &errmsg))
4993 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4994 errmsg.buf);
4995 strbuf_release(&errmsg);
4997 * The caller knows a dirstat-related option is given from the command
4998 * line; allow it to say "return this_function();"
5000 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5001 options->output_format |= DIFF_FORMAT_DIRSTAT;
5002 return 1;
5005 static int diff_opt_diff_filter(const struct option *option,
5006 const char *optarg, int unset)
5008 struct diff_options *opt = option->value;
5009 int i, optch;
5011 BUG_ON_OPT_NEG(unset);
5012 prepare_filter_bits();
5014 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5015 unsigned int bit;
5016 int negate;
5018 if ('a' <= optch && optch <= 'z') {
5019 negate = 1;
5020 optch = toupper(optch);
5021 } else {
5022 negate = 0;
5025 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5026 if (!bit)
5027 return error(_("unknown change class '%c' in --diff-filter=%s"),
5028 optarg[i], optarg);
5029 if (negate)
5030 opt->filter_not |= bit;
5031 else
5032 opt->filter |= bit;
5034 return 0;
5037 static void enable_patch_output(int *fmt)
5039 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5040 *fmt |= DIFF_FORMAT_PATCH;
5043 static int diff_opt_ws_error_highlight(const struct option *option,
5044 const char *arg, int unset)
5046 struct diff_options *opt = option->value;
5047 int val = parse_ws_error_highlight(arg);
5049 BUG_ON_OPT_NEG(unset);
5050 if (val < 0)
5051 return error(_("unknown value after ws-error-highlight=%.*s"),
5052 -1 - val, arg);
5053 opt->ws_error_highlight = val;
5054 return 0;
5057 static int diff_opt_find_object(const struct option *option,
5058 const char *arg, int unset)
5060 struct diff_options *opt = option->value;
5061 struct object_id oid;
5063 BUG_ON_OPT_NEG(unset);
5064 if (repo_get_oid(the_repository, arg, &oid))
5065 return error(_("unable to resolve '%s'"), arg);
5067 if (!opt->objfind)
5068 CALLOC_ARRAY(opt->objfind, 1);
5070 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5071 opt->flags.recursive = 1;
5072 opt->flags.tree_in_recursive = 1;
5073 oidset_insert(opt->objfind, &oid);
5074 return 0;
5077 static int diff_opt_anchored(const struct option *opt,
5078 const char *arg, int unset)
5080 struct diff_options *options = opt->value;
5082 BUG_ON_OPT_NEG(unset);
5083 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5084 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5085 options->anchors_alloc);
5086 options->anchors[options->anchors_nr++] = xstrdup(arg);
5087 return 0;
5090 static int diff_opt_binary(const struct option *opt,
5091 const char *arg, int unset)
5093 struct diff_options *options = opt->value;
5095 BUG_ON_OPT_NEG(unset);
5096 BUG_ON_OPT_ARG(arg);
5097 enable_patch_output(&options->output_format);
5098 options->flags.binary = 1;
5099 return 0;
5102 static int diff_opt_break_rewrites(const struct option *opt,
5103 const char *arg, int unset)
5105 int *break_opt = opt->value;
5106 int opt1, opt2;
5108 BUG_ON_OPT_NEG(unset);
5109 if (!arg)
5110 arg = "";
5111 opt1 = parse_rename_score(&arg);
5112 if (*arg == 0)
5113 opt2 = 0;
5114 else if (*arg != '/')
5115 return error(_("%s expects <n>/<m> form"), opt->long_name);
5116 else {
5117 arg++;
5118 opt2 = parse_rename_score(&arg);
5120 if (*arg != 0)
5121 return error(_("%s expects <n>/<m> form"), opt->long_name);
5122 *break_opt = opt1 | (opt2 << 16);
5123 return 0;
5126 static int diff_opt_char(const struct option *opt,
5127 const char *arg, int unset)
5129 char *value = opt->value;
5131 BUG_ON_OPT_NEG(unset);
5132 if (arg[1])
5133 return error(_("%s expects a character, got '%s'"),
5134 opt->long_name, arg);
5135 *value = arg[0];
5136 return 0;
5139 static int diff_opt_color_moved(const struct option *opt,
5140 const char *arg, int unset)
5142 struct diff_options *options = opt->value;
5144 if (unset) {
5145 options->color_moved = COLOR_MOVED_NO;
5146 } else if (!arg) {
5147 if (diff_color_moved_default)
5148 options->color_moved = diff_color_moved_default;
5149 if (options->color_moved == COLOR_MOVED_NO)
5150 options->color_moved = COLOR_MOVED_DEFAULT;
5151 } else {
5152 int cm = parse_color_moved(arg);
5153 if (cm < 0)
5154 return error(_("bad --color-moved argument: %s"), arg);
5155 options->color_moved = cm;
5157 return 0;
5160 static int diff_opt_color_moved_ws(const struct option *opt,
5161 const char *arg, int unset)
5163 struct diff_options *options = opt->value;
5164 unsigned cm;
5166 if (unset) {
5167 options->color_moved_ws_handling = 0;
5168 return 0;
5171 cm = parse_color_moved_ws(arg);
5172 if (cm & COLOR_MOVED_WS_ERROR)
5173 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5174 options->color_moved_ws_handling = cm;
5175 return 0;
5178 static int diff_opt_color_words(const struct option *opt,
5179 const char *arg, int unset)
5181 struct diff_options *options = opt->value;
5183 BUG_ON_OPT_NEG(unset);
5184 options->use_color = 1;
5185 options->word_diff = DIFF_WORDS_COLOR;
5186 options->word_regex = arg;
5187 return 0;
5190 static int diff_opt_compact_summary(const struct option *opt,
5191 const char *arg, int unset)
5193 struct diff_options *options = opt->value;
5195 BUG_ON_OPT_ARG(arg);
5196 if (unset) {
5197 options->flags.stat_with_summary = 0;
5198 } else {
5199 options->flags.stat_with_summary = 1;
5200 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5201 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5203 return 0;
5206 static int diff_opt_diff_algorithm(const struct option *opt,
5207 const char *arg, int unset)
5209 struct diff_options *options = opt->value;
5211 BUG_ON_OPT_NEG(unset);
5213 if (set_diff_algorithm(options, arg))
5214 return error(_("option diff-algorithm accepts \"myers\", "
5215 "\"minimal\", \"patience\" and \"histogram\""));
5217 options->ignore_driver_algorithm = 1;
5219 return 0;
5222 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5223 const char *arg, int unset)
5225 struct diff_options *options = opt->value;
5227 BUG_ON_OPT_NEG(unset);
5228 BUG_ON_OPT_ARG(arg);
5230 if (set_diff_algorithm(options, opt->long_name))
5231 BUG("available diff algorithms include \"myers\", "
5232 "\"minimal\", \"patience\" and \"histogram\"");
5234 options->ignore_driver_algorithm = 1;
5236 return 0;
5239 static int diff_opt_dirstat(const struct option *opt,
5240 const char *arg, int unset)
5242 struct diff_options *options = opt->value;
5244 BUG_ON_OPT_NEG(unset);
5245 if (!strcmp(opt->long_name, "cumulative")) {
5246 if (arg)
5247 BUG("how come --cumulative take a value?");
5248 arg = "cumulative";
5249 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5250 parse_dirstat_opt(options, "files");
5251 parse_dirstat_opt(options, arg ? arg : "");
5252 return 0;
5255 static int diff_opt_find_copies(const struct option *opt,
5256 const char *arg, int unset)
5258 struct diff_options *options = opt->value;
5260 BUG_ON_OPT_NEG(unset);
5261 if (!arg)
5262 arg = "";
5263 options->rename_score = parse_rename_score(&arg);
5264 if (*arg != 0)
5265 return error(_("invalid argument to %s"), opt->long_name);
5267 if (options->detect_rename == DIFF_DETECT_COPY)
5268 options->flags.find_copies_harder = 1;
5269 else
5270 options->detect_rename = DIFF_DETECT_COPY;
5272 return 0;
5275 static int diff_opt_find_renames(const struct option *opt,
5276 const char *arg, int unset)
5278 struct diff_options *options = opt->value;
5280 BUG_ON_OPT_NEG(unset);
5281 if (!arg)
5282 arg = "";
5283 options->rename_score = parse_rename_score(&arg);
5284 if (*arg != 0)
5285 return error(_("invalid argument to %s"), opt->long_name);
5287 options->detect_rename = DIFF_DETECT_RENAME;
5288 return 0;
5291 static int diff_opt_follow(const struct option *opt,
5292 const char *arg, int unset)
5294 struct diff_options *options = opt->value;
5296 BUG_ON_OPT_ARG(arg);
5297 if (unset) {
5298 options->flags.follow_renames = 0;
5299 options->flags.default_follow_renames = 0;
5300 } else {
5301 options->flags.follow_renames = 1;
5303 return 0;
5306 static int diff_opt_ignore_submodules(const struct option *opt,
5307 const char *arg, int unset)
5309 struct diff_options *options = opt->value;
5311 BUG_ON_OPT_NEG(unset);
5312 if (!arg)
5313 arg = "all";
5314 options->flags.override_submodule_config = 1;
5315 handle_ignore_submodules_arg(options, arg);
5316 return 0;
5319 static int diff_opt_line_prefix(const struct option *opt,
5320 const char *optarg, int unset)
5322 struct diff_options *options = opt->value;
5324 BUG_ON_OPT_NEG(unset);
5325 options->line_prefix = optarg;
5326 options->line_prefix_length = strlen(options->line_prefix);
5327 graph_setup_line_prefix(options);
5328 return 0;
5331 static int diff_opt_no_prefix(const struct option *opt,
5332 const char *optarg, int unset)
5334 struct diff_options *options = opt->value;
5336 BUG_ON_OPT_NEG(unset);
5337 BUG_ON_OPT_ARG(optarg);
5338 diff_set_noprefix(options);
5339 return 0;
5342 static int diff_opt_default_prefix(const struct option *opt,
5343 const char *optarg, int unset)
5345 struct diff_options *options = opt->value;
5347 BUG_ON_OPT_NEG(unset);
5348 BUG_ON_OPT_ARG(optarg);
5349 diff_set_default_prefix(options);
5350 return 0;
5353 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5354 const struct option *opt,
5355 const char *arg, int unset)
5357 struct diff_options *options = opt->value;
5358 char *path;
5360 BUG_ON_OPT_NEG(unset);
5361 path = prefix_filename(ctx->prefix, arg);
5362 options->file = xfopen(path, "w");
5363 options->close_file = 1;
5364 if (options->use_color != GIT_COLOR_ALWAYS)
5365 options->use_color = GIT_COLOR_NEVER;
5366 free(path);
5367 return 0;
5370 static int diff_opt_patience(const struct option *opt,
5371 const char *arg, int unset)
5373 struct diff_options *options = opt->value;
5374 int i;
5376 BUG_ON_OPT_NEG(unset);
5377 BUG_ON_OPT_ARG(arg);
5379 * Both --patience and --anchored use PATIENCE_DIFF
5380 * internally, so remove any anchors previously
5381 * specified.
5383 for (i = 0; i < options->anchors_nr; i++)
5384 free(options->anchors[i]);
5385 options->anchors_nr = 0;
5386 options->ignore_driver_algorithm = 1;
5388 return set_diff_algorithm(options, "patience");
5391 static int diff_opt_ignore_regex(const struct option *opt,
5392 const char *arg, int unset)
5394 struct diff_options *options = opt->value;
5395 regex_t *regex;
5397 BUG_ON_OPT_NEG(unset);
5398 regex = xmalloc(sizeof(*regex));
5399 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5400 return error(_("invalid regex given to -I: '%s'"), arg);
5401 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5402 options->ignore_regex_alloc);
5403 options->ignore_regex[options->ignore_regex_nr++] = regex;
5404 return 0;
5407 static int diff_opt_pickaxe_regex(const struct option *opt,
5408 const char *arg, int unset)
5410 struct diff_options *options = opt->value;
5412 BUG_ON_OPT_NEG(unset);
5413 options->pickaxe = arg;
5414 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5415 return 0;
5418 static int diff_opt_pickaxe_string(const struct option *opt,
5419 const char *arg, int unset)
5421 struct diff_options *options = opt->value;
5423 BUG_ON_OPT_NEG(unset);
5424 options->pickaxe = arg;
5425 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5426 return 0;
5429 static int diff_opt_relative(const struct option *opt,
5430 const char *arg, int unset)
5432 struct diff_options *options = opt->value;
5434 options->flags.relative_name = !unset;
5435 if (arg)
5436 options->prefix = arg;
5437 return 0;
5440 static int diff_opt_submodule(const struct option *opt,
5441 const char *arg, int unset)
5443 struct diff_options *options = opt->value;
5445 BUG_ON_OPT_NEG(unset);
5446 if (!arg)
5447 arg = "log";
5448 if (parse_submodule_params(options, arg))
5449 return error(_("failed to parse --submodule option parameter: '%s'"),
5450 arg);
5451 return 0;
5454 static int diff_opt_textconv(const struct option *opt,
5455 const char *arg, int unset)
5457 struct diff_options *options = opt->value;
5459 BUG_ON_OPT_ARG(arg);
5460 if (unset) {
5461 options->flags.allow_textconv = 0;
5462 } else {
5463 options->flags.allow_textconv = 1;
5464 options->flags.textconv_set_via_cmdline = 1;
5466 return 0;
5469 static int diff_opt_unified(const struct option *opt,
5470 const char *arg, int unset)
5472 struct diff_options *options = opt->value;
5473 char *s;
5475 BUG_ON_OPT_NEG(unset);
5477 if (arg) {
5478 options->context = strtol(arg, &s, 10);
5479 if (*s)
5480 return error(_("%s expects a numerical value"), "--unified");
5482 enable_patch_output(&options->output_format);
5484 return 0;
5487 static int diff_opt_word_diff(const struct option *opt,
5488 const char *arg, int unset)
5490 struct diff_options *options = opt->value;
5492 BUG_ON_OPT_NEG(unset);
5493 if (arg) {
5494 if (!strcmp(arg, "plain"))
5495 options->word_diff = DIFF_WORDS_PLAIN;
5496 else if (!strcmp(arg, "color")) {
5497 options->use_color = 1;
5498 options->word_diff = DIFF_WORDS_COLOR;
5500 else if (!strcmp(arg, "porcelain"))
5501 options->word_diff = DIFF_WORDS_PORCELAIN;
5502 else if (!strcmp(arg, "none"))
5503 options->word_diff = DIFF_WORDS_NONE;
5504 else
5505 return error(_("bad --word-diff argument: %s"), arg);
5506 } else {
5507 if (options->word_diff == DIFF_WORDS_NONE)
5508 options->word_diff = DIFF_WORDS_PLAIN;
5510 return 0;
5513 static int diff_opt_word_diff_regex(const struct option *opt,
5514 const char *arg, int unset)
5516 struct diff_options *options = opt->value;
5518 BUG_ON_OPT_NEG(unset);
5519 if (options->word_diff == DIFF_WORDS_NONE)
5520 options->word_diff = DIFF_WORDS_PLAIN;
5521 options->word_regex = arg;
5522 return 0;
5525 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5527 struct diff_options *options = opt->value;
5529 BUG_ON_OPT_NEG(unset);
5530 if (!strcmp(opt->long_name, "skip-to"))
5531 options->skip_instead_of_rotate = 1;
5532 else
5533 options->skip_instead_of_rotate = 0;
5534 options->rotate_to = arg;
5535 return 0;
5539 * Consider adding new flags to __git_diff_common_options
5540 * in contrib/completion/git-completion.bash
5542 struct option *add_diff_options(const struct option *opts,
5543 struct diff_options *options)
5545 struct option parseopts[] = {
5546 OPT_GROUP(N_("Diff output format options")),
5547 OPT_BITOP('p', "patch", &options->output_format,
5548 N_("generate patch"),
5549 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5550 OPT_SET_INT('s', "no-patch", &options->output_format,
5551 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5552 OPT_BITOP('u', NULL, &options->output_format,
5553 N_("generate patch"),
5554 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5555 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5556 N_("generate diffs with <n> lines context"),
5557 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5558 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5559 N_("generate diffs with <n> lines context")),
5560 OPT_BITOP(0, "raw", &options->output_format,
5561 N_("generate the diff in raw format"),
5562 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5563 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5564 N_("synonym for '-p --raw'"),
5565 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5566 DIFF_FORMAT_NO_OUTPUT),
5567 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5568 N_("synonym for '-p --stat'"),
5569 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5570 DIFF_FORMAT_NO_OUTPUT),
5571 OPT_BITOP(0, "numstat", &options->output_format,
5572 N_("machine friendly --stat"),
5573 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5574 OPT_BITOP(0, "shortstat", &options->output_format,
5575 N_("output only the last line of --stat"),
5576 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5577 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5578 N_("output the distribution of relative amount of changes for each sub-directory"),
5579 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5580 diff_opt_dirstat),
5581 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5582 N_("synonym for --dirstat=cumulative"),
5583 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5584 diff_opt_dirstat),
5585 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5586 N_("synonym for --dirstat=files,param1,param2..."),
5587 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5588 diff_opt_dirstat),
5589 OPT_BIT_F(0, "check", &options->output_format,
5590 N_("warn if changes introduce conflict markers or whitespace errors"),
5591 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5592 OPT_BITOP(0, "summary", &options->output_format,
5593 N_("condensed summary such as creations, renames and mode changes"),
5594 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5595 OPT_BIT_F(0, "name-only", &options->output_format,
5596 N_("show only names of changed files"),
5597 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5598 OPT_BIT_F(0, "name-status", &options->output_format,
5599 N_("show only names and status of changed files"),
5600 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5601 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5602 N_("generate diffstat"),
5603 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5604 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5605 N_("generate diffstat with a given width"),
5606 PARSE_OPT_NONEG, diff_opt_stat),
5607 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5608 N_("generate diffstat with a given name width"),
5609 PARSE_OPT_NONEG, diff_opt_stat),
5610 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5611 N_("generate diffstat with a given graph width"),
5612 PARSE_OPT_NONEG, diff_opt_stat),
5613 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5614 N_("generate diffstat with limited lines"),
5615 PARSE_OPT_NONEG, diff_opt_stat),
5616 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5617 N_("generate compact summary in diffstat"),
5618 PARSE_OPT_NOARG, diff_opt_compact_summary),
5619 OPT_CALLBACK_F(0, "binary", options, NULL,
5620 N_("output a binary diff that can be applied"),
5621 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5622 OPT_BOOL(0, "full-index", &options->flags.full_index,
5623 N_("show full pre- and post-image object names on the \"index\" lines")),
5624 OPT_COLOR_FLAG(0, "color", &options->use_color,
5625 N_("show colored diff")),
5626 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5627 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5628 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5629 OPT_SET_INT('z', NULL, &options->line_termination,
5630 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5632 OPT__ABBREV(&options->abbrev),
5633 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5634 N_("show the given source prefix instead of \"a/\""),
5635 PARSE_OPT_NONEG),
5636 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5637 N_("show the given destination prefix instead of \"b/\""),
5638 PARSE_OPT_NONEG),
5639 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5640 N_("prepend an additional prefix to every line of output"),
5641 PARSE_OPT_NONEG, diff_opt_line_prefix),
5642 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5643 N_("do not show any source or destination prefix"),
5644 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5645 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5646 N_("use default prefixes a/ and b/"),
5647 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5648 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5649 N_("show context between diff hunks up to the specified number of lines"),
5650 PARSE_OPT_NONEG),
5651 OPT_CALLBACK_F(0, "output-indicator-new",
5652 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5653 N_("<char>"),
5654 N_("specify the character to indicate a new line instead of '+'"),
5655 PARSE_OPT_NONEG, diff_opt_char),
5656 OPT_CALLBACK_F(0, "output-indicator-old",
5657 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5658 N_("<char>"),
5659 N_("specify the character to indicate an old line instead of '-'"),
5660 PARSE_OPT_NONEG, diff_opt_char),
5661 OPT_CALLBACK_F(0, "output-indicator-context",
5662 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5663 N_("<char>"),
5664 N_("specify the character to indicate a context instead of ' '"),
5665 PARSE_OPT_NONEG, diff_opt_char),
5667 OPT_GROUP(N_("Diff rename options")),
5668 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5669 N_("break complete rewrite changes into pairs of delete and create"),
5670 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5671 diff_opt_break_rewrites),
5672 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5673 N_("detect renames"),
5674 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5675 diff_opt_find_renames),
5676 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5677 N_("omit the preimage for deletes"),
5678 1, PARSE_OPT_NONEG),
5679 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5680 N_("detect copies"),
5681 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5682 diff_opt_find_copies),
5683 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5684 N_("use unmodified files as source to find copies")),
5685 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5686 N_("disable rename detection"),
5687 0, PARSE_OPT_NONEG),
5688 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5689 N_("use empty blobs as rename source")),
5690 OPT_CALLBACK_F(0, "follow", options, NULL,
5691 N_("continue listing the history of a file beyond renames"),
5692 PARSE_OPT_NOARG, diff_opt_follow),
5693 OPT_INTEGER('l', NULL, &options->rename_limit,
5694 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5696 OPT_GROUP(N_("Diff algorithm options")),
5697 OPT_CALLBACK_F(0, "minimal", options, NULL,
5698 N_("produce the smallest possible diff"),
5699 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5700 diff_opt_diff_algorithm_no_arg),
5701 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5702 N_("ignore whitespace when comparing lines"),
5703 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5704 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5705 N_("ignore changes in amount of whitespace"),
5706 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5707 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5708 N_("ignore changes in whitespace at EOL"),
5709 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5710 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5711 N_("ignore carrier-return at the end of line"),
5712 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5713 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5714 N_("ignore changes whose lines are all blank"),
5715 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5716 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5717 N_("ignore changes whose all lines match <regex>"),
5718 0, diff_opt_ignore_regex),
5719 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5720 N_("heuristic to shift diff hunk boundaries for easy reading"),
5721 XDF_INDENT_HEURISTIC),
5722 OPT_CALLBACK_F(0, "patience", options, NULL,
5723 N_("generate diff using the \"patience diff\" algorithm"),
5724 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5725 diff_opt_patience),
5726 OPT_CALLBACK_F(0, "histogram", options, NULL,
5727 N_("generate diff using the \"histogram diff\" algorithm"),
5728 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5729 diff_opt_diff_algorithm_no_arg),
5730 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5731 N_("choose a diff algorithm"),
5732 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5733 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5734 N_("generate diff using the \"anchored diff\" algorithm"),
5735 PARSE_OPT_NONEG, diff_opt_anchored),
5736 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5737 N_("show word diff, using <mode> to delimit changed words"),
5738 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5739 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5740 N_("use <regex> to decide what a word is"),
5741 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5742 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5743 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5744 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5745 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5746 N_("moved lines of code are colored differently"),
5747 PARSE_OPT_OPTARG, diff_opt_color_moved),
5748 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5749 N_("how white spaces are ignored in --color-moved"),
5750 0, diff_opt_color_moved_ws),
5752 OPT_GROUP(N_("Other diff options")),
5753 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5754 N_("when run from subdir, exclude changes outside and show relative paths"),
5755 PARSE_OPT_OPTARG,
5756 diff_opt_relative),
5757 OPT_BOOL('a', "text", &options->flags.text,
5758 N_("treat all files as text")),
5759 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5760 N_("swap two inputs, reverse the diff")),
5761 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5762 N_("exit with 1 if there were differences, 0 otherwise")),
5763 OPT_BOOL(0, "quiet", &options->flags.quick,
5764 N_("disable all output of the program")),
5765 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5766 N_("allow an external diff helper to be executed")),
5767 OPT_CALLBACK_F(0, "textconv", options, NULL,
5768 N_("run external text conversion filters when comparing binary files"),
5769 PARSE_OPT_NOARG, diff_opt_textconv),
5770 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5771 N_("ignore changes to submodules in the diff generation"),
5772 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5773 diff_opt_ignore_submodules),
5774 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5775 N_("specify how differences in submodules are shown"),
5776 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5777 diff_opt_submodule),
5778 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5779 N_("hide 'git add -N' entries from the index"),
5780 1, PARSE_OPT_NONEG),
5781 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5782 N_("treat 'git add -N' entries as real in the index"),
5783 0, PARSE_OPT_NONEG),
5784 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5785 N_("look for differences that change the number of occurrences of the specified string"),
5786 0, diff_opt_pickaxe_string),
5787 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5788 N_("look for differences that change the number of occurrences of the specified regex"),
5789 0, diff_opt_pickaxe_regex),
5790 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5791 N_("show all changes in the changeset with -S or -G"),
5792 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5793 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5794 N_("treat <string> in -S as extended POSIX regular expression"),
5795 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5796 OPT_FILENAME('O', NULL, &options->orderfile,
5797 N_("control the order in which files appear in the output")),
5798 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5799 N_("show the change in the specified path first"),
5800 PARSE_OPT_NONEG, diff_opt_rotate_to),
5801 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5802 N_("skip the output to the specified path"),
5803 PARSE_OPT_NONEG, diff_opt_rotate_to),
5804 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5805 N_("look for differences that change the number of occurrences of the specified object"),
5806 PARSE_OPT_NONEG, diff_opt_find_object),
5807 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5808 N_("select files by diff type"),
5809 PARSE_OPT_NONEG, diff_opt_diff_filter),
5810 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5811 N_("output to a specific file"),
5812 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5814 OPT_END()
5817 return parse_options_concat(opts, parseopts);
5820 int diff_opt_parse(struct diff_options *options,
5821 const char **av, int ac, const char *prefix)
5823 struct option no_options[] = { OPT_END() };
5824 struct option *parseopts = add_diff_options(no_options, options);
5826 if (!prefix)
5827 prefix = "";
5829 ac = parse_options(ac, av, prefix, parseopts, NULL,
5830 PARSE_OPT_KEEP_DASHDASH |
5831 PARSE_OPT_KEEP_UNKNOWN_OPT |
5832 PARSE_OPT_NO_INTERNAL_HELP |
5833 PARSE_OPT_ONE_SHOT |
5834 PARSE_OPT_STOP_AT_NON_OPTION);
5835 free(parseopts);
5837 return ac;
5840 int parse_rename_score(const char **cp_p)
5842 unsigned long num, scale;
5843 int ch, dot;
5844 const char *cp = *cp_p;
5846 num = 0;
5847 scale = 1;
5848 dot = 0;
5849 for (;;) {
5850 ch = *cp;
5851 if ( !dot && ch == '.' ) {
5852 scale = 1;
5853 dot = 1;
5854 } else if ( ch == '%' ) {
5855 scale = dot ? scale*100 : 100;
5856 cp++; /* % is always at the end */
5857 break;
5858 } else if ( ch >= '0' && ch <= '9' ) {
5859 if ( scale < 100000 ) {
5860 scale *= 10;
5861 num = (num*10) + (ch-'0');
5863 } else {
5864 break;
5866 cp++;
5868 *cp_p = cp;
5870 /* user says num divided by scale and we say internally that
5871 * is MAX_SCORE * num / scale.
5873 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5876 struct diff_queue_struct diff_queued_diff;
5878 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5880 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5881 queue->queue[queue->nr++] = dp;
5884 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5885 struct diff_filespec *one,
5886 struct diff_filespec *two)
5888 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5889 dp->one = one;
5890 dp->two = two;
5891 if (queue)
5892 diff_q(queue, dp);
5893 return dp;
5896 void diff_free_filepair(struct diff_filepair *p)
5898 free_filespec(p->one);
5899 free_filespec(p->two);
5900 free(p);
5903 void diff_free_queue(struct diff_queue_struct *q)
5905 for (int i = 0; i < q->nr; i++)
5906 diff_free_filepair(q->queue[i]);
5907 free(q->queue);
5910 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5912 int abblen;
5913 const char *abbrev;
5915 /* Do we want all 40 hex characters? */
5916 if (len == the_hash_algo->hexsz)
5917 return oid_to_hex(oid);
5919 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5920 abbrev = diff_abbrev_oid(oid, len);
5922 if (!print_sha1_ellipsis())
5923 return abbrev;
5925 abblen = strlen(abbrev);
5928 * In well-behaved cases, where the abbreviated result is the
5929 * same as the requested length, append three dots after the
5930 * abbreviation (hence the whole logic is limited to the case
5931 * where abblen < 37); when the actual abbreviated result is a
5932 * bit longer than the requested length, we reduce the number
5933 * of dots so that they match the well-behaved ones. However,
5934 * if the actual abbreviation is longer than the requested
5935 * length by more than three, we give up on aligning, and add
5936 * three dots anyway, to indicate that the output is not the
5937 * full object name. Yes, this may be suboptimal, but this
5938 * appears only in "diff --raw --abbrev" output and it is not
5939 * worth the effort to change it now. Note that this would
5940 * likely to work fine when the automatic sizing of default
5941 * abbreviation length is used--we would be fed -1 in "len" in
5942 * that case, and will end up always appending three-dots, but
5943 * the automatic sizing is supposed to give abblen that ensures
5944 * uniqueness across all objects (statistically speaking).
5946 if (abblen < the_hash_algo->hexsz - 3) {
5947 static char hex[GIT_MAX_HEXSZ + 1];
5948 if (len < abblen && abblen <= len + 2)
5949 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5950 else
5951 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5952 return hex;
5955 return oid_to_hex(oid);
5958 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5960 int line_termination = opt->line_termination;
5961 int inter_name_termination = line_termination ? '\t' : '\0';
5963 fprintf(opt->file, "%s", diff_line_prefix(opt));
5964 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5965 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5966 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5967 fprintf(opt->file, "%s ",
5968 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5970 if (p->score) {
5971 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5972 inter_name_termination);
5973 } else {
5974 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5977 if (p->status == DIFF_STATUS_COPIED ||
5978 p->status == DIFF_STATUS_RENAMED) {
5979 const char *name_a, *name_b;
5980 name_a = p->one->path;
5981 name_b = p->two->path;
5982 strip_prefix(opt->prefix_length, &name_a, &name_b);
5983 write_name_quoted(name_a, opt->file, inter_name_termination);
5984 write_name_quoted(name_b, opt->file, line_termination);
5985 } else {
5986 const char *name_a, *name_b;
5987 name_a = p->one->mode ? p->one->path : p->two->path;
5988 name_b = NULL;
5989 strip_prefix(opt->prefix_length, &name_a, &name_b);
5990 write_name_quoted(name_a, opt->file, line_termination);
5994 int diff_unmodified_pair(struct diff_filepair *p)
5996 /* This function is written stricter than necessary to support
5997 * the currently implemented transformers, but the idea is to
5998 * let transformers to produce diff_filepairs any way they want,
5999 * and filter and clean them up here before producing the output.
6001 struct diff_filespec *one = p->one, *two = p->two;
6003 if (DIFF_PAIR_UNMERGED(p))
6004 return 0; /* unmerged is interesting */
6006 /* deletion, addition, mode or type change
6007 * and rename are all interesting.
6009 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6010 DIFF_PAIR_MODE_CHANGED(p) ||
6011 strcmp(one->path, two->path))
6012 return 0;
6014 /* both are valid and point at the same path. that is, we are
6015 * dealing with a change.
6017 if (one->oid_valid && two->oid_valid &&
6018 oideq(&one->oid, &two->oid) &&
6019 !one->dirty_submodule && !two->dirty_submodule)
6020 return 1; /* no change */
6021 if (!one->oid_valid && !two->oid_valid)
6022 return 1; /* both look at the same file on the filesystem. */
6023 return 0;
6026 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6028 int include_conflict_headers =
6029 (additional_headers(o, p->one->path) &&
6030 !o->pickaxe_opts &&
6031 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6034 * Check if we can return early without showing a diff. Note that
6035 * diff_filepair only stores {oid, path, mode, is_valid}
6036 * information for each path, and thus diff_unmodified_pair() only
6037 * considers those bits of info. However, we do not want pairs
6038 * created by create_filepairs_for_header_only_notifications()
6039 * (which always look like unmodified pairs) to be ignored, so
6040 * return early if both p is unmodified AND we don't want to
6041 * include_conflict_headers.
6043 if (diff_unmodified_pair(p) && !include_conflict_headers)
6044 return;
6046 /* Actually, we can also return early to avoid showing tree diffs */
6047 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6048 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6049 return;
6051 run_diff(p, o);
6054 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6055 struct diffstat_t *diffstat)
6057 if (diff_unmodified_pair(p))
6058 return;
6060 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6061 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6062 return; /* no useful stat for tree diffs */
6064 run_diffstat(p, o, diffstat);
6067 static void diff_flush_checkdiff(struct diff_filepair *p,
6068 struct diff_options *o)
6070 if (diff_unmodified_pair(p))
6071 return;
6073 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6074 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6075 return; /* nothing to check in tree diffs */
6077 run_checkdiff(p, o);
6080 int diff_queue_is_empty(struct diff_options *o)
6082 struct diff_queue_struct *q = &diff_queued_diff;
6083 int i;
6084 int include_conflict_headers =
6085 (o->additional_path_headers &&
6086 strmap_get_size(o->additional_path_headers) &&
6087 !o->pickaxe_opts &&
6088 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6090 if (include_conflict_headers)
6091 return 0;
6093 for (i = 0; i < q->nr; i++)
6094 if (!diff_unmodified_pair(q->queue[i]))
6095 return 0;
6096 return 1;
6099 #if DIFF_DEBUG
6100 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6102 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6103 x, one ? one : "",
6104 s->path,
6105 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6106 s->mode,
6107 s->oid_valid ? oid_to_hex(&s->oid) : "");
6108 fprintf(stderr, "queue[%d] %s size %lu\n",
6109 x, one ? one : "",
6110 s->size);
6113 void diff_debug_filepair(const struct diff_filepair *p, int i)
6115 diff_debug_filespec(p->one, i, "one");
6116 diff_debug_filespec(p->two, i, "two");
6117 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6118 p->score, p->status ? p->status : '?',
6119 p->one->rename_used, p->broken_pair);
6122 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6124 int i;
6125 if (msg)
6126 fprintf(stderr, "%s\n", msg);
6127 fprintf(stderr, "q->nr = %d\n", q->nr);
6128 for (i = 0; i < q->nr; i++) {
6129 struct diff_filepair *p = q->queue[i];
6130 diff_debug_filepair(p, i);
6133 #endif
6135 static void diff_resolve_rename_copy(void)
6137 int i;
6138 struct diff_filepair *p;
6139 struct diff_queue_struct *q = &diff_queued_diff;
6141 diff_debug_queue("resolve-rename-copy", q);
6143 for (i = 0; i < q->nr; i++) {
6144 p = q->queue[i];
6145 p->status = 0; /* undecided */
6146 if (DIFF_PAIR_UNMERGED(p))
6147 p->status = DIFF_STATUS_UNMERGED;
6148 else if (!DIFF_FILE_VALID(p->one))
6149 p->status = DIFF_STATUS_ADDED;
6150 else if (!DIFF_FILE_VALID(p->two))
6151 p->status = DIFF_STATUS_DELETED;
6152 else if (DIFF_PAIR_TYPE_CHANGED(p))
6153 p->status = DIFF_STATUS_TYPE_CHANGED;
6155 /* from this point on, we are dealing with a pair
6156 * whose both sides are valid and of the same type, i.e.
6157 * either in-place edit or rename/copy edit.
6159 else if (DIFF_PAIR_RENAME(p)) {
6161 * A rename might have re-connected a broken
6162 * pair up, causing the pathnames to be the
6163 * same again. If so, that's not a rename at
6164 * all, just a modification..
6166 * Otherwise, see if this source was used for
6167 * multiple renames, in which case we decrement
6168 * the count, and call it a copy.
6170 if (!strcmp(p->one->path, p->two->path))
6171 p->status = DIFF_STATUS_MODIFIED;
6172 else if (--p->one->rename_used > 0)
6173 p->status = DIFF_STATUS_COPIED;
6174 else
6175 p->status = DIFF_STATUS_RENAMED;
6177 else if (!oideq(&p->one->oid, &p->two->oid) ||
6178 p->one->mode != p->two->mode ||
6179 p->one->dirty_submodule ||
6180 p->two->dirty_submodule ||
6181 is_null_oid(&p->one->oid))
6182 p->status = DIFF_STATUS_MODIFIED;
6183 else {
6184 /* This is a "no-change" entry and should not
6185 * happen anymore, but prepare for broken callers.
6187 error("feeding unmodified %s to diffcore",
6188 p->one->path);
6189 p->status = DIFF_STATUS_UNKNOWN;
6192 diff_debug_queue("resolve-rename-copy done", q);
6195 static int check_pair_status(struct diff_filepair *p)
6197 switch (p->status) {
6198 case DIFF_STATUS_UNKNOWN:
6199 return 0;
6200 case 0:
6201 die("internal error in diff-resolve-rename-copy");
6202 default:
6203 return 1;
6207 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6209 int fmt = opt->output_format;
6211 if (fmt & DIFF_FORMAT_CHECKDIFF)
6212 diff_flush_checkdiff(p, opt);
6213 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6214 diff_flush_raw(p, opt);
6215 else if (fmt & DIFF_FORMAT_NAME) {
6216 const char *name_a, *name_b;
6217 name_a = p->two->path;
6218 name_b = NULL;
6219 strip_prefix(opt->prefix_length, &name_a, &name_b);
6220 fprintf(opt->file, "%s", diff_line_prefix(opt));
6221 write_name_quoted(name_a, opt->file, opt->line_termination);
6224 opt->found_changes = 1;
6227 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6229 struct strbuf sb = STRBUF_INIT;
6230 if (fs->mode)
6231 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6232 else
6233 strbuf_addf(&sb, " %s ", newdelete);
6235 quote_c_style(fs->path, &sb, NULL, 0);
6236 strbuf_addch(&sb, '\n');
6237 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6238 sb.buf, sb.len, 0);
6239 strbuf_release(&sb);
6242 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6243 int show_name)
6245 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6246 struct strbuf sb = STRBUF_INIT;
6247 strbuf_addf(&sb, " mode change %06o => %06o",
6248 p->one->mode, p->two->mode);
6249 if (show_name) {
6250 strbuf_addch(&sb, ' ');
6251 quote_c_style(p->two->path, &sb, NULL, 0);
6253 strbuf_addch(&sb, '\n');
6254 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6255 sb.buf, sb.len, 0);
6256 strbuf_release(&sb);
6260 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6261 struct diff_filepair *p)
6263 struct strbuf sb = STRBUF_INIT;
6264 struct strbuf names = STRBUF_INIT;
6266 pprint_rename(&names, p->one->path, p->two->path);
6267 strbuf_addf(&sb, " %s %s (%d%%)\n",
6268 renamecopy, names.buf, similarity_index(p));
6269 strbuf_release(&names);
6270 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6271 sb.buf, sb.len, 0);
6272 show_mode_change(opt, p, 0);
6273 strbuf_release(&sb);
6276 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6278 switch(p->status) {
6279 case DIFF_STATUS_DELETED:
6280 show_file_mode_name(opt, "delete", p->one);
6281 break;
6282 case DIFF_STATUS_ADDED:
6283 show_file_mode_name(opt, "create", p->two);
6284 break;
6285 case DIFF_STATUS_COPIED:
6286 show_rename_copy(opt, "copy", p);
6287 break;
6288 case DIFF_STATUS_RENAMED:
6289 show_rename_copy(opt, "rename", p);
6290 break;
6291 default:
6292 if (p->score) {
6293 struct strbuf sb = STRBUF_INIT;
6294 strbuf_addstr(&sb, " rewrite ");
6295 quote_c_style(p->two->path, &sb, NULL, 0);
6296 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6297 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6298 sb.buf, sb.len, 0);
6299 strbuf_release(&sb);
6301 show_mode_change(opt, p, !p->score);
6302 break;
6306 struct patch_id_t {
6307 git_hash_ctx *ctx;
6308 int patchlen;
6311 static int remove_space(char *line, int len)
6313 int i;
6314 char *dst = line;
6315 unsigned char c;
6317 for (i = 0; i < len; i++)
6318 if (!isspace((c = line[i])))
6319 *dst++ = c;
6321 return dst - line;
6324 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6326 unsigned char hash[GIT_MAX_RAWSZ];
6327 unsigned short carry = 0;
6328 int i;
6330 the_hash_algo->final_fn(hash, ctx);
6331 the_hash_algo->init_fn(ctx);
6332 /* 20-byte sum, with carry */
6333 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6334 carry += result->hash[i] + hash[i];
6335 result->hash[i] = carry;
6336 carry >>= 8;
6340 static int patch_id_consume(void *priv, char *line, unsigned long len)
6342 struct patch_id_t *data = priv;
6343 int new_len;
6345 if (len > 12 && starts_with(line, "\\ "))
6346 return 0;
6347 new_len = remove_space(line, len);
6349 the_hash_algo->update_fn(data->ctx, line, new_len);
6350 data->patchlen += new_len;
6351 return 0;
6354 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6356 the_hash_algo->update_fn(ctx, str, strlen(str));
6359 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6361 /* large enough for 2^32 in octal */
6362 char buf[12];
6363 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6364 the_hash_algo->update_fn(ctx, buf, len);
6367 /* returns 0 upon success, and writes result into oid */
6368 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6370 struct diff_queue_struct *q = &diff_queued_diff;
6371 int i;
6372 git_hash_ctx ctx;
6373 struct patch_id_t data;
6375 the_hash_algo->init_fn(&ctx);
6376 memset(&data, 0, sizeof(struct patch_id_t));
6377 data.ctx = &ctx;
6378 oidclr(oid);
6380 for (i = 0; i < q->nr; i++) {
6381 xpparam_t xpp;
6382 xdemitconf_t xecfg;
6383 mmfile_t mf1, mf2;
6384 struct diff_filepair *p = q->queue[i];
6385 int len1, len2;
6387 memset(&xpp, 0, sizeof(xpp));
6388 memset(&xecfg, 0, sizeof(xecfg));
6389 if (p->status == 0)
6390 return error("internal diff status error");
6391 if (p->status == DIFF_STATUS_UNKNOWN)
6392 continue;
6393 if (diff_unmodified_pair(p))
6394 continue;
6395 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6396 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6397 continue;
6398 if (DIFF_PAIR_UNMERGED(p))
6399 continue;
6401 diff_fill_oid_info(p->one, options->repo->index);
6402 diff_fill_oid_info(p->two, options->repo->index);
6404 len1 = remove_space(p->one->path, strlen(p->one->path));
6405 len2 = remove_space(p->two->path, strlen(p->two->path));
6406 patch_id_add_string(&ctx, "diff--git");
6407 patch_id_add_string(&ctx, "a/");
6408 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6409 patch_id_add_string(&ctx, "b/");
6410 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6412 if (p->one->mode == 0) {
6413 patch_id_add_string(&ctx, "newfilemode");
6414 patch_id_add_mode(&ctx, p->two->mode);
6415 } else if (p->two->mode == 0) {
6416 patch_id_add_string(&ctx, "deletedfilemode");
6417 patch_id_add_mode(&ctx, p->one->mode);
6418 } else if (p->one->mode != p->two->mode) {
6419 patch_id_add_string(&ctx, "oldmode");
6420 patch_id_add_mode(&ctx, p->one->mode);
6421 patch_id_add_string(&ctx, "newmode");
6422 patch_id_add_mode(&ctx, p->two->mode);
6425 if (diff_header_only) {
6426 /* don't do anything since we're only populating header info */
6427 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6428 diff_filespec_is_binary(options->repo, p->two)) {
6429 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6430 the_hash_algo->hexsz);
6431 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6432 the_hash_algo->hexsz);
6433 } else {
6434 if (p->one->mode == 0) {
6435 patch_id_add_string(&ctx, "---/dev/null");
6436 patch_id_add_string(&ctx, "+++b/");
6437 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6438 } else if (p->two->mode == 0) {
6439 patch_id_add_string(&ctx, "---a/");
6440 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6441 patch_id_add_string(&ctx, "+++/dev/null");
6442 } else {
6443 patch_id_add_string(&ctx, "---a/");
6444 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6445 patch_id_add_string(&ctx, "+++b/");
6446 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6449 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6450 fill_mmfile(options->repo, &mf2, p->two) < 0)
6451 return error("unable to read files to diff");
6452 xpp.flags = 0;
6453 xecfg.ctxlen = 3;
6454 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6455 if (xdi_diff_outf(&mf1, &mf2, NULL,
6456 patch_id_consume, &data, &xpp, &xecfg))
6457 return error("unable to generate patch-id diff for %s",
6458 p->one->path);
6460 flush_one_hunk(oid, &ctx);
6463 return 0;
6466 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6468 struct diff_queue_struct *q = &diff_queued_diff;
6469 int result = diff_get_patch_id(options, oid, diff_header_only);
6471 diff_free_queue(q);
6472 DIFF_QUEUE_CLEAR(q);
6474 return result;
6477 static int is_summary_empty(const struct diff_queue_struct *q)
6479 int i;
6481 for (i = 0; i < q->nr; i++) {
6482 const struct diff_filepair *p = q->queue[i];
6484 switch (p->status) {
6485 case DIFF_STATUS_DELETED:
6486 case DIFF_STATUS_ADDED:
6487 case DIFF_STATUS_COPIED:
6488 case DIFF_STATUS_RENAMED:
6489 return 0;
6490 default:
6491 if (p->score)
6492 return 0;
6493 if (p->one->mode && p->two->mode &&
6494 p->one->mode != p->two->mode)
6495 return 0;
6496 break;
6499 return 1;
6502 static const char rename_limit_warning[] =
6503 N_("exhaustive rename detection was skipped due to too many files.");
6505 static const char degrade_cc_to_c_warning[] =
6506 N_("only found copies from modified paths due to too many files.");
6508 static const char rename_limit_advice[] =
6509 N_("you may want to set your %s variable to at least "
6510 "%d and retry the command.");
6512 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6514 fflush(stdout);
6515 if (degraded_cc)
6516 warning(_(degrade_cc_to_c_warning));
6517 else if (needed)
6518 warning(_(rename_limit_warning));
6519 else
6520 return;
6521 if (0 < needed)
6522 warning(_(rename_limit_advice), varname, needed);
6525 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6527 struct strset present;
6528 struct diff_queue_struct *q = &diff_queued_diff;
6529 struct hashmap_iter iter;
6530 struct strmap_entry *e;
6531 int i;
6533 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6536 * Find out which paths exist in diff_queued_diff, preferring
6537 * one->path for any pair that has multiple paths.
6539 for (i = 0; i < q->nr; i++) {
6540 struct diff_filepair *p = q->queue[i];
6541 char *path = p->one->path ? p->one->path : p->two->path;
6543 if (strmap_contains(o->additional_path_headers, path))
6544 strset_add(&present, path);
6548 * Loop over paths in additional_path_headers; for each NOT already
6549 * in diff_queued_diff, create a synthetic filepair and insert that
6550 * into diff_queued_diff.
6552 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6553 if (!strset_contains(&present, e->key)) {
6554 struct diff_filespec *one, *two;
6555 struct diff_filepair *p;
6557 one = alloc_filespec(e->key);
6558 two = alloc_filespec(e->key);
6559 fill_filespec(one, null_oid(), 0, 0);
6560 fill_filespec(two, null_oid(), 0, 0);
6561 p = diff_queue(q, one, two);
6562 p->status = DIFF_STATUS_MODIFIED;
6566 /* Re-sort the filepairs */
6567 diffcore_fix_diff_index();
6569 /* Cleanup */
6570 strset_clear(&present);
6573 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6575 int i;
6576 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6577 struct diff_queue_struct *q = &diff_queued_diff;
6579 if (WSEH_NEW & WS_RULE_MASK)
6580 BUG("WS rules bit mask overlaps with diff symbol flags");
6582 if (o->color_moved)
6583 o->emitted_symbols = &esm;
6585 if (o->additional_path_headers)
6586 create_filepairs_for_header_only_notifications(o);
6588 for (i = 0; i < q->nr; i++) {
6589 struct diff_filepair *p = q->queue[i];
6590 if (check_pair_status(p))
6591 diff_flush_patch(p, o);
6594 if (o->emitted_symbols) {
6595 if (o->color_moved) {
6596 struct mem_pool entry_pool;
6597 struct moved_entry_list *entry_list;
6599 mem_pool_init(&entry_pool, 1024 * 1024);
6600 entry_list = add_lines_to_move_detection(o,
6601 &entry_pool);
6602 mark_color_as_moved(o, entry_list);
6603 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6604 dim_moved_lines(o);
6606 mem_pool_discard(&entry_pool, 0);
6607 free(entry_list);
6610 for (i = 0; i < esm.nr; i++)
6611 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6613 for (i = 0; i < esm.nr; i++)
6614 free((void *)esm.buf[i].line);
6615 esm.nr = 0;
6617 o->emitted_symbols = NULL;
6621 static void diff_free_file(struct diff_options *options)
6623 if (options->close_file)
6624 fclose(options->file);
6627 static void diff_free_ignore_regex(struct diff_options *options)
6629 int i;
6631 for (i = 0; i < options->ignore_regex_nr; i++) {
6632 regfree(options->ignore_regex[i]);
6633 free(options->ignore_regex[i]);
6635 free(options->ignore_regex);
6638 void diff_free(struct diff_options *options)
6640 if (options->no_free)
6641 return;
6643 diff_free_file(options);
6644 diff_free_ignore_regex(options);
6645 clear_pathspec(&options->pathspec);
6648 void diff_flush(struct diff_options *options)
6650 struct diff_queue_struct *q = &diff_queued_diff;
6651 int i, output_format = options->output_format;
6652 int separator = 0;
6653 int dirstat_by_line = 0;
6656 * Order: raw, stat, summary, patch
6657 * or: name/name-status/checkdiff (other bits clear)
6659 if (!q->nr && !options->additional_path_headers)
6660 goto free_queue;
6662 if (output_format & (DIFF_FORMAT_RAW |
6663 DIFF_FORMAT_NAME |
6664 DIFF_FORMAT_NAME_STATUS |
6665 DIFF_FORMAT_CHECKDIFF)) {
6666 for (i = 0; i < q->nr; i++) {
6667 struct diff_filepair *p = q->queue[i];
6668 if (check_pair_status(p))
6669 flush_one_pair(p, options);
6671 separator++;
6674 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6675 dirstat_by_line = 1;
6677 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6678 dirstat_by_line) {
6679 struct diffstat_t diffstat;
6681 compute_diffstat(options, &diffstat, q);
6682 if (output_format & DIFF_FORMAT_NUMSTAT)
6683 show_numstat(&diffstat, options);
6684 if (output_format & DIFF_FORMAT_DIFFSTAT)
6685 show_stats(&diffstat, options);
6686 if (output_format & DIFF_FORMAT_SHORTSTAT)
6687 show_shortstats(&diffstat, options);
6688 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6689 show_dirstat_by_line(&diffstat, options);
6690 free_diffstat_info(&diffstat);
6691 separator++;
6693 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6694 show_dirstat(options);
6696 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6697 for (i = 0; i < q->nr; i++) {
6698 diff_summary(options, q->queue[i]);
6700 separator++;
6703 if (output_format & DIFF_FORMAT_PATCH) {
6704 if (separator) {
6705 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6706 if (options->stat_sep)
6707 /* attach patch instead of inline */
6708 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6709 NULL, 0, 0);
6712 diff_flush_patch_all_file_pairs(options);
6715 if (output_format & DIFF_FORMAT_CALLBACK)
6716 options->format_callback(q, options, options->format_callback_data);
6718 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6719 options->flags.exit_with_status &&
6720 options->flags.diff_from_contents) {
6722 * run diff_flush_patch for the exit status. setting
6723 * options->file to /dev/null should be safe, because we
6724 * aren't supposed to produce any output anyway.
6726 diff_free_file(options);
6727 options->file = xfopen("/dev/null", "w");
6728 options->close_file = 1;
6729 options->color_moved = 0;
6730 for (i = 0; i < q->nr; i++) {
6731 struct diff_filepair *p = q->queue[i];
6732 if (check_pair_status(p))
6733 diff_flush_patch(p, options);
6734 if (options->found_changes)
6735 break;
6739 free_queue:
6740 diff_free_queue(q);
6741 DIFF_QUEUE_CLEAR(q);
6742 diff_free(options);
6745 * Report the content-level differences with HAS_CHANGES;
6746 * diff_addremove/diff_change does not set the bit when
6747 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6749 if (options->flags.diff_from_contents) {
6750 if (options->found_changes)
6751 options->flags.has_changes = 1;
6752 else
6753 options->flags.has_changes = 0;
6757 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6759 return (((p->status == DIFF_STATUS_MODIFIED) &&
6760 ((p->score &&
6761 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6762 (!p->score &&
6763 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6764 ((p->status != DIFF_STATUS_MODIFIED) &&
6765 filter_bit_tst(p->status, options)));
6768 static void diffcore_apply_filter(struct diff_options *options)
6770 int i;
6771 struct diff_queue_struct *q = &diff_queued_diff;
6772 struct diff_queue_struct outq;
6774 DIFF_QUEUE_CLEAR(&outq);
6776 if (!options->filter)
6777 return;
6779 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6780 int found;
6781 for (i = found = 0; !found && i < q->nr; i++) {
6782 if (match_filter(options, q->queue[i]))
6783 found++;
6785 if (found)
6786 return;
6788 /* otherwise we will clear the whole queue
6789 * by copying the empty outq at the end of this
6790 * function, but first clear the current entries
6791 * in the queue.
6793 for (i = 0; i < q->nr; i++)
6794 diff_free_filepair(q->queue[i]);
6796 else {
6797 /* Only the matching ones */
6798 for (i = 0; i < q->nr; i++) {
6799 struct diff_filepair *p = q->queue[i];
6800 if (match_filter(options, p))
6801 diff_q(&outq, p);
6802 else
6803 diff_free_filepair(p);
6806 free(q->queue);
6807 *q = outq;
6810 /* Check whether two filespecs with the same mode and size are identical */
6811 static int diff_filespec_is_identical(struct repository *r,
6812 struct diff_filespec *one,
6813 struct diff_filespec *two)
6815 if (S_ISGITLINK(one->mode))
6816 return 0;
6817 if (diff_populate_filespec(r, one, NULL))
6818 return 0;
6819 if (diff_populate_filespec(r, two, NULL))
6820 return 0;
6821 return !memcmp(one->data, two->data, one->size);
6824 static int diff_filespec_check_stat_unmatch(struct repository *r,
6825 struct diff_filepair *p)
6827 struct diff_populate_filespec_options dpf_options = {
6828 .check_size_only = 1,
6829 .missing_object_cb = diff_queued_diff_prefetch,
6830 .missing_object_data = r,
6833 if (p->done_skip_stat_unmatch)
6834 return p->skip_stat_unmatch_result;
6836 p->done_skip_stat_unmatch = 1;
6837 p->skip_stat_unmatch_result = 0;
6839 * 1. Entries that come from stat info dirtiness
6840 * always have both sides (iow, not create/delete),
6841 * one side of the object name is unknown, with
6842 * the same mode and size. Keep the ones that
6843 * do not match these criteria. They have real
6844 * differences.
6846 * 2. At this point, the file is known to be modified,
6847 * with the same mode and size, and the object
6848 * name of one side is unknown. Need to inspect
6849 * the identical contents.
6851 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6852 !DIFF_FILE_VALID(p->two) ||
6853 (p->one->oid_valid && p->two->oid_valid) ||
6854 (p->one->mode != p->two->mode) ||
6855 diff_populate_filespec(r, p->one, &dpf_options) ||
6856 diff_populate_filespec(r, p->two, &dpf_options) ||
6857 (p->one->size != p->two->size) ||
6858 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6859 p->skip_stat_unmatch_result = 1;
6860 return p->skip_stat_unmatch_result;
6863 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6865 int i;
6866 struct diff_queue_struct *q = &diff_queued_diff;
6867 struct diff_queue_struct outq;
6868 DIFF_QUEUE_CLEAR(&outq);
6870 for (i = 0; i < q->nr; i++) {
6871 struct diff_filepair *p = q->queue[i];
6873 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6874 diff_q(&outq, p);
6875 else {
6877 * The caller can subtract 1 from skip_stat_unmatch
6878 * to determine how many paths were dirty only
6879 * due to stat info mismatch.
6881 if (!diffopt->flags.no_index)
6882 diffopt->skip_stat_unmatch++;
6883 diff_free_filepair(p);
6886 free(q->queue);
6887 *q = outq;
6890 static int diffnamecmp(const void *a_, const void *b_)
6892 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6893 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6894 const char *name_a, *name_b;
6896 name_a = a->one ? a->one->path : a->two->path;
6897 name_b = b->one ? b->one->path : b->two->path;
6898 return strcmp(name_a, name_b);
6901 void diffcore_fix_diff_index(void)
6903 struct diff_queue_struct *q = &diff_queued_diff;
6904 QSORT(q->queue, q->nr, diffnamecmp);
6907 void diff_add_if_missing(struct repository *r,
6908 struct oid_array *to_fetch,
6909 const struct diff_filespec *filespec)
6911 if (filespec && filespec->oid_valid &&
6912 !S_ISGITLINK(filespec->mode) &&
6913 oid_object_info_extended(r, &filespec->oid, NULL,
6914 OBJECT_INFO_FOR_PREFETCH))
6915 oid_array_append(to_fetch, &filespec->oid);
6918 void diff_queued_diff_prefetch(void *repository)
6920 struct repository *repo = repository;
6921 int i;
6922 struct diff_queue_struct *q = &diff_queued_diff;
6923 struct oid_array to_fetch = OID_ARRAY_INIT;
6925 for (i = 0; i < q->nr; i++) {
6926 struct diff_filepair *p = q->queue[i];
6927 diff_add_if_missing(repo, &to_fetch, p->one);
6928 diff_add_if_missing(repo, &to_fetch, p->two);
6932 * NEEDSWORK: Consider deduplicating the OIDs sent.
6934 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6936 oid_array_clear(&to_fetch);
6939 void init_diffstat_widths(struct diff_options *options)
6941 options->stat_width = -1; /* use full terminal width */
6942 options->stat_name_width = -1; /* respect diff.statNameWidth config */
6943 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
6946 void diffcore_std(struct diff_options *options)
6948 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6949 DIFF_FORMAT_NUMSTAT |
6950 DIFF_FORMAT_PATCH |
6951 DIFF_FORMAT_SHORTSTAT |
6952 DIFF_FORMAT_DIRSTAT;
6955 * Check if the user requested a blob-data-requiring diff output and/or
6956 * break-rewrite detection (which requires blob data). If yes, prefetch
6957 * the diff pairs.
6959 * If no prefetching occurs, diffcore_rename() will prefetch if it
6960 * decides that it needs inexact rename detection.
6962 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6963 (options->output_format & output_formats_to_prefetch ||
6964 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6965 diff_queued_diff_prefetch(options->repo);
6967 /* NOTE please keep the following in sync with diff_tree_combined() */
6968 if (options->skip_stat_unmatch)
6969 diffcore_skip_stat_unmatch(options);
6970 if (!options->found_follow) {
6971 /* See try_to_follow_renames() in tree-diff.c */
6972 if (options->break_opt != -1)
6973 diffcore_break(options->repo,
6974 options->break_opt);
6975 if (options->detect_rename)
6976 diffcore_rename(options);
6977 if (options->break_opt != -1)
6978 diffcore_merge_broken();
6980 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6981 diffcore_pickaxe(options);
6982 if (options->orderfile)
6983 diffcore_order(options->orderfile);
6984 if (options->rotate_to)
6985 diffcore_rotate(options);
6986 if (!options->found_follow)
6987 /* See try_to_follow_renames() in tree-diff.c */
6988 diff_resolve_rename_copy();
6989 diffcore_apply_filter(options);
6991 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6992 options->flags.has_changes = 1;
6993 else
6994 options->flags.has_changes = 0;
6996 options->found_follow = 0;
6999 int diff_result_code(struct diff_options *opt)
7001 int result = 0;
7003 diff_warn_rename_limit("diff.renameLimit",
7004 opt->needed_rename_limit,
7005 opt->degraded_cc_to_c);
7007 if (opt->flags.exit_with_status &&
7008 opt->flags.has_changes)
7009 result |= 01;
7010 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7011 opt->flags.check_failed)
7012 result |= 02;
7013 return result;
7016 int diff_can_quit_early(struct diff_options *opt)
7018 return (opt->flags.quick &&
7019 !opt->filter &&
7020 opt->flags.has_changes);
7024 * Shall changes to this submodule be ignored?
7026 * Submodule changes can be configured to be ignored separately for each path,
7027 * but that configuration can be overridden from the command line.
7029 static int is_submodule_ignored(const char *path, struct diff_options *options)
7031 int ignored = 0;
7032 struct diff_flags orig_flags = options->flags;
7033 if (!options->flags.override_submodule_config)
7034 set_diffopt_flags_from_submodule_config(options, path);
7035 if (options->flags.ignore_submodules)
7036 ignored = 1;
7037 options->flags = orig_flags;
7038 return ignored;
7041 void compute_diffstat(struct diff_options *options,
7042 struct diffstat_t *diffstat,
7043 struct diff_queue_struct *q)
7045 int i;
7047 memset(diffstat, 0, sizeof(struct diffstat_t));
7048 for (i = 0; i < q->nr; i++) {
7049 struct diff_filepair *p = q->queue[i];
7050 if (check_pair_status(p))
7051 diff_flush_stat(p, options, diffstat);
7053 options->found_changes = !!diffstat->nr;
7056 void diff_addremove(struct diff_options *options,
7057 int addremove, unsigned mode,
7058 const struct object_id *oid,
7059 int oid_valid,
7060 const char *concatpath, unsigned dirty_submodule)
7062 struct diff_filespec *one, *two;
7064 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7065 return;
7067 /* This may look odd, but it is a preparation for
7068 * feeding "there are unchanged files which should
7069 * not produce diffs, but when you are doing copy
7070 * detection you would need them, so here they are"
7071 * entries to the diff-core. They will be prefixed
7072 * with something like '=' or '*' (I haven't decided
7073 * which but should not make any difference).
7074 * Feeding the same new and old to diff_change()
7075 * also has the same effect.
7076 * Before the final output happens, they are pruned after
7077 * merged into rename/copy pairs as appropriate.
7079 if (options->flags.reverse_diff)
7080 addremove = (addremove == '+' ? '-' :
7081 addremove == '-' ? '+' : addremove);
7083 if (options->prefix &&
7084 strncmp(concatpath, options->prefix, options->prefix_length))
7085 return;
7087 one = alloc_filespec(concatpath);
7088 two = alloc_filespec(concatpath);
7090 if (addremove != '+')
7091 fill_filespec(one, oid, oid_valid, mode);
7092 if (addremove != '-') {
7093 fill_filespec(two, oid, oid_valid, mode);
7094 two->dirty_submodule = dirty_submodule;
7097 diff_queue(&diff_queued_diff, one, two);
7098 if (!options->flags.diff_from_contents)
7099 options->flags.has_changes = 1;
7102 void diff_change(struct diff_options *options,
7103 unsigned old_mode, unsigned new_mode,
7104 const struct object_id *old_oid,
7105 const struct object_id *new_oid,
7106 int old_oid_valid, int new_oid_valid,
7107 const char *concatpath,
7108 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7110 struct diff_filespec *one, *two;
7111 struct diff_filepair *p;
7113 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7114 is_submodule_ignored(concatpath, options))
7115 return;
7117 if (options->flags.reverse_diff) {
7118 SWAP(old_mode, new_mode);
7119 SWAP(old_oid, new_oid);
7120 SWAP(old_oid_valid, new_oid_valid);
7121 SWAP(old_dirty_submodule, new_dirty_submodule);
7124 if (options->prefix &&
7125 strncmp(concatpath, options->prefix, options->prefix_length))
7126 return;
7128 one = alloc_filespec(concatpath);
7129 two = alloc_filespec(concatpath);
7130 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7131 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7132 one->dirty_submodule = old_dirty_submodule;
7133 two->dirty_submodule = new_dirty_submodule;
7134 p = diff_queue(&diff_queued_diff, one, two);
7136 if (options->flags.diff_from_contents)
7137 return;
7139 if (options->flags.quick && options->skip_stat_unmatch &&
7140 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7141 diff_free_filespec_data(p->one);
7142 diff_free_filespec_data(p->two);
7143 return;
7146 options->flags.has_changes = 1;
7149 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7151 struct diff_filepair *pair;
7152 struct diff_filespec *one, *two;
7154 if (options->prefix &&
7155 strncmp(path, options->prefix, options->prefix_length))
7156 return NULL;
7158 one = alloc_filespec(path);
7159 two = alloc_filespec(path);
7160 pair = diff_queue(&diff_queued_diff, one, two);
7161 pair->is_unmerged = 1;
7162 return pair;
7165 static char *run_textconv(struct repository *r,
7166 const char *pgm,
7167 struct diff_filespec *spec,
7168 size_t *outsize)
7170 struct diff_tempfile *temp;
7171 struct child_process child = CHILD_PROCESS_INIT;
7172 struct strbuf buf = STRBUF_INIT;
7173 int err = 0;
7175 temp = prepare_temp_file(r, spec);
7176 strvec_push(&child.args, pgm);
7177 strvec_push(&child.args, temp->name);
7179 child.use_shell = 1;
7180 child.out = -1;
7181 if (start_command(&child)) {
7182 remove_tempfile();
7183 return NULL;
7186 if (strbuf_read(&buf, child.out, 0) < 0)
7187 err = error("error reading from textconv command '%s'", pgm);
7188 close(child.out);
7190 if (finish_command(&child) || err) {
7191 strbuf_release(&buf);
7192 remove_tempfile();
7193 return NULL;
7195 remove_tempfile();
7197 return strbuf_detach(&buf, outsize);
7200 size_t fill_textconv(struct repository *r,
7201 struct userdiff_driver *driver,
7202 struct diff_filespec *df,
7203 char **outbuf)
7205 size_t size;
7207 if (!driver) {
7208 if (!DIFF_FILE_VALID(df)) {
7209 *outbuf = "";
7210 return 0;
7212 if (diff_populate_filespec(r, df, NULL))
7213 die("unable to read files to diff");
7214 *outbuf = df->data;
7215 return df->size;
7218 if (!driver->textconv)
7219 BUG("fill_textconv called with non-textconv driver");
7221 if (driver->textconv_cache && df->oid_valid) {
7222 *outbuf = notes_cache_get(driver->textconv_cache,
7223 &df->oid,
7224 &size);
7225 if (*outbuf)
7226 return size;
7229 *outbuf = run_textconv(r, driver->textconv, df, &size);
7230 if (!*outbuf)
7231 die("unable to read files to diff");
7233 if (driver->textconv_cache && df->oid_valid) {
7234 /* ignore errors, as we might be in a readonly repository */
7235 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7236 size);
7238 * we could save up changes and flush them all at the end,
7239 * but we would need an extra call after all diffing is done.
7240 * Since generating a cache entry is the slow path anyway,
7241 * this extra overhead probably isn't a big deal.
7243 notes_cache_write(driver->textconv_cache);
7246 return size;
7249 int textconv_object(struct repository *r,
7250 const char *path,
7251 unsigned mode,
7252 const struct object_id *oid,
7253 int oid_valid,
7254 char **buf,
7255 unsigned long *buf_size)
7257 struct diff_filespec *df;
7258 struct userdiff_driver *textconv;
7260 df = alloc_filespec(path);
7261 fill_filespec(df, oid, oid_valid, mode);
7262 textconv = get_textconv(r, df);
7263 if (!textconv) {
7264 free_filespec(df);
7265 return 0;
7268 *buf_size = fill_textconv(r, textconv, df, buf);
7269 free_filespec(df);
7270 return 1;
7273 void setup_diff_pager(struct diff_options *opt)
7276 * If the user asked for our exit code, then either they want --quiet
7277 * or --exit-code. We should definitely not bother with a pager in the
7278 * former case, as we will generate no output. Since we still properly
7279 * report our exit code even when a pager is run, we _could_ run a
7280 * pager with --exit-code. But since we have not done so historically,
7281 * and because it is easy to find people oneline advising "git diff
7282 * --exit-code" in hooks and other scripts, we do not do so.
7284 if (!opt->flags.exit_with_status &&
7285 check_pager_config("diff") != 0)
7286 setup_pager();