trace2/tr2_tls.h: remove unnecessary include
[git.git] / diff.c
blob587341805c2c0abbe75108640c827319efcc69fd
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 "run-command.h"
20 #include "utf8.h"
21 #include "object-store-ll.h"
22 #include "userdiff.h"
23 #include "submodule.h"
24 #include "hashmap.h"
25 #include "mem-pool.h"
26 #include "merge-ll.h"
27 #include "string-list.h"
28 #include "strvec.h"
29 #include "graph.h"
30 #include "oid-array.h"
31 #include "packfile.h"
32 #include "pager.h"
33 #include "parse-options.h"
34 #include "help.h"
35 #include "promisor-remote.h"
36 #include "dir.h"
37 #include "object-file.h"
38 #include "object-name.h"
39 #include "read-cache-ll.h"
40 #include "setup.h"
41 #include "strmap.h"
42 #include "ws.h"
44 #ifdef NO_FAST_WORKING_DIRECTORY
45 #define FAST_WORKING_DIRECTORY 0
46 #else
47 #define FAST_WORKING_DIRECTORY 1
48 #endif
50 static int diff_detect_rename_default;
51 static int diff_indent_heuristic = 1;
52 static int diff_rename_limit_default = 1000;
53 static int diff_suppress_blank_empty;
54 static int diff_use_color_default = -1;
55 static int diff_color_moved_default;
56 static int diff_color_moved_ws_default;
57 static int diff_context_default = 3;
58 static int diff_interhunk_context_default;
59 static const char *diff_word_regex_cfg;
60 static const char *external_diff_cmd_cfg;
61 static const char *diff_order_file_cfg;
62 int diff_auto_refresh_index = 1;
63 static int diff_mnemonic_prefix;
64 static int diff_no_prefix;
65 static int diff_relative;
66 static int diff_stat_name_width;
67 static int diff_stat_graph_width;
68 static int diff_dirstat_permille_default = 30;
69 static struct diff_options default_diff_options;
70 static long diff_algorithm;
71 static unsigned ws_error_highlight_default = WSEH_NEW;
73 static char diff_colors[][COLOR_MAXLEN] = {
74 GIT_COLOR_RESET,
75 GIT_COLOR_NORMAL, /* CONTEXT */
76 GIT_COLOR_BOLD, /* METAINFO */
77 GIT_COLOR_CYAN, /* FRAGINFO */
78 GIT_COLOR_RED, /* OLD */
79 GIT_COLOR_GREEN, /* NEW */
80 GIT_COLOR_YELLOW, /* COMMIT */
81 GIT_COLOR_BG_RED, /* WHITESPACE */
82 GIT_COLOR_NORMAL, /* FUNCINFO */
83 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
84 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
85 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
86 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
87 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
88 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
89 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
90 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
91 GIT_COLOR_FAINT, /* CONTEXT_DIM */
92 GIT_COLOR_FAINT_RED, /* OLD_DIM */
93 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
94 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
95 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
96 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
99 static const char *color_diff_slots[] = {
100 [DIFF_CONTEXT] = "context",
101 [DIFF_METAINFO] = "meta",
102 [DIFF_FRAGINFO] = "frag",
103 [DIFF_FILE_OLD] = "old",
104 [DIFF_FILE_NEW] = "new",
105 [DIFF_COMMIT] = "commit",
106 [DIFF_WHITESPACE] = "whitespace",
107 [DIFF_FUNCINFO] = "func",
108 [DIFF_FILE_OLD_MOVED] = "oldMoved",
109 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
110 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
111 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
112 [DIFF_FILE_NEW_MOVED] = "newMoved",
113 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
114 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
115 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
116 [DIFF_CONTEXT_DIM] = "contextDimmed",
117 [DIFF_FILE_OLD_DIM] = "oldDimmed",
118 [DIFF_FILE_NEW_DIM] = "newDimmed",
119 [DIFF_CONTEXT_BOLD] = "contextBold",
120 [DIFF_FILE_OLD_BOLD] = "oldBold",
121 [DIFF_FILE_NEW_BOLD] = "newBold",
124 define_list_config_array_extra(color_diff_slots, {"plain"});
126 static int parse_diff_color_slot(const char *var)
128 if (!strcasecmp(var, "plain"))
129 return DIFF_CONTEXT;
130 return LOOKUP_CONFIG(color_diff_slots, var);
133 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
134 struct strbuf *errmsg)
136 char *params_copy = xstrdup(params_string);
137 struct string_list params = STRING_LIST_INIT_NODUP;
138 int ret = 0;
139 int i;
141 if (*params_copy)
142 string_list_split_in_place(&params, params_copy, ",", -1);
143 for (i = 0; i < params.nr; i++) {
144 const char *p = params.items[i].string;
145 if (!strcmp(p, "changes")) {
146 options->flags.dirstat_by_line = 0;
147 options->flags.dirstat_by_file = 0;
148 } else if (!strcmp(p, "lines")) {
149 options->flags.dirstat_by_line = 1;
150 options->flags.dirstat_by_file = 0;
151 } else if (!strcmp(p, "files")) {
152 options->flags.dirstat_by_line = 0;
153 options->flags.dirstat_by_file = 1;
154 } else if (!strcmp(p, "noncumulative")) {
155 options->flags.dirstat_cumulative = 0;
156 } else if (!strcmp(p, "cumulative")) {
157 options->flags.dirstat_cumulative = 1;
158 } else if (isdigit(*p)) {
159 char *end;
160 int permille = strtoul(p, &end, 10) * 10;
161 if (*end == '.' && isdigit(*++end)) {
162 /* only use first digit */
163 permille += *end - '0';
164 /* .. and ignore any further digits */
165 while (isdigit(*++end))
166 ; /* nothing */
168 if (!*end)
169 options->dirstat_permille = permille;
170 else {
171 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
173 ret++;
175 } else {
176 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
177 ret++;
181 string_list_clear(&params, 0);
182 free(params_copy);
183 return ret;
186 static int parse_submodule_params(struct diff_options *options, const char *value)
188 if (!strcmp(value, "log"))
189 options->submodule_format = DIFF_SUBMODULE_LOG;
190 else if (!strcmp(value, "short"))
191 options->submodule_format = DIFF_SUBMODULE_SHORT;
192 else if (!strcmp(value, "diff"))
193 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
195 * Please update $__git_diff_submodule_formats in
196 * git-completion.bash when you add new formats.
198 else
199 return -1;
200 return 0;
203 int git_config_rename(const char *var, const char *value)
205 if (!value)
206 return DIFF_DETECT_RENAME;
207 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
208 return DIFF_DETECT_COPY;
209 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
212 long parse_algorithm_value(const char *value)
214 if (!value)
215 return -1;
216 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
217 return 0;
218 else if (!strcasecmp(value, "minimal"))
219 return XDF_NEED_MINIMAL;
220 else if (!strcasecmp(value, "patience"))
221 return XDF_PATIENCE_DIFF;
222 else if (!strcasecmp(value, "histogram"))
223 return XDF_HISTOGRAM_DIFF;
225 * Please update $__git_diff_algorithms in git-completion.bash
226 * when you add new algorithms.
228 return -1;
231 static int parse_one_token(const char **arg, const char *token)
233 const char *rest;
234 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
235 *arg = rest;
236 return 1;
238 return 0;
241 static int parse_ws_error_highlight(const char *arg)
243 const char *orig_arg = arg;
244 unsigned val = 0;
246 while (*arg) {
247 if (parse_one_token(&arg, "none"))
248 val = 0;
249 else if (parse_one_token(&arg, "default"))
250 val = WSEH_NEW;
251 else if (parse_one_token(&arg, "all"))
252 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
253 else if (parse_one_token(&arg, "new"))
254 val |= WSEH_NEW;
255 else if (parse_one_token(&arg, "old"))
256 val |= WSEH_OLD;
257 else if (parse_one_token(&arg, "context"))
258 val |= WSEH_CONTEXT;
259 else {
260 return -1 - (int)(arg - orig_arg);
262 if (*arg)
263 arg++;
265 return val;
269 * These are to give UI layer defaults.
270 * The core-level commands such as git-diff-files should
271 * never be affected by the setting of diff.renames
272 * the user happens to have in the configuration file.
274 void init_diff_ui_defaults(void)
276 diff_detect_rename_default = DIFF_DETECT_RENAME;
279 int git_diff_heuristic_config(const char *var, const char *value,
280 void *cb UNUSED)
282 if (!strcmp(var, "diff.indentheuristic"))
283 diff_indent_heuristic = git_config_bool(var, value);
284 return 0;
287 static int parse_color_moved(const char *arg)
289 switch (git_parse_maybe_bool(arg)) {
290 case 0:
291 return COLOR_MOVED_NO;
292 case 1:
293 return COLOR_MOVED_DEFAULT;
294 default:
295 break;
298 if (!strcmp(arg, "no"))
299 return COLOR_MOVED_NO;
300 else if (!strcmp(arg, "plain"))
301 return COLOR_MOVED_PLAIN;
302 else if (!strcmp(arg, "blocks"))
303 return COLOR_MOVED_BLOCKS;
304 else if (!strcmp(arg, "zebra"))
305 return COLOR_MOVED_ZEBRA;
306 else if (!strcmp(arg, "default"))
307 return COLOR_MOVED_DEFAULT;
308 else if (!strcmp(arg, "dimmed-zebra"))
309 return COLOR_MOVED_ZEBRA_DIM;
310 else if (!strcmp(arg, "dimmed_zebra"))
311 return COLOR_MOVED_ZEBRA_DIM;
312 else
313 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
316 static unsigned parse_color_moved_ws(const char *arg)
318 int ret = 0;
319 struct string_list l = STRING_LIST_INIT_DUP;
320 struct string_list_item *i;
322 string_list_split(&l, arg, ',', -1);
324 for_each_string_list_item(i, &l) {
325 struct strbuf sb = STRBUF_INIT;
326 strbuf_addstr(&sb, i->string);
327 strbuf_trim(&sb);
329 if (!strcmp(sb.buf, "no"))
330 ret = 0;
331 else if (!strcmp(sb.buf, "ignore-space-change"))
332 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
333 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
334 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
335 else if (!strcmp(sb.buf, "ignore-all-space"))
336 ret |= XDF_IGNORE_WHITESPACE;
337 else if (!strcmp(sb.buf, "allow-indentation-change"))
338 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
339 else {
340 ret |= COLOR_MOVED_WS_ERROR;
341 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);
344 strbuf_release(&sb);
347 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
348 (ret & XDF_WHITESPACE_FLAGS)) {
349 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
350 ret |= COLOR_MOVED_WS_ERROR;
353 string_list_clear(&l, 0);
355 return ret;
358 int git_diff_ui_config(const char *var, const char *value,
359 const struct config_context *ctx, void *cb)
361 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
362 diff_use_color_default = git_config_colorbool(var, value);
363 return 0;
365 if (!strcmp(var, "diff.colormoved")) {
366 int cm = parse_color_moved(value);
367 if (cm < 0)
368 return -1;
369 diff_color_moved_default = cm;
370 return 0;
372 if (!strcmp(var, "diff.colormovedws")) {
373 unsigned cm = parse_color_moved_ws(value);
374 if (cm & COLOR_MOVED_WS_ERROR)
375 return -1;
376 diff_color_moved_ws_default = cm;
377 return 0;
379 if (!strcmp(var, "diff.context")) {
380 diff_context_default = git_config_int(var, value, ctx->kvi);
381 if (diff_context_default < 0)
382 return -1;
383 return 0;
385 if (!strcmp(var, "diff.interhunkcontext")) {
386 diff_interhunk_context_default = git_config_int(var, value,
387 ctx->kvi);
388 if (diff_interhunk_context_default < 0)
389 return -1;
390 return 0;
392 if (!strcmp(var, "diff.renames")) {
393 diff_detect_rename_default = git_config_rename(var, value);
394 return 0;
396 if (!strcmp(var, "diff.autorefreshindex")) {
397 diff_auto_refresh_index = git_config_bool(var, value);
398 return 0;
400 if (!strcmp(var, "diff.mnemonicprefix")) {
401 diff_mnemonic_prefix = git_config_bool(var, value);
402 return 0;
404 if (!strcmp(var, "diff.noprefix")) {
405 diff_no_prefix = git_config_bool(var, value);
406 return 0;
408 if (!strcmp(var, "diff.relative")) {
409 diff_relative = git_config_bool(var, value);
410 return 0;
412 if (!strcmp(var, "diff.statnamewidth")) {
413 diff_stat_name_width = git_config_int(var, value, ctx->kvi);
414 return 0;
416 if (!strcmp(var, "diff.statgraphwidth")) {
417 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
418 return 0;
420 if (!strcmp(var, "diff.external"))
421 return git_config_string(&external_diff_cmd_cfg, var, value);
422 if (!strcmp(var, "diff.wordregex"))
423 return git_config_string(&diff_word_regex_cfg, var, value);
424 if (!strcmp(var, "diff.orderfile"))
425 return git_config_pathname(&diff_order_file_cfg, var, value);
427 if (!strcmp(var, "diff.ignoresubmodules"))
428 handle_ignore_submodules_arg(&default_diff_options, value);
430 if (!strcmp(var, "diff.submodule")) {
431 if (parse_submodule_params(&default_diff_options, value))
432 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
433 value);
434 return 0;
437 if (!strcmp(var, "diff.algorithm")) {
438 diff_algorithm = parse_algorithm_value(value);
439 if (diff_algorithm < 0)
440 return -1;
441 return 0;
444 if (git_color_config(var, value, cb) < 0)
445 return -1;
447 return git_diff_basic_config(var, value, ctx, cb);
450 int git_diff_basic_config(const char *var, const char *value,
451 const struct config_context *ctx, void *cb)
453 const char *name;
455 if (!strcmp(var, "diff.renamelimit")) {
456 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
457 return 0;
460 if (userdiff_config(var, value) < 0)
461 return -1;
463 if (skip_prefix(var, "diff.color.", &name) ||
464 skip_prefix(var, "color.diff.", &name)) {
465 int slot = parse_diff_color_slot(name);
466 if (slot < 0)
467 return 0;
468 if (!value)
469 return config_error_nonbool(var);
470 return color_parse(value, diff_colors[slot]);
473 if (!strcmp(var, "diff.wserrorhighlight")) {
474 int val = parse_ws_error_highlight(value);
475 if (val < 0)
476 return -1;
477 ws_error_highlight_default = val;
478 return 0;
481 /* like GNU diff's --suppress-blank-empty option */
482 if (!strcmp(var, "diff.suppressblankempty") ||
483 /* for backwards compatibility */
484 !strcmp(var, "diff.suppress-blank-empty")) {
485 diff_suppress_blank_empty = git_config_bool(var, value);
486 return 0;
489 if (!strcmp(var, "diff.dirstat")) {
490 struct strbuf errmsg = STRBUF_INIT;
491 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
492 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
493 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
494 errmsg.buf);
495 strbuf_release(&errmsg);
496 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
497 return 0;
500 if (git_diff_heuristic_config(var, value, cb) < 0)
501 return -1;
503 return git_default_config(var, value, ctx, cb);
506 static char *quote_two(const char *one, const char *two)
508 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
509 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
510 struct strbuf res = STRBUF_INIT;
512 if (need_one + need_two) {
513 strbuf_addch(&res, '"');
514 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
515 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
516 strbuf_addch(&res, '"');
517 } else {
518 strbuf_addstr(&res, one);
519 strbuf_addstr(&res, two);
521 return strbuf_detach(&res, NULL);
524 static const char *external_diff(void)
526 static const char *external_diff_cmd = NULL;
527 static int done_preparing = 0;
529 if (done_preparing)
530 return external_diff_cmd;
531 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
532 if (!external_diff_cmd)
533 external_diff_cmd = external_diff_cmd_cfg;
534 done_preparing = 1;
535 return external_diff_cmd;
539 * Keep track of files used for diffing. Sometimes such an entry
540 * refers to a temporary file, sometimes to an existing file, and
541 * sometimes to "/dev/null".
543 static struct diff_tempfile {
545 * filename external diff should read from, or NULL if this
546 * entry is currently not in use:
548 const char *name;
550 char hex[GIT_MAX_HEXSZ + 1];
551 char mode[10];
554 * If this diff_tempfile instance refers to a temporary file,
555 * this tempfile object is used to manage its lifetime.
557 struct tempfile *tempfile;
558 } diff_temp[2];
560 struct emit_callback {
561 int color_diff;
562 unsigned ws_rule;
563 int blank_at_eof_in_preimage;
564 int blank_at_eof_in_postimage;
565 int lno_in_preimage;
566 int lno_in_postimage;
567 const char **label_path;
568 struct diff_words_data *diff_words;
569 struct diff_options *opt;
570 struct strbuf *header;
573 static int count_lines(const char *data, int size)
575 int count, ch, completely_empty = 1, nl_just_seen = 0;
576 count = 0;
577 while (0 < size--) {
578 ch = *data++;
579 if (ch == '\n') {
580 count++;
581 nl_just_seen = 1;
582 completely_empty = 0;
584 else {
585 nl_just_seen = 0;
586 completely_empty = 0;
589 if (completely_empty)
590 return 0;
591 if (!nl_just_seen)
592 count++; /* no trailing newline */
593 return count;
596 static int fill_mmfile(struct repository *r, mmfile_t *mf,
597 struct diff_filespec *one)
599 if (!DIFF_FILE_VALID(one)) {
600 mf->ptr = (char *)""; /* does not matter */
601 mf->size = 0;
602 return 0;
604 else if (diff_populate_filespec(r, one, NULL))
605 return -1;
607 mf->ptr = one->data;
608 mf->size = one->size;
609 return 0;
612 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
613 static unsigned long diff_filespec_size(struct repository *r,
614 struct diff_filespec *one)
616 struct diff_populate_filespec_options dpf_options = {
617 .check_size_only = 1,
620 if (!DIFF_FILE_VALID(one))
621 return 0;
622 diff_populate_filespec(r, one, &dpf_options);
623 return one->size;
626 static int count_trailing_blank(mmfile_t *mf)
628 char *ptr = mf->ptr;
629 long size = mf->size;
630 int cnt = 0;
632 if (!size)
633 return cnt;
634 ptr += size - 1; /* pointing at the very end */
635 if (*ptr != '\n')
636 ; /* incomplete line */
637 else
638 ptr--; /* skip the last LF */
639 while (mf->ptr < ptr) {
640 char *prev_eol;
641 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
642 if (*prev_eol == '\n')
643 break;
644 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
645 break;
646 cnt++;
647 ptr = prev_eol - 1;
649 return cnt;
652 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
653 struct emit_callback *ecbdata)
655 int l1, l2, at;
656 l1 = count_trailing_blank(mf1);
657 l2 = count_trailing_blank(mf2);
658 if (l2 <= l1) {
659 ecbdata->blank_at_eof_in_preimage = 0;
660 ecbdata->blank_at_eof_in_postimage = 0;
661 return;
663 at = count_lines(mf1->ptr, mf1->size);
664 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
666 at = count_lines(mf2->ptr, mf2->size);
667 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
670 static void emit_line_0(struct diff_options *o,
671 const char *set_sign, const char *set, unsigned reverse, const char *reset,
672 int first, const char *line, int len)
674 int has_trailing_newline, has_trailing_carriage_return;
675 int needs_reset = 0; /* at the end of the line */
676 FILE *file = o->file;
678 fputs(diff_line_prefix(o), file);
680 has_trailing_newline = (len > 0 && line[len-1] == '\n');
681 if (has_trailing_newline)
682 len--;
684 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
685 if (has_trailing_carriage_return)
686 len--;
688 if (!len && !first)
689 goto end_of_line;
691 if (reverse && want_color(o->use_color)) {
692 fputs(GIT_COLOR_REVERSE, file);
693 needs_reset = 1;
696 if (set_sign) {
697 fputs(set_sign, file);
698 needs_reset = 1;
701 if (first)
702 fputc(first, file);
704 if (!len)
705 goto end_of_line;
707 if (set) {
708 if (set_sign && set != set_sign)
709 fputs(reset, file);
710 fputs(set, file);
711 needs_reset = 1;
713 fwrite(line, len, 1, file);
714 needs_reset = 1; /* 'line' may contain color codes. */
716 end_of_line:
717 if (needs_reset)
718 fputs(reset, file);
719 if (has_trailing_carriage_return)
720 fputc('\r', file);
721 if (has_trailing_newline)
722 fputc('\n', file);
725 static void emit_line(struct diff_options *o, const char *set, const char *reset,
726 const char *line, int len)
728 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
731 enum diff_symbol {
732 DIFF_SYMBOL_BINARY_DIFF_HEADER,
733 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
734 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
735 DIFF_SYMBOL_BINARY_DIFF_BODY,
736 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
737 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
738 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
739 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
740 DIFF_SYMBOL_STATS_LINE,
741 DIFF_SYMBOL_WORD_DIFF,
742 DIFF_SYMBOL_STAT_SEP,
743 DIFF_SYMBOL_SUMMARY,
744 DIFF_SYMBOL_SUBMODULE_ADD,
745 DIFF_SYMBOL_SUBMODULE_DEL,
746 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
747 DIFF_SYMBOL_SUBMODULE_MODIFIED,
748 DIFF_SYMBOL_SUBMODULE_HEADER,
749 DIFF_SYMBOL_SUBMODULE_ERROR,
750 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
751 DIFF_SYMBOL_REWRITE_DIFF,
752 DIFF_SYMBOL_BINARY_FILES,
753 DIFF_SYMBOL_HEADER,
754 DIFF_SYMBOL_FILEPAIR_PLUS,
755 DIFF_SYMBOL_FILEPAIR_MINUS,
756 DIFF_SYMBOL_WORDS_PORCELAIN,
757 DIFF_SYMBOL_WORDS,
758 DIFF_SYMBOL_CONTEXT,
759 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
760 DIFF_SYMBOL_PLUS,
761 DIFF_SYMBOL_MINUS,
762 DIFF_SYMBOL_NO_LF_EOF,
763 DIFF_SYMBOL_CONTEXT_FRAGINFO,
764 DIFF_SYMBOL_CONTEXT_MARKER,
765 DIFF_SYMBOL_SEPARATOR
768 * Flags for content lines:
769 * 0..12 are whitespace rules
770 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
771 * 16 is marking if the line is blank at EOF
773 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
774 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
775 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
776 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
777 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
780 * This struct is used when we need to buffer the output of the diff output.
782 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
783 * into the pre/post image file. This pointer could be a union with the
784 * line pointer. By storing an offset into the file instead of the literal line,
785 * we can decrease the memory footprint for the buffered output. At first we
786 * may want to only have indirection for the content lines, but we could also
787 * enhance the state for emitting prefabricated lines, e.g. the similarity
788 * score line or hunk/file headers would only need to store a number or path
789 * and then the output can be constructed later on depending on state.
791 struct emitted_diff_symbol {
792 const char *line;
793 int len;
794 int flags;
795 int indent_off; /* Offset to first non-whitespace character */
796 int indent_width; /* The visual width of the indentation */
797 unsigned id;
798 enum diff_symbol s;
800 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
802 struct emitted_diff_symbols {
803 struct emitted_diff_symbol *buf;
804 int nr, alloc;
806 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
808 static void append_emitted_diff_symbol(struct diff_options *o,
809 struct emitted_diff_symbol *e)
811 struct emitted_diff_symbol *f;
813 ALLOC_GROW(o->emitted_symbols->buf,
814 o->emitted_symbols->nr + 1,
815 o->emitted_symbols->alloc);
816 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
818 memcpy(f, e, sizeof(struct emitted_diff_symbol));
819 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
822 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
824 if (!e)
825 return;
826 free(e->buf);
827 free(e);
830 struct moved_entry {
831 const struct emitted_diff_symbol *es;
832 struct moved_entry *next_line;
833 struct moved_entry *next_match;
836 struct moved_block {
837 struct moved_entry *match;
838 int wsd; /* The whitespace delta of this block */
841 #define INDENT_BLANKLINE INT_MIN
843 static void fill_es_indent_data(struct emitted_diff_symbol *es)
845 unsigned int off = 0, i;
846 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
847 const char *s = es->line;
848 const int len = es->len;
850 /* skip any \v \f \r at start of indentation */
851 while (s[off] == '\f' || s[off] == '\v' ||
852 (s[off] == '\r' && off < len - 1))
853 off++;
855 /* calculate the visual width of indentation */
856 while(1) {
857 if (s[off] == ' ') {
858 width++;
859 off++;
860 } else if (s[off] == '\t') {
861 width += tab_width - (width % tab_width);
862 while (s[++off] == '\t')
863 width += tab_width;
864 } else {
865 break;
869 /* check if this line is blank */
870 for (i = off; i < len; i++)
871 if (!isspace(s[i]))
872 break;
874 if (i == len) {
875 es->indent_width = INDENT_BLANKLINE;
876 es->indent_off = len;
877 } else {
878 es->indent_off = off;
879 es->indent_width = width;
883 static int compute_ws_delta(const struct emitted_diff_symbol *a,
884 const struct emitted_diff_symbol *b)
886 int a_width = a->indent_width,
887 b_width = b->indent_width;
889 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
890 return INDENT_BLANKLINE;
892 return a_width - b_width;
895 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
896 const struct emitted_diff_symbol *l,
897 struct moved_block *pmb)
899 int a_width = cur->es->indent_width, b_width = l->indent_width;
900 int delta;
902 /* The text of each line must match */
903 if (cur->es->id != l->id)
904 return 1;
907 * If 'l' and 'cur' are both blank then we don't need to check the
908 * indent. We only need to check cur as we know the strings match.
909 * */
910 if (a_width == INDENT_BLANKLINE)
911 return 0;
914 * The indent changes of the block are known and stored in pmb->wsd;
915 * however we need to check if the indent changes of the current line
916 * match those of the current block.
918 delta = b_width - a_width;
921 * If the previous lines of this block were all blank then set its
922 * whitespace delta.
924 if (pmb->wsd == INDENT_BLANKLINE)
925 pmb->wsd = delta;
927 return delta != pmb->wsd;
930 struct interned_diff_symbol {
931 struct hashmap_entry ent;
932 struct emitted_diff_symbol *es;
935 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
936 const struct hashmap_entry *eptr,
937 const struct hashmap_entry *entry_or_key,
938 const void *keydata UNUSED)
940 const struct diff_options *diffopt = hashmap_cmp_fn_data;
941 const struct emitted_diff_symbol *a, *b;
942 unsigned flags = diffopt->color_moved_ws_handling
943 & XDF_WHITESPACE_FLAGS;
945 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
946 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
948 return !xdiff_compare_lines(a->line + a->indent_off,
949 a->len - a->indent_off,
950 b->line + b->indent_off,
951 b->len - b->indent_off, flags);
954 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
955 struct interned_diff_symbol *s)
957 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
958 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
959 l->len - l->indent_off, flags);
961 hashmap_entry_init(&s->ent, hash);
962 s->es = l;
965 struct moved_entry_list {
966 struct moved_entry *add, *del;
969 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
970 struct mem_pool *entry_mem_pool)
972 struct moved_entry *prev_line = NULL;
973 struct mem_pool interned_pool;
974 struct hashmap interned_map;
975 struct moved_entry_list *entry_list = NULL;
976 size_t entry_list_alloc = 0;
977 unsigned id = 0;
978 int n;
980 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
981 mem_pool_init(&interned_pool, 1024 * 1024);
983 for (n = 0; n < o->emitted_symbols->nr; n++) {
984 struct interned_diff_symbol key;
985 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
986 struct interned_diff_symbol *s;
987 struct moved_entry *entry;
989 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
990 prev_line = NULL;
991 continue;
994 if (o->color_moved_ws_handling &
995 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
996 fill_es_indent_data(l);
998 prepare_entry(o, l, &key);
999 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1000 if (s) {
1001 l->id = s->es->id;
1002 } else {
1003 l->id = id;
1004 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1005 hashmap_add(&interned_map,
1006 memcpy(mem_pool_alloc(&interned_pool,
1007 sizeof(key)),
1008 &key, sizeof(key)));
1010 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1011 entry->es = l;
1012 entry->next_line = NULL;
1013 if (prev_line && prev_line->es->s == l->s)
1014 prev_line->next_line = entry;
1015 prev_line = entry;
1016 if (l->s == DIFF_SYMBOL_PLUS) {
1017 entry->next_match = entry_list[l->id].add;
1018 entry_list[l->id].add = entry;
1019 } else {
1020 entry->next_match = entry_list[l->id].del;
1021 entry_list[l->id].del = entry;
1025 hashmap_clear(&interned_map);
1026 mem_pool_discard(&interned_pool, 0);
1028 return entry_list;
1031 static void pmb_advance_or_null(struct diff_options *o,
1032 struct emitted_diff_symbol *l,
1033 struct moved_block *pmb,
1034 int *pmb_nr)
1036 int i, j;
1038 for (i = 0, j = 0; i < *pmb_nr; i++) {
1039 int match;
1040 struct moved_entry *prev = pmb[i].match;
1041 struct moved_entry *cur = (prev && prev->next_line) ?
1042 prev->next_line : NULL;
1044 if (o->color_moved_ws_handling &
1045 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1046 match = cur &&
1047 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1048 else
1049 match = cur && cur->es->id == l->id;
1051 if (match) {
1052 pmb[j] = pmb[i];
1053 pmb[j++].match = cur;
1056 *pmb_nr = j;
1059 static void fill_potential_moved_blocks(struct diff_options *o,
1060 struct moved_entry *match,
1061 struct emitted_diff_symbol *l,
1062 struct moved_block **pmb_p,
1063 int *pmb_alloc_p, int *pmb_nr_p)
1066 struct moved_block *pmb = *pmb_p;
1067 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1070 * The current line is the start of a new block.
1071 * Setup the set of potential blocks.
1073 for (; match; match = match->next_match) {
1074 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1075 if (o->color_moved_ws_handling &
1076 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1077 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1078 else
1079 pmb[pmb_nr].wsd = 0;
1080 pmb[pmb_nr++].match = match;
1083 *pmb_p = pmb;
1084 *pmb_alloc_p = pmb_alloc;
1085 *pmb_nr_p = pmb_nr;
1089 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1091 * Otherwise, if the last block has fewer alphanumeric characters than
1092 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1093 * that block.
1095 * The last block consists of the (n - block_length)'th line up to but not
1096 * including the nth line.
1098 * Returns 0 if the last block is empty or is unset by this function, non zero
1099 * otherwise.
1101 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1102 * Think of a way to unify them.
1104 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1105 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1106 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1108 int i, alnum_count = 0;
1109 if (o->color_moved == COLOR_MOVED_PLAIN)
1110 return block_length;
1111 for (i = 1; i < block_length + 1; i++) {
1112 const char *c = o->emitted_symbols->buf[n - i].line;
1113 for (; *c; c++) {
1114 if (!isalnum(*c))
1115 continue;
1116 alnum_count++;
1117 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1118 return 1;
1121 for (i = 1; i < block_length + 1; i++)
1122 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1123 return 0;
1126 /* Find blocks of moved code, delegate actual coloring decision to helper */
1127 static void mark_color_as_moved(struct diff_options *o,
1128 struct moved_entry_list *entry_list)
1130 struct moved_block *pmb = NULL; /* potentially moved blocks */
1131 int pmb_nr = 0, pmb_alloc = 0;
1132 int n, flipped_block = 0, block_length = 0;
1133 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1136 for (n = 0; n < o->emitted_symbols->nr; n++) {
1137 struct moved_entry *match = NULL;
1138 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1140 switch (l->s) {
1141 case DIFF_SYMBOL_PLUS:
1142 match = entry_list[l->id].del;
1143 break;
1144 case DIFF_SYMBOL_MINUS:
1145 match = entry_list[l->id].add;
1146 break;
1147 default:
1148 flipped_block = 0;
1151 if (pmb_nr && (!match || l->s != moved_symbol)) {
1152 if (!adjust_last_block(o, n, block_length) &&
1153 block_length > 1) {
1155 * Rewind in case there is another match
1156 * starting at the second line of the block
1158 match = NULL;
1159 n -= block_length;
1161 pmb_nr = 0;
1162 block_length = 0;
1163 flipped_block = 0;
1165 if (!match) {
1166 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1167 continue;
1170 if (o->color_moved == COLOR_MOVED_PLAIN) {
1171 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1172 continue;
1175 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1177 if (pmb_nr == 0) {
1178 int contiguous = adjust_last_block(o, n, block_length);
1180 if (!contiguous && block_length > 1)
1182 * Rewind in case there is another match
1183 * starting at the second line of the block
1185 n -= block_length;
1186 else
1187 fill_potential_moved_blocks(o, match, l,
1188 &pmb, &pmb_alloc,
1189 &pmb_nr);
1191 if (contiguous && pmb_nr && moved_symbol == l->s)
1192 flipped_block = (flipped_block + 1) % 2;
1193 else
1194 flipped_block = 0;
1196 if (pmb_nr)
1197 moved_symbol = l->s;
1198 else
1199 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1201 block_length = 0;
1204 if (pmb_nr) {
1205 block_length++;
1206 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1207 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1208 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1211 adjust_last_block(o, n, block_length);
1213 free(pmb);
1216 static void dim_moved_lines(struct diff_options *o)
1218 int n;
1219 for (n = 0; n < o->emitted_symbols->nr; n++) {
1220 struct emitted_diff_symbol *prev = (n != 0) ?
1221 &o->emitted_symbols->buf[n - 1] : NULL;
1222 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1223 struct emitted_diff_symbol *next =
1224 (n < o->emitted_symbols->nr - 1) ?
1225 &o->emitted_symbols->buf[n + 1] : NULL;
1227 /* Not a plus or minus line? */
1228 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1229 continue;
1231 /* Not a moved line? */
1232 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1233 continue;
1236 * If prev or next are not a plus or minus line,
1237 * pretend they don't exist
1239 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1240 prev->s != DIFF_SYMBOL_MINUS)
1241 prev = NULL;
1242 if (next && next->s != DIFF_SYMBOL_PLUS &&
1243 next->s != DIFF_SYMBOL_MINUS)
1244 next = NULL;
1246 /* Inside a block? */
1247 if ((prev &&
1248 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1249 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1250 (next &&
1251 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1252 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1253 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1254 continue;
1257 /* Check if we are at an interesting bound: */
1258 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1259 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1260 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1261 continue;
1262 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1263 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1264 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1265 continue;
1268 * The boundary to prev and next are not interesting,
1269 * so this line is not interesting as a whole
1271 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1275 static void emit_line_ws_markup(struct diff_options *o,
1276 const char *set_sign, const char *set,
1277 const char *reset,
1278 int sign_index, const char *line, int len,
1279 unsigned ws_rule, int blank_at_eof)
1281 const char *ws = NULL;
1282 int sign = o->output_indicators[sign_index];
1284 if (o->ws_error_highlight & ws_rule) {
1285 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1286 if (!*ws)
1287 ws = NULL;
1290 if (!ws && !set_sign)
1291 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1292 else if (!ws) {
1293 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1294 } else if (blank_at_eof)
1295 /* Blank line at EOF - paint '+' as well */
1296 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1297 else {
1298 /* Emit just the prefix, then the rest. */
1299 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1300 sign, "", 0);
1301 ws_check_emit(line, len, ws_rule,
1302 o->file, set, reset, ws);
1306 static void emit_diff_symbol_from_struct(struct diff_options *o,
1307 struct emitted_diff_symbol *eds)
1309 static const char *nneof = " No newline at end of file\n";
1310 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1312 enum diff_symbol s = eds->s;
1313 const char *line = eds->line;
1314 int len = eds->len;
1315 unsigned flags = eds->flags;
1317 switch (s) {
1318 case DIFF_SYMBOL_NO_LF_EOF:
1319 context = diff_get_color_opt(o, DIFF_CONTEXT);
1320 reset = diff_get_color_opt(o, DIFF_RESET);
1321 putc('\n', o->file);
1322 emit_line_0(o, context, NULL, 0, reset, '\\',
1323 nneof, strlen(nneof));
1324 break;
1325 case DIFF_SYMBOL_SUBMODULE_HEADER:
1326 case DIFF_SYMBOL_SUBMODULE_ERROR:
1327 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1328 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1329 case DIFF_SYMBOL_SUMMARY:
1330 case DIFF_SYMBOL_STATS_LINE:
1331 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1332 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1333 emit_line(o, "", "", line, len);
1334 break;
1335 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1336 case DIFF_SYMBOL_CONTEXT_MARKER:
1337 context = diff_get_color_opt(o, DIFF_CONTEXT);
1338 reset = diff_get_color_opt(o, DIFF_RESET);
1339 emit_line(o, context, reset, line, len);
1340 break;
1341 case DIFF_SYMBOL_SEPARATOR:
1342 fprintf(o->file, "%s%c",
1343 diff_line_prefix(o),
1344 o->line_termination);
1345 break;
1346 case DIFF_SYMBOL_CONTEXT:
1347 set = diff_get_color_opt(o, DIFF_CONTEXT);
1348 reset = diff_get_color_opt(o, DIFF_RESET);
1349 set_sign = NULL;
1350 if (o->flags.dual_color_diffed_diffs) {
1351 char c = !len ? 0 : line[0];
1353 if (c == '+')
1354 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1355 else if (c == '@')
1356 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1357 else if (c == '-')
1358 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1360 emit_line_ws_markup(o, set_sign, set, reset,
1361 OUTPUT_INDICATOR_CONTEXT, line, len,
1362 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1363 break;
1364 case DIFF_SYMBOL_PLUS:
1365 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1366 DIFF_SYMBOL_MOVED_LINE_ALT |
1367 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1368 case DIFF_SYMBOL_MOVED_LINE |
1369 DIFF_SYMBOL_MOVED_LINE_ALT |
1370 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1371 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1372 break;
1373 case DIFF_SYMBOL_MOVED_LINE |
1374 DIFF_SYMBOL_MOVED_LINE_ALT:
1375 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1376 break;
1377 case DIFF_SYMBOL_MOVED_LINE |
1378 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1379 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1380 break;
1381 case DIFF_SYMBOL_MOVED_LINE:
1382 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1383 break;
1384 default:
1385 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1387 reset = diff_get_color_opt(o, DIFF_RESET);
1388 if (!o->flags.dual_color_diffed_diffs)
1389 set_sign = NULL;
1390 else {
1391 char c = !len ? 0 : line[0];
1393 set_sign = set;
1394 if (c == '-')
1395 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1396 else if (c == '@')
1397 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1398 else if (c == '+')
1399 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1400 else
1401 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1402 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1404 emit_line_ws_markup(o, set_sign, set, reset,
1405 OUTPUT_INDICATOR_NEW, line, len,
1406 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1407 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1408 break;
1409 case DIFF_SYMBOL_MINUS:
1410 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1411 DIFF_SYMBOL_MOVED_LINE_ALT |
1412 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1413 case DIFF_SYMBOL_MOVED_LINE |
1414 DIFF_SYMBOL_MOVED_LINE_ALT |
1415 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1416 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1417 break;
1418 case DIFF_SYMBOL_MOVED_LINE |
1419 DIFF_SYMBOL_MOVED_LINE_ALT:
1420 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1421 break;
1422 case DIFF_SYMBOL_MOVED_LINE |
1423 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1424 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1425 break;
1426 case DIFF_SYMBOL_MOVED_LINE:
1427 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1428 break;
1429 default:
1430 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1432 reset = diff_get_color_opt(o, DIFF_RESET);
1433 if (!o->flags.dual_color_diffed_diffs)
1434 set_sign = NULL;
1435 else {
1436 char c = !len ? 0 : line[0];
1438 set_sign = set;
1439 if (c == '+')
1440 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1441 else if (c == '@')
1442 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1443 else if (c == '-')
1444 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1445 else
1446 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1448 emit_line_ws_markup(o, set_sign, set, reset,
1449 OUTPUT_INDICATOR_OLD, line, len,
1450 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1451 break;
1452 case DIFF_SYMBOL_WORDS_PORCELAIN:
1453 context = diff_get_color_opt(o, DIFF_CONTEXT);
1454 reset = diff_get_color_opt(o, DIFF_RESET);
1455 emit_line(o, context, reset, line, len);
1456 fputs("~\n", o->file);
1457 break;
1458 case DIFF_SYMBOL_WORDS:
1459 context = diff_get_color_opt(o, DIFF_CONTEXT);
1460 reset = diff_get_color_opt(o, DIFF_RESET);
1462 * Skip the prefix character, if any. With
1463 * diff_suppress_blank_empty, there may be
1464 * none.
1466 if (line[0] != '\n') {
1467 line++;
1468 len--;
1470 emit_line(o, context, reset, line, len);
1471 break;
1472 case DIFF_SYMBOL_FILEPAIR_PLUS:
1473 meta = diff_get_color_opt(o, DIFF_METAINFO);
1474 reset = diff_get_color_opt(o, DIFF_RESET);
1475 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1476 line, reset,
1477 strchr(line, ' ') ? "\t" : "");
1478 break;
1479 case DIFF_SYMBOL_FILEPAIR_MINUS:
1480 meta = diff_get_color_opt(o, DIFF_METAINFO);
1481 reset = diff_get_color_opt(o, DIFF_RESET);
1482 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1483 line, reset,
1484 strchr(line, ' ') ? "\t" : "");
1485 break;
1486 case DIFF_SYMBOL_BINARY_FILES:
1487 case DIFF_SYMBOL_HEADER:
1488 fprintf(o->file, "%s", line);
1489 break;
1490 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1491 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1492 break;
1493 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1494 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1495 break;
1496 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1497 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1498 break;
1499 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1500 fputs(diff_line_prefix(o), o->file);
1501 fputc('\n', o->file);
1502 break;
1503 case DIFF_SYMBOL_REWRITE_DIFF:
1504 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1505 reset = diff_get_color_opt(o, DIFF_RESET);
1506 emit_line(o, fraginfo, reset, line, len);
1507 break;
1508 case DIFF_SYMBOL_SUBMODULE_ADD:
1509 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1510 reset = diff_get_color_opt(o, DIFF_RESET);
1511 emit_line(o, set, reset, line, len);
1512 break;
1513 case DIFF_SYMBOL_SUBMODULE_DEL:
1514 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1515 reset = diff_get_color_opt(o, DIFF_RESET);
1516 emit_line(o, set, reset, line, len);
1517 break;
1518 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1519 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1520 diff_line_prefix(o), line);
1521 break;
1522 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1523 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1524 diff_line_prefix(o), line);
1525 break;
1526 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1527 emit_line(o, "", "", " 0 files changed\n",
1528 strlen(" 0 files changed\n"));
1529 break;
1530 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1531 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1532 break;
1533 case DIFF_SYMBOL_WORD_DIFF:
1534 fprintf(o->file, "%.*s", len, line);
1535 break;
1536 case DIFF_SYMBOL_STAT_SEP:
1537 fputs(o->stat_sep, o->file);
1538 break;
1539 default:
1540 BUG("unknown diff symbol");
1544 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1545 const char *line, int len, unsigned flags)
1547 struct emitted_diff_symbol e = {
1548 .line = line, .len = len, .flags = flags, .s = s
1551 if (o->emitted_symbols)
1552 append_emitted_diff_symbol(o, &e);
1553 else
1554 emit_diff_symbol_from_struct(o, &e);
1557 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1559 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1562 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1564 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1567 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1569 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1570 path, strlen(path), 0);
1573 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1575 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1576 path, strlen(path), 0);
1579 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1581 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1582 header, strlen(header), 0);
1585 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1587 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1590 void diff_emit_submodule_pipethrough(struct diff_options *o,
1591 const char *line, int len)
1593 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1596 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1598 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1599 ecbdata->blank_at_eof_in_preimage &&
1600 ecbdata->blank_at_eof_in_postimage &&
1601 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1602 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1603 return 0;
1604 return ws_blank_line(line, len);
1607 static void emit_add_line(struct emit_callback *ecbdata,
1608 const char *line, int len)
1610 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1611 if (new_blank_line_at_eof(ecbdata, line, len))
1612 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1614 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1617 static void emit_del_line(struct emit_callback *ecbdata,
1618 const char *line, int len)
1620 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1621 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1624 static void emit_context_line(struct emit_callback *ecbdata,
1625 const char *line, int len)
1627 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1628 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1631 static void emit_hunk_header(struct emit_callback *ecbdata,
1632 const char *line, int len)
1634 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1635 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1636 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1637 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1638 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1639 static const char atat[2] = { '@', '@' };
1640 const char *cp, *ep;
1641 struct strbuf msgbuf = STRBUF_INIT;
1642 int org_len = len;
1643 int i = 1;
1646 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1647 * it always is at least 10 bytes long.
1649 if (len < 10 ||
1650 memcmp(line, atat, 2) ||
1651 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1652 emit_diff_symbol(ecbdata->opt,
1653 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1654 return;
1656 ep += 2; /* skip over @@ */
1658 /* The hunk header in fraginfo color */
1659 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1660 strbuf_addstr(&msgbuf, reverse);
1661 strbuf_addstr(&msgbuf, frag);
1662 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1663 strbuf_add(&msgbuf, atat, sizeof(atat));
1664 else
1665 strbuf_add(&msgbuf, line, ep - line);
1666 strbuf_addstr(&msgbuf, reset);
1669 * trailing "\r\n"
1671 for ( ; i < 3; i++)
1672 if (line[len - i] == '\r' || line[len - i] == '\n')
1673 len--;
1675 /* blank before the func header */
1676 for (cp = ep; ep - line < len; ep++)
1677 if (*ep != ' ' && *ep != '\t')
1678 break;
1679 if (ep != cp) {
1680 strbuf_addstr(&msgbuf, context);
1681 strbuf_add(&msgbuf, cp, ep - cp);
1682 strbuf_addstr(&msgbuf, reset);
1685 if (ep < line + len) {
1686 strbuf_addstr(&msgbuf, func);
1687 strbuf_add(&msgbuf, ep, line + len - ep);
1688 strbuf_addstr(&msgbuf, reset);
1691 strbuf_add(&msgbuf, line + len, org_len - len);
1692 strbuf_complete_line(&msgbuf);
1693 emit_diff_symbol(ecbdata->opt,
1694 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1695 strbuf_release(&msgbuf);
1698 static struct diff_tempfile *claim_diff_tempfile(void)
1700 int i;
1701 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1702 if (!diff_temp[i].name)
1703 return diff_temp + i;
1704 BUG("diff is failing to clean up its tempfiles");
1707 static void remove_tempfile(void)
1709 int i;
1710 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1711 if (is_tempfile_active(diff_temp[i].tempfile))
1712 delete_tempfile(&diff_temp[i].tempfile);
1713 diff_temp[i].name = NULL;
1717 static void add_line_count(struct strbuf *out, int count)
1719 switch (count) {
1720 case 0:
1721 strbuf_addstr(out, "0,0");
1722 break;
1723 case 1:
1724 strbuf_addstr(out, "1");
1725 break;
1726 default:
1727 strbuf_addf(out, "1,%d", count);
1728 break;
1732 static void emit_rewrite_lines(struct emit_callback *ecb,
1733 int prefix, const char *data, int size)
1735 const char *endp = NULL;
1737 while (0 < size) {
1738 int len;
1740 endp = memchr(data, '\n', size);
1741 len = endp ? (endp - data + 1) : size;
1742 if (prefix != '+') {
1743 ecb->lno_in_preimage++;
1744 emit_del_line(ecb, data, len);
1745 } else {
1746 ecb->lno_in_postimage++;
1747 emit_add_line(ecb, data, len);
1749 size -= len;
1750 data += len;
1752 if (!endp)
1753 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1756 static void emit_rewrite_diff(const char *name_a,
1757 const char *name_b,
1758 struct diff_filespec *one,
1759 struct diff_filespec *two,
1760 struct userdiff_driver *textconv_one,
1761 struct userdiff_driver *textconv_two,
1762 struct diff_options *o)
1764 int lc_a, lc_b;
1765 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1766 const char *a_prefix, *b_prefix;
1767 char *data_one, *data_two;
1768 size_t size_one, size_two;
1769 struct emit_callback ecbdata;
1770 struct strbuf out = STRBUF_INIT;
1772 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1773 a_prefix = o->b_prefix;
1774 b_prefix = o->a_prefix;
1775 } else {
1776 a_prefix = o->a_prefix;
1777 b_prefix = o->b_prefix;
1780 name_a += (*name_a == '/');
1781 name_b += (*name_b == '/');
1783 strbuf_reset(&a_name);
1784 strbuf_reset(&b_name);
1785 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1786 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1788 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1789 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1791 memset(&ecbdata, 0, sizeof(ecbdata));
1792 ecbdata.color_diff = want_color(o->use_color);
1793 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1794 ecbdata.opt = o;
1795 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1796 mmfile_t mf1, mf2;
1797 mf1.ptr = (char *)data_one;
1798 mf2.ptr = (char *)data_two;
1799 mf1.size = size_one;
1800 mf2.size = size_two;
1801 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1803 ecbdata.lno_in_preimage = 1;
1804 ecbdata.lno_in_postimage = 1;
1806 lc_a = count_lines(data_one, size_one);
1807 lc_b = count_lines(data_two, size_two);
1809 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1810 a_name.buf, a_name.len, 0);
1811 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1812 b_name.buf, b_name.len, 0);
1814 strbuf_addstr(&out, "@@ -");
1815 if (!o->irreversible_delete)
1816 add_line_count(&out, lc_a);
1817 else
1818 strbuf_addstr(&out, "?,?");
1819 strbuf_addstr(&out, " +");
1820 add_line_count(&out, lc_b);
1821 strbuf_addstr(&out, " @@\n");
1822 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1823 strbuf_release(&out);
1825 if (lc_a && !o->irreversible_delete)
1826 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1827 if (lc_b)
1828 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1829 if (textconv_one)
1830 free((char *)data_one);
1831 if (textconv_two)
1832 free((char *)data_two);
1835 struct diff_words_buffer {
1836 mmfile_t text;
1837 unsigned long alloc;
1838 struct diff_words_orig {
1839 const char *begin, *end;
1840 } *orig;
1841 int orig_nr, orig_alloc;
1844 static void diff_words_append(char *line, unsigned long len,
1845 struct diff_words_buffer *buffer)
1847 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1848 line++;
1849 len--;
1850 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1851 buffer->text.size += len;
1852 buffer->text.ptr[buffer->text.size] = '\0';
1855 struct diff_words_style_elem {
1856 const char *prefix;
1857 const char *suffix;
1858 const char *color; /* NULL; filled in by the setup code if
1859 * color is enabled */
1862 struct diff_words_style {
1863 enum diff_words_type type;
1864 struct diff_words_style_elem new_word, old_word, ctx;
1865 const char *newline;
1868 static struct diff_words_style diff_words_styles[] = {
1869 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1870 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1871 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1874 struct diff_words_data {
1875 struct diff_words_buffer minus, plus;
1876 const char *current_plus;
1877 int last_minus;
1878 struct diff_options *opt;
1879 regex_t *word_regex;
1880 enum diff_words_type type;
1881 struct diff_words_style *style;
1884 static int fn_out_diff_words_write_helper(struct diff_options *o,
1885 struct diff_words_style_elem *st_el,
1886 const char *newline,
1887 size_t count, const char *buf)
1889 int print = 0;
1890 struct strbuf sb = STRBUF_INIT;
1892 while (count) {
1893 char *p = memchr(buf, '\n', count);
1894 if (print)
1895 strbuf_addstr(&sb, diff_line_prefix(o));
1897 if (p != buf) {
1898 const char *reset = st_el->color && *st_el->color ?
1899 GIT_COLOR_RESET : NULL;
1900 if (st_el->color && *st_el->color)
1901 strbuf_addstr(&sb, st_el->color);
1902 strbuf_addstr(&sb, st_el->prefix);
1903 strbuf_add(&sb, buf, p ? p - buf : count);
1904 strbuf_addstr(&sb, st_el->suffix);
1905 if (reset)
1906 strbuf_addstr(&sb, reset);
1908 if (!p)
1909 goto out;
1911 strbuf_addstr(&sb, newline);
1912 count -= p + 1 - buf;
1913 buf = p + 1;
1914 print = 1;
1915 if (count) {
1916 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1917 sb.buf, sb.len, 0);
1918 strbuf_reset(&sb);
1922 out:
1923 if (sb.len)
1924 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1925 sb.buf, sb.len, 0);
1926 strbuf_release(&sb);
1927 return 0;
1931 * '--color-words' algorithm can be described as:
1933 * 1. collect the minus/plus lines of a diff hunk, divided into
1934 * minus-lines and plus-lines;
1936 * 2. break both minus-lines and plus-lines into words and
1937 * place them into two mmfile_t with one word for each line;
1939 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1941 * And for the common parts of the both file, we output the plus side text.
1942 * diff_words->current_plus is used to trace the current position of the plus file
1943 * which printed. diff_words->last_minus is used to trace the last minus word
1944 * printed.
1946 * For '--graph' to work with '--color-words', we need to output the graph prefix
1947 * on each line of color words output. Generally, there are two conditions on
1948 * which we should output the prefix.
1950 * 1. diff_words->last_minus == 0 &&
1951 * diff_words->current_plus == diff_words->plus.text.ptr
1953 * that is: the plus text must start as a new line, and if there is no minus
1954 * word printed, a graph prefix must be printed.
1956 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1957 * *(diff_words->current_plus - 1) == '\n'
1959 * that is: a graph prefix must be printed following a '\n'
1961 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1963 if ((diff_words->last_minus == 0 &&
1964 diff_words->current_plus == diff_words->plus.text.ptr) ||
1965 (diff_words->current_plus > diff_words->plus.text.ptr &&
1966 *(diff_words->current_plus - 1) == '\n')) {
1967 return 1;
1968 } else {
1969 return 0;
1973 static void fn_out_diff_words_aux(void *priv,
1974 long minus_first, long minus_len,
1975 long plus_first, long plus_len,
1976 const char *func UNUSED, long funclen UNUSED)
1978 struct diff_words_data *diff_words = priv;
1979 struct diff_words_style *style = diff_words->style;
1980 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1981 struct diff_options *opt = diff_words->opt;
1982 const char *line_prefix;
1984 assert(opt);
1985 line_prefix = diff_line_prefix(opt);
1987 /* POSIX requires that first be decremented by one if len == 0... */
1988 if (minus_len) {
1989 minus_begin = diff_words->minus.orig[minus_first].begin;
1990 minus_end =
1991 diff_words->minus.orig[minus_first + minus_len - 1].end;
1992 } else
1993 minus_begin = minus_end =
1994 diff_words->minus.orig[minus_first].end;
1996 if (plus_len) {
1997 plus_begin = diff_words->plus.orig[plus_first].begin;
1998 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1999 } else
2000 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2002 if (color_words_output_graph_prefix(diff_words)) {
2003 fputs(line_prefix, diff_words->opt->file);
2005 if (diff_words->current_plus != plus_begin) {
2006 fn_out_diff_words_write_helper(diff_words->opt,
2007 &style->ctx, style->newline,
2008 plus_begin - diff_words->current_plus,
2009 diff_words->current_plus);
2011 if (minus_begin != minus_end) {
2012 fn_out_diff_words_write_helper(diff_words->opt,
2013 &style->old_word, style->newline,
2014 minus_end - minus_begin, minus_begin);
2016 if (plus_begin != plus_end) {
2017 fn_out_diff_words_write_helper(diff_words->opt,
2018 &style->new_word, style->newline,
2019 plus_end - plus_begin, plus_begin);
2022 diff_words->current_plus = plus_end;
2023 diff_words->last_minus = minus_first;
2026 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2027 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2028 int *begin, int *end)
2030 while (word_regex && *begin < buffer->size) {
2031 regmatch_t match[1];
2032 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2033 buffer->size - *begin, 1, match, 0)) {
2034 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2035 '\n', match[0].rm_eo - match[0].rm_so);
2036 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2037 *begin += match[0].rm_so;
2038 if (*begin == *end)
2039 (*begin)++;
2040 else
2041 return *begin > *end;
2042 } else {
2043 return -1;
2047 /* find the next word */
2048 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2049 (*begin)++;
2050 if (*begin >= buffer->size)
2051 return -1;
2053 /* find the end of the word */
2054 *end = *begin + 1;
2055 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2056 (*end)++;
2058 return 0;
2062 * This function splits the words in buffer->text, stores the list with
2063 * newline separator into out, and saves the offsets of the original words
2064 * in buffer->orig.
2066 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2067 regex_t *word_regex)
2069 int i, j;
2070 long alloc = 0;
2072 out->size = 0;
2073 out->ptr = NULL;
2075 /* fake an empty "0th" word */
2076 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2077 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2078 buffer->orig_nr = 1;
2080 for (i = 0; i < buffer->text.size; i++) {
2081 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2082 return;
2084 /* store original boundaries */
2085 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2086 buffer->orig_alloc);
2087 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2088 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2089 buffer->orig_nr++;
2091 /* store one word */
2092 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2093 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2094 out->ptr[out->size + j - i] = '\n';
2095 out->size += j - i + 1;
2097 i = j - 1;
2101 /* this executes the word diff on the accumulated buffers */
2102 static void diff_words_show(struct diff_words_data *diff_words)
2104 xpparam_t xpp;
2105 xdemitconf_t xecfg;
2106 mmfile_t minus, plus;
2107 struct diff_words_style *style = diff_words->style;
2109 struct diff_options *opt = diff_words->opt;
2110 const char *line_prefix;
2112 assert(opt);
2113 line_prefix = diff_line_prefix(opt);
2115 /* special case: only removal */
2116 if (!diff_words->plus.text.size) {
2117 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2118 line_prefix, strlen(line_prefix), 0);
2119 fn_out_diff_words_write_helper(diff_words->opt,
2120 &style->old_word, style->newline,
2121 diff_words->minus.text.size,
2122 diff_words->minus.text.ptr);
2123 diff_words->minus.text.size = 0;
2124 return;
2127 diff_words->current_plus = diff_words->plus.text.ptr;
2128 diff_words->last_minus = 0;
2130 memset(&xpp, 0, sizeof(xpp));
2131 memset(&xecfg, 0, sizeof(xecfg));
2132 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2133 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2134 xpp.flags = 0;
2135 /* as only the hunk header will be parsed, we need a 0-context */
2136 xecfg.ctxlen = 0;
2137 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2138 diff_words, &xpp, &xecfg))
2139 die("unable to generate word diff");
2140 free(minus.ptr);
2141 free(plus.ptr);
2142 if (diff_words->current_plus != diff_words->plus.text.ptr +
2143 diff_words->plus.text.size) {
2144 if (color_words_output_graph_prefix(diff_words))
2145 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2146 line_prefix, strlen(line_prefix), 0);
2147 fn_out_diff_words_write_helper(diff_words->opt,
2148 &style->ctx, style->newline,
2149 diff_words->plus.text.ptr + diff_words->plus.text.size
2150 - diff_words->current_plus, diff_words->current_plus);
2152 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2155 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2156 static void diff_words_flush(struct emit_callback *ecbdata)
2158 struct diff_options *wo = ecbdata->diff_words->opt;
2160 if (ecbdata->diff_words->minus.text.size ||
2161 ecbdata->diff_words->plus.text.size)
2162 diff_words_show(ecbdata->diff_words);
2164 if (wo->emitted_symbols) {
2165 struct diff_options *o = ecbdata->opt;
2166 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2167 int i;
2170 * NEEDSWORK:
2171 * Instead of appending each, concat all words to a line?
2173 for (i = 0; i < wol->nr; i++)
2174 append_emitted_diff_symbol(o, &wol->buf[i]);
2176 for (i = 0; i < wol->nr; i++)
2177 free((void *)wol->buf[i].line);
2179 wol->nr = 0;
2183 static void diff_filespec_load_driver(struct diff_filespec *one,
2184 struct index_state *istate)
2186 /* Use already-loaded driver */
2187 if (one->driver)
2188 return;
2190 if (S_ISREG(one->mode))
2191 one->driver = userdiff_find_by_path(istate, one->path);
2193 /* Fallback to default settings */
2194 if (!one->driver)
2195 one->driver = userdiff_find_by_name("default");
2198 static const char *userdiff_word_regex(struct diff_filespec *one,
2199 struct index_state *istate)
2201 diff_filespec_load_driver(one, istate);
2202 return one->driver->word_regex;
2205 static void init_diff_words_data(struct emit_callback *ecbdata,
2206 struct diff_options *orig_opts,
2207 struct diff_filespec *one,
2208 struct diff_filespec *two)
2210 int i;
2211 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2212 memcpy(o, orig_opts, sizeof(struct diff_options));
2214 CALLOC_ARRAY(ecbdata->diff_words, 1);
2215 ecbdata->diff_words->type = o->word_diff;
2216 ecbdata->diff_words->opt = o;
2218 if (orig_opts->emitted_symbols)
2219 CALLOC_ARRAY(o->emitted_symbols, 1);
2221 if (!o->word_regex)
2222 o->word_regex = userdiff_word_regex(one, o->repo->index);
2223 if (!o->word_regex)
2224 o->word_regex = userdiff_word_regex(two, o->repo->index);
2225 if (!o->word_regex)
2226 o->word_regex = diff_word_regex_cfg;
2227 if (o->word_regex) {
2228 ecbdata->diff_words->word_regex = (regex_t *)
2229 xmalloc(sizeof(regex_t));
2230 if (regcomp(ecbdata->diff_words->word_regex,
2231 o->word_regex,
2232 REG_EXTENDED | REG_NEWLINE))
2233 die("invalid regular expression: %s",
2234 o->word_regex);
2236 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2237 if (o->word_diff == diff_words_styles[i].type) {
2238 ecbdata->diff_words->style =
2239 &diff_words_styles[i];
2240 break;
2243 if (want_color(o->use_color)) {
2244 struct diff_words_style *st = ecbdata->diff_words->style;
2245 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2246 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2247 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2251 static void free_diff_words_data(struct emit_callback *ecbdata)
2253 if (ecbdata->diff_words) {
2254 diff_words_flush(ecbdata);
2255 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2256 free (ecbdata->diff_words->opt);
2257 free (ecbdata->diff_words->minus.text.ptr);
2258 free (ecbdata->diff_words->minus.orig);
2259 free (ecbdata->diff_words->plus.text.ptr);
2260 free (ecbdata->diff_words->plus.orig);
2261 if (ecbdata->diff_words->word_regex) {
2262 regfree(ecbdata->diff_words->word_regex);
2263 free(ecbdata->diff_words->word_regex);
2265 FREE_AND_NULL(ecbdata->diff_words);
2269 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2271 if (want_color(diff_use_color))
2272 return diff_colors[ix];
2273 return "";
2276 const char *diff_line_prefix(struct diff_options *opt)
2278 struct strbuf *msgbuf;
2279 if (!opt->output_prefix)
2280 return "";
2282 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2283 return msgbuf->buf;
2286 static unsigned long sane_truncate_line(char *line, unsigned long len)
2288 const char *cp;
2289 unsigned long allot;
2290 size_t l = len;
2292 cp = line;
2293 allot = l;
2294 while (0 < l) {
2295 (void) utf8_width(&cp, &l);
2296 if (!cp)
2297 break; /* truncated in the middle? */
2299 return allot - l;
2302 static void find_lno(const char *line, struct emit_callback *ecbdata)
2304 const char *p;
2305 ecbdata->lno_in_preimage = 0;
2306 ecbdata->lno_in_postimage = 0;
2307 p = strchr(line, '-');
2308 if (!p)
2309 return; /* cannot happen */
2310 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2311 p = strchr(p, '+');
2312 if (!p)
2313 return; /* cannot happen */
2314 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2317 static int fn_out_consume(void *priv, char *line, unsigned long len)
2319 struct emit_callback *ecbdata = priv;
2320 struct diff_options *o = ecbdata->opt;
2322 o->found_changes = 1;
2324 if (ecbdata->header) {
2325 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2326 ecbdata->header->buf, ecbdata->header->len, 0);
2327 strbuf_reset(ecbdata->header);
2328 ecbdata->header = NULL;
2331 if (ecbdata->label_path[0]) {
2332 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2333 ecbdata->label_path[0],
2334 strlen(ecbdata->label_path[0]), 0);
2335 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2336 ecbdata->label_path[1],
2337 strlen(ecbdata->label_path[1]), 0);
2338 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2341 if (diff_suppress_blank_empty
2342 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2343 line[0] = '\n';
2344 len = 1;
2347 if (line[0] == '@') {
2348 if (ecbdata->diff_words)
2349 diff_words_flush(ecbdata);
2350 len = sane_truncate_line(line, len);
2351 find_lno(line, ecbdata);
2352 emit_hunk_header(ecbdata, line, len);
2353 return 0;
2356 if (ecbdata->diff_words) {
2357 enum diff_symbol s =
2358 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2359 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2360 if (line[0] == '-') {
2361 diff_words_append(line, len,
2362 &ecbdata->diff_words->minus);
2363 return 0;
2364 } else if (line[0] == '+') {
2365 diff_words_append(line, len,
2366 &ecbdata->diff_words->plus);
2367 return 0;
2368 } else if (starts_with(line, "\\ ")) {
2370 * Eat the "no newline at eof" marker as if we
2371 * saw a "+" or "-" line with nothing on it,
2372 * and return without diff_words_flush() to
2373 * defer processing. If this is the end of
2374 * preimage, more "+" lines may come after it.
2376 return 0;
2378 diff_words_flush(ecbdata);
2379 emit_diff_symbol(o, s, line, len, 0);
2380 return 0;
2383 switch (line[0]) {
2384 case '+':
2385 ecbdata->lno_in_postimage++;
2386 emit_add_line(ecbdata, line + 1, len - 1);
2387 break;
2388 case '-':
2389 ecbdata->lno_in_preimage++;
2390 emit_del_line(ecbdata, line + 1, len - 1);
2391 break;
2392 case ' ':
2393 ecbdata->lno_in_postimage++;
2394 ecbdata->lno_in_preimage++;
2395 emit_context_line(ecbdata, line + 1, len - 1);
2396 break;
2397 default:
2398 /* incomplete line at the end */
2399 ecbdata->lno_in_preimage++;
2400 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2401 line, len, 0);
2402 break;
2404 return 0;
2407 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2409 const char *old_name = a;
2410 const char *new_name = b;
2411 int pfx_length, sfx_length;
2412 int pfx_adjust_for_slash;
2413 int len_a = strlen(a);
2414 int len_b = strlen(b);
2415 int a_midlen, b_midlen;
2416 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2417 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2419 if (qlen_a || qlen_b) {
2420 quote_c_style(a, name, NULL, 0);
2421 strbuf_addstr(name, " => ");
2422 quote_c_style(b, name, NULL, 0);
2423 return;
2426 /* Find common prefix */
2427 pfx_length = 0;
2428 while (*old_name && *new_name && *old_name == *new_name) {
2429 if (*old_name == '/')
2430 pfx_length = old_name - a + 1;
2431 old_name++;
2432 new_name++;
2435 /* Find common suffix */
2436 old_name = a + len_a;
2437 new_name = b + len_b;
2438 sfx_length = 0;
2440 * If there is a common prefix, it must end in a slash. In
2441 * that case we let this loop run 1 into the prefix to see the
2442 * same slash.
2444 * If there is no common prefix, we cannot do this as it would
2445 * underrun the input strings.
2447 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2448 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2449 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2450 *old_name == *new_name) {
2451 if (*old_name == '/')
2452 sfx_length = len_a - (old_name - a);
2453 old_name--;
2454 new_name--;
2458 * pfx{mid-a => mid-b}sfx
2459 * {pfx-a => pfx-b}sfx
2460 * pfx{sfx-a => sfx-b}
2461 * name-a => name-b
2463 a_midlen = len_a - pfx_length - sfx_length;
2464 b_midlen = len_b - pfx_length - sfx_length;
2465 if (a_midlen < 0)
2466 a_midlen = 0;
2467 if (b_midlen < 0)
2468 b_midlen = 0;
2470 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2471 if (pfx_length + sfx_length) {
2472 strbuf_add(name, a, pfx_length);
2473 strbuf_addch(name, '{');
2475 strbuf_add(name, a + pfx_length, a_midlen);
2476 strbuf_addstr(name, " => ");
2477 strbuf_add(name, b + pfx_length, b_midlen);
2478 if (pfx_length + sfx_length) {
2479 strbuf_addch(name, '}');
2480 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2484 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2485 const char *name_a,
2486 const char *name_b)
2488 struct diffstat_file *x;
2489 CALLOC_ARRAY(x, 1);
2490 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2491 diffstat->files[diffstat->nr++] = x;
2492 if (name_b) {
2493 x->from_name = xstrdup(name_a);
2494 x->name = xstrdup(name_b);
2495 x->is_renamed = 1;
2497 else {
2498 x->from_name = NULL;
2499 x->name = xstrdup(name_a);
2501 return x;
2504 static int diffstat_consume(void *priv, char *line, unsigned long len)
2506 struct diffstat_t *diffstat = priv;
2507 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2509 if (!len)
2510 BUG("xdiff fed us an empty line");
2512 if (line[0] == '+')
2513 x->added++;
2514 else if (line[0] == '-')
2515 x->deleted++;
2516 return 0;
2519 const char mime_boundary_leader[] = "------------";
2521 static int scale_linear(int it, int width, int max_change)
2523 if (!it)
2524 return 0;
2526 * make sure that at least one '-' or '+' is printed if
2527 * there is any change to this path. The easiest way is to
2528 * scale linearly as if the allotted width is one column shorter
2529 * than it is, and then add 1 to the result.
2531 return 1 + (it * (width - 1) / max_change);
2534 static void show_graph(struct strbuf *out, char ch, int cnt,
2535 const char *set, const char *reset)
2537 if (cnt <= 0)
2538 return;
2539 strbuf_addstr(out, set);
2540 strbuf_addchars(out, ch, cnt);
2541 strbuf_addstr(out, reset);
2544 static void fill_print_name(struct diffstat_file *file)
2546 struct strbuf pname = STRBUF_INIT;
2548 if (file->print_name)
2549 return;
2551 if (file->is_renamed)
2552 pprint_rename(&pname, file->from_name, file->name);
2553 else
2554 quote_c_style(file->name, &pname, NULL, 0);
2556 if (file->comments)
2557 strbuf_addf(&pname, " (%s)", file->comments);
2559 file->print_name = strbuf_detach(&pname, NULL);
2562 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2563 int files, int insertions, int deletions)
2565 struct strbuf sb = STRBUF_INIT;
2567 if (!files) {
2568 assert(insertions == 0 && deletions == 0);
2569 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2570 NULL, 0, 0);
2571 return;
2574 strbuf_addf(&sb,
2575 (files == 1) ? " %d file changed" : " %d files changed",
2576 files);
2579 * For binary diff, the caller may want to print "x files
2580 * changed" with insertions == 0 && deletions == 0.
2582 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2583 * is probably less confusing (i.e skip over "2 files changed
2584 * but nothing about added/removed lines? Is this a bug in Git?").
2586 if (insertions || deletions == 0) {
2587 strbuf_addf(&sb,
2588 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2589 insertions);
2592 if (deletions || insertions == 0) {
2593 strbuf_addf(&sb,
2594 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2595 deletions);
2597 strbuf_addch(&sb, '\n');
2598 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2599 sb.buf, sb.len, 0);
2600 strbuf_release(&sb);
2603 void print_stat_summary(FILE *fp, int files,
2604 int insertions, int deletions)
2606 struct diff_options o;
2607 memset(&o, 0, sizeof(o));
2608 o.file = fp;
2610 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2613 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2615 int i, len, add, del, adds = 0, dels = 0;
2616 uintmax_t max_change = 0, max_len = 0;
2617 int total_files = data->nr, count;
2618 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2619 const char *reset, *add_c, *del_c;
2620 int extra_shown = 0;
2621 const char *line_prefix = diff_line_prefix(options);
2622 struct strbuf out = STRBUF_INIT;
2624 if (data->nr == 0)
2625 return;
2627 count = options->stat_count ? options->stat_count : data->nr;
2629 reset = diff_get_color_opt(options, DIFF_RESET);
2630 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2631 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2634 * Find the longest filename and max number of changes
2636 for (i = 0; (i < count) && (i < data->nr); i++) {
2637 struct diffstat_file *file = data->files[i];
2638 uintmax_t change = file->added + file->deleted;
2640 if (!file->is_interesting && (change == 0)) {
2641 count++; /* not shown == room for one more */
2642 continue;
2644 fill_print_name(file);
2645 len = utf8_strwidth(file->print_name);
2646 if (max_len < len)
2647 max_len = len;
2649 if (file->is_unmerged) {
2650 /* "Unmerged" is 8 characters */
2651 bin_width = bin_width < 8 ? 8 : bin_width;
2652 continue;
2654 if (file->is_binary) {
2655 /* "Bin XXX -> YYY bytes" */
2656 int w = 14 + decimal_width(file->added)
2657 + decimal_width(file->deleted);
2658 bin_width = bin_width < w ? w : bin_width;
2659 /* Display change counts aligned with "Bin" */
2660 number_width = 3;
2661 continue;
2664 if (max_change < change)
2665 max_change = change;
2667 count = i; /* where we can stop scanning in data->files[] */
2670 * We have width = stat_width or term_columns() columns total.
2671 * We want a maximum of min(max_len, stat_name_width) for the name part.
2672 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2673 * We also need 1 for " " and 4 + decimal_width(max_change)
2674 * for " | NNNN " and one the empty column at the end, altogether
2675 * 6 + decimal_width(max_change).
2677 * If there's not enough space, we will use the smaller of
2678 * stat_name_width (if set) and 5/8*width for the filename,
2679 * and the rest for constant elements + graph part, but no more
2680 * than stat_graph_width for the graph part.
2681 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2682 * for the standard terminal size).
2684 * In other words: stat_width limits the maximum width, and
2685 * stat_name_width fixes the maximum width of the filename,
2686 * and is also used to divide available columns if there
2687 * aren't enough.
2689 * Binary files are displayed with "Bin XXX -> YYY bytes"
2690 * instead of the change count and graph. This part is treated
2691 * similarly to the graph part, except that it is not
2692 * "scaled". If total width is too small to accommodate the
2693 * guaranteed minimum width of the filename part and the
2694 * separators and this message, this message will "overflow"
2695 * making the line longer than the maximum width.
2699 * NEEDSWORK: line_prefix is often used for "log --graph" output
2700 * and contains ANSI-colored string. utf8_strnwidth() should be
2701 * used to correctly count the display width instead of strlen().
2703 if (options->stat_width == -1)
2704 width = term_columns() - strlen(line_prefix);
2705 else
2706 width = options->stat_width ? options->stat_width : 80;
2707 number_width = decimal_width(max_change) > number_width ?
2708 decimal_width(max_change) : number_width;
2710 if (options->stat_name_width == -1)
2711 options->stat_name_width = diff_stat_name_width;
2712 if (options->stat_graph_width == -1)
2713 options->stat_graph_width = diff_stat_graph_width;
2716 * Guarantee 3/8*16 == 6 for the graph part
2717 * and 5/8*16 == 10 for the filename part
2719 if (width < 16 + 6 + number_width)
2720 width = 16 + 6 + number_width;
2723 * First assign sizes that are wanted, ignoring available width.
2724 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2725 * starting from "XXX" should fit in graph_width.
2727 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2728 if (options->stat_graph_width &&
2729 options->stat_graph_width < graph_width)
2730 graph_width = options->stat_graph_width;
2732 name_width = (options->stat_name_width > 0 &&
2733 options->stat_name_width < max_len) ?
2734 options->stat_name_width : max_len;
2737 * Adjust adjustable widths not to exceed maximum width
2739 if (name_width + number_width + 6 + graph_width > width) {
2740 if (graph_width > width * 3/8 - number_width - 6) {
2741 graph_width = width * 3/8 - number_width - 6;
2742 if (graph_width < 6)
2743 graph_width = 6;
2746 if (options->stat_graph_width &&
2747 graph_width > options->stat_graph_width)
2748 graph_width = options->stat_graph_width;
2749 if (name_width > width - number_width - 6 - graph_width)
2750 name_width = width - number_width - 6 - graph_width;
2751 else
2752 graph_width = width - number_width - 6 - name_width;
2756 * From here name_width is the width of the name area,
2757 * and graph_width is the width of the graph area.
2758 * max_change is used to scale graph properly.
2760 for (i = 0; i < count; i++) {
2761 const char *prefix = "";
2762 struct diffstat_file *file = data->files[i];
2763 char *name = file->print_name;
2764 uintmax_t added = file->added;
2765 uintmax_t deleted = file->deleted;
2766 int name_len, padding;
2768 if (!file->is_interesting && (added + deleted == 0))
2769 continue;
2772 * "scale" the filename
2774 len = name_width;
2775 name_len = utf8_strwidth(name);
2776 if (name_width < name_len) {
2777 char *slash;
2778 prefix = "...";
2779 len -= 3;
2781 * NEEDSWORK: (name_len - len) counts the display
2782 * width, which would be shorter than the byte
2783 * length of the corresponding substring.
2784 * Advancing "name" by that number of bytes does
2785 * *NOT* skip over that many columns, so it is
2786 * very likely that chomping the pathname at the
2787 * slash we will find starting from "name" will
2788 * leave the resulting string still too long.
2790 name += name_len - len;
2791 slash = strchr(name, '/');
2792 if (slash)
2793 name = slash;
2795 padding = len - utf8_strwidth(name);
2796 if (padding < 0)
2797 padding = 0;
2799 if (file->is_binary) {
2800 strbuf_addf(&out, " %s%s%*s | %*s",
2801 prefix, name, padding, "",
2802 number_width, "Bin");
2803 if (!added && !deleted) {
2804 strbuf_addch(&out, '\n');
2805 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2806 out.buf, out.len, 0);
2807 strbuf_reset(&out);
2808 continue;
2810 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2811 del_c, deleted, reset);
2812 strbuf_addstr(&out, " -> ");
2813 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2814 add_c, added, reset);
2815 strbuf_addstr(&out, " bytes\n");
2816 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2817 out.buf, out.len, 0);
2818 strbuf_reset(&out);
2819 continue;
2821 else if (file->is_unmerged) {
2822 strbuf_addf(&out, " %s%s%*s | %*s",
2823 prefix, name, padding, "",
2824 number_width, "Unmerged\n");
2825 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2826 out.buf, out.len, 0);
2827 strbuf_reset(&out);
2828 continue;
2832 * scale the add/delete
2834 add = added;
2835 del = deleted;
2837 if (graph_width <= max_change) {
2838 int total = scale_linear(add + del, graph_width, max_change);
2839 if (total < 2 && add && del)
2840 /* width >= 2 due to the sanity check */
2841 total = 2;
2842 if (add < del) {
2843 add = scale_linear(add, graph_width, max_change);
2844 del = total - add;
2845 } else {
2846 del = scale_linear(del, graph_width, max_change);
2847 add = total - del;
2850 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2851 prefix, name, padding, "",
2852 number_width, added + deleted,
2853 added + deleted ? " " : "");
2854 show_graph(&out, '+', add, add_c, reset);
2855 show_graph(&out, '-', del, del_c, reset);
2856 strbuf_addch(&out, '\n');
2857 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2858 out.buf, out.len, 0);
2859 strbuf_reset(&out);
2862 for (i = 0; i < data->nr; i++) {
2863 struct diffstat_file *file = data->files[i];
2864 uintmax_t added = file->added;
2865 uintmax_t deleted = file->deleted;
2867 if (file->is_unmerged ||
2868 (!file->is_interesting && (added + deleted == 0))) {
2869 total_files--;
2870 continue;
2873 if (!file->is_binary) {
2874 adds += added;
2875 dels += deleted;
2877 if (i < count)
2878 continue;
2879 if (!extra_shown)
2880 emit_diff_symbol(options,
2881 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2882 NULL, 0, 0);
2883 extra_shown = 1;
2886 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2887 strbuf_release(&out);
2890 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2892 int i, adds = 0, dels = 0, total_files = data->nr;
2894 if (data->nr == 0)
2895 return;
2897 for (i = 0; i < data->nr; i++) {
2898 int added = data->files[i]->added;
2899 int deleted = data->files[i]->deleted;
2901 if (data->files[i]->is_unmerged ||
2902 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2903 total_files--;
2904 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2905 adds += added;
2906 dels += deleted;
2909 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2912 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2914 int i;
2916 if (data->nr == 0)
2917 return;
2919 for (i = 0; i < data->nr; i++) {
2920 struct diffstat_file *file = data->files[i];
2922 fprintf(options->file, "%s", diff_line_prefix(options));
2924 if (file->is_binary)
2925 fprintf(options->file, "-\t-\t");
2926 else
2927 fprintf(options->file,
2928 "%"PRIuMAX"\t%"PRIuMAX"\t",
2929 file->added, file->deleted);
2930 if (options->line_termination) {
2931 fill_print_name(file);
2932 if (!file->is_renamed)
2933 write_name_quoted(file->name, options->file,
2934 options->line_termination);
2935 else {
2936 fputs(file->print_name, options->file);
2937 putc(options->line_termination, options->file);
2939 } else {
2940 if (file->is_renamed) {
2941 putc('\0', options->file);
2942 write_name_quoted(file->from_name, options->file, '\0');
2944 write_name_quoted(file->name, options->file, '\0');
2949 struct dirstat_file {
2950 const char *name;
2951 unsigned long changed;
2954 struct dirstat_dir {
2955 struct dirstat_file *files;
2956 int alloc, nr, permille, cumulative;
2959 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2960 unsigned long changed, const char *base, int baselen)
2962 unsigned long sum_changes = 0;
2963 unsigned int sources = 0;
2964 const char *line_prefix = diff_line_prefix(opt);
2966 while (dir->nr) {
2967 struct dirstat_file *f = dir->files;
2968 int namelen = strlen(f->name);
2969 unsigned long changes;
2970 char *slash;
2972 if (namelen < baselen)
2973 break;
2974 if (memcmp(f->name, base, baselen))
2975 break;
2976 slash = strchr(f->name + baselen, '/');
2977 if (slash) {
2978 int newbaselen = slash + 1 - f->name;
2979 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2980 sources++;
2981 } else {
2982 changes = f->changed;
2983 dir->files++;
2984 dir->nr--;
2985 sources += 2;
2987 sum_changes += changes;
2991 * We don't report dirstat's for
2992 * - the top level
2993 * - or cases where everything came from a single directory
2994 * under this directory (sources == 1).
2996 if (baselen && sources != 1) {
2997 if (sum_changes) {
2998 int permille = sum_changes * 1000 / changed;
2999 if (permille >= dir->permille) {
3000 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3001 permille / 10, permille % 10, baselen, base);
3002 if (!dir->cumulative)
3003 return 0;
3007 return sum_changes;
3010 static int dirstat_compare(const void *_a, const void *_b)
3012 const struct dirstat_file *a = _a;
3013 const struct dirstat_file *b = _b;
3014 return strcmp(a->name, b->name);
3017 static void conclude_dirstat(struct diff_options *options,
3018 struct dirstat_dir *dir,
3019 unsigned long changed)
3021 struct dirstat_file *to_free = dir->files;
3023 if (!changed) {
3024 /* This can happen even with many files, if everything was renames */
3026 } else {
3027 /* Show all directories with more than x% of the changes */
3028 QSORT(dir->files, dir->nr, dirstat_compare);
3029 gather_dirstat(options, dir, changed, "", 0);
3032 free(to_free);
3035 static void show_dirstat(struct diff_options *options)
3037 int i;
3038 unsigned long changed;
3039 struct dirstat_dir dir;
3040 struct diff_queue_struct *q = &diff_queued_diff;
3042 dir.files = NULL;
3043 dir.alloc = 0;
3044 dir.nr = 0;
3045 dir.permille = options->dirstat_permille;
3046 dir.cumulative = options->flags.dirstat_cumulative;
3048 changed = 0;
3049 for (i = 0; i < q->nr; i++) {
3050 struct diff_filepair *p = q->queue[i];
3051 const char *name;
3052 unsigned long copied, added, damage;
3053 struct diff_populate_filespec_options dpf_options = {
3054 .check_size_only = 1,
3057 name = p->two->path ? p->two->path : p->one->path;
3059 if (p->one->oid_valid && p->two->oid_valid &&
3060 oideq(&p->one->oid, &p->two->oid)) {
3062 * The SHA1 has not changed, so pre-/post-content is
3063 * identical. We can therefore skip looking at the
3064 * file contents altogether.
3066 damage = 0;
3067 goto found_damage;
3070 if (options->flags.dirstat_by_file) {
3072 * In --dirstat-by-file mode, we don't really need to
3073 * look at the actual file contents at all.
3074 * The fact that the SHA1 changed is enough for us to
3075 * add this file to the list of results
3076 * (with each file contributing equal damage).
3078 damage = 1;
3079 goto found_damage;
3082 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3083 diff_populate_filespec(options->repo, p->one, NULL);
3084 diff_populate_filespec(options->repo, p->two, NULL);
3085 diffcore_count_changes(options->repo,
3086 p->one, p->two, NULL, NULL,
3087 &copied, &added);
3088 diff_free_filespec_data(p->one);
3089 diff_free_filespec_data(p->two);
3090 } else if (DIFF_FILE_VALID(p->one)) {
3091 diff_populate_filespec(options->repo, p->one, &dpf_options);
3092 copied = added = 0;
3093 diff_free_filespec_data(p->one);
3094 } else if (DIFF_FILE_VALID(p->two)) {
3095 diff_populate_filespec(options->repo, p->two, &dpf_options);
3096 copied = 0;
3097 added = p->two->size;
3098 diff_free_filespec_data(p->two);
3099 } else
3100 continue;
3103 * Original minus copied is the removed material,
3104 * added is the new material. They are both damages
3105 * made to the preimage.
3106 * If the resulting damage is zero, we know that
3107 * diffcore_count_changes() considers the two entries to
3108 * be identical, but since the oid changed, we
3109 * know that there must have been _some_ kind of change,
3110 * so we force all entries to have damage > 0.
3112 damage = (p->one->size - copied) + added;
3113 if (!damage)
3114 damage = 1;
3116 found_damage:
3117 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3118 dir.files[dir.nr].name = name;
3119 dir.files[dir.nr].changed = damage;
3120 changed += damage;
3121 dir.nr++;
3124 conclude_dirstat(options, &dir, changed);
3127 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3129 int i;
3130 unsigned long changed;
3131 struct dirstat_dir dir;
3133 if (data->nr == 0)
3134 return;
3136 dir.files = NULL;
3137 dir.alloc = 0;
3138 dir.nr = 0;
3139 dir.permille = options->dirstat_permille;
3140 dir.cumulative = options->flags.dirstat_cumulative;
3142 changed = 0;
3143 for (i = 0; i < data->nr; i++) {
3144 struct diffstat_file *file = data->files[i];
3145 unsigned long damage = file->added + file->deleted;
3146 if (file->is_binary)
3148 * binary files counts bytes, not lines. Must find some
3149 * way to normalize binary bytes vs. textual lines.
3150 * The following heuristic assumes that there are 64
3151 * bytes per "line".
3152 * This is stupid and ugly, but very cheap...
3154 damage = DIV_ROUND_UP(damage, 64);
3155 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3156 dir.files[dir.nr].name = file->name;
3157 dir.files[dir.nr].changed = damage;
3158 changed += damage;
3159 dir.nr++;
3162 conclude_dirstat(options, &dir, changed);
3165 static void free_diffstat_file(struct diffstat_file *f)
3167 free(f->print_name);
3168 free(f->name);
3169 free(f->from_name);
3170 free(f);
3173 void free_diffstat_info(struct diffstat_t *diffstat)
3175 int i;
3176 for (i = 0; i < diffstat->nr; i++)
3177 free_diffstat_file(diffstat->files[i]);
3178 free(diffstat->files);
3181 struct checkdiff_t {
3182 const char *filename;
3183 int lineno;
3184 int conflict_marker_size;
3185 struct diff_options *o;
3186 unsigned ws_rule;
3187 unsigned status;
3190 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3192 char firstchar;
3193 int cnt;
3195 if (len < marker_size + 1)
3196 return 0;
3197 firstchar = line[0];
3198 switch (firstchar) {
3199 case '=': case '>': case '<': case '|':
3200 break;
3201 default:
3202 return 0;
3204 for (cnt = 1; cnt < marker_size; cnt++)
3205 if (line[cnt] != firstchar)
3206 return 0;
3207 /* line[1] through line[marker_size-1] are same as firstchar */
3208 if (len < marker_size + 1 || !isspace(line[marker_size]))
3209 return 0;
3210 return 1;
3213 static void checkdiff_consume_hunk(void *priv,
3214 long ob UNUSED, long on UNUSED,
3215 long nb, long nn UNUSED,
3216 const char *func UNUSED, long funclen UNUSED)
3219 struct checkdiff_t *data = priv;
3220 data->lineno = nb - 1;
3223 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3225 struct checkdiff_t *data = priv;
3226 int marker_size = data->conflict_marker_size;
3227 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3228 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3229 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3230 char *err;
3231 const char *line_prefix;
3233 assert(data->o);
3234 line_prefix = diff_line_prefix(data->o);
3236 if (line[0] == '+') {
3237 unsigned bad;
3238 data->lineno++;
3239 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3240 data->status |= 1;
3241 fprintf(data->o->file,
3242 "%s%s:%d: leftover conflict marker\n",
3243 line_prefix, data->filename, data->lineno);
3245 bad = ws_check(line + 1, len - 1, data->ws_rule);
3246 if (!bad)
3247 return 0;
3248 data->status |= bad;
3249 err = whitespace_error_string(bad);
3250 fprintf(data->o->file, "%s%s:%d: %s.\n",
3251 line_prefix, data->filename, data->lineno, err);
3252 free(err);
3253 emit_line(data->o, set, reset, line, 1);
3254 ws_check_emit(line + 1, len - 1, data->ws_rule,
3255 data->o->file, set, reset, ws);
3256 } else if (line[0] == ' ') {
3257 data->lineno++;
3259 return 0;
3262 static unsigned char *deflate_it(char *data,
3263 unsigned long size,
3264 unsigned long *result_size)
3266 int bound;
3267 unsigned char *deflated;
3268 git_zstream stream;
3270 git_deflate_init(&stream, zlib_compression_level);
3271 bound = git_deflate_bound(&stream, size);
3272 deflated = xmalloc(bound);
3273 stream.next_out = deflated;
3274 stream.avail_out = bound;
3276 stream.next_in = (unsigned char *)data;
3277 stream.avail_in = size;
3278 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3279 ; /* nothing */
3280 git_deflate_end(&stream);
3281 *result_size = stream.total_out;
3282 return deflated;
3285 static void emit_binary_diff_body(struct diff_options *o,
3286 mmfile_t *one, mmfile_t *two)
3288 void *cp;
3289 void *delta;
3290 void *deflated;
3291 void *data;
3292 unsigned long orig_size;
3293 unsigned long delta_size;
3294 unsigned long deflate_size;
3295 unsigned long data_size;
3297 /* We could do deflated delta, or we could do just deflated two,
3298 * whichever is smaller.
3300 delta = NULL;
3301 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3302 if (one->size && two->size) {
3303 delta = diff_delta(one->ptr, one->size,
3304 two->ptr, two->size,
3305 &delta_size, deflate_size);
3306 if (delta) {
3307 void *to_free = delta;
3308 orig_size = delta_size;
3309 delta = deflate_it(delta, delta_size, &delta_size);
3310 free(to_free);
3314 if (delta && delta_size < deflate_size) {
3315 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3316 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3317 s, strlen(s), 0);
3318 free(s);
3319 free(deflated);
3320 data = delta;
3321 data_size = delta_size;
3322 } else {
3323 char *s = xstrfmt("%lu", two->size);
3324 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3325 s, strlen(s), 0);
3326 free(s);
3327 free(delta);
3328 data = deflated;
3329 data_size = deflate_size;
3332 /* emit data encoded in base85 */
3333 cp = data;
3334 while (data_size) {
3335 int len;
3336 int bytes = (52 < data_size) ? 52 : data_size;
3337 char line[71];
3338 data_size -= bytes;
3339 if (bytes <= 26)
3340 line[0] = bytes + 'A' - 1;
3341 else
3342 line[0] = bytes - 26 + 'a' - 1;
3343 encode_85(line + 1, cp, bytes);
3344 cp = (char *) cp + bytes;
3346 len = strlen(line);
3347 line[len++] = '\n';
3348 line[len] = '\0';
3350 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3351 line, len, 0);
3353 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3354 free(data);
3357 static void emit_binary_diff(struct diff_options *o,
3358 mmfile_t *one, mmfile_t *two)
3360 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3361 emit_binary_diff_body(o, one, two);
3362 emit_binary_diff_body(o, two, one);
3365 int diff_filespec_is_binary(struct repository *r,
3366 struct diff_filespec *one)
3368 struct diff_populate_filespec_options dpf_options = {
3369 .check_binary = 1,
3372 if (one->is_binary == -1) {
3373 diff_filespec_load_driver(one, r->index);
3374 if (one->driver->binary != -1)
3375 one->is_binary = one->driver->binary;
3376 else {
3377 if (!one->data && DIFF_FILE_VALID(one))
3378 diff_populate_filespec(r, one, &dpf_options);
3379 if (one->is_binary == -1 && one->data)
3380 one->is_binary = buffer_is_binary(one->data,
3381 one->size);
3382 if (one->is_binary == -1)
3383 one->is_binary = 0;
3386 return one->is_binary;
3389 static const struct userdiff_funcname *
3390 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3392 diff_filespec_load_driver(one, o->repo->index);
3393 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3396 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3398 if (!options->a_prefix)
3399 options->a_prefix = a;
3400 if (!options->b_prefix)
3401 options->b_prefix = b;
3404 void diff_set_noprefix(struct diff_options *options)
3406 options->a_prefix = options->b_prefix = "";
3409 void diff_set_default_prefix(struct diff_options *options)
3411 options->a_prefix = "a/";
3412 options->b_prefix = "b/";
3415 struct userdiff_driver *get_textconv(struct repository *r,
3416 struct diff_filespec *one)
3418 if (!DIFF_FILE_VALID(one))
3419 return NULL;
3421 diff_filespec_load_driver(one, r->index);
3422 return userdiff_get_textconv(r, one->driver);
3425 static struct string_list *additional_headers(struct diff_options *o,
3426 const char *path)
3428 if (!o->additional_path_headers)
3429 return NULL;
3430 return strmap_get(o->additional_path_headers, path);
3433 static void add_formatted_header(struct strbuf *msg,
3434 const char *header,
3435 const char *line_prefix,
3436 const char *meta,
3437 const char *reset)
3439 const char *next, *newline;
3441 for (next = header; *next; next = newline) {
3442 newline = strchrnul(next, '\n');
3443 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3444 (int)(newline - next), next, reset);
3445 if (*newline)
3446 newline++;
3450 static void add_formatted_headers(struct strbuf *msg,
3451 struct string_list *more_headers,
3452 const char *line_prefix,
3453 const char *meta,
3454 const char *reset)
3456 int i;
3458 for (i = 0; i < more_headers->nr; i++)
3459 add_formatted_header(msg, more_headers->items[i].string,
3460 line_prefix, meta, reset);
3463 static int diff_filepair_is_phoney(struct diff_filespec *one,
3464 struct diff_filespec *two)
3467 * This function specifically looks for pairs injected by
3468 * create_filepairs_for_header_only_notifications(). Such
3469 * pairs are "phoney" in that they do not represent any
3470 * content or even mode difference, but were inserted because
3471 * diff_queued_diff previously had no pair associated with
3472 * that path but we needed some pair to avoid losing the
3473 * "remerge CONFLICT" header associated with the path.
3475 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3478 static int set_diff_algorithm(struct diff_options *opts,
3479 const char *alg)
3481 long value = parse_algorithm_value(alg);
3483 if (value < 0)
3484 return -1;
3486 /* clear out previous settings */
3487 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3488 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3489 opts->xdl_opts |= value;
3491 return 0;
3494 static void builtin_diff(const char *name_a,
3495 const char *name_b,
3496 struct diff_filespec *one,
3497 struct diff_filespec *two,
3498 const char *xfrm_msg,
3499 int must_show_header,
3500 struct diff_options *o,
3501 int complete_rewrite)
3503 mmfile_t mf1, mf2;
3504 const char *lbl[2];
3505 char *a_one, *b_two;
3506 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3507 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3508 const char *a_prefix, *b_prefix;
3509 struct userdiff_driver *textconv_one = NULL;
3510 struct userdiff_driver *textconv_two = NULL;
3511 struct strbuf header = STRBUF_INIT;
3512 const char *line_prefix = diff_line_prefix(o);
3514 diff_set_mnemonic_prefix(o, "a/", "b/");
3515 if (o->flags.reverse_diff) {
3516 a_prefix = o->b_prefix;
3517 b_prefix = o->a_prefix;
3518 } else {
3519 a_prefix = o->a_prefix;
3520 b_prefix = o->b_prefix;
3523 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3524 (!one->mode || S_ISGITLINK(one->mode)) &&
3525 (!two->mode || S_ISGITLINK(two->mode)) &&
3526 (!diff_filepair_is_phoney(one, two))) {
3527 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3528 &one->oid, &two->oid,
3529 two->dirty_submodule);
3530 return;
3531 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3532 (!one->mode || S_ISGITLINK(one->mode)) &&
3533 (!two->mode || S_ISGITLINK(two->mode)) &&
3534 (!diff_filepair_is_phoney(one, two))) {
3535 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3536 &one->oid, &two->oid,
3537 two->dirty_submodule);
3538 return;
3541 if (o->flags.allow_textconv) {
3542 textconv_one = get_textconv(o->repo, one);
3543 textconv_two = get_textconv(o->repo, two);
3546 /* Never use a non-valid filename anywhere if at all possible */
3547 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3548 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3550 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3551 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3552 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3553 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3554 if (diff_filepair_is_phoney(one, two)) {
3556 * We should only reach this point for pairs generated from
3557 * create_filepairs_for_header_only_notifications(). For
3558 * these, we want to avoid the "/dev/null" special casing
3559 * above, because we do not want such pairs shown as either
3560 * "new file" or "deleted file" below.
3562 lbl[0] = a_one;
3563 lbl[1] = b_two;
3565 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3566 if (lbl[0][0] == '/') {
3567 /* /dev/null */
3568 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3569 if (xfrm_msg)
3570 strbuf_addstr(&header, xfrm_msg);
3571 o->found_changes = 1;
3572 must_show_header = 1;
3574 else if (lbl[1][0] == '/') {
3575 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3576 if (xfrm_msg)
3577 strbuf_addstr(&header, xfrm_msg);
3578 o->found_changes = 1;
3579 must_show_header = 1;
3581 else {
3582 if (one->mode != two->mode) {
3583 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3584 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3585 o->found_changes = 1;
3586 must_show_header = 1;
3588 if (xfrm_msg)
3589 strbuf_addstr(&header, xfrm_msg);
3592 * we do not run diff between different kind
3593 * of objects.
3595 if ((one->mode ^ two->mode) & S_IFMT)
3596 goto free_ab_and_return;
3597 if (complete_rewrite &&
3598 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3599 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3600 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3601 header.buf, header.len, 0);
3602 strbuf_reset(&header);
3603 emit_rewrite_diff(name_a, name_b, one, two,
3604 textconv_one, textconv_two, o);
3605 o->found_changes = 1;
3606 goto free_ab_and_return;
3610 if (o->irreversible_delete && lbl[1][0] == '/') {
3611 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3612 header.len, 0);
3613 strbuf_reset(&header);
3614 goto free_ab_and_return;
3615 } else if (!o->flags.text &&
3616 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3617 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3618 struct strbuf sb = STRBUF_INIT;
3619 if (!one->data && !two->data &&
3620 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3621 !o->flags.binary) {
3622 if (oideq(&one->oid, &two->oid)) {
3623 if (must_show_header)
3624 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3625 header.buf, header.len,
3627 goto free_ab_and_return;
3629 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3630 header.buf, header.len, 0);
3631 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3632 diff_line_prefix(o), lbl[0], lbl[1]);
3633 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3634 sb.buf, sb.len, 0);
3635 strbuf_release(&sb);
3636 goto free_ab_and_return;
3638 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3639 fill_mmfile(o->repo, &mf2, two) < 0)
3640 die("unable to read files to diff");
3641 /* Quite common confusing case */
3642 if (mf1.size == mf2.size &&
3643 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3644 if (must_show_header)
3645 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3646 header.buf, header.len, 0);
3647 goto free_ab_and_return;
3649 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3650 strbuf_reset(&header);
3651 if (o->flags.binary)
3652 emit_binary_diff(o, &mf1, &mf2);
3653 else {
3654 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3655 diff_line_prefix(o), lbl[0], lbl[1]);
3656 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3657 sb.buf, sb.len, 0);
3658 strbuf_release(&sb);
3660 o->found_changes = 1;
3661 } else {
3662 /* Crazy xdl interfaces.. */
3663 const char *diffopts;
3664 const char *v;
3665 xpparam_t xpp;
3666 xdemitconf_t xecfg;
3667 struct emit_callback ecbdata;
3668 const struct userdiff_funcname *pe;
3670 if (must_show_header) {
3671 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3672 header.buf, header.len, 0);
3673 strbuf_reset(&header);
3676 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3677 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3679 pe = diff_funcname_pattern(o, one);
3680 if (!pe)
3681 pe = diff_funcname_pattern(o, two);
3683 memset(&xpp, 0, sizeof(xpp));
3684 memset(&xecfg, 0, sizeof(xecfg));
3685 memset(&ecbdata, 0, sizeof(ecbdata));
3686 if (o->flags.suppress_diff_headers)
3687 lbl[0] = NULL;
3688 ecbdata.label_path = lbl;
3689 ecbdata.color_diff = want_color(o->use_color);
3690 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3691 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3692 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3693 ecbdata.opt = o;
3694 if (header.len && !o->flags.suppress_diff_headers)
3695 ecbdata.header = &header;
3696 xpp.flags = o->xdl_opts;
3697 xpp.ignore_regex = o->ignore_regex;
3698 xpp.ignore_regex_nr = o->ignore_regex_nr;
3699 xpp.anchors = o->anchors;
3700 xpp.anchors_nr = o->anchors_nr;
3701 xecfg.ctxlen = o->context;
3702 xecfg.interhunkctxlen = o->interhunkcontext;
3703 xecfg.flags = XDL_EMIT_FUNCNAMES;
3704 if (o->flags.funccontext)
3705 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3706 if (pe)
3707 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3709 diffopts = getenv("GIT_DIFF_OPTS");
3710 if (!diffopts)
3712 else if (skip_prefix(diffopts, "--unified=", &v))
3713 xecfg.ctxlen = strtoul(v, NULL, 10);
3714 else if (skip_prefix(diffopts, "-u", &v))
3715 xecfg.ctxlen = strtoul(v, NULL, 10);
3717 if (o->word_diff)
3718 init_diff_words_data(&ecbdata, o, one, two);
3719 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3720 &ecbdata, &xpp, &xecfg))
3721 die("unable to generate diff for %s", one->path);
3722 if (o->word_diff)
3723 free_diff_words_data(&ecbdata);
3724 if (textconv_one)
3725 free(mf1.ptr);
3726 if (textconv_two)
3727 free(mf2.ptr);
3728 xdiff_clear_find_func(&xecfg);
3731 free_ab_and_return:
3732 strbuf_release(&header);
3733 diff_free_filespec_data(one);
3734 diff_free_filespec_data(two);
3735 free(a_one);
3736 free(b_two);
3737 return;
3740 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3742 if (!is_renamed) {
3743 if (p->status == DIFF_STATUS_ADDED) {
3744 if (S_ISLNK(p->two->mode))
3745 return "new +l";
3746 else if ((p->two->mode & 0777) == 0755)
3747 return "new +x";
3748 else
3749 return "new";
3750 } else if (p->status == DIFF_STATUS_DELETED)
3751 return "gone";
3753 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3754 return "mode -l";
3755 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3756 return "mode +l";
3757 else if ((p->one->mode & 0777) == 0644 &&
3758 (p->two->mode & 0777) == 0755)
3759 return "mode +x";
3760 else if ((p->one->mode & 0777) == 0755 &&
3761 (p->two->mode & 0777) == 0644)
3762 return "mode -x";
3763 return NULL;
3766 static void builtin_diffstat(const char *name_a, const char *name_b,
3767 struct diff_filespec *one,
3768 struct diff_filespec *two,
3769 struct diffstat_t *diffstat,
3770 struct diff_options *o,
3771 struct diff_filepair *p)
3773 mmfile_t mf1, mf2;
3774 struct diffstat_file *data;
3775 int may_differ;
3776 int complete_rewrite = 0;
3778 if (!DIFF_PAIR_UNMERGED(p)) {
3779 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3780 complete_rewrite = 1;
3783 data = diffstat_add(diffstat, name_a, name_b);
3784 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3785 if (o->flags.stat_with_summary)
3786 data->comments = get_compact_summary(p, data->is_renamed);
3788 if (!one || !two) {
3789 data->is_unmerged = 1;
3790 return;
3793 /* saves some reads if true, not a guarantee of diff outcome */
3794 may_differ = !(one->oid_valid && two->oid_valid &&
3795 oideq(&one->oid, &two->oid));
3797 if (diff_filespec_is_binary(o->repo, one) ||
3798 diff_filespec_is_binary(o->repo, two)) {
3799 data->is_binary = 1;
3800 if (!may_differ) {
3801 data->added = 0;
3802 data->deleted = 0;
3803 } else {
3804 data->added = diff_filespec_size(o->repo, two);
3805 data->deleted = diff_filespec_size(o->repo, one);
3809 else if (complete_rewrite) {
3810 diff_populate_filespec(o->repo, one, NULL);
3811 diff_populate_filespec(o->repo, two, NULL);
3812 data->deleted = count_lines(one->data, one->size);
3813 data->added = count_lines(two->data, two->size);
3816 else if (may_differ) {
3817 /* Crazy xdl interfaces.. */
3818 xpparam_t xpp;
3819 xdemitconf_t xecfg;
3821 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3822 fill_mmfile(o->repo, &mf2, two) < 0)
3823 die("unable to read files to diff");
3825 memset(&xpp, 0, sizeof(xpp));
3826 memset(&xecfg, 0, sizeof(xecfg));
3827 xpp.flags = o->xdl_opts;
3828 xpp.ignore_regex = o->ignore_regex;
3829 xpp.ignore_regex_nr = o->ignore_regex_nr;
3830 xpp.anchors = o->anchors;
3831 xpp.anchors_nr = o->anchors_nr;
3832 xecfg.ctxlen = o->context;
3833 xecfg.interhunkctxlen = o->interhunkcontext;
3834 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3835 if (xdi_diff_outf(&mf1, &mf2, NULL,
3836 diffstat_consume, diffstat, &xpp, &xecfg))
3837 die("unable to generate diffstat for %s", one->path);
3839 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3840 struct diffstat_file *file =
3841 diffstat->files[diffstat->nr - 1];
3843 * Omit diffstats of modified files where nothing changed.
3844 * Even if may_differ, this might be the case due to
3845 * ignoring whitespace changes, etc.
3847 * But note that we special-case additions, deletions,
3848 * renames, and mode changes as adding an empty file,
3849 * for example is still of interest.
3851 if ((p->status == DIFF_STATUS_MODIFIED)
3852 && !file->added
3853 && !file->deleted
3854 && one->mode == two->mode) {
3855 free_diffstat_file(file);
3856 diffstat->nr--;
3861 diff_free_filespec_data(one);
3862 diff_free_filespec_data(two);
3865 static void builtin_checkdiff(const char *name_a, const char *name_b,
3866 const char *attr_path,
3867 struct diff_filespec *one,
3868 struct diff_filespec *two,
3869 struct diff_options *o)
3871 mmfile_t mf1, mf2;
3872 struct checkdiff_t data;
3874 if (!two)
3875 return;
3877 memset(&data, 0, sizeof(data));
3878 data.filename = name_b ? name_b : name_a;
3879 data.lineno = 0;
3880 data.o = o;
3881 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3882 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3884 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3885 fill_mmfile(o->repo, &mf2, two) < 0)
3886 die("unable to read files to diff");
3889 * All the other codepaths check both sides, but not checking
3890 * the "old" side here is deliberate. We are checking the newly
3891 * introduced changes, and as long as the "new" side is text, we
3892 * can and should check what it introduces.
3894 if (diff_filespec_is_binary(o->repo, two))
3895 goto free_and_return;
3896 else {
3897 /* Crazy xdl interfaces.. */
3898 xpparam_t xpp;
3899 xdemitconf_t xecfg;
3901 memset(&xpp, 0, sizeof(xpp));
3902 memset(&xecfg, 0, sizeof(xecfg));
3903 xecfg.ctxlen = 1; /* at least one context line */
3904 xpp.flags = 0;
3905 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3906 checkdiff_consume, &data,
3907 &xpp, &xecfg))
3908 die("unable to generate checkdiff for %s", one->path);
3910 if (data.ws_rule & WS_BLANK_AT_EOF) {
3911 struct emit_callback ecbdata;
3912 int blank_at_eof;
3914 ecbdata.ws_rule = data.ws_rule;
3915 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3916 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3918 if (blank_at_eof) {
3919 static char *err;
3920 if (!err)
3921 err = whitespace_error_string(WS_BLANK_AT_EOF);
3922 fprintf(o->file, "%s:%d: %s.\n",
3923 data.filename, blank_at_eof, err);
3924 data.status = 1; /* report errors */
3928 free_and_return:
3929 diff_free_filespec_data(one);
3930 diff_free_filespec_data(two);
3931 if (data.status)
3932 o->flags.check_failed = 1;
3935 struct diff_filespec *alloc_filespec(const char *path)
3937 struct diff_filespec *spec;
3939 FLEXPTR_ALLOC_STR(spec, path, path);
3940 spec->count = 1;
3941 spec->is_binary = -1;
3942 return spec;
3945 void free_filespec(struct diff_filespec *spec)
3947 if (!--spec->count) {
3948 diff_free_filespec_data(spec);
3949 free(spec);
3953 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3954 int oid_valid, unsigned short mode)
3956 if (mode) {
3957 spec->mode = canon_mode(mode);
3958 oidcpy(&spec->oid, oid);
3959 spec->oid_valid = oid_valid;
3964 * Given a name and sha1 pair, if the index tells us the file in
3965 * the work tree has that object contents, return true, so that
3966 * prepare_temp_file() does not have to inflate and extract.
3968 static int reuse_worktree_file(struct index_state *istate,
3969 const char *name,
3970 const struct object_id *oid,
3971 int want_file)
3973 const struct cache_entry *ce;
3974 struct stat st;
3975 int pos, len;
3978 * We do not read the cache ourselves here, because the
3979 * benchmark with my previous version that always reads cache
3980 * shows that it makes things worse for diff-tree comparing
3981 * two linux-2.6 kernel trees in an already checked out work
3982 * tree. This is because most diff-tree comparisons deal with
3983 * only a small number of files, while reading the cache is
3984 * expensive for a large project, and its cost outweighs the
3985 * savings we get by not inflating the object to a temporary
3986 * file. Practically, this code only helps when we are used
3987 * by diff-cache --cached, which does read the cache before
3988 * calling us.
3990 if (!istate->cache)
3991 return 0;
3993 /* We want to avoid the working directory if our caller
3994 * doesn't need the data in a normal file, this system
3995 * is rather slow with its stat/open/mmap/close syscalls,
3996 * and the object is contained in a pack file. The pack
3997 * is probably already open and will be faster to obtain
3998 * the data through than the working directory. Loose
3999 * objects however would tend to be slower as they need
4000 * to be individually opened and inflated.
4002 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
4003 return 0;
4006 * Similarly, if we'd have to convert the file contents anyway, that
4007 * makes the optimization not worthwhile.
4009 if (!want_file && would_convert_to_git(istate, name))
4010 return 0;
4013 * If this path does not match our sparse-checkout definition,
4014 * then the file will not be in the working directory.
4016 if (!path_in_sparse_checkout(name, istate))
4017 return 0;
4019 len = strlen(name);
4020 pos = index_name_pos(istate, name, len);
4021 if (pos < 0)
4022 return 0;
4023 ce = istate->cache[pos];
4026 * This is not the sha1 we are looking for, or
4027 * unreusable because it is not a regular file.
4029 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4030 return 0;
4033 * If ce is marked as "assume unchanged", there is no
4034 * guarantee that work tree matches what we are looking for.
4036 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4037 return 0;
4040 * If ce matches the file in the work tree, we can reuse it.
4042 if (ce_uptodate(ce) ||
4043 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4044 return 1;
4046 return 0;
4049 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4051 struct strbuf buf = STRBUF_INIT;
4052 char *dirty = "";
4054 /* Are we looking at the work tree? */
4055 if (s->dirty_submodule)
4056 dirty = "-dirty";
4058 strbuf_addf(&buf, "Subproject commit %s%s\n",
4059 oid_to_hex(&s->oid), dirty);
4060 s->size = buf.len;
4061 if (size_only) {
4062 s->data = NULL;
4063 strbuf_release(&buf);
4064 } else {
4065 s->data = strbuf_detach(&buf, NULL);
4066 s->should_free = 1;
4068 return 0;
4072 * While doing rename detection and pickaxe operation, we may need to
4073 * grab the data for the blob (or file) for our own in-core comparison.
4074 * diff_filespec has data and size fields for this purpose.
4076 int diff_populate_filespec(struct repository *r,
4077 struct diff_filespec *s,
4078 const struct diff_populate_filespec_options *options)
4080 int size_only = options ? options->check_size_only : 0;
4081 int check_binary = options ? options->check_binary : 0;
4082 int err = 0;
4083 int conv_flags = global_conv_flags_eol;
4085 * demote FAIL to WARN to allow inspecting the situation
4086 * instead of refusing.
4088 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4089 conv_flags = CONV_EOL_RNDTRP_WARN;
4091 if (!DIFF_FILE_VALID(s))
4092 die("internal error: asking to populate invalid file.");
4093 if (S_ISDIR(s->mode))
4094 return -1;
4096 if (s->data)
4097 return 0;
4099 if (size_only && 0 < s->size)
4100 return 0;
4102 if (S_ISGITLINK(s->mode))
4103 return diff_populate_gitlink(s, size_only);
4105 if (!s->oid_valid ||
4106 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4107 struct strbuf buf = STRBUF_INIT;
4108 struct stat st;
4109 int fd;
4111 if (lstat(s->path, &st) < 0) {
4112 err_empty:
4113 err = -1;
4114 empty:
4115 s->data = (char *)"";
4116 s->size = 0;
4117 return err;
4119 s->size = xsize_t(st.st_size);
4120 if (!s->size)
4121 goto empty;
4122 if (S_ISLNK(st.st_mode)) {
4123 struct strbuf sb = STRBUF_INIT;
4125 if (strbuf_readlink(&sb, s->path, s->size))
4126 goto err_empty;
4127 s->size = sb.len;
4128 s->data = strbuf_detach(&sb, NULL);
4129 s->should_free = 1;
4130 return 0;
4134 * Even if the caller would be happy with getting
4135 * only the size, we cannot return early at this
4136 * point if the path requires us to run the content
4137 * conversion.
4139 if (size_only && !would_convert_to_git(r->index, s->path))
4140 return 0;
4143 * Note: this check uses xsize_t(st.st_size) that may
4144 * not be the true size of the blob after it goes
4145 * through convert_to_git(). This may not strictly be
4146 * correct, but the whole point of big_file_threshold
4147 * and is_binary check being that we want to avoid
4148 * opening the file and inspecting the contents, this
4149 * is probably fine.
4151 if (check_binary &&
4152 s->size > big_file_threshold && s->is_binary == -1) {
4153 s->is_binary = 1;
4154 return 0;
4156 fd = open(s->path, O_RDONLY);
4157 if (fd < 0)
4158 goto err_empty;
4159 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4160 close(fd);
4161 s->should_munmap = 1;
4164 * Convert from working tree format to canonical git format
4166 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4167 size_t size = 0;
4168 munmap(s->data, s->size);
4169 s->should_munmap = 0;
4170 s->data = strbuf_detach(&buf, &size);
4171 s->size = size;
4172 s->should_free = 1;
4175 else {
4176 struct object_info info = {
4177 .sizep = &s->size
4180 if (!(size_only || check_binary))
4182 * Set contentp, since there is no chance that merely
4183 * the size is sufficient.
4185 info.contentp = &s->data;
4187 if (options && options->missing_object_cb) {
4188 if (!oid_object_info_extended(r, &s->oid, &info,
4189 OBJECT_INFO_LOOKUP_REPLACE |
4190 OBJECT_INFO_SKIP_FETCH_OBJECT))
4191 goto object_read;
4192 options->missing_object_cb(options->missing_object_data);
4194 if (oid_object_info_extended(r, &s->oid, &info,
4195 OBJECT_INFO_LOOKUP_REPLACE))
4196 die("unable to read %s", oid_to_hex(&s->oid));
4198 object_read:
4199 if (size_only || check_binary) {
4200 if (size_only)
4201 return 0;
4202 if (s->size > big_file_threshold && s->is_binary == -1) {
4203 s->is_binary = 1;
4204 return 0;
4207 if (!info.contentp) {
4208 info.contentp = &s->data;
4209 if (oid_object_info_extended(r, &s->oid, &info,
4210 OBJECT_INFO_LOOKUP_REPLACE))
4211 die("unable to read %s", oid_to_hex(&s->oid));
4213 s->should_free = 1;
4215 return 0;
4218 void diff_free_filespec_blob(struct diff_filespec *s)
4220 if (s->should_free)
4221 free(s->data);
4222 else if (s->should_munmap)
4223 munmap(s->data, s->size);
4225 if (s->should_free || s->should_munmap) {
4226 s->should_free = s->should_munmap = 0;
4227 s->data = NULL;
4231 void diff_free_filespec_data(struct diff_filespec *s)
4233 if (!s)
4234 return;
4236 diff_free_filespec_blob(s);
4237 FREE_AND_NULL(s->cnt_data);
4240 static void prep_temp_blob(struct index_state *istate,
4241 const char *path, struct diff_tempfile *temp,
4242 void *blob,
4243 unsigned long size,
4244 const struct object_id *oid,
4245 int mode)
4247 struct strbuf buf = STRBUF_INIT;
4248 char *path_dup = xstrdup(path);
4249 const char *base = basename(path_dup);
4250 struct checkout_metadata meta;
4252 init_checkout_metadata(&meta, NULL, NULL, oid);
4254 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4255 if (!temp->tempfile)
4256 die_errno("unable to create temp-file");
4257 if (convert_to_working_tree(istate, path,
4258 (const char *)blob, (size_t)size, &buf, &meta)) {
4259 blob = buf.buf;
4260 size = buf.len;
4262 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4263 close_tempfile_gently(temp->tempfile))
4264 die_errno("unable to write temp-file");
4265 temp->name = get_tempfile_path(temp->tempfile);
4266 oid_to_hex_r(temp->hex, oid);
4267 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4268 strbuf_release(&buf);
4269 free(path_dup);
4272 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4273 struct diff_filespec *one)
4275 struct diff_tempfile *temp = claim_diff_tempfile();
4277 if (!DIFF_FILE_VALID(one)) {
4278 not_a_valid_file:
4279 /* A '-' entry produces this for file-2, and
4280 * a '+' entry produces this for file-1.
4282 temp->name = "/dev/null";
4283 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4284 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4285 return temp;
4288 if (!S_ISGITLINK(one->mode) &&
4289 (!one->oid_valid ||
4290 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4291 struct stat st;
4292 if (lstat(one->path, &st) < 0) {
4293 if (errno == ENOENT)
4294 goto not_a_valid_file;
4295 die_errno("stat(%s)", one->path);
4297 if (S_ISLNK(st.st_mode)) {
4298 struct strbuf sb = STRBUF_INIT;
4299 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4300 die_errno("readlink(%s)", one->path);
4301 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4302 (one->oid_valid ?
4303 &one->oid : null_oid()),
4304 (one->oid_valid ?
4305 one->mode : S_IFLNK));
4306 strbuf_release(&sb);
4308 else {
4309 /* we can borrow from the file in the work tree */
4310 temp->name = one->path;
4311 if (!one->oid_valid)
4312 oid_to_hex_r(temp->hex, null_oid());
4313 else
4314 oid_to_hex_r(temp->hex, &one->oid);
4315 /* Even though we may sometimes borrow the
4316 * contents from the work tree, we always want
4317 * one->mode. mode is trustworthy even when
4318 * !(one->oid_valid), as long as
4319 * DIFF_FILE_VALID(one).
4321 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4323 return temp;
4325 else {
4326 if (diff_populate_filespec(r, one, NULL))
4327 die("cannot read data blob for %s", one->path);
4328 prep_temp_blob(r->index, one->path, temp,
4329 one->data, one->size,
4330 &one->oid, one->mode);
4332 return temp;
4335 static void add_external_diff_name(struct repository *r,
4336 struct strvec *argv,
4337 struct diff_filespec *df)
4339 struct diff_tempfile *temp = prepare_temp_file(r, df);
4340 strvec_push(argv, temp->name);
4341 strvec_push(argv, temp->hex);
4342 strvec_push(argv, temp->mode);
4345 /* An external diff command takes:
4347 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4348 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4351 static void run_external_diff(const char *pgm,
4352 const char *name,
4353 const char *other,
4354 struct diff_filespec *one,
4355 struct diff_filespec *two,
4356 const char *xfrm_msg,
4357 struct diff_options *o)
4359 struct child_process cmd = CHILD_PROCESS_INIT;
4360 struct diff_queue_struct *q = &diff_queued_diff;
4362 strvec_push(&cmd.args, pgm);
4363 strvec_push(&cmd.args, name);
4365 if (one && two) {
4366 add_external_diff_name(o->repo, &cmd.args, one);
4367 add_external_diff_name(o->repo, &cmd.args, two);
4368 if (other) {
4369 strvec_push(&cmd.args, other);
4370 strvec_push(&cmd.args, xfrm_msg);
4374 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4375 ++o->diff_path_counter);
4376 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4378 diff_free_filespec_data(one);
4379 diff_free_filespec_data(two);
4380 cmd.use_shell = 1;
4381 if (run_command(&cmd))
4382 die(_("external diff died, stopping at %s"), name);
4384 remove_tempfile();
4387 static int similarity_index(struct diff_filepair *p)
4389 return p->score * 100 / MAX_SCORE;
4392 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4394 if (startup_info->have_repository)
4395 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4396 else {
4397 char *hex = oid_to_hex(oid);
4398 if (abbrev < 0)
4399 abbrev = FALLBACK_DEFAULT_ABBREV;
4400 if (abbrev > the_hash_algo->hexsz)
4401 BUG("oid abbreviation out of range: %d", abbrev);
4402 if (abbrev)
4403 hex[abbrev] = '\0';
4404 return hex;
4408 static void fill_metainfo(struct strbuf *msg,
4409 const char *name,
4410 const char *other,
4411 struct diff_filespec *one,
4412 struct diff_filespec *two,
4413 struct diff_options *o,
4414 struct diff_filepair *p,
4415 int *must_show_header,
4416 int use_color)
4418 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4419 const char *reset = diff_get_color(use_color, DIFF_RESET);
4420 const char *line_prefix = diff_line_prefix(o);
4421 struct string_list *more_headers = NULL;
4423 *must_show_header = 1;
4424 strbuf_init(msg, PATH_MAX * 2 + 300);
4425 switch (p->status) {
4426 case DIFF_STATUS_COPIED:
4427 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4428 line_prefix, set, similarity_index(p));
4429 strbuf_addf(msg, "%s\n%s%scopy from ",
4430 reset, line_prefix, set);
4431 quote_c_style(name, msg, NULL, 0);
4432 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4433 quote_c_style(other, msg, NULL, 0);
4434 strbuf_addf(msg, "%s\n", reset);
4435 break;
4436 case DIFF_STATUS_RENAMED:
4437 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4438 line_prefix, set, similarity_index(p));
4439 strbuf_addf(msg, "%s\n%s%srename from ",
4440 reset, line_prefix, set);
4441 quote_c_style(name, msg, NULL, 0);
4442 strbuf_addf(msg, "%s\n%s%srename to ",
4443 reset, line_prefix, set);
4444 quote_c_style(other, msg, NULL, 0);
4445 strbuf_addf(msg, "%s\n", reset);
4446 break;
4447 case DIFF_STATUS_MODIFIED:
4448 if (p->score) {
4449 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4450 line_prefix,
4451 set, similarity_index(p), reset);
4452 break;
4454 /* fallthru */
4455 default:
4456 *must_show_header = 0;
4458 if ((more_headers = additional_headers(o, name))) {
4459 add_formatted_headers(msg, more_headers,
4460 line_prefix, set, reset);
4461 *must_show_header = 1;
4463 if (one && two && !oideq(&one->oid, &two->oid)) {
4464 const unsigned hexsz = the_hash_algo->hexsz;
4465 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4467 if (o->flags.full_index)
4468 abbrev = hexsz;
4470 if (o->flags.binary) {
4471 mmfile_t mf;
4472 if ((!fill_mmfile(o->repo, &mf, one) &&
4473 diff_filespec_is_binary(o->repo, one)) ||
4474 (!fill_mmfile(o->repo, &mf, two) &&
4475 diff_filespec_is_binary(o->repo, two)))
4476 abbrev = hexsz;
4478 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4479 diff_abbrev_oid(&one->oid, abbrev),
4480 diff_abbrev_oid(&two->oid, abbrev));
4481 if (one->mode == two->mode)
4482 strbuf_addf(msg, " %06o", one->mode);
4483 strbuf_addf(msg, "%s\n", reset);
4487 static void run_diff_cmd(const char *pgm,
4488 const char *name,
4489 const char *other,
4490 const char *attr_path,
4491 struct diff_filespec *one,
4492 struct diff_filespec *two,
4493 struct strbuf *msg,
4494 struct diff_options *o,
4495 struct diff_filepair *p)
4497 const char *xfrm_msg = NULL;
4498 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4499 int must_show_header = 0;
4500 struct userdiff_driver *drv = NULL;
4502 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4503 drv = userdiff_find_by_path(o->repo->index, attr_path);
4505 if (o->flags.allow_external && drv && drv->external)
4506 pgm = drv->external;
4508 if (msg) {
4510 * don't use colors when the header is intended for an
4511 * external diff driver
4513 fill_metainfo(msg, name, other, one, two, o, p,
4514 &must_show_header,
4515 want_color(o->use_color) && !pgm);
4516 xfrm_msg = msg->len ? msg->buf : NULL;
4519 if (pgm) {
4520 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4521 return;
4523 if (one && two) {
4524 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4525 set_diff_algorithm(o, drv->algorithm);
4527 builtin_diff(name, other ? other : name,
4528 one, two, xfrm_msg, must_show_header,
4529 o, complete_rewrite);
4530 } else {
4531 fprintf(o->file, "* Unmerged path %s\n", name);
4535 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4537 if (DIFF_FILE_VALID(one)) {
4538 if (!one->oid_valid) {
4539 struct stat st;
4540 if (one->is_stdin) {
4541 oidclr(&one->oid);
4542 return;
4544 if (lstat(one->path, &st) < 0)
4545 die_errno("stat '%s'", one->path);
4546 if (index_path(istate, &one->oid, one->path, &st, 0))
4547 die("cannot hash %s", one->path);
4550 else
4551 oidclr(&one->oid);
4554 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4556 /* Strip the prefix but do not molest /dev/null and absolute paths */
4557 if (*namep && !is_absolute_path(*namep)) {
4558 *namep += prefix_length;
4559 if (**namep == '/')
4560 ++*namep;
4562 if (*otherp && !is_absolute_path(*otherp)) {
4563 *otherp += prefix_length;
4564 if (**otherp == '/')
4565 ++*otherp;
4569 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4571 const char *pgm = external_diff();
4572 struct strbuf msg;
4573 struct diff_filespec *one = p->one;
4574 struct diff_filespec *two = p->two;
4575 const char *name;
4576 const char *other;
4577 const char *attr_path;
4579 name = one->path;
4580 other = (strcmp(name, two->path) ? two->path : NULL);
4581 attr_path = name;
4582 if (o->prefix_length)
4583 strip_prefix(o->prefix_length, &name, &other);
4585 if (!o->flags.allow_external)
4586 pgm = NULL;
4588 if (DIFF_PAIR_UNMERGED(p)) {
4589 run_diff_cmd(pgm, name, NULL, attr_path,
4590 NULL, NULL, NULL, o, p);
4591 return;
4594 diff_fill_oid_info(one, o->repo->index);
4595 diff_fill_oid_info(two, o->repo->index);
4597 if (!pgm &&
4598 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4599 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4601 * a filepair that changes between file and symlink
4602 * needs to be split into deletion and creation.
4604 struct diff_filespec *null = alloc_filespec(two->path);
4605 run_diff_cmd(NULL, name, other, attr_path,
4606 one, null, &msg,
4607 o, p);
4608 free(null);
4609 strbuf_release(&msg);
4611 null = alloc_filespec(one->path);
4612 run_diff_cmd(NULL, name, other, attr_path,
4613 null, two, &msg, o, p);
4614 free(null);
4616 else
4617 run_diff_cmd(pgm, name, other, attr_path,
4618 one, two, &msg, o, p);
4620 strbuf_release(&msg);
4623 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4624 struct diffstat_t *diffstat)
4626 const char *name;
4627 const char *other;
4629 if (!o->ignore_driver_algorithm) {
4630 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4631 p->one->path);
4633 if (drv && drv->algorithm)
4634 set_diff_algorithm(o, drv->algorithm);
4637 if (DIFF_PAIR_UNMERGED(p)) {
4638 /* unmerged */
4639 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4640 diffstat, o, p);
4641 return;
4644 name = p->one->path;
4645 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4647 if (o->prefix_length)
4648 strip_prefix(o->prefix_length, &name, &other);
4650 diff_fill_oid_info(p->one, o->repo->index);
4651 diff_fill_oid_info(p->two, o->repo->index);
4653 builtin_diffstat(name, other, p->one, p->two,
4654 diffstat, o, p);
4657 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4659 const char *name;
4660 const char *other;
4661 const char *attr_path;
4663 if (DIFF_PAIR_UNMERGED(p)) {
4664 /* unmerged */
4665 return;
4668 name = p->one->path;
4669 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4670 attr_path = other ? other : name;
4672 if (o->prefix_length)
4673 strip_prefix(o->prefix_length, &name, &other);
4675 diff_fill_oid_info(p->one, o->repo->index);
4676 diff_fill_oid_info(p->two, o->repo->index);
4678 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4681 void repo_diff_setup(struct repository *r, struct diff_options *options)
4683 memcpy(options, &default_diff_options, sizeof(*options));
4685 options->file = stdout;
4686 options->repo = r;
4688 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4689 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4690 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4691 options->abbrev = DEFAULT_ABBREV;
4692 options->line_termination = '\n';
4693 options->break_opt = -1;
4694 options->rename_limit = -1;
4695 options->dirstat_permille = diff_dirstat_permille_default;
4696 options->context = diff_context_default;
4697 options->interhunkcontext = diff_interhunk_context_default;
4698 options->ws_error_highlight = ws_error_highlight_default;
4699 options->flags.rename_empty = 1;
4700 options->flags.relative_name = diff_relative;
4701 options->objfind = NULL;
4703 /* pathchange left =NULL by default */
4704 options->change = diff_change;
4705 options->add_remove = diff_addremove;
4706 options->use_color = diff_use_color_default;
4707 options->detect_rename = diff_detect_rename_default;
4708 options->xdl_opts |= diff_algorithm;
4709 if (diff_indent_heuristic)
4710 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4712 options->orderfile = diff_order_file_cfg;
4714 if (!options->flags.ignore_submodule_set)
4715 options->flags.ignore_untracked_in_submodules = 1;
4717 if (diff_no_prefix) {
4718 diff_set_noprefix(options);
4719 } else if (!diff_mnemonic_prefix) {
4720 diff_set_default_prefix(options);
4723 options->color_moved = diff_color_moved_default;
4724 options->color_moved_ws_handling = diff_color_moved_ws_default;
4727 static const char diff_status_letters[] = {
4728 DIFF_STATUS_ADDED,
4729 DIFF_STATUS_COPIED,
4730 DIFF_STATUS_DELETED,
4731 DIFF_STATUS_MODIFIED,
4732 DIFF_STATUS_RENAMED,
4733 DIFF_STATUS_TYPE_CHANGED,
4734 DIFF_STATUS_UNKNOWN,
4735 DIFF_STATUS_UNMERGED,
4736 DIFF_STATUS_FILTER_AON,
4737 DIFF_STATUS_FILTER_BROKEN,
4738 '\0',
4741 static unsigned int filter_bit['Z' + 1];
4743 static void prepare_filter_bits(void)
4745 int i;
4747 if (!filter_bit[DIFF_STATUS_ADDED]) {
4748 for (i = 0; diff_status_letters[i]; i++)
4749 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4753 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4755 return opt->filter & filter_bit[(int) status];
4758 unsigned diff_filter_bit(char status)
4760 prepare_filter_bits();
4761 return filter_bit[(int) status];
4764 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4766 unsigned forbidden_magic;
4768 if (ps->nr != 1) {
4769 if (die_on_error)
4770 die(_("--follow requires exactly one pathspec"));
4771 return 0;
4774 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4775 PATHSPEC_LITERAL);
4776 if (forbidden_magic) {
4777 if (die_on_error) {
4778 struct strbuf sb = STRBUF_INIT;
4779 pathspec_magic_names(forbidden_magic, &sb);
4780 die(_("pathspec magic not supported by --follow: %s"),
4781 sb.buf);
4783 return 0;
4786 return 1;
4789 void diff_setup_done(struct diff_options *options)
4791 unsigned check_mask = DIFF_FORMAT_NAME |
4792 DIFF_FORMAT_NAME_STATUS |
4793 DIFF_FORMAT_CHECKDIFF |
4794 DIFF_FORMAT_NO_OUTPUT;
4796 * This must be signed because we're comparing against a potentially
4797 * negative value.
4799 const int hexsz = the_hash_algo->hexsz;
4801 if (options->set_default)
4802 options->set_default(options);
4804 if (HAS_MULTI_BITS(options->output_format & check_mask))
4805 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4806 "--name-only", "--name-status", "--check", "-s");
4808 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4809 die(_("options '%s', '%s', and '%s' cannot be used together"),
4810 "-G", "-S", "--find-object");
4812 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4813 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4814 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4816 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4817 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4818 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4821 * Most of the time we can say "there are changes"
4822 * only by checking if there are changed paths, but
4823 * --ignore-whitespace* options force us to look
4824 * inside contents.
4827 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4828 options->ignore_regex_nr)
4829 options->flags.diff_from_contents = 1;
4830 else
4831 options->flags.diff_from_contents = 0;
4833 if (options->flags.find_copies_harder)
4834 options->detect_rename = DIFF_DETECT_COPY;
4836 if (!options->flags.relative_name)
4837 options->prefix = NULL;
4838 if (options->prefix)
4839 options->prefix_length = strlen(options->prefix);
4840 else
4841 options->prefix_length = 0;
4844 * --name-only, --name-status, --checkdiff, and -s
4845 * turn other output format off.
4847 if (options->output_format & (DIFF_FORMAT_NAME |
4848 DIFF_FORMAT_NAME_STATUS |
4849 DIFF_FORMAT_CHECKDIFF |
4850 DIFF_FORMAT_NO_OUTPUT))
4851 options->output_format &= ~(DIFF_FORMAT_RAW |
4852 DIFF_FORMAT_NUMSTAT |
4853 DIFF_FORMAT_DIFFSTAT |
4854 DIFF_FORMAT_SHORTSTAT |
4855 DIFF_FORMAT_DIRSTAT |
4856 DIFF_FORMAT_SUMMARY |
4857 DIFF_FORMAT_PATCH);
4860 * These cases always need recursive; we do not drop caller-supplied
4861 * recursive bits for other formats here.
4863 if (options->output_format & (DIFF_FORMAT_PATCH |
4864 DIFF_FORMAT_NUMSTAT |
4865 DIFF_FORMAT_DIFFSTAT |
4866 DIFF_FORMAT_SHORTSTAT |
4867 DIFF_FORMAT_DIRSTAT |
4868 DIFF_FORMAT_SUMMARY |
4869 DIFF_FORMAT_CHECKDIFF))
4870 options->flags.recursive = 1;
4872 * Also pickaxe would not work very well if you do not say recursive
4874 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4875 options->flags.recursive = 1;
4877 * When patches are generated, submodules diffed against the work tree
4878 * must be checked for dirtiness too so it can be shown in the output
4880 if (options->output_format & DIFF_FORMAT_PATCH)
4881 options->flags.dirty_submodules = 1;
4883 if (options->detect_rename && options->rename_limit < 0)
4884 options->rename_limit = diff_rename_limit_default;
4885 if (hexsz < options->abbrev)
4886 options->abbrev = hexsz; /* full */
4889 * It does not make sense to show the first hit we happened
4890 * to have found. It does not make sense not to return with
4891 * exit code in such a case either.
4893 if (options->flags.quick) {
4894 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4895 options->flags.exit_with_status = 1;
4898 options->diff_path_counter = 0;
4900 if (options->flags.follow_renames)
4901 diff_check_follow_pathspec(&options->pathspec, 1);
4903 if (!options->use_color || external_diff())
4904 options->color_moved = 0;
4906 if (options->filter_not) {
4907 if (!options->filter)
4908 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4909 options->filter &= ~options->filter_not;
4913 int parse_long_opt(const char *opt, const char **argv,
4914 const char **optarg)
4916 const char *arg = argv[0];
4917 if (!skip_prefix(arg, "--", &arg))
4918 return 0;
4919 if (!skip_prefix(arg, opt, &arg))
4920 return 0;
4921 if (*arg == '=') { /* stuck form: --option=value */
4922 *optarg = arg + 1;
4923 return 1;
4925 if (*arg != '\0')
4926 return 0;
4927 /* separate form: --option value */
4928 if (!argv[1])
4929 die("Option '--%s' requires a value", opt);
4930 *optarg = argv[1];
4931 return 2;
4934 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4936 struct diff_options *options = opt->value;
4937 int width = options->stat_width;
4938 int name_width = options->stat_name_width;
4939 int graph_width = options->stat_graph_width;
4940 int count = options->stat_count;
4941 char *end;
4943 BUG_ON_OPT_NEG(unset);
4945 if (!strcmp(opt->long_name, "stat")) {
4946 if (value) {
4947 width = strtoul(value, &end, 10);
4948 if (*end == ',')
4949 name_width = strtoul(end+1, &end, 10);
4950 if (*end == ',')
4951 count = strtoul(end+1, &end, 10);
4952 if (*end)
4953 return error(_("invalid --stat value: %s"), value);
4955 } else if (!strcmp(opt->long_name, "stat-width")) {
4956 width = strtoul(value, &end, 10);
4957 if (*end)
4958 return error(_("%s expects a numerical value"),
4959 opt->long_name);
4960 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4961 name_width = strtoul(value, &end, 10);
4962 if (*end)
4963 return error(_("%s expects a numerical value"),
4964 opt->long_name);
4965 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4966 graph_width = strtoul(value, &end, 10);
4967 if (*end)
4968 return error(_("%s expects a numerical value"),
4969 opt->long_name);
4970 } else if (!strcmp(opt->long_name, "stat-count")) {
4971 count = strtoul(value, &end, 10);
4972 if (*end)
4973 return error(_("%s expects a numerical value"),
4974 opt->long_name);
4975 } else
4976 BUG("%s should not get here", opt->long_name);
4978 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4979 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4980 options->stat_name_width = name_width;
4981 options->stat_graph_width = graph_width;
4982 options->stat_width = width;
4983 options->stat_count = count;
4984 return 0;
4987 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4989 struct strbuf errmsg = STRBUF_INIT;
4990 if (parse_dirstat_params(options, params, &errmsg))
4991 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4992 errmsg.buf);
4993 strbuf_release(&errmsg);
4995 * The caller knows a dirstat-related option is given from the command
4996 * line; allow it to say "return this_function();"
4998 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4999 options->output_format |= DIFF_FORMAT_DIRSTAT;
5000 return 1;
5003 static int diff_opt_diff_filter(const struct option *option,
5004 const char *optarg, int unset)
5006 struct diff_options *opt = option->value;
5007 int i, optch;
5009 BUG_ON_OPT_NEG(unset);
5010 prepare_filter_bits();
5012 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5013 unsigned int bit;
5014 int negate;
5016 if ('a' <= optch && optch <= 'z') {
5017 negate = 1;
5018 optch = toupper(optch);
5019 } else {
5020 negate = 0;
5023 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5024 if (!bit)
5025 return error(_("unknown change class '%c' in --diff-filter=%s"),
5026 optarg[i], optarg);
5027 if (negate)
5028 opt->filter_not |= bit;
5029 else
5030 opt->filter |= bit;
5032 return 0;
5035 static void enable_patch_output(int *fmt)
5037 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5038 *fmt |= DIFF_FORMAT_PATCH;
5041 static int diff_opt_ws_error_highlight(const struct option *option,
5042 const char *arg, int unset)
5044 struct diff_options *opt = option->value;
5045 int val = parse_ws_error_highlight(arg);
5047 BUG_ON_OPT_NEG(unset);
5048 if (val < 0)
5049 return error(_("unknown value after ws-error-highlight=%.*s"),
5050 -1 - val, arg);
5051 opt->ws_error_highlight = val;
5052 return 0;
5055 static int diff_opt_find_object(const struct option *option,
5056 const char *arg, int unset)
5058 struct diff_options *opt = option->value;
5059 struct object_id oid;
5061 BUG_ON_OPT_NEG(unset);
5062 if (repo_get_oid(the_repository, arg, &oid))
5063 return error(_("unable to resolve '%s'"), arg);
5065 if (!opt->objfind)
5066 CALLOC_ARRAY(opt->objfind, 1);
5068 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5069 opt->flags.recursive = 1;
5070 opt->flags.tree_in_recursive = 1;
5071 oidset_insert(opt->objfind, &oid);
5072 return 0;
5075 static int diff_opt_anchored(const struct option *opt,
5076 const char *arg, int unset)
5078 struct diff_options *options = opt->value;
5080 BUG_ON_OPT_NEG(unset);
5081 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5082 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5083 options->anchors_alloc);
5084 options->anchors[options->anchors_nr++] = xstrdup(arg);
5085 return 0;
5088 static int diff_opt_binary(const struct option *opt,
5089 const char *arg, int unset)
5091 struct diff_options *options = opt->value;
5093 BUG_ON_OPT_NEG(unset);
5094 BUG_ON_OPT_ARG(arg);
5095 enable_patch_output(&options->output_format);
5096 options->flags.binary = 1;
5097 return 0;
5100 static int diff_opt_break_rewrites(const struct option *opt,
5101 const char *arg, int unset)
5103 int *break_opt = opt->value;
5104 int opt1, opt2;
5106 BUG_ON_OPT_NEG(unset);
5107 if (!arg)
5108 arg = "";
5109 opt1 = parse_rename_score(&arg);
5110 if (*arg == 0)
5111 opt2 = 0;
5112 else if (*arg != '/')
5113 return error(_("%s expects <n>/<m> form"), opt->long_name);
5114 else {
5115 arg++;
5116 opt2 = parse_rename_score(&arg);
5118 if (*arg != 0)
5119 return error(_("%s expects <n>/<m> form"), opt->long_name);
5120 *break_opt = opt1 | (opt2 << 16);
5121 return 0;
5124 static int diff_opt_char(const struct option *opt,
5125 const char *arg, int unset)
5127 char *value = opt->value;
5129 BUG_ON_OPT_NEG(unset);
5130 if (arg[1])
5131 return error(_("%s expects a character, got '%s'"),
5132 opt->long_name, arg);
5133 *value = arg[0];
5134 return 0;
5137 static int diff_opt_color_moved(const struct option *opt,
5138 const char *arg, int unset)
5140 struct diff_options *options = opt->value;
5142 if (unset) {
5143 options->color_moved = COLOR_MOVED_NO;
5144 } else if (!arg) {
5145 if (diff_color_moved_default)
5146 options->color_moved = diff_color_moved_default;
5147 if (options->color_moved == COLOR_MOVED_NO)
5148 options->color_moved = COLOR_MOVED_DEFAULT;
5149 } else {
5150 int cm = parse_color_moved(arg);
5151 if (cm < 0)
5152 return error(_("bad --color-moved argument: %s"), arg);
5153 options->color_moved = cm;
5155 return 0;
5158 static int diff_opt_color_moved_ws(const struct option *opt,
5159 const char *arg, int unset)
5161 struct diff_options *options = opt->value;
5162 unsigned cm;
5164 if (unset) {
5165 options->color_moved_ws_handling = 0;
5166 return 0;
5169 cm = parse_color_moved_ws(arg);
5170 if (cm & COLOR_MOVED_WS_ERROR)
5171 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5172 options->color_moved_ws_handling = cm;
5173 return 0;
5176 static int diff_opt_color_words(const struct option *opt,
5177 const char *arg, int unset)
5179 struct diff_options *options = opt->value;
5181 BUG_ON_OPT_NEG(unset);
5182 options->use_color = 1;
5183 options->word_diff = DIFF_WORDS_COLOR;
5184 options->word_regex = arg;
5185 return 0;
5188 static int diff_opt_compact_summary(const struct option *opt,
5189 const char *arg, int unset)
5191 struct diff_options *options = opt->value;
5193 BUG_ON_OPT_ARG(arg);
5194 if (unset) {
5195 options->flags.stat_with_summary = 0;
5196 } else {
5197 options->flags.stat_with_summary = 1;
5198 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5199 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5201 return 0;
5204 static int diff_opt_diff_algorithm(const struct option *opt,
5205 const char *arg, int unset)
5207 struct diff_options *options = opt->value;
5209 BUG_ON_OPT_NEG(unset);
5211 if (set_diff_algorithm(options, arg))
5212 return error(_("option diff-algorithm accepts \"myers\", "
5213 "\"minimal\", \"patience\" and \"histogram\""));
5215 options->ignore_driver_algorithm = 1;
5217 return 0;
5220 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5221 const char *arg, int unset)
5223 struct diff_options *options = opt->value;
5225 BUG_ON_OPT_NEG(unset);
5226 BUG_ON_OPT_ARG(arg);
5228 if (set_diff_algorithm(options, opt->long_name))
5229 BUG("available diff algorithms include \"myers\", "
5230 "\"minimal\", \"patience\" and \"histogram\"");
5232 options->ignore_driver_algorithm = 1;
5234 return 0;
5237 static int diff_opt_dirstat(const struct option *opt,
5238 const char *arg, int unset)
5240 struct diff_options *options = opt->value;
5242 BUG_ON_OPT_NEG(unset);
5243 if (!strcmp(opt->long_name, "cumulative")) {
5244 if (arg)
5245 BUG("how come --cumulative take a value?");
5246 arg = "cumulative";
5247 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5248 parse_dirstat_opt(options, "files");
5249 parse_dirstat_opt(options, arg ? arg : "");
5250 return 0;
5253 static int diff_opt_find_copies(const struct option *opt,
5254 const char *arg, int unset)
5256 struct diff_options *options = opt->value;
5258 BUG_ON_OPT_NEG(unset);
5259 if (!arg)
5260 arg = "";
5261 options->rename_score = parse_rename_score(&arg);
5262 if (*arg != 0)
5263 return error(_("invalid argument to %s"), opt->long_name);
5265 if (options->detect_rename == DIFF_DETECT_COPY)
5266 options->flags.find_copies_harder = 1;
5267 else
5268 options->detect_rename = DIFF_DETECT_COPY;
5270 return 0;
5273 static int diff_opt_find_renames(const struct option *opt,
5274 const char *arg, int unset)
5276 struct diff_options *options = opt->value;
5278 BUG_ON_OPT_NEG(unset);
5279 if (!arg)
5280 arg = "";
5281 options->rename_score = parse_rename_score(&arg);
5282 if (*arg != 0)
5283 return error(_("invalid argument to %s"), opt->long_name);
5285 options->detect_rename = DIFF_DETECT_RENAME;
5286 return 0;
5289 static int diff_opt_follow(const struct option *opt,
5290 const char *arg, int unset)
5292 struct diff_options *options = opt->value;
5294 BUG_ON_OPT_ARG(arg);
5295 if (unset) {
5296 options->flags.follow_renames = 0;
5297 options->flags.default_follow_renames = 0;
5298 } else {
5299 options->flags.follow_renames = 1;
5301 return 0;
5304 static int diff_opt_ignore_submodules(const struct option *opt,
5305 const char *arg, int unset)
5307 struct diff_options *options = opt->value;
5309 BUG_ON_OPT_NEG(unset);
5310 if (!arg)
5311 arg = "all";
5312 options->flags.override_submodule_config = 1;
5313 handle_ignore_submodules_arg(options, arg);
5314 return 0;
5317 static int diff_opt_line_prefix(const struct option *opt,
5318 const char *optarg, int unset)
5320 struct diff_options *options = opt->value;
5322 BUG_ON_OPT_NEG(unset);
5323 options->line_prefix = optarg;
5324 options->line_prefix_length = strlen(options->line_prefix);
5325 graph_setup_line_prefix(options);
5326 return 0;
5329 static int diff_opt_no_prefix(const struct option *opt,
5330 const char *optarg, int unset)
5332 struct diff_options *options = opt->value;
5334 BUG_ON_OPT_NEG(unset);
5335 BUG_ON_OPT_ARG(optarg);
5336 diff_set_noprefix(options);
5337 return 0;
5340 static int diff_opt_default_prefix(const struct option *opt,
5341 const char *optarg, int unset)
5343 struct diff_options *options = opt->value;
5345 BUG_ON_OPT_NEG(unset);
5346 BUG_ON_OPT_ARG(optarg);
5347 diff_set_default_prefix(options);
5348 return 0;
5351 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5352 const struct option *opt,
5353 const char *arg, int unset)
5355 struct diff_options *options = opt->value;
5356 char *path;
5358 BUG_ON_OPT_NEG(unset);
5359 path = prefix_filename(ctx->prefix, arg);
5360 options->file = xfopen(path, "w");
5361 options->close_file = 1;
5362 if (options->use_color != GIT_COLOR_ALWAYS)
5363 options->use_color = GIT_COLOR_NEVER;
5364 free(path);
5365 return 0;
5368 static int diff_opt_patience(const struct option *opt,
5369 const char *arg, int unset)
5371 struct diff_options *options = opt->value;
5372 int i;
5374 BUG_ON_OPT_NEG(unset);
5375 BUG_ON_OPT_ARG(arg);
5377 * Both --patience and --anchored use PATIENCE_DIFF
5378 * internally, so remove any anchors previously
5379 * specified.
5381 for (i = 0; i < options->anchors_nr; i++)
5382 free(options->anchors[i]);
5383 options->anchors_nr = 0;
5384 options->ignore_driver_algorithm = 1;
5386 return set_diff_algorithm(options, "patience");
5389 static int diff_opt_ignore_regex(const struct option *opt,
5390 const char *arg, int unset)
5392 struct diff_options *options = opt->value;
5393 regex_t *regex;
5395 BUG_ON_OPT_NEG(unset);
5396 regex = xmalloc(sizeof(*regex));
5397 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5398 return error(_("invalid regex given to -I: '%s'"), arg);
5399 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5400 options->ignore_regex_alloc);
5401 options->ignore_regex[options->ignore_regex_nr++] = regex;
5402 return 0;
5405 static int diff_opt_pickaxe_regex(const struct option *opt,
5406 const char *arg, int unset)
5408 struct diff_options *options = opt->value;
5410 BUG_ON_OPT_NEG(unset);
5411 options->pickaxe = arg;
5412 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5413 return 0;
5416 static int diff_opt_pickaxe_string(const struct option *opt,
5417 const char *arg, int unset)
5419 struct diff_options *options = opt->value;
5421 BUG_ON_OPT_NEG(unset);
5422 options->pickaxe = arg;
5423 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5424 return 0;
5427 static int diff_opt_relative(const struct option *opt,
5428 const char *arg, int unset)
5430 struct diff_options *options = opt->value;
5432 options->flags.relative_name = !unset;
5433 if (arg)
5434 options->prefix = arg;
5435 return 0;
5438 static int diff_opt_submodule(const struct option *opt,
5439 const char *arg, int unset)
5441 struct diff_options *options = opt->value;
5443 BUG_ON_OPT_NEG(unset);
5444 if (!arg)
5445 arg = "log";
5446 if (parse_submodule_params(options, arg))
5447 return error(_("failed to parse --submodule option parameter: '%s'"),
5448 arg);
5449 return 0;
5452 static int diff_opt_textconv(const struct option *opt,
5453 const char *arg, int unset)
5455 struct diff_options *options = opt->value;
5457 BUG_ON_OPT_ARG(arg);
5458 if (unset) {
5459 options->flags.allow_textconv = 0;
5460 } else {
5461 options->flags.allow_textconv = 1;
5462 options->flags.textconv_set_via_cmdline = 1;
5464 return 0;
5467 static int diff_opt_unified(const struct option *opt,
5468 const char *arg, int unset)
5470 struct diff_options *options = opt->value;
5471 char *s;
5473 BUG_ON_OPT_NEG(unset);
5475 if (arg) {
5476 options->context = strtol(arg, &s, 10);
5477 if (*s)
5478 return error(_("%s expects a numerical value"), "--unified");
5480 enable_patch_output(&options->output_format);
5482 return 0;
5485 static int diff_opt_word_diff(const struct option *opt,
5486 const char *arg, int unset)
5488 struct diff_options *options = opt->value;
5490 BUG_ON_OPT_NEG(unset);
5491 if (arg) {
5492 if (!strcmp(arg, "plain"))
5493 options->word_diff = DIFF_WORDS_PLAIN;
5494 else if (!strcmp(arg, "color")) {
5495 options->use_color = 1;
5496 options->word_diff = DIFF_WORDS_COLOR;
5498 else if (!strcmp(arg, "porcelain"))
5499 options->word_diff = DIFF_WORDS_PORCELAIN;
5500 else if (!strcmp(arg, "none"))
5501 options->word_diff = DIFF_WORDS_NONE;
5502 else
5503 return error(_("bad --word-diff argument: %s"), arg);
5504 } else {
5505 if (options->word_diff == DIFF_WORDS_NONE)
5506 options->word_diff = DIFF_WORDS_PLAIN;
5508 return 0;
5511 static int diff_opt_word_diff_regex(const struct option *opt,
5512 const char *arg, int unset)
5514 struct diff_options *options = opt->value;
5516 BUG_ON_OPT_NEG(unset);
5517 if (options->word_diff == DIFF_WORDS_NONE)
5518 options->word_diff = DIFF_WORDS_PLAIN;
5519 options->word_regex = arg;
5520 return 0;
5523 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5525 struct diff_options *options = opt->value;
5527 BUG_ON_OPT_NEG(unset);
5528 if (!strcmp(opt->long_name, "skip-to"))
5529 options->skip_instead_of_rotate = 1;
5530 else
5531 options->skip_instead_of_rotate = 0;
5532 options->rotate_to = arg;
5533 return 0;
5537 * Consider adding new flags to __git_diff_common_options
5538 * in contrib/completion/git-completion.bash
5540 struct option *add_diff_options(const struct option *opts,
5541 struct diff_options *options)
5543 struct option parseopts[] = {
5544 OPT_GROUP(N_("Diff output format options")),
5545 OPT_BITOP('p', "patch", &options->output_format,
5546 N_("generate patch"),
5547 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5548 OPT_SET_INT('s', "no-patch", &options->output_format,
5549 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5550 OPT_BITOP('u', NULL, &options->output_format,
5551 N_("generate patch"),
5552 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5553 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5554 N_("generate diffs with <n> lines context"),
5555 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5556 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5557 N_("generate diffs with <n> lines context")),
5558 OPT_BITOP(0, "raw", &options->output_format,
5559 N_("generate the diff in raw format"),
5560 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5561 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5562 N_("synonym for '-p --raw'"),
5563 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5564 DIFF_FORMAT_NO_OUTPUT),
5565 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5566 N_("synonym for '-p --stat'"),
5567 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5568 DIFF_FORMAT_NO_OUTPUT),
5569 OPT_BITOP(0, "numstat", &options->output_format,
5570 N_("machine friendly --stat"),
5571 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5572 OPT_BITOP(0, "shortstat", &options->output_format,
5573 N_("output only the last line of --stat"),
5574 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5575 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5576 N_("output the distribution of relative amount of changes for each sub-directory"),
5577 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5578 diff_opt_dirstat),
5579 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5580 N_("synonym for --dirstat=cumulative"),
5581 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5582 diff_opt_dirstat),
5583 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5584 N_("synonym for --dirstat=files,param1,param2..."),
5585 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5586 diff_opt_dirstat),
5587 OPT_BIT_F(0, "check", &options->output_format,
5588 N_("warn if changes introduce conflict markers or whitespace errors"),
5589 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5590 OPT_BITOP(0, "summary", &options->output_format,
5591 N_("condensed summary such as creations, renames and mode changes"),
5592 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5593 OPT_BIT_F(0, "name-only", &options->output_format,
5594 N_("show only names of changed files"),
5595 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5596 OPT_BIT_F(0, "name-status", &options->output_format,
5597 N_("show only names and status of changed files"),
5598 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5599 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5600 N_("generate diffstat"),
5601 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5602 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5603 N_("generate diffstat with a given width"),
5604 PARSE_OPT_NONEG, diff_opt_stat),
5605 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5606 N_("generate diffstat with a given name width"),
5607 PARSE_OPT_NONEG, diff_opt_stat),
5608 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5609 N_("generate diffstat with a given graph width"),
5610 PARSE_OPT_NONEG, diff_opt_stat),
5611 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5612 N_("generate diffstat with limited lines"),
5613 PARSE_OPT_NONEG, diff_opt_stat),
5614 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5615 N_("generate compact summary in diffstat"),
5616 PARSE_OPT_NOARG, diff_opt_compact_summary),
5617 OPT_CALLBACK_F(0, "binary", options, NULL,
5618 N_("output a binary diff that can be applied"),
5619 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5620 OPT_BOOL(0, "full-index", &options->flags.full_index,
5621 N_("show full pre- and post-image object names on the \"index\" lines")),
5622 OPT_COLOR_FLAG(0, "color", &options->use_color,
5623 N_("show colored diff")),
5624 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5625 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5626 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5627 OPT_SET_INT('z', NULL, &options->line_termination,
5628 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5630 OPT__ABBREV(&options->abbrev),
5631 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5632 N_("show the given source prefix instead of \"a/\""),
5633 PARSE_OPT_NONEG),
5634 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5635 N_("show the given destination prefix instead of \"b/\""),
5636 PARSE_OPT_NONEG),
5637 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5638 N_("prepend an additional prefix to every line of output"),
5639 PARSE_OPT_NONEG, diff_opt_line_prefix),
5640 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5641 N_("do not show any source or destination prefix"),
5642 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5643 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5644 N_("use default prefixes a/ and b/"),
5645 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5646 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5647 N_("show context between diff hunks up to the specified number of lines"),
5648 PARSE_OPT_NONEG),
5649 OPT_CALLBACK_F(0, "output-indicator-new",
5650 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5651 N_("<char>"),
5652 N_("specify the character to indicate a new line instead of '+'"),
5653 PARSE_OPT_NONEG, diff_opt_char),
5654 OPT_CALLBACK_F(0, "output-indicator-old",
5655 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5656 N_("<char>"),
5657 N_("specify the character to indicate an old line instead of '-'"),
5658 PARSE_OPT_NONEG, diff_opt_char),
5659 OPT_CALLBACK_F(0, "output-indicator-context",
5660 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5661 N_("<char>"),
5662 N_("specify the character to indicate a context instead of ' '"),
5663 PARSE_OPT_NONEG, diff_opt_char),
5665 OPT_GROUP(N_("Diff rename options")),
5666 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5667 N_("break complete rewrite changes into pairs of delete and create"),
5668 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5669 diff_opt_break_rewrites),
5670 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5671 N_("detect renames"),
5672 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5673 diff_opt_find_renames),
5674 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5675 N_("omit the preimage for deletes"),
5676 1, PARSE_OPT_NONEG),
5677 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5678 N_("detect copies"),
5679 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5680 diff_opt_find_copies),
5681 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5682 N_("use unmodified files as source to find copies")),
5683 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5684 N_("disable rename detection"),
5685 0, PARSE_OPT_NONEG),
5686 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5687 N_("use empty blobs as rename source")),
5688 OPT_CALLBACK_F(0, "follow", options, NULL,
5689 N_("continue listing the history of a file beyond renames"),
5690 PARSE_OPT_NOARG, diff_opt_follow),
5691 OPT_INTEGER('l', NULL, &options->rename_limit,
5692 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5694 OPT_GROUP(N_("Diff algorithm options")),
5695 OPT_CALLBACK_F(0, "minimal", options, NULL,
5696 N_("produce the smallest possible diff"),
5697 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5698 diff_opt_diff_algorithm_no_arg),
5699 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5700 N_("ignore whitespace when comparing lines"),
5701 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5702 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5703 N_("ignore changes in amount of whitespace"),
5704 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5705 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5706 N_("ignore changes in whitespace at EOL"),
5707 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5708 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5709 N_("ignore carrier-return at the end of line"),
5710 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5711 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5712 N_("ignore changes whose lines are all blank"),
5713 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5714 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5715 N_("ignore changes whose all lines match <regex>"),
5716 0, diff_opt_ignore_regex),
5717 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5718 N_("heuristic to shift diff hunk boundaries for easy reading"),
5719 XDF_INDENT_HEURISTIC),
5720 OPT_CALLBACK_F(0, "patience", options, NULL,
5721 N_("generate diff using the \"patience diff\" algorithm"),
5722 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5723 diff_opt_patience),
5724 OPT_CALLBACK_F(0, "histogram", options, NULL,
5725 N_("generate diff using the \"histogram diff\" algorithm"),
5726 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5727 diff_opt_diff_algorithm_no_arg),
5728 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5729 N_("choose a diff algorithm"),
5730 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5731 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5732 N_("generate diff using the \"anchored diff\" algorithm"),
5733 PARSE_OPT_NONEG, diff_opt_anchored),
5734 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5735 N_("show word diff, using <mode> to delimit changed words"),
5736 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5737 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5738 N_("use <regex> to decide what a word is"),
5739 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5740 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5741 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5742 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5743 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5744 N_("moved lines of code are colored differently"),
5745 PARSE_OPT_OPTARG, diff_opt_color_moved),
5746 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5747 N_("how white spaces are ignored in --color-moved"),
5748 0, diff_opt_color_moved_ws),
5750 OPT_GROUP(N_("Other diff options")),
5751 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5752 N_("when run from subdir, exclude changes outside and show relative paths"),
5753 PARSE_OPT_OPTARG,
5754 diff_opt_relative),
5755 OPT_BOOL('a', "text", &options->flags.text,
5756 N_("treat all files as text")),
5757 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5758 N_("swap two inputs, reverse the diff")),
5759 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5760 N_("exit with 1 if there were differences, 0 otherwise")),
5761 OPT_BOOL(0, "quiet", &options->flags.quick,
5762 N_("disable all output of the program")),
5763 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5764 N_("allow an external diff helper to be executed")),
5765 OPT_CALLBACK_F(0, "textconv", options, NULL,
5766 N_("run external text conversion filters when comparing binary files"),
5767 PARSE_OPT_NOARG, diff_opt_textconv),
5768 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5769 N_("ignore changes to submodules in the diff generation"),
5770 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5771 diff_opt_ignore_submodules),
5772 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5773 N_("specify how differences in submodules are shown"),
5774 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5775 diff_opt_submodule),
5776 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5777 N_("hide 'git add -N' entries from the index"),
5778 1, PARSE_OPT_NONEG),
5779 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5780 N_("treat 'git add -N' entries as real in the index"),
5781 0, PARSE_OPT_NONEG),
5782 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5783 N_("look for differences that change the number of occurrences of the specified string"),
5784 0, diff_opt_pickaxe_string),
5785 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5786 N_("look for differences that change the number of occurrences of the specified regex"),
5787 0, diff_opt_pickaxe_regex),
5788 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5789 N_("show all changes in the changeset with -S or -G"),
5790 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5791 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5792 N_("treat <string> in -S as extended POSIX regular expression"),
5793 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5794 OPT_FILENAME('O', NULL, &options->orderfile,
5795 N_("control the order in which files appear in the output")),
5796 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5797 N_("show the change in the specified path first"),
5798 PARSE_OPT_NONEG, diff_opt_rotate_to),
5799 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5800 N_("skip the output to the specified path"),
5801 PARSE_OPT_NONEG, diff_opt_rotate_to),
5802 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5803 N_("look for differences that change the number of occurrences of the specified object"),
5804 PARSE_OPT_NONEG, diff_opt_find_object),
5805 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5806 N_("select files by diff type"),
5807 PARSE_OPT_NONEG, diff_opt_diff_filter),
5808 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5809 N_("output to a specific file"),
5810 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5812 OPT_END()
5815 return parse_options_concat(opts, parseopts);
5818 int diff_opt_parse(struct diff_options *options,
5819 const char **av, int ac, const char *prefix)
5821 struct option no_options[] = { OPT_END() };
5822 struct option *parseopts = add_diff_options(no_options, options);
5824 if (!prefix)
5825 prefix = "";
5827 ac = parse_options(ac, av, prefix, parseopts, NULL,
5828 PARSE_OPT_KEEP_DASHDASH |
5829 PARSE_OPT_KEEP_UNKNOWN_OPT |
5830 PARSE_OPT_NO_INTERNAL_HELP |
5831 PARSE_OPT_ONE_SHOT |
5832 PARSE_OPT_STOP_AT_NON_OPTION);
5833 free(parseopts);
5835 return ac;
5838 int parse_rename_score(const char **cp_p)
5840 unsigned long num, scale;
5841 int ch, dot;
5842 const char *cp = *cp_p;
5844 num = 0;
5845 scale = 1;
5846 dot = 0;
5847 for (;;) {
5848 ch = *cp;
5849 if ( !dot && ch == '.' ) {
5850 scale = 1;
5851 dot = 1;
5852 } else if ( ch == '%' ) {
5853 scale = dot ? scale*100 : 100;
5854 cp++; /* % is always at the end */
5855 break;
5856 } else if ( ch >= '0' && ch <= '9' ) {
5857 if ( scale < 100000 ) {
5858 scale *= 10;
5859 num = (num*10) + (ch-'0');
5861 } else {
5862 break;
5864 cp++;
5866 *cp_p = cp;
5868 /* user says num divided by scale and we say internally that
5869 * is MAX_SCORE * num / scale.
5871 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5874 struct diff_queue_struct diff_queued_diff;
5876 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5878 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5879 queue->queue[queue->nr++] = dp;
5882 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5883 struct diff_filespec *one,
5884 struct diff_filespec *two)
5886 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5887 dp->one = one;
5888 dp->two = two;
5889 if (queue)
5890 diff_q(queue, dp);
5891 return dp;
5894 void diff_free_filepair(struct diff_filepair *p)
5896 free_filespec(p->one);
5897 free_filespec(p->two);
5898 free(p);
5901 void diff_free_queue(struct diff_queue_struct *q)
5903 for (int i = 0; i < q->nr; i++)
5904 diff_free_filepair(q->queue[i]);
5905 free(q->queue);
5908 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5910 int abblen;
5911 const char *abbrev;
5913 /* Do we want all 40 hex characters? */
5914 if (len == the_hash_algo->hexsz)
5915 return oid_to_hex(oid);
5917 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5918 abbrev = diff_abbrev_oid(oid, len);
5920 if (!print_sha1_ellipsis())
5921 return abbrev;
5923 abblen = strlen(abbrev);
5926 * In well-behaved cases, where the abbreviated result is the
5927 * same as the requested length, append three dots after the
5928 * abbreviation (hence the whole logic is limited to the case
5929 * where abblen < 37); when the actual abbreviated result is a
5930 * bit longer than the requested length, we reduce the number
5931 * of dots so that they match the well-behaved ones. However,
5932 * if the actual abbreviation is longer than the requested
5933 * length by more than three, we give up on aligning, and add
5934 * three dots anyway, to indicate that the output is not the
5935 * full object name. Yes, this may be suboptimal, but this
5936 * appears only in "diff --raw --abbrev" output and it is not
5937 * worth the effort to change it now. Note that this would
5938 * likely to work fine when the automatic sizing of default
5939 * abbreviation length is used--we would be fed -1 in "len" in
5940 * that case, and will end up always appending three-dots, but
5941 * the automatic sizing is supposed to give abblen that ensures
5942 * uniqueness across all objects (statistically speaking).
5944 if (abblen < the_hash_algo->hexsz - 3) {
5945 static char hex[GIT_MAX_HEXSZ + 1];
5946 if (len < abblen && abblen <= len + 2)
5947 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5948 else
5949 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5950 return hex;
5953 return oid_to_hex(oid);
5956 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5958 int line_termination = opt->line_termination;
5959 int inter_name_termination = line_termination ? '\t' : '\0';
5961 fprintf(opt->file, "%s", diff_line_prefix(opt));
5962 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5963 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5964 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5965 fprintf(opt->file, "%s ",
5966 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5968 if (p->score) {
5969 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5970 inter_name_termination);
5971 } else {
5972 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5975 if (p->status == DIFF_STATUS_COPIED ||
5976 p->status == DIFF_STATUS_RENAMED) {
5977 const char *name_a, *name_b;
5978 name_a = p->one->path;
5979 name_b = p->two->path;
5980 strip_prefix(opt->prefix_length, &name_a, &name_b);
5981 write_name_quoted(name_a, opt->file, inter_name_termination);
5982 write_name_quoted(name_b, opt->file, line_termination);
5983 } else {
5984 const char *name_a, *name_b;
5985 name_a = p->one->mode ? p->one->path : p->two->path;
5986 name_b = NULL;
5987 strip_prefix(opt->prefix_length, &name_a, &name_b);
5988 write_name_quoted(name_a, opt->file, line_termination);
5992 int diff_unmodified_pair(struct diff_filepair *p)
5994 /* This function is written stricter than necessary to support
5995 * the currently implemented transformers, but the idea is to
5996 * let transformers to produce diff_filepairs any way they want,
5997 * and filter and clean them up here before producing the output.
5999 struct diff_filespec *one = p->one, *two = p->two;
6001 if (DIFF_PAIR_UNMERGED(p))
6002 return 0; /* unmerged is interesting */
6004 /* deletion, addition, mode or type change
6005 * and rename are all interesting.
6007 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6008 DIFF_PAIR_MODE_CHANGED(p) ||
6009 strcmp(one->path, two->path))
6010 return 0;
6012 /* both are valid and point at the same path. that is, we are
6013 * dealing with a change.
6015 if (one->oid_valid && two->oid_valid &&
6016 oideq(&one->oid, &two->oid) &&
6017 !one->dirty_submodule && !two->dirty_submodule)
6018 return 1; /* no change */
6019 if (!one->oid_valid && !two->oid_valid)
6020 return 1; /* both look at the same file on the filesystem. */
6021 return 0;
6024 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6026 int include_conflict_headers =
6027 (additional_headers(o, p->one->path) &&
6028 !o->pickaxe_opts &&
6029 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6032 * Check if we can return early without showing a diff. Note that
6033 * diff_filepair only stores {oid, path, mode, is_valid}
6034 * information for each path, and thus diff_unmodified_pair() only
6035 * considers those bits of info. However, we do not want pairs
6036 * created by create_filepairs_for_header_only_notifications()
6037 * (which always look like unmodified pairs) to be ignored, so
6038 * return early if both p is unmodified AND we don't want to
6039 * include_conflict_headers.
6041 if (diff_unmodified_pair(p) && !include_conflict_headers)
6042 return;
6044 /* Actually, we can also return early to avoid showing tree diffs */
6045 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6046 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6047 return;
6049 run_diff(p, o);
6052 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6053 struct diffstat_t *diffstat)
6055 if (diff_unmodified_pair(p))
6056 return;
6058 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6059 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6060 return; /* no useful stat for tree diffs */
6062 run_diffstat(p, o, diffstat);
6065 static void diff_flush_checkdiff(struct diff_filepair *p,
6066 struct diff_options *o)
6068 if (diff_unmodified_pair(p))
6069 return;
6071 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6072 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6073 return; /* nothing to check in tree diffs */
6075 run_checkdiff(p, o);
6078 int diff_queue_is_empty(struct diff_options *o)
6080 struct diff_queue_struct *q = &diff_queued_diff;
6081 int i;
6082 int include_conflict_headers =
6083 (o->additional_path_headers &&
6084 strmap_get_size(o->additional_path_headers) &&
6085 !o->pickaxe_opts &&
6086 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6088 if (include_conflict_headers)
6089 return 0;
6091 for (i = 0; i < q->nr; i++)
6092 if (!diff_unmodified_pair(q->queue[i]))
6093 return 0;
6094 return 1;
6097 #if DIFF_DEBUG
6098 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6100 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6101 x, one ? one : "",
6102 s->path,
6103 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6104 s->mode,
6105 s->oid_valid ? oid_to_hex(&s->oid) : "");
6106 fprintf(stderr, "queue[%d] %s size %lu\n",
6107 x, one ? one : "",
6108 s->size);
6111 void diff_debug_filepair(const struct diff_filepair *p, int i)
6113 diff_debug_filespec(p->one, i, "one");
6114 diff_debug_filespec(p->two, i, "two");
6115 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6116 p->score, p->status ? p->status : '?',
6117 p->one->rename_used, p->broken_pair);
6120 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6122 int i;
6123 if (msg)
6124 fprintf(stderr, "%s\n", msg);
6125 fprintf(stderr, "q->nr = %d\n", q->nr);
6126 for (i = 0; i < q->nr; i++) {
6127 struct diff_filepair *p = q->queue[i];
6128 diff_debug_filepair(p, i);
6131 #endif
6133 static void diff_resolve_rename_copy(void)
6135 int i;
6136 struct diff_filepair *p;
6137 struct diff_queue_struct *q = &diff_queued_diff;
6139 diff_debug_queue("resolve-rename-copy", q);
6141 for (i = 0; i < q->nr; i++) {
6142 p = q->queue[i];
6143 p->status = 0; /* undecided */
6144 if (DIFF_PAIR_UNMERGED(p))
6145 p->status = DIFF_STATUS_UNMERGED;
6146 else if (!DIFF_FILE_VALID(p->one))
6147 p->status = DIFF_STATUS_ADDED;
6148 else if (!DIFF_FILE_VALID(p->two))
6149 p->status = DIFF_STATUS_DELETED;
6150 else if (DIFF_PAIR_TYPE_CHANGED(p))
6151 p->status = DIFF_STATUS_TYPE_CHANGED;
6153 /* from this point on, we are dealing with a pair
6154 * whose both sides are valid and of the same type, i.e.
6155 * either in-place edit or rename/copy edit.
6157 else if (DIFF_PAIR_RENAME(p)) {
6159 * A rename might have re-connected a broken
6160 * pair up, causing the pathnames to be the
6161 * same again. If so, that's not a rename at
6162 * all, just a modification..
6164 * Otherwise, see if this source was used for
6165 * multiple renames, in which case we decrement
6166 * the count, and call it a copy.
6168 if (!strcmp(p->one->path, p->two->path))
6169 p->status = DIFF_STATUS_MODIFIED;
6170 else if (--p->one->rename_used > 0)
6171 p->status = DIFF_STATUS_COPIED;
6172 else
6173 p->status = DIFF_STATUS_RENAMED;
6175 else if (!oideq(&p->one->oid, &p->two->oid) ||
6176 p->one->mode != p->two->mode ||
6177 p->one->dirty_submodule ||
6178 p->two->dirty_submodule ||
6179 is_null_oid(&p->one->oid))
6180 p->status = DIFF_STATUS_MODIFIED;
6181 else {
6182 /* This is a "no-change" entry and should not
6183 * happen anymore, but prepare for broken callers.
6185 error("feeding unmodified %s to diffcore",
6186 p->one->path);
6187 p->status = DIFF_STATUS_UNKNOWN;
6190 diff_debug_queue("resolve-rename-copy done", q);
6193 static int check_pair_status(struct diff_filepair *p)
6195 switch (p->status) {
6196 case DIFF_STATUS_UNKNOWN:
6197 return 0;
6198 case 0:
6199 die("internal error in diff-resolve-rename-copy");
6200 default:
6201 return 1;
6205 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6207 int fmt = opt->output_format;
6209 if (fmt & DIFF_FORMAT_CHECKDIFF)
6210 diff_flush_checkdiff(p, opt);
6211 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6212 diff_flush_raw(p, opt);
6213 else if (fmt & DIFF_FORMAT_NAME) {
6214 const char *name_a, *name_b;
6215 name_a = p->two->path;
6216 name_b = NULL;
6217 strip_prefix(opt->prefix_length, &name_a, &name_b);
6218 fprintf(opt->file, "%s", diff_line_prefix(opt));
6219 write_name_quoted(name_a, opt->file, opt->line_termination);
6222 opt->found_changes = 1;
6225 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6227 struct strbuf sb = STRBUF_INIT;
6228 if (fs->mode)
6229 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6230 else
6231 strbuf_addf(&sb, " %s ", newdelete);
6233 quote_c_style(fs->path, &sb, NULL, 0);
6234 strbuf_addch(&sb, '\n');
6235 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6236 sb.buf, sb.len, 0);
6237 strbuf_release(&sb);
6240 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6241 int show_name)
6243 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6244 struct strbuf sb = STRBUF_INIT;
6245 strbuf_addf(&sb, " mode change %06o => %06o",
6246 p->one->mode, p->two->mode);
6247 if (show_name) {
6248 strbuf_addch(&sb, ' ');
6249 quote_c_style(p->two->path, &sb, NULL, 0);
6251 strbuf_addch(&sb, '\n');
6252 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6253 sb.buf, sb.len, 0);
6254 strbuf_release(&sb);
6258 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6259 struct diff_filepair *p)
6261 struct strbuf sb = STRBUF_INIT;
6262 struct strbuf names = STRBUF_INIT;
6264 pprint_rename(&names, p->one->path, p->two->path);
6265 strbuf_addf(&sb, " %s %s (%d%%)\n",
6266 renamecopy, names.buf, similarity_index(p));
6267 strbuf_release(&names);
6268 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6269 sb.buf, sb.len, 0);
6270 show_mode_change(opt, p, 0);
6271 strbuf_release(&sb);
6274 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6276 switch(p->status) {
6277 case DIFF_STATUS_DELETED:
6278 show_file_mode_name(opt, "delete", p->one);
6279 break;
6280 case DIFF_STATUS_ADDED:
6281 show_file_mode_name(opt, "create", p->two);
6282 break;
6283 case DIFF_STATUS_COPIED:
6284 show_rename_copy(opt, "copy", p);
6285 break;
6286 case DIFF_STATUS_RENAMED:
6287 show_rename_copy(opt, "rename", p);
6288 break;
6289 default:
6290 if (p->score) {
6291 struct strbuf sb = STRBUF_INIT;
6292 strbuf_addstr(&sb, " rewrite ");
6293 quote_c_style(p->two->path, &sb, NULL, 0);
6294 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6295 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6296 sb.buf, sb.len, 0);
6297 strbuf_release(&sb);
6299 show_mode_change(opt, p, !p->score);
6300 break;
6304 struct patch_id_t {
6305 git_hash_ctx *ctx;
6306 int patchlen;
6309 static int remove_space(char *line, int len)
6311 int i;
6312 char *dst = line;
6313 unsigned char c;
6315 for (i = 0; i < len; i++)
6316 if (!isspace((c = line[i])))
6317 *dst++ = c;
6319 return dst - line;
6322 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6324 unsigned char hash[GIT_MAX_RAWSZ];
6325 unsigned short carry = 0;
6326 int i;
6328 the_hash_algo->final_fn(hash, ctx);
6329 the_hash_algo->init_fn(ctx);
6330 /* 20-byte sum, with carry */
6331 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6332 carry += result->hash[i] + hash[i];
6333 result->hash[i] = carry;
6334 carry >>= 8;
6338 static int patch_id_consume(void *priv, char *line, unsigned long len)
6340 struct patch_id_t *data = priv;
6341 int new_len;
6343 if (len > 12 && starts_with(line, "\\ "))
6344 return 0;
6345 new_len = remove_space(line, len);
6347 the_hash_algo->update_fn(data->ctx, line, new_len);
6348 data->patchlen += new_len;
6349 return 0;
6352 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6354 the_hash_algo->update_fn(ctx, str, strlen(str));
6357 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6359 /* large enough for 2^32 in octal */
6360 char buf[12];
6361 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6362 the_hash_algo->update_fn(ctx, buf, len);
6365 /* returns 0 upon success, and writes result into oid */
6366 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6368 struct diff_queue_struct *q = &diff_queued_diff;
6369 int i;
6370 git_hash_ctx ctx;
6371 struct patch_id_t data;
6373 the_hash_algo->init_fn(&ctx);
6374 memset(&data, 0, sizeof(struct patch_id_t));
6375 data.ctx = &ctx;
6376 oidclr(oid);
6378 for (i = 0; i < q->nr; i++) {
6379 xpparam_t xpp;
6380 xdemitconf_t xecfg;
6381 mmfile_t mf1, mf2;
6382 struct diff_filepair *p = q->queue[i];
6383 int len1, len2;
6385 memset(&xpp, 0, sizeof(xpp));
6386 memset(&xecfg, 0, sizeof(xecfg));
6387 if (p->status == 0)
6388 return error("internal diff status error");
6389 if (p->status == DIFF_STATUS_UNKNOWN)
6390 continue;
6391 if (diff_unmodified_pair(p))
6392 continue;
6393 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6394 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6395 continue;
6396 if (DIFF_PAIR_UNMERGED(p))
6397 continue;
6399 diff_fill_oid_info(p->one, options->repo->index);
6400 diff_fill_oid_info(p->two, options->repo->index);
6402 len1 = remove_space(p->one->path, strlen(p->one->path));
6403 len2 = remove_space(p->two->path, strlen(p->two->path));
6404 patch_id_add_string(&ctx, "diff--git");
6405 patch_id_add_string(&ctx, "a/");
6406 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6407 patch_id_add_string(&ctx, "b/");
6408 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6410 if (p->one->mode == 0) {
6411 patch_id_add_string(&ctx, "newfilemode");
6412 patch_id_add_mode(&ctx, p->two->mode);
6413 } else if (p->two->mode == 0) {
6414 patch_id_add_string(&ctx, "deletedfilemode");
6415 patch_id_add_mode(&ctx, p->one->mode);
6416 } else if (p->one->mode != p->two->mode) {
6417 patch_id_add_string(&ctx, "oldmode");
6418 patch_id_add_mode(&ctx, p->one->mode);
6419 patch_id_add_string(&ctx, "newmode");
6420 patch_id_add_mode(&ctx, p->two->mode);
6423 if (diff_header_only) {
6424 /* don't do anything since we're only populating header info */
6425 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6426 diff_filespec_is_binary(options->repo, p->two)) {
6427 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6428 the_hash_algo->hexsz);
6429 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6430 the_hash_algo->hexsz);
6431 } else {
6432 if (p->one->mode == 0) {
6433 patch_id_add_string(&ctx, "---/dev/null");
6434 patch_id_add_string(&ctx, "+++b/");
6435 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6436 } else if (p->two->mode == 0) {
6437 patch_id_add_string(&ctx, "---a/");
6438 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6439 patch_id_add_string(&ctx, "+++/dev/null");
6440 } else {
6441 patch_id_add_string(&ctx, "---a/");
6442 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6443 patch_id_add_string(&ctx, "+++b/");
6444 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6447 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6448 fill_mmfile(options->repo, &mf2, p->two) < 0)
6449 return error("unable to read files to diff");
6450 xpp.flags = 0;
6451 xecfg.ctxlen = 3;
6452 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6453 if (xdi_diff_outf(&mf1, &mf2, NULL,
6454 patch_id_consume, &data, &xpp, &xecfg))
6455 return error("unable to generate patch-id diff for %s",
6456 p->one->path);
6458 flush_one_hunk(oid, &ctx);
6461 return 0;
6464 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6466 struct diff_queue_struct *q = &diff_queued_diff;
6467 int result = diff_get_patch_id(options, oid, diff_header_only);
6469 diff_free_queue(q);
6470 DIFF_QUEUE_CLEAR(q);
6472 return result;
6475 static int is_summary_empty(const struct diff_queue_struct *q)
6477 int i;
6479 for (i = 0; i < q->nr; i++) {
6480 const struct diff_filepair *p = q->queue[i];
6482 switch (p->status) {
6483 case DIFF_STATUS_DELETED:
6484 case DIFF_STATUS_ADDED:
6485 case DIFF_STATUS_COPIED:
6486 case DIFF_STATUS_RENAMED:
6487 return 0;
6488 default:
6489 if (p->score)
6490 return 0;
6491 if (p->one->mode && p->two->mode &&
6492 p->one->mode != p->two->mode)
6493 return 0;
6494 break;
6497 return 1;
6500 static const char rename_limit_warning[] =
6501 N_("exhaustive rename detection was skipped due to too many files.");
6503 static const char degrade_cc_to_c_warning[] =
6504 N_("only found copies from modified paths due to too many files.");
6506 static const char rename_limit_advice[] =
6507 N_("you may want to set your %s variable to at least "
6508 "%d and retry the command.");
6510 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6512 fflush(stdout);
6513 if (degraded_cc)
6514 warning(_(degrade_cc_to_c_warning));
6515 else if (needed)
6516 warning(_(rename_limit_warning));
6517 else
6518 return;
6519 if (0 < needed)
6520 warning(_(rename_limit_advice), varname, needed);
6523 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6525 struct strset present;
6526 struct diff_queue_struct *q = &diff_queued_diff;
6527 struct hashmap_iter iter;
6528 struct strmap_entry *e;
6529 int i;
6531 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6534 * Find out which paths exist in diff_queued_diff, preferring
6535 * one->path for any pair that has multiple paths.
6537 for (i = 0; i < q->nr; i++) {
6538 struct diff_filepair *p = q->queue[i];
6539 char *path = p->one->path ? p->one->path : p->two->path;
6541 if (strmap_contains(o->additional_path_headers, path))
6542 strset_add(&present, path);
6546 * Loop over paths in additional_path_headers; for each NOT already
6547 * in diff_queued_diff, create a synthetic filepair and insert that
6548 * into diff_queued_diff.
6550 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6551 if (!strset_contains(&present, e->key)) {
6552 struct diff_filespec *one, *two;
6553 struct diff_filepair *p;
6555 one = alloc_filespec(e->key);
6556 two = alloc_filespec(e->key);
6557 fill_filespec(one, null_oid(), 0, 0);
6558 fill_filespec(two, null_oid(), 0, 0);
6559 p = diff_queue(q, one, two);
6560 p->status = DIFF_STATUS_MODIFIED;
6564 /* Re-sort the filepairs */
6565 diffcore_fix_diff_index();
6567 /* Cleanup */
6568 strset_clear(&present);
6571 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6573 int i;
6574 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6575 struct diff_queue_struct *q = &diff_queued_diff;
6577 if (WSEH_NEW & WS_RULE_MASK)
6578 BUG("WS rules bit mask overlaps with diff symbol flags");
6580 if (o->color_moved)
6581 o->emitted_symbols = &esm;
6583 if (o->additional_path_headers)
6584 create_filepairs_for_header_only_notifications(o);
6586 for (i = 0; i < q->nr; i++) {
6587 struct diff_filepair *p = q->queue[i];
6588 if (check_pair_status(p))
6589 diff_flush_patch(p, o);
6592 if (o->emitted_symbols) {
6593 if (o->color_moved) {
6594 struct mem_pool entry_pool;
6595 struct moved_entry_list *entry_list;
6597 mem_pool_init(&entry_pool, 1024 * 1024);
6598 entry_list = add_lines_to_move_detection(o,
6599 &entry_pool);
6600 mark_color_as_moved(o, entry_list);
6601 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6602 dim_moved_lines(o);
6604 mem_pool_discard(&entry_pool, 0);
6605 free(entry_list);
6608 for (i = 0; i < esm.nr; i++)
6609 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6611 for (i = 0; i < esm.nr; i++)
6612 free((void *)esm.buf[i].line);
6613 esm.nr = 0;
6615 o->emitted_symbols = NULL;
6619 static void diff_free_file(struct diff_options *options)
6621 if (options->close_file)
6622 fclose(options->file);
6625 static void diff_free_ignore_regex(struct diff_options *options)
6627 int i;
6629 for (i = 0; i < options->ignore_regex_nr; i++) {
6630 regfree(options->ignore_regex[i]);
6631 free(options->ignore_regex[i]);
6633 free(options->ignore_regex);
6636 void diff_free(struct diff_options *options)
6638 if (options->no_free)
6639 return;
6641 diff_free_file(options);
6642 diff_free_ignore_regex(options);
6643 clear_pathspec(&options->pathspec);
6646 void diff_flush(struct diff_options *options)
6648 struct diff_queue_struct *q = &diff_queued_diff;
6649 int i, output_format = options->output_format;
6650 int separator = 0;
6651 int dirstat_by_line = 0;
6654 * Order: raw, stat, summary, patch
6655 * or: name/name-status/checkdiff (other bits clear)
6657 if (!q->nr && !options->additional_path_headers)
6658 goto free_queue;
6660 if (output_format & (DIFF_FORMAT_RAW |
6661 DIFF_FORMAT_NAME |
6662 DIFF_FORMAT_NAME_STATUS |
6663 DIFF_FORMAT_CHECKDIFF)) {
6664 for (i = 0; i < q->nr; i++) {
6665 struct diff_filepair *p = q->queue[i];
6666 if (check_pair_status(p))
6667 flush_one_pair(p, options);
6669 separator++;
6672 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6673 dirstat_by_line = 1;
6675 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6676 dirstat_by_line) {
6677 struct diffstat_t diffstat;
6679 compute_diffstat(options, &diffstat, q);
6680 if (output_format & DIFF_FORMAT_NUMSTAT)
6681 show_numstat(&diffstat, options);
6682 if (output_format & DIFF_FORMAT_DIFFSTAT)
6683 show_stats(&diffstat, options);
6684 if (output_format & DIFF_FORMAT_SHORTSTAT)
6685 show_shortstats(&diffstat, options);
6686 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6687 show_dirstat_by_line(&diffstat, options);
6688 free_diffstat_info(&diffstat);
6689 separator++;
6691 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6692 show_dirstat(options);
6694 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6695 for (i = 0; i < q->nr; i++) {
6696 diff_summary(options, q->queue[i]);
6698 separator++;
6701 if (output_format & DIFF_FORMAT_PATCH) {
6702 if (separator) {
6703 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6704 if (options->stat_sep)
6705 /* attach patch instead of inline */
6706 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6707 NULL, 0, 0);
6710 diff_flush_patch_all_file_pairs(options);
6713 if (output_format & DIFF_FORMAT_CALLBACK)
6714 options->format_callback(q, options, options->format_callback_data);
6716 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6717 options->flags.exit_with_status &&
6718 options->flags.diff_from_contents) {
6720 * run diff_flush_patch for the exit status. setting
6721 * options->file to /dev/null should be safe, because we
6722 * aren't supposed to produce any output anyway.
6724 diff_free_file(options);
6725 options->file = xfopen("/dev/null", "w");
6726 options->close_file = 1;
6727 options->color_moved = 0;
6728 for (i = 0; i < q->nr; i++) {
6729 struct diff_filepair *p = q->queue[i];
6730 if (check_pair_status(p))
6731 diff_flush_patch(p, options);
6732 if (options->found_changes)
6733 break;
6737 free_queue:
6738 diff_free_queue(q);
6739 DIFF_QUEUE_CLEAR(q);
6740 diff_free(options);
6743 * Report the content-level differences with HAS_CHANGES;
6744 * diff_addremove/diff_change does not set the bit when
6745 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6747 if (options->flags.diff_from_contents) {
6748 if (options->found_changes)
6749 options->flags.has_changes = 1;
6750 else
6751 options->flags.has_changes = 0;
6755 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6757 return (((p->status == DIFF_STATUS_MODIFIED) &&
6758 ((p->score &&
6759 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6760 (!p->score &&
6761 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6762 ((p->status != DIFF_STATUS_MODIFIED) &&
6763 filter_bit_tst(p->status, options)));
6766 static void diffcore_apply_filter(struct diff_options *options)
6768 int i;
6769 struct diff_queue_struct *q = &diff_queued_diff;
6770 struct diff_queue_struct outq;
6772 DIFF_QUEUE_CLEAR(&outq);
6774 if (!options->filter)
6775 return;
6777 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6778 int found;
6779 for (i = found = 0; !found && i < q->nr; i++) {
6780 if (match_filter(options, q->queue[i]))
6781 found++;
6783 if (found)
6784 return;
6786 /* otherwise we will clear the whole queue
6787 * by copying the empty outq at the end of this
6788 * function, but first clear the current entries
6789 * in the queue.
6791 for (i = 0; i < q->nr; i++)
6792 diff_free_filepair(q->queue[i]);
6794 else {
6795 /* Only the matching ones */
6796 for (i = 0; i < q->nr; i++) {
6797 struct diff_filepair *p = q->queue[i];
6798 if (match_filter(options, p))
6799 diff_q(&outq, p);
6800 else
6801 diff_free_filepair(p);
6804 free(q->queue);
6805 *q = outq;
6808 /* Check whether two filespecs with the same mode and size are identical */
6809 static int diff_filespec_is_identical(struct repository *r,
6810 struct diff_filespec *one,
6811 struct diff_filespec *two)
6813 if (S_ISGITLINK(one->mode))
6814 return 0;
6815 if (diff_populate_filespec(r, one, NULL))
6816 return 0;
6817 if (diff_populate_filespec(r, two, NULL))
6818 return 0;
6819 return !memcmp(one->data, two->data, one->size);
6822 static int diff_filespec_check_stat_unmatch(struct repository *r,
6823 struct diff_filepair *p)
6825 struct diff_populate_filespec_options dpf_options = {
6826 .check_size_only = 1,
6827 .missing_object_cb = diff_queued_diff_prefetch,
6828 .missing_object_data = r,
6831 if (p->done_skip_stat_unmatch)
6832 return p->skip_stat_unmatch_result;
6834 p->done_skip_stat_unmatch = 1;
6835 p->skip_stat_unmatch_result = 0;
6837 * 1. Entries that come from stat info dirtiness
6838 * always have both sides (iow, not create/delete),
6839 * one side of the object name is unknown, with
6840 * the same mode and size. Keep the ones that
6841 * do not match these criteria. They have real
6842 * differences.
6844 * 2. At this point, the file is known to be modified,
6845 * with the same mode and size, and the object
6846 * name of one side is unknown. Need to inspect
6847 * the identical contents.
6849 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6850 !DIFF_FILE_VALID(p->two) ||
6851 (p->one->oid_valid && p->two->oid_valid) ||
6852 (p->one->mode != p->two->mode) ||
6853 diff_populate_filespec(r, p->one, &dpf_options) ||
6854 diff_populate_filespec(r, p->two, &dpf_options) ||
6855 (p->one->size != p->two->size) ||
6856 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6857 p->skip_stat_unmatch_result = 1;
6858 return p->skip_stat_unmatch_result;
6861 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6863 int i;
6864 struct diff_queue_struct *q = &diff_queued_diff;
6865 struct diff_queue_struct outq;
6866 DIFF_QUEUE_CLEAR(&outq);
6868 for (i = 0; i < q->nr; i++) {
6869 struct diff_filepair *p = q->queue[i];
6871 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6872 diff_q(&outq, p);
6873 else {
6875 * The caller can subtract 1 from skip_stat_unmatch
6876 * to determine how many paths were dirty only
6877 * due to stat info mismatch.
6879 if (!diffopt->flags.no_index)
6880 diffopt->skip_stat_unmatch++;
6881 diff_free_filepair(p);
6884 free(q->queue);
6885 *q = outq;
6888 static int diffnamecmp(const void *a_, const void *b_)
6890 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6891 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6892 const char *name_a, *name_b;
6894 name_a = a->one ? a->one->path : a->two->path;
6895 name_b = b->one ? b->one->path : b->two->path;
6896 return strcmp(name_a, name_b);
6899 void diffcore_fix_diff_index(void)
6901 struct diff_queue_struct *q = &diff_queued_diff;
6902 QSORT(q->queue, q->nr, diffnamecmp);
6905 void diff_add_if_missing(struct repository *r,
6906 struct oid_array *to_fetch,
6907 const struct diff_filespec *filespec)
6909 if (filespec && filespec->oid_valid &&
6910 !S_ISGITLINK(filespec->mode) &&
6911 oid_object_info_extended(r, &filespec->oid, NULL,
6912 OBJECT_INFO_FOR_PREFETCH))
6913 oid_array_append(to_fetch, &filespec->oid);
6916 void diff_queued_diff_prefetch(void *repository)
6918 struct repository *repo = repository;
6919 int i;
6920 struct diff_queue_struct *q = &diff_queued_diff;
6921 struct oid_array to_fetch = OID_ARRAY_INIT;
6923 for (i = 0; i < q->nr; i++) {
6924 struct diff_filepair *p = q->queue[i];
6925 diff_add_if_missing(repo, &to_fetch, p->one);
6926 diff_add_if_missing(repo, &to_fetch, p->two);
6930 * NEEDSWORK: Consider deduplicating the OIDs sent.
6932 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6934 oid_array_clear(&to_fetch);
6937 void init_diffstat_widths(struct diff_options *options)
6939 options->stat_width = -1; /* use full terminal width */
6940 options->stat_name_width = -1; /* respect diff.statNameWidth config */
6941 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
6944 void diffcore_std(struct diff_options *options)
6946 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6947 DIFF_FORMAT_NUMSTAT |
6948 DIFF_FORMAT_PATCH |
6949 DIFF_FORMAT_SHORTSTAT |
6950 DIFF_FORMAT_DIRSTAT;
6953 * Check if the user requested a blob-data-requiring diff output and/or
6954 * break-rewrite detection (which requires blob data). If yes, prefetch
6955 * the diff pairs.
6957 * If no prefetching occurs, diffcore_rename() will prefetch if it
6958 * decides that it needs inexact rename detection.
6960 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6961 (options->output_format & output_formats_to_prefetch ||
6962 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6963 diff_queued_diff_prefetch(options->repo);
6965 /* NOTE please keep the following in sync with diff_tree_combined() */
6966 if (options->skip_stat_unmatch)
6967 diffcore_skip_stat_unmatch(options);
6968 if (!options->found_follow) {
6969 /* See try_to_follow_renames() in tree-diff.c */
6970 if (options->break_opt != -1)
6971 diffcore_break(options->repo,
6972 options->break_opt);
6973 if (options->detect_rename)
6974 diffcore_rename(options);
6975 if (options->break_opt != -1)
6976 diffcore_merge_broken();
6978 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6979 diffcore_pickaxe(options);
6980 if (options->orderfile)
6981 diffcore_order(options->orderfile);
6982 if (options->rotate_to)
6983 diffcore_rotate(options);
6984 if (!options->found_follow)
6985 /* See try_to_follow_renames() in tree-diff.c */
6986 diff_resolve_rename_copy();
6987 diffcore_apply_filter(options);
6989 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6990 options->flags.has_changes = 1;
6991 else
6992 options->flags.has_changes = 0;
6994 options->found_follow = 0;
6997 int diff_result_code(struct diff_options *opt)
6999 int result = 0;
7001 diff_warn_rename_limit("diff.renameLimit",
7002 opt->needed_rename_limit,
7003 opt->degraded_cc_to_c);
7005 if (opt->flags.exit_with_status &&
7006 opt->flags.has_changes)
7007 result |= 01;
7008 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7009 opt->flags.check_failed)
7010 result |= 02;
7011 return result;
7014 int diff_can_quit_early(struct diff_options *opt)
7016 return (opt->flags.quick &&
7017 !opt->filter &&
7018 opt->flags.has_changes);
7022 * Shall changes to this submodule be ignored?
7024 * Submodule changes can be configured to be ignored separately for each path,
7025 * but that configuration can be overridden from the command line.
7027 static int is_submodule_ignored(const char *path, struct diff_options *options)
7029 int ignored = 0;
7030 struct diff_flags orig_flags = options->flags;
7031 if (!options->flags.override_submodule_config)
7032 set_diffopt_flags_from_submodule_config(options, path);
7033 if (options->flags.ignore_submodules)
7034 ignored = 1;
7035 options->flags = orig_flags;
7036 return ignored;
7039 void compute_diffstat(struct diff_options *options,
7040 struct diffstat_t *diffstat,
7041 struct diff_queue_struct *q)
7043 int i;
7045 memset(diffstat, 0, sizeof(struct diffstat_t));
7046 for (i = 0; i < q->nr; i++) {
7047 struct diff_filepair *p = q->queue[i];
7048 if (check_pair_status(p))
7049 diff_flush_stat(p, options, diffstat);
7051 options->found_changes = !!diffstat->nr;
7054 void diff_addremove(struct diff_options *options,
7055 int addremove, unsigned mode,
7056 const struct object_id *oid,
7057 int oid_valid,
7058 const char *concatpath, unsigned dirty_submodule)
7060 struct diff_filespec *one, *two;
7062 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7063 return;
7065 /* This may look odd, but it is a preparation for
7066 * feeding "there are unchanged files which should
7067 * not produce diffs, but when you are doing copy
7068 * detection you would need them, so here they are"
7069 * entries to the diff-core. They will be prefixed
7070 * with something like '=' or '*' (I haven't decided
7071 * which but should not make any difference).
7072 * Feeding the same new and old to diff_change()
7073 * also has the same effect.
7074 * Before the final output happens, they are pruned after
7075 * merged into rename/copy pairs as appropriate.
7077 if (options->flags.reverse_diff)
7078 addremove = (addremove == '+' ? '-' :
7079 addremove == '-' ? '+' : addremove);
7081 if (options->prefix &&
7082 strncmp(concatpath, options->prefix, options->prefix_length))
7083 return;
7085 one = alloc_filespec(concatpath);
7086 two = alloc_filespec(concatpath);
7088 if (addremove != '+')
7089 fill_filespec(one, oid, oid_valid, mode);
7090 if (addremove != '-') {
7091 fill_filespec(two, oid, oid_valid, mode);
7092 two->dirty_submodule = dirty_submodule;
7095 diff_queue(&diff_queued_diff, one, two);
7096 if (!options->flags.diff_from_contents)
7097 options->flags.has_changes = 1;
7100 void diff_change(struct diff_options *options,
7101 unsigned old_mode, unsigned new_mode,
7102 const struct object_id *old_oid,
7103 const struct object_id *new_oid,
7104 int old_oid_valid, int new_oid_valid,
7105 const char *concatpath,
7106 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7108 struct diff_filespec *one, *two;
7109 struct diff_filepair *p;
7111 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7112 is_submodule_ignored(concatpath, options))
7113 return;
7115 if (options->flags.reverse_diff) {
7116 SWAP(old_mode, new_mode);
7117 SWAP(old_oid, new_oid);
7118 SWAP(old_oid_valid, new_oid_valid);
7119 SWAP(old_dirty_submodule, new_dirty_submodule);
7122 if (options->prefix &&
7123 strncmp(concatpath, options->prefix, options->prefix_length))
7124 return;
7126 one = alloc_filespec(concatpath);
7127 two = alloc_filespec(concatpath);
7128 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7129 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7130 one->dirty_submodule = old_dirty_submodule;
7131 two->dirty_submodule = new_dirty_submodule;
7132 p = diff_queue(&diff_queued_diff, one, two);
7134 if (options->flags.diff_from_contents)
7135 return;
7137 if (options->flags.quick && options->skip_stat_unmatch &&
7138 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7139 diff_free_filespec_data(p->one);
7140 diff_free_filespec_data(p->two);
7141 return;
7144 options->flags.has_changes = 1;
7147 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7149 struct diff_filepair *pair;
7150 struct diff_filespec *one, *two;
7152 if (options->prefix &&
7153 strncmp(path, options->prefix, options->prefix_length))
7154 return NULL;
7156 one = alloc_filespec(path);
7157 two = alloc_filespec(path);
7158 pair = diff_queue(&diff_queued_diff, one, two);
7159 pair->is_unmerged = 1;
7160 return pair;
7163 static char *run_textconv(struct repository *r,
7164 const char *pgm,
7165 struct diff_filespec *spec,
7166 size_t *outsize)
7168 struct diff_tempfile *temp;
7169 struct child_process child = CHILD_PROCESS_INIT;
7170 struct strbuf buf = STRBUF_INIT;
7171 int err = 0;
7173 temp = prepare_temp_file(r, spec);
7174 strvec_push(&child.args, pgm);
7175 strvec_push(&child.args, temp->name);
7177 child.use_shell = 1;
7178 child.out = -1;
7179 if (start_command(&child)) {
7180 remove_tempfile();
7181 return NULL;
7184 if (strbuf_read(&buf, child.out, 0) < 0)
7185 err = error("error reading from textconv command '%s'", pgm);
7186 close(child.out);
7188 if (finish_command(&child) || err) {
7189 strbuf_release(&buf);
7190 remove_tempfile();
7191 return NULL;
7193 remove_tempfile();
7195 return strbuf_detach(&buf, outsize);
7198 size_t fill_textconv(struct repository *r,
7199 struct userdiff_driver *driver,
7200 struct diff_filespec *df,
7201 char **outbuf)
7203 size_t size;
7205 if (!driver) {
7206 if (!DIFF_FILE_VALID(df)) {
7207 *outbuf = "";
7208 return 0;
7210 if (diff_populate_filespec(r, df, NULL))
7211 die("unable to read files to diff");
7212 *outbuf = df->data;
7213 return df->size;
7216 if (!driver->textconv)
7217 BUG("fill_textconv called with non-textconv driver");
7219 if (driver->textconv_cache && df->oid_valid) {
7220 *outbuf = notes_cache_get(driver->textconv_cache,
7221 &df->oid,
7222 &size);
7223 if (*outbuf)
7224 return size;
7227 *outbuf = run_textconv(r, driver->textconv, df, &size);
7228 if (!*outbuf)
7229 die("unable to read files to diff");
7231 if (driver->textconv_cache && df->oid_valid) {
7232 /* ignore errors, as we might be in a readonly repository */
7233 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7234 size);
7236 * we could save up changes and flush them all at the end,
7237 * but we would need an extra call after all diffing is done.
7238 * Since generating a cache entry is the slow path anyway,
7239 * this extra overhead probably isn't a big deal.
7241 notes_cache_write(driver->textconv_cache);
7244 return size;
7247 int textconv_object(struct repository *r,
7248 const char *path,
7249 unsigned mode,
7250 const struct object_id *oid,
7251 int oid_valid,
7252 char **buf,
7253 unsigned long *buf_size)
7255 struct diff_filespec *df;
7256 struct userdiff_driver *textconv;
7258 df = alloc_filespec(path);
7259 fill_filespec(df, oid, oid_valid, mode);
7260 textconv = get_textconv(r, df);
7261 if (!textconv) {
7262 free_filespec(df);
7263 return 0;
7266 *buf_size = fill_textconv(r, textconv, df, buf);
7267 free_filespec(df);
7268 return 1;
7271 void setup_diff_pager(struct diff_options *opt)
7274 * If the user asked for our exit code, then either they want --quiet
7275 * or --exit-code. We should definitely not bother with a pager in the
7276 * former case, as we will generate no output. Since we still properly
7277 * report our exit code even when a pager is run, we _could_ run a
7278 * pager with --exit-code. But since we have not done so historically,
7279 * and because it is easy to find people oneline advising "git diff
7280 * --exit-code" in hooks and other scripts, we do not do so.
7282 if (!opt->flags.exit_with_status &&
7283 check_pager_config("diff") != 0)
7284 setup_pager();