config: pass kvi to die_bad_number()
[git/gitster.git] / diff.c
blob460211e7d40c3f4a011a09bf134ef48ab08410fe
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "abspath.h"
6 #include "alloc.h"
7 #include "base85.h"
8 #include "config.h"
9 #include "convert.h"
10 #include "environment.h"
11 #include "gettext.h"
12 #include "tempfile.h"
13 #include "quote.h"
14 #include "diff.h"
15 #include "diffcore.h"
16 #include "delta.h"
17 #include "hex.h"
18 #include "xdiff-interface.h"
19 #include "color.h"
20 #include "attr.h"
21 #include "run-command.h"
22 #include "utf8.h"
23 #include "object-store.h"
24 #include "userdiff.h"
25 #include "submodule-config.h"
26 #include "submodule.h"
27 #include "hashmap.h"
28 #include "mem-pool.h"
29 #include "ll-merge.h"
30 #include "string-list.h"
31 #include "strvec.h"
32 #include "graph.h"
33 #include "oid-array.h"
34 #include "packfile.h"
35 #include "pager.h"
36 #include "parse-options.h"
37 #include "help.h"
38 #include "promisor-remote.h"
39 #include "dir.h"
40 #include "object-file.h"
41 #include "object-name.h"
42 #include "setup.h"
43 #include "strmap.h"
44 #include "ws.h"
45 #include "wrapper.h"
47 #ifdef NO_FAST_WORKING_DIRECTORY
48 #define FAST_WORKING_DIRECTORY 0
49 #else
50 #define FAST_WORKING_DIRECTORY 1
51 #endif
53 static int diff_detect_rename_default;
54 static int diff_indent_heuristic = 1;
55 static int diff_rename_limit_default = 1000;
56 static int diff_suppress_blank_empty;
57 static int diff_use_color_default = -1;
58 static int diff_color_moved_default;
59 static int diff_color_moved_ws_default;
60 static int diff_context_default = 3;
61 static int diff_interhunk_context_default;
62 static const char *diff_word_regex_cfg;
63 static const char *external_diff_cmd_cfg;
64 static const char *diff_order_file_cfg;
65 int diff_auto_refresh_index = 1;
66 static int diff_mnemonic_prefix;
67 static int diff_no_prefix;
68 static int diff_relative;
69 static int diff_stat_graph_width;
70 static int diff_dirstat_permille_default = 30;
71 static struct diff_options default_diff_options;
72 static long diff_algorithm;
73 static unsigned ws_error_highlight_default = WSEH_NEW;
75 static char diff_colors[][COLOR_MAXLEN] = {
76 GIT_COLOR_RESET,
77 GIT_COLOR_NORMAL, /* CONTEXT */
78 GIT_COLOR_BOLD, /* METAINFO */
79 GIT_COLOR_CYAN, /* FRAGINFO */
80 GIT_COLOR_RED, /* OLD */
81 GIT_COLOR_GREEN, /* NEW */
82 GIT_COLOR_YELLOW, /* COMMIT */
83 GIT_COLOR_BG_RED, /* WHITESPACE */
84 GIT_COLOR_NORMAL, /* FUNCINFO */
85 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
86 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
87 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
88 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
89 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
90 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
91 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
92 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
93 GIT_COLOR_FAINT, /* CONTEXT_DIM */
94 GIT_COLOR_FAINT_RED, /* OLD_DIM */
95 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
96 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
97 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
98 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
101 static const char *color_diff_slots[] = {
102 [DIFF_CONTEXT] = "context",
103 [DIFF_METAINFO] = "meta",
104 [DIFF_FRAGINFO] = "frag",
105 [DIFF_FILE_OLD] = "old",
106 [DIFF_FILE_NEW] = "new",
107 [DIFF_COMMIT] = "commit",
108 [DIFF_WHITESPACE] = "whitespace",
109 [DIFF_FUNCINFO] = "func",
110 [DIFF_FILE_OLD_MOVED] = "oldMoved",
111 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
112 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
113 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
114 [DIFF_FILE_NEW_MOVED] = "newMoved",
115 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
116 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
117 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
118 [DIFF_CONTEXT_DIM] = "contextDimmed",
119 [DIFF_FILE_OLD_DIM] = "oldDimmed",
120 [DIFF_FILE_NEW_DIM] = "newDimmed",
121 [DIFF_CONTEXT_BOLD] = "contextBold",
122 [DIFF_FILE_OLD_BOLD] = "oldBold",
123 [DIFF_FILE_NEW_BOLD] = "newBold",
126 define_list_config_array_extra(color_diff_slots, {"plain"});
128 static int parse_diff_color_slot(const char *var)
130 if (!strcasecmp(var, "plain"))
131 return DIFF_CONTEXT;
132 return LOOKUP_CONFIG(color_diff_slots, var);
135 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
136 struct strbuf *errmsg)
138 char *params_copy = xstrdup(params_string);
139 struct string_list params = STRING_LIST_INIT_NODUP;
140 int ret = 0;
141 int i;
143 if (*params_copy)
144 string_list_split_in_place(&params, params_copy, ",", -1);
145 for (i = 0; i < params.nr; i++) {
146 const char *p = params.items[i].string;
147 if (!strcmp(p, "changes")) {
148 options->flags.dirstat_by_line = 0;
149 options->flags.dirstat_by_file = 0;
150 } else if (!strcmp(p, "lines")) {
151 options->flags.dirstat_by_line = 1;
152 options->flags.dirstat_by_file = 0;
153 } else if (!strcmp(p, "files")) {
154 options->flags.dirstat_by_line = 0;
155 options->flags.dirstat_by_file = 1;
156 } else if (!strcmp(p, "noncumulative")) {
157 options->flags.dirstat_cumulative = 0;
158 } else if (!strcmp(p, "cumulative")) {
159 options->flags.dirstat_cumulative = 1;
160 } else if (isdigit(*p)) {
161 char *end;
162 int permille = strtoul(p, &end, 10) * 10;
163 if (*end == '.' && isdigit(*++end)) {
164 /* only use first digit */
165 permille += *end - '0';
166 /* .. and ignore any further digits */
167 while (isdigit(*++end))
168 ; /* nothing */
170 if (!*end)
171 options->dirstat_permille = permille;
172 else {
173 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
175 ret++;
177 } else {
178 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
179 ret++;
183 string_list_clear(&params, 0);
184 free(params_copy);
185 return ret;
188 static int parse_submodule_params(struct diff_options *options, const char *value)
190 if (!strcmp(value, "log"))
191 options->submodule_format = DIFF_SUBMODULE_LOG;
192 else if (!strcmp(value, "short"))
193 options->submodule_format = DIFF_SUBMODULE_SHORT;
194 else if (!strcmp(value, "diff"))
195 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
197 * Please update $__git_diff_submodule_formats in
198 * git-completion.bash when you add new formats.
200 else
201 return -1;
202 return 0;
205 int git_config_rename(const char *var, const char *value)
207 if (!value)
208 return DIFF_DETECT_RENAME;
209 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
210 return DIFF_DETECT_COPY;
211 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
214 long parse_algorithm_value(const char *value)
216 if (!value)
217 return -1;
218 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
219 return 0;
220 else if (!strcasecmp(value, "minimal"))
221 return XDF_NEED_MINIMAL;
222 else if (!strcasecmp(value, "patience"))
223 return XDF_PATIENCE_DIFF;
224 else if (!strcasecmp(value, "histogram"))
225 return XDF_HISTOGRAM_DIFF;
227 * Please update $__git_diff_algorithms in git-completion.bash
228 * when you add new algorithms.
230 return -1;
233 static int parse_one_token(const char **arg, const char *token)
235 const char *rest;
236 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
237 *arg = rest;
238 return 1;
240 return 0;
243 static int parse_ws_error_highlight(const char *arg)
245 const char *orig_arg = arg;
246 unsigned val = 0;
248 while (*arg) {
249 if (parse_one_token(&arg, "none"))
250 val = 0;
251 else if (parse_one_token(&arg, "default"))
252 val = WSEH_NEW;
253 else if (parse_one_token(&arg, "all"))
254 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
255 else if (parse_one_token(&arg, "new"))
256 val |= WSEH_NEW;
257 else if (parse_one_token(&arg, "old"))
258 val |= WSEH_OLD;
259 else if (parse_one_token(&arg, "context"))
260 val |= WSEH_CONTEXT;
261 else {
262 return -1 - (int)(arg - orig_arg);
264 if (*arg)
265 arg++;
267 return val;
271 * These are to give UI layer defaults.
272 * The core-level commands such as git-diff-files should
273 * never be affected by the setting of diff.renames
274 * the user happens to have in the configuration file.
276 void init_diff_ui_defaults(void)
278 diff_detect_rename_default = DIFF_DETECT_RENAME;
281 int git_diff_heuristic_config(const char *var, const char *value,
282 void *cb UNUSED)
284 if (!strcmp(var, "diff.indentheuristic"))
285 diff_indent_heuristic = git_config_bool(var, value);
286 return 0;
289 static int parse_color_moved(const char *arg)
291 switch (git_parse_maybe_bool(arg)) {
292 case 0:
293 return COLOR_MOVED_NO;
294 case 1:
295 return COLOR_MOVED_DEFAULT;
296 default:
297 break;
300 if (!strcmp(arg, "no"))
301 return COLOR_MOVED_NO;
302 else if (!strcmp(arg, "plain"))
303 return COLOR_MOVED_PLAIN;
304 else if (!strcmp(arg, "blocks"))
305 return COLOR_MOVED_BLOCKS;
306 else if (!strcmp(arg, "zebra"))
307 return COLOR_MOVED_ZEBRA;
308 else if (!strcmp(arg, "default"))
309 return COLOR_MOVED_DEFAULT;
310 else if (!strcmp(arg, "dimmed-zebra"))
311 return COLOR_MOVED_ZEBRA_DIM;
312 else if (!strcmp(arg, "dimmed_zebra"))
313 return COLOR_MOVED_ZEBRA_DIM;
314 else
315 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
318 static unsigned parse_color_moved_ws(const char *arg)
320 int ret = 0;
321 struct string_list l = STRING_LIST_INIT_DUP;
322 struct string_list_item *i;
324 string_list_split(&l, arg, ',', -1);
326 for_each_string_list_item(i, &l) {
327 struct strbuf sb = STRBUF_INIT;
328 strbuf_addstr(&sb, i->string);
329 strbuf_trim(&sb);
331 if (!strcmp(sb.buf, "no"))
332 ret = 0;
333 else if (!strcmp(sb.buf, "ignore-space-change"))
334 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
335 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
336 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
337 else if (!strcmp(sb.buf, "ignore-all-space"))
338 ret |= XDF_IGNORE_WHITESPACE;
339 else if (!strcmp(sb.buf, "allow-indentation-change"))
340 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
341 else {
342 ret |= COLOR_MOVED_WS_ERROR;
343 error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), sb.buf);
346 strbuf_release(&sb);
349 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
350 (ret & XDF_WHITESPACE_FLAGS)) {
351 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
352 ret |= COLOR_MOVED_WS_ERROR;
355 string_list_clear(&l, 0);
357 return ret;
360 int git_diff_ui_config(const char *var, const char *value,
361 const struct config_context *ctx, void *cb)
363 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
364 diff_use_color_default = git_config_colorbool(var, value);
365 return 0;
367 if (!strcmp(var, "diff.colormoved")) {
368 int cm = parse_color_moved(value);
369 if (cm < 0)
370 return -1;
371 diff_color_moved_default = cm;
372 return 0;
374 if (!strcmp(var, "diff.colormovedws")) {
375 unsigned cm = parse_color_moved_ws(value);
376 if (cm & COLOR_MOVED_WS_ERROR)
377 return -1;
378 diff_color_moved_ws_default = cm;
379 return 0;
381 if (!strcmp(var, "diff.context")) {
382 diff_context_default = git_config_int(var, value, ctx->kvi);
383 if (diff_context_default < 0)
384 return -1;
385 return 0;
387 if (!strcmp(var, "diff.interhunkcontext")) {
388 diff_interhunk_context_default = git_config_int(var, value,
389 ctx->kvi);
390 if (diff_interhunk_context_default < 0)
391 return -1;
392 return 0;
394 if (!strcmp(var, "diff.renames")) {
395 diff_detect_rename_default = git_config_rename(var, value);
396 return 0;
398 if (!strcmp(var, "diff.autorefreshindex")) {
399 diff_auto_refresh_index = git_config_bool(var, value);
400 return 0;
402 if (!strcmp(var, "diff.mnemonicprefix")) {
403 diff_mnemonic_prefix = git_config_bool(var, value);
404 return 0;
406 if (!strcmp(var, "diff.noprefix")) {
407 diff_no_prefix = git_config_bool(var, value);
408 return 0;
410 if (!strcmp(var, "diff.relative")) {
411 diff_relative = git_config_bool(var, value);
412 return 0;
414 if (!strcmp(var, "diff.statgraphwidth")) {
415 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
416 return 0;
418 if (!strcmp(var, "diff.external"))
419 return git_config_string(&external_diff_cmd_cfg, var, value);
420 if (!strcmp(var, "diff.wordregex"))
421 return git_config_string(&diff_word_regex_cfg, var, value);
422 if (!strcmp(var, "diff.orderfile"))
423 return git_config_pathname(&diff_order_file_cfg, var, value);
425 if (!strcmp(var, "diff.ignoresubmodules"))
426 handle_ignore_submodules_arg(&default_diff_options, value);
428 if (!strcmp(var, "diff.submodule")) {
429 if (parse_submodule_params(&default_diff_options, value))
430 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
431 value);
432 return 0;
435 if (!strcmp(var, "diff.algorithm")) {
436 diff_algorithm = parse_algorithm_value(value);
437 if (diff_algorithm < 0)
438 return -1;
439 return 0;
442 if (git_color_config(var, value, cb) < 0)
443 return -1;
445 return git_diff_basic_config(var, value, ctx, cb);
448 int git_diff_basic_config(const char *var, const char *value,
449 const struct config_context *ctx, void *cb)
451 const char *name;
453 if (!strcmp(var, "diff.renamelimit")) {
454 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
455 return 0;
458 if (userdiff_config(var, value) < 0)
459 return -1;
461 if (skip_prefix(var, "diff.color.", &name) ||
462 skip_prefix(var, "color.diff.", &name)) {
463 int slot = parse_diff_color_slot(name);
464 if (slot < 0)
465 return 0;
466 if (!value)
467 return config_error_nonbool(var);
468 return color_parse(value, diff_colors[slot]);
471 if (!strcmp(var, "diff.wserrorhighlight")) {
472 int val = parse_ws_error_highlight(value);
473 if (val < 0)
474 return -1;
475 ws_error_highlight_default = val;
476 return 0;
479 /* like GNU diff's --suppress-blank-empty option */
480 if (!strcmp(var, "diff.suppressblankempty") ||
481 /* for backwards compatibility */
482 !strcmp(var, "diff.suppress-blank-empty")) {
483 diff_suppress_blank_empty = git_config_bool(var, value);
484 return 0;
487 if (!strcmp(var, "diff.dirstat")) {
488 struct strbuf errmsg = STRBUF_INIT;
489 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
490 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
491 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
492 errmsg.buf);
493 strbuf_release(&errmsg);
494 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
495 return 0;
498 if (git_diff_heuristic_config(var, value, cb) < 0)
499 return -1;
501 return git_default_config(var, value, ctx, cb);
504 static char *quote_two(const char *one, const char *two)
506 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
507 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
508 struct strbuf res = STRBUF_INIT;
510 if (need_one + need_two) {
511 strbuf_addch(&res, '"');
512 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
513 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
514 strbuf_addch(&res, '"');
515 } else {
516 strbuf_addstr(&res, one);
517 strbuf_addstr(&res, two);
519 return strbuf_detach(&res, NULL);
522 static const char *external_diff(void)
524 static const char *external_diff_cmd = NULL;
525 static int done_preparing = 0;
527 if (done_preparing)
528 return external_diff_cmd;
529 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
530 if (!external_diff_cmd)
531 external_diff_cmd = external_diff_cmd_cfg;
532 done_preparing = 1;
533 return external_diff_cmd;
537 * Keep track of files used for diffing. Sometimes such an entry
538 * refers to a temporary file, sometimes to an existing file, and
539 * sometimes to "/dev/null".
541 static struct diff_tempfile {
543 * filename external diff should read from, or NULL if this
544 * entry is currently not in use:
546 const char *name;
548 char hex[GIT_MAX_HEXSZ + 1];
549 char mode[10];
552 * If this diff_tempfile instance refers to a temporary file,
553 * this tempfile object is used to manage its lifetime.
555 struct tempfile *tempfile;
556 } diff_temp[2];
558 struct emit_callback {
559 int color_diff;
560 unsigned ws_rule;
561 int blank_at_eof_in_preimage;
562 int blank_at_eof_in_postimage;
563 int lno_in_preimage;
564 int lno_in_postimage;
565 const char **label_path;
566 struct diff_words_data *diff_words;
567 struct diff_options *opt;
568 struct strbuf *header;
571 static int count_lines(const char *data, int size)
573 int count, ch, completely_empty = 1, nl_just_seen = 0;
574 count = 0;
575 while (0 < size--) {
576 ch = *data++;
577 if (ch == '\n') {
578 count++;
579 nl_just_seen = 1;
580 completely_empty = 0;
582 else {
583 nl_just_seen = 0;
584 completely_empty = 0;
587 if (completely_empty)
588 return 0;
589 if (!nl_just_seen)
590 count++; /* no trailing newline */
591 return count;
594 static int fill_mmfile(struct repository *r, mmfile_t *mf,
595 struct diff_filespec *one)
597 if (!DIFF_FILE_VALID(one)) {
598 mf->ptr = (char *)""; /* does not matter */
599 mf->size = 0;
600 return 0;
602 else if (diff_populate_filespec(r, one, NULL))
603 return -1;
605 mf->ptr = one->data;
606 mf->size = one->size;
607 return 0;
610 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
611 static unsigned long diff_filespec_size(struct repository *r,
612 struct diff_filespec *one)
614 struct diff_populate_filespec_options dpf_options = {
615 .check_size_only = 1,
618 if (!DIFF_FILE_VALID(one))
619 return 0;
620 diff_populate_filespec(r, one, &dpf_options);
621 return one->size;
624 static int count_trailing_blank(mmfile_t *mf)
626 char *ptr = mf->ptr;
627 long size = mf->size;
628 int cnt = 0;
630 if (!size)
631 return cnt;
632 ptr += size - 1; /* pointing at the very end */
633 if (*ptr != '\n')
634 ; /* incomplete line */
635 else
636 ptr--; /* skip the last LF */
637 while (mf->ptr < ptr) {
638 char *prev_eol;
639 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
640 if (*prev_eol == '\n')
641 break;
642 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
643 break;
644 cnt++;
645 ptr = prev_eol - 1;
647 return cnt;
650 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
651 struct emit_callback *ecbdata)
653 int l1, l2, at;
654 l1 = count_trailing_blank(mf1);
655 l2 = count_trailing_blank(mf2);
656 if (l2 <= l1) {
657 ecbdata->blank_at_eof_in_preimage = 0;
658 ecbdata->blank_at_eof_in_postimage = 0;
659 return;
661 at = count_lines(mf1->ptr, mf1->size);
662 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
664 at = count_lines(mf2->ptr, mf2->size);
665 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
668 static void emit_line_0(struct diff_options *o,
669 const char *set_sign, const char *set, unsigned reverse, const char *reset,
670 int first, const char *line, int len)
672 int has_trailing_newline, has_trailing_carriage_return;
673 int needs_reset = 0; /* at the end of the line */
674 FILE *file = o->file;
676 fputs(diff_line_prefix(o), file);
678 has_trailing_newline = (len > 0 && line[len-1] == '\n');
679 if (has_trailing_newline)
680 len--;
682 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
683 if (has_trailing_carriage_return)
684 len--;
686 if (!len && !first)
687 goto end_of_line;
689 if (reverse && want_color(o->use_color)) {
690 fputs(GIT_COLOR_REVERSE, file);
691 needs_reset = 1;
694 if (set_sign) {
695 fputs(set_sign, file);
696 needs_reset = 1;
699 if (first)
700 fputc(first, file);
702 if (!len)
703 goto end_of_line;
705 if (set) {
706 if (set_sign && set != set_sign)
707 fputs(reset, file);
708 fputs(set, file);
709 needs_reset = 1;
711 fwrite(line, len, 1, file);
712 needs_reset = 1; /* 'line' may contain color codes. */
714 end_of_line:
715 if (needs_reset)
716 fputs(reset, file);
717 if (has_trailing_carriage_return)
718 fputc('\r', file);
719 if (has_trailing_newline)
720 fputc('\n', file);
723 static void emit_line(struct diff_options *o, const char *set, const char *reset,
724 const char *line, int len)
726 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
729 enum diff_symbol {
730 DIFF_SYMBOL_BINARY_DIFF_HEADER,
731 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
732 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
733 DIFF_SYMBOL_BINARY_DIFF_BODY,
734 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
735 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
736 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
737 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
738 DIFF_SYMBOL_STATS_LINE,
739 DIFF_SYMBOL_WORD_DIFF,
740 DIFF_SYMBOL_STAT_SEP,
741 DIFF_SYMBOL_SUMMARY,
742 DIFF_SYMBOL_SUBMODULE_ADD,
743 DIFF_SYMBOL_SUBMODULE_DEL,
744 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
745 DIFF_SYMBOL_SUBMODULE_MODIFIED,
746 DIFF_SYMBOL_SUBMODULE_HEADER,
747 DIFF_SYMBOL_SUBMODULE_ERROR,
748 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
749 DIFF_SYMBOL_REWRITE_DIFF,
750 DIFF_SYMBOL_BINARY_FILES,
751 DIFF_SYMBOL_HEADER,
752 DIFF_SYMBOL_FILEPAIR_PLUS,
753 DIFF_SYMBOL_FILEPAIR_MINUS,
754 DIFF_SYMBOL_WORDS_PORCELAIN,
755 DIFF_SYMBOL_WORDS,
756 DIFF_SYMBOL_CONTEXT,
757 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
758 DIFF_SYMBOL_PLUS,
759 DIFF_SYMBOL_MINUS,
760 DIFF_SYMBOL_NO_LF_EOF,
761 DIFF_SYMBOL_CONTEXT_FRAGINFO,
762 DIFF_SYMBOL_CONTEXT_MARKER,
763 DIFF_SYMBOL_SEPARATOR
766 * Flags for content lines:
767 * 0..12 are whitespace rules
768 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
769 * 16 is marking if the line is blank at EOF
771 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
772 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
773 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
774 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
775 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
778 * This struct is used when we need to buffer the output of the diff output.
780 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
781 * into the pre/post image file. This pointer could be a union with the
782 * line pointer. By storing an offset into the file instead of the literal line,
783 * we can decrease the memory footprint for the buffered output. At first we
784 * may want to only have indirection for the content lines, but we could also
785 * enhance the state for emitting prefabricated lines, e.g. the similarity
786 * score line or hunk/file headers would only need to store a number or path
787 * and then the output can be constructed later on depending on state.
789 struct emitted_diff_symbol {
790 const char *line;
791 int len;
792 int flags;
793 int indent_off; /* Offset to first non-whitespace character */
794 int indent_width; /* The visual width of the indentation */
795 unsigned id;
796 enum diff_symbol s;
798 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
800 struct emitted_diff_symbols {
801 struct emitted_diff_symbol *buf;
802 int nr, alloc;
804 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
806 static void append_emitted_diff_symbol(struct diff_options *o,
807 struct emitted_diff_symbol *e)
809 struct emitted_diff_symbol *f;
811 ALLOC_GROW(o->emitted_symbols->buf,
812 o->emitted_symbols->nr + 1,
813 o->emitted_symbols->alloc);
814 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
816 memcpy(f, e, sizeof(struct emitted_diff_symbol));
817 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
820 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
822 if (!e)
823 return;
824 free(e->buf);
825 free(e);
828 struct moved_entry {
829 const struct emitted_diff_symbol *es;
830 struct moved_entry *next_line;
831 struct moved_entry *next_match;
834 struct moved_block {
835 struct moved_entry *match;
836 int wsd; /* The whitespace delta of this block */
839 #define INDENT_BLANKLINE INT_MIN
841 static void fill_es_indent_data(struct emitted_diff_symbol *es)
843 unsigned int off = 0, i;
844 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
845 const char *s = es->line;
846 const int len = es->len;
848 /* skip any \v \f \r at start of indentation */
849 while (s[off] == '\f' || s[off] == '\v' ||
850 (s[off] == '\r' && off < len - 1))
851 off++;
853 /* calculate the visual width of indentation */
854 while(1) {
855 if (s[off] == ' ') {
856 width++;
857 off++;
858 } else if (s[off] == '\t') {
859 width += tab_width - (width % tab_width);
860 while (s[++off] == '\t')
861 width += tab_width;
862 } else {
863 break;
867 /* check if this line is blank */
868 for (i = off; i < len; i++)
869 if (!isspace(s[i]))
870 break;
872 if (i == len) {
873 es->indent_width = INDENT_BLANKLINE;
874 es->indent_off = len;
875 } else {
876 es->indent_off = off;
877 es->indent_width = width;
881 static int compute_ws_delta(const struct emitted_diff_symbol *a,
882 const struct emitted_diff_symbol *b)
884 int a_width = a->indent_width,
885 b_width = b->indent_width;
887 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
888 return INDENT_BLANKLINE;
890 return a_width - b_width;
893 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
894 const struct emitted_diff_symbol *l,
895 struct moved_block *pmb)
897 int a_width = cur->es->indent_width, b_width = l->indent_width;
898 int delta;
900 /* The text of each line must match */
901 if (cur->es->id != l->id)
902 return 1;
905 * If 'l' and 'cur' are both blank then we don't need to check the
906 * indent. We only need to check cur as we know the strings match.
907 * */
908 if (a_width == INDENT_BLANKLINE)
909 return 0;
912 * The indent changes of the block are known and stored in pmb->wsd;
913 * however we need to check if the indent changes of the current line
914 * match those of the current block.
916 delta = b_width - a_width;
919 * If the previous lines of this block were all blank then set its
920 * whitespace delta.
922 if (pmb->wsd == INDENT_BLANKLINE)
923 pmb->wsd = delta;
925 return delta != pmb->wsd;
928 struct interned_diff_symbol {
929 struct hashmap_entry ent;
930 struct emitted_diff_symbol *es;
933 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
934 const struct hashmap_entry *eptr,
935 const struct hashmap_entry *entry_or_key,
936 const void *keydata UNUSED)
938 const struct diff_options *diffopt = hashmap_cmp_fn_data;
939 const struct emitted_diff_symbol *a, *b;
940 unsigned flags = diffopt->color_moved_ws_handling
941 & XDF_WHITESPACE_FLAGS;
943 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
944 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
946 return !xdiff_compare_lines(a->line + a->indent_off,
947 a->len - a->indent_off,
948 b->line + b->indent_off,
949 b->len - b->indent_off, flags);
952 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
953 struct interned_diff_symbol *s)
955 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
956 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
957 l->len - l->indent_off, flags);
959 hashmap_entry_init(&s->ent, hash);
960 s->es = l;
963 struct moved_entry_list {
964 struct moved_entry *add, *del;
967 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
968 struct mem_pool *entry_mem_pool)
970 struct moved_entry *prev_line = NULL;
971 struct mem_pool interned_pool;
972 struct hashmap interned_map;
973 struct moved_entry_list *entry_list = NULL;
974 size_t entry_list_alloc = 0;
975 unsigned id = 0;
976 int n;
978 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
979 mem_pool_init(&interned_pool, 1024 * 1024);
981 for (n = 0; n < o->emitted_symbols->nr; n++) {
982 struct interned_diff_symbol key;
983 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
984 struct interned_diff_symbol *s;
985 struct moved_entry *entry;
987 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
988 prev_line = NULL;
989 continue;
992 if (o->color_moved_ws_handling &
993 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
994 fill_es_indent_data(l);
996 prepare_entry(o, l, &key);
997 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
998 if (s) {
999 l->id = s->es->id;
1000 } else {
1001 l->id = id;
1002 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1003 hashmap_add(&interned_map,
1004 memcpy(mem_pool_alloc(&interned_pool,
1005 sizeof(key)),
1006 &key, sizeof(key)));
1008 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1009 entry->es = l;
1010 entry->next_line = NULL;
1011 if (prev_line && prev_line->es->s == l->s)
1012 prev_line->next_line = entry;
1013 prev_line = entry;
1014 if (l->s == DIFF_SYMBOL_PLUS) {
1015 entry->next_match = entry_list[l->id].add;
1016 entry_list[l->id].add = entry;
1017 } else {
1018 entry->next_match = entry_list[l->id].del;
1019 entry_list[l->id].del = entry;
1023 hashmap_clear(&interned_map);
1024 mem_pool_discard(&interned_pool, 0);
1026 return entry_list;
1029 static void pmb_advance_or_null(struct diff_options *o,
1030 struct emitted_diff_symbol *l,
1031 struct moved_block *pmb,
1032 int *pmb_nr)
1034 int i, j;
1036 for (i = 0, j = 0; i < *pmb_nr; i++) {
1037 int match;
1038 struct moved_entry *prev = pmb[i].match;
1039 struct moved_entry *cur = (prev && prev->next_line) ?
1040 prev->next_line : NULL;
1042 if (o->color_moved_ws_handling &
1043 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1044 match = cur &&
1045 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1046 else
1047 match = cur && cur->es->id == l->id;
1049 if (match) {
1050 pmb[j] = pmb[i];
1051 pmb[j++].match = cur;
1054 *pmb_nr = j;
1057 static void fill_potential_moved_blocks(struct diff_options *o,
1058 struct moved_entry *match,
1059 struct emitted_diff_symbol *l,
1060 struct moved_block **pmb_p,
1061 int *pmb_alloc_p, int *pmb_nr_p)
1064 struct moved_block *pmb = *pmb_p;
1065 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1068 * The current line is the start of a new block.
1069 * Setup the set of potential blocks.
1071 for (; match; match = match->next_match) {
1072 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1073 if (o->color_moved_ws_handling &
1074 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1075 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1076 else
1077 pmb[pmb_nr].wsd = 0;
1078 pmb[pmb_nr++].match = match;
1081 *pmb_p = pmb;
1082 *pmb_alloc_p = pmb_alloc;
1083 *pmb_nr_p = pmb_nr;
1087 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1089 * Otherwise, if the last block has fewer alphanumeric characters than
1090 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1091 * that block.
1093 * The last block consists of the (n - block_length)'th line up to but not
1094 * including the nth line.
1096 * Returns 0 if the last block is empty or is unset by this function, non zero
1097 * otherwise.
1099 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1100 * Think of a way to unify them.
1102 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1103 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1104 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1106 int i, alnum_count = 0;
1107 if (o->color_moved == COLOR_MOVED_PLAIN)
1108 return block_length;
1109 for (i = 1; i < block_length + 1; i++) {
1110 const char *c = o->emitted_symbols->buf[n - i].line;
1111 for (; *c; c++) {
1112 if (!isalnum(*c))
1113 continue;
1114 alnum_count++;
1115 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1116 return 1;
1119 for (i = 1; i < block_length + 1; i++)
1120 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1121 return 0;
1124 /* Find blocks of moved code, delegate actual coloring decision to helper */
1125 static void mark_color_as_moved(struct diff_options *o,
1126 struct moved_entry_list *entry_list)
1128 struct moved_block *pmb = NULL; /* potentially moved blocks */
1129 int pmb_nr = 0, pmb_alloc = 0;
1130 int n, flipped_block = 0, block_length = 0;
1131 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1134 for (n = 0; n < o->emitted_symbols->nr; n++) {
1135 struct moved_entry *match = NULL;
1136 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1138 switch (l->s) {
1139 case DIFF_SYMBOL_PLUS:
1140 match = entry_list[l->id].del;
1141 break;
1142 case DIFF_SYMBOL_MINUS:
1143 match = entry_list[l->id].add;
1144 break;
1145 default:
1146 flipped_block = 0;
1149 if (pmb_nr && (!match || l->s != moved_symbol)) {
1150 if (!adjust_last_block(o, n, block_length) &&
1151 block_length > 1) {
1153 * Rewind in case there is another match
1154 * starting at the second line of the block
1156 match = NULL;
1157 n -= block_length;
1159 pmb_nr = 0;
1160 block_length = 0;
1161 flipped_block = 0;
1163 if (!match) {
1164 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1165 continue;
1168 if (o->color_moved == COLOR_MOVED_PLAIN) {
1169 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1170 continue;
1173 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1175 if (pmb_nr == 0) {
1176 int contiguous = adjust_last_block(o, n, block_length);
1178 if (!contiguous && block_length > 1)
1180 * Rewind in case there is another match
1181 * starting at the second line of the block
1183 n -= block_length;
1184 else
1185 fill_potential_moved_blocks(o, match, l,
1186 &pmb, &pmb_alloc,
1187 &pmb_nr);
1189 if (contiguous && pmb_nr && moved_symbol == l->s)
1190 flipped_block = (flipped_block + 1) % 2;
1191 else
1192 flipped_block = 0;
1194 if (pmb_nr)
1195 moved_symbol = l->s;
1196 else
1197 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1199 block_length = 0;
1202 if (pmb_nr) {
1203 block_length++;
1204 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1205 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1206 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1209 adjust_last_block(o, n, block_length);
1211 free(pmb);
1214 static void dim_moved_lines(struct diff_options *o)
1216 int n;
1217 for (n = 0; n < o->emitted_symbols->nr; n++) {
1218 struct emitted_diff_symbol *prev = (n != 0) ?
1219 &o->emitted_symbols->buf[n - 1] : NULL;
1220 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1221 struct emitted_diff_symbol *next =
1222 (n < o->emitted_symbols->nr - 1) ?
1223 &o->emitted_symbols->buf[n + 1] : NULL;
1225 /* Not a plus or minus line? */
1226 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1227 continue;
1229 /* Not a moved line? */
1230 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1231 continue;
1234 * If prev or next are not a plus or minus line,
1235 * pretend they don't exist
1237 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1238 prev->s != DIFF_SYMBOL_MINUS)
1239 prev = NULL;
1240 if (next && next->s != DIFF_SYMBOL_PLUS &&
1241 next->s != DIFF_SYMBOL_MINUS)
1242 next = NULL;
1244 /* Inside a block? */
1245 if ((prev &&
1246 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1247 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1248 (next &&
1249 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1250 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1251 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1252 continue;
1255 /* Check if we are at an interesting bound: */
1256 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1257 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1258 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1259 continue;
1260 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1261 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1262 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1263 continue;
1266 * The boundary to prev and next are not interesting,
1267 * so this line is not interesting as a whole
1269 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1273 static void emit_line_ws_markup(struct diff_options *o,
1274 const char *set_sign, const char *set,
1275 const char *reset,
1276 int sign_index, const char *line, int len,
1277 unsigned ws_rule, int blank_at_eof)
1279 const char *ws = NULL;
1280 int sign = o->output_indicators[sign_index];
1282 if (o->ws_error_highlight & ws_rule) {
1283 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1284 if (!*ws)
1285 ws = NULL;
1288 if (!ws && !set_sign)
1289 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1290 else if (!ws) {
1291 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1292 } else if (blank_at_eof)
1293 /* Blank line at EOF - paint '+' as well */
1294 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1295 else {
1296 /* Emit just the prefix, then the rest. */
1297 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1298 sign, "", 0);
1299 ws_check_emit(line, len, ws_rule,
1300 o->file, set, reset, ws);
1304 static void emit_diff_symbol_from_struct(struct diff_options *o,
1305 struct emitted_diff_symbol *eds)
1307 static const char *nneof = " No newline at end of file\n";
1308 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1310 enum diff_symbol s = eds->s;
1311 const char *line = eds->line;
1312 int len = eds->len;
1313 unsigned flags = eds->flags;
1315 switch (s) {
1316 case DIFF_SYMBOL_NO_LF_EOF:
1317 context = diff_get_color_opt(o, DIFF_CONTEXT);
1318 reset = diff_get_color_opt(o, DIFF_RESET);
1319 putc('\n', o->file);
1320 emit_line_0(o, context, NULL, 0, reset, '\\',
1321 nneof, strlen(nneof));
1322 break;
1323 case DIFF_SYMBOL_SUBMODULE_HEADER:
1324 case DIFF_SYMBOL_SUBMODULE_ERROR:
1325 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1326 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1327 case DIFF_SYMBOL_SUMMARY:
1328 case DIFF_SYMBOL_STATS_LINE:
1329 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1330 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1331 emit_line(o, "", "", line, len);
1332 break;
1333 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1334 case DIFF_SYMBOL_CONTEXT_MARKER:
1335 context = diff_get_color_opt(o, DIFF_CONTEXT);
1336 reset = diff_get_color_opt(o, DIFF_RESET);
1337 emit_line(o, context, reset, line, len);
1338 break;
1339 case DIFF_SYMBOL_SEPARATOR:
1340 fprintf(o->file, "%s%c",
1341 diff_line_prefix(o),
1342 o->line_termination);
1343 break;
1344 case DIFF_SYMBOL_CONTEXT:
1345 set = diff_get_color_opt(o, DIFF_CONTEXT);
1346 reset = diff_get_color_opt(o, DIFF_RESET);
1347 set_sign = NULL;
1348 if (o->flags.dual_color_diffed_diffs) {
1349 char c = !len ? 0 : line[0];
1351 if (c == '+')
1352 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1353 else if (c == '@')
1354 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1355 else if (c == '-')
1356 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1358 emit_line_ws_markup(o, set_sign, set, reset,
1359 OUTPUT_INDICATOR_CONTEXT, line, len,
1360 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1361 break;
1362 case DIFF_SYMBOL_PLUS:
1363 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1364 DIFF_SYMBOL_MOVED_LINE_ALT |
1365 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1366 case DIFF_SYMBOL_MOVED_LINE |
1367 DIFF_SYMBOL_MOVED_LINE_ALT |
1368 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1369 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1370 break;
1371 case DIFF_SYMBOL_MOVED_LINE |
1372 DIFF_SYMBOL_MOVED_LINE_ALT:
1373 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1374 break;
1375 case DIFF_SYMBOL_MOVED_LINE |
1376 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1377 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1378 break;
1379 case DIFF_SYMBOL_MOVED_LINE:
1380 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1381 break;
1382 default:
1383 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1385 reset = diff_get_color_opt(o, DIFF_RESET);
1386 if (!o->flags.dual_color_diffed_diffs)
1387 set_sign = NULL;
1388 else {
1389 char c = !len ? 0 : line[0];
1391 set_sign = set;
1392 if (c == '-')
1393 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1394 else if (c == '@')
1395 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1396 else if (c == '+')
1397 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1398 else
1399 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1400 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1402 emit_line_ws_markup(o, set_sign, set, reset,
1403 OUTPUT_INDICATOR_NEW, line, len,
1404 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1405 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1406 break;
1407 case DIFF_SYMBOL_MINUS:
1408 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1409 DIFF_SYMBOL_MOVED_LINE_ALT |
1410 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1411 case DIFF_SYMBOL_MOVED_LINE |
1412 DIFF_SYMBOL_MOVED_LINE_ALT |
1413 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1414 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1415 break;
1416 case DIFF_SYMBOL_MOVED_LINE |
1417 DIFF_SYMBOL_MOVED_LINE_ALT:
1418 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1419 break;
1420 case DIFF_SYMBOL_MOVED_LINE |
1421 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1422 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1423 break;
1424 case DIFF_SYMBOL_MOVED_LINE:
1425 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1426 break;
1427 default:
1428 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1430 reset = diff_get_color_opt(o, DIFF_RESET);
1431 if (!o->flags.dual_color_diffed_diffs)
1432 set_sign = NULL;
1433 else {
1434 char c = !len ? 0 : line[0];
1436 set_sign = set;
1437 if (c == '+')
1438 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1439 else if (c == '@')
1440 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1441 else if (c == '-')
1442 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1443 else
1444 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1446 emit_line_ws_markup(o, set_sign, set, reset,
1447 OUTPUT_INDICATOR_OLD, line, len,
1448 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1449 break;
1450 case DIFF_SYMBOL_WORDS_PORCELAIN:
1451 context = diff_get_color_opt(o, DIFF_CONTEXT);
1452 reset = diff_get_color_opt(o, DIFF_RESET);
1453 emit_line(o, context, reset, line, len);
1454 fputs("~\n", o->file);
1455 break;
1456 case DIFF_SYMBOL_WORDS:
1457 context = diff_get_color_opt(o, DIFF_CONTEXT);
1458 reset = diff_get_color_opt(o, DIFF_RESET);
1460 * Skip the prefix character, if any. With
1461 * diff_suppress_blank_empty, there may be
1462 * none.
1464 if (line[0] != '\n') {
1465 line++;
1466 len--;
1468 emit_line(o, context, reset, line, len);
1469 break;
1470 case DIFF_SYMBOL_FILEPAIR_PLUS:
1471 meta = diff_get_color_opt(o, DIFF_METAINFO);
1472 reset = diff_get_color_opt(o, DIFF_RESET);
1473 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1474 line, reset,
1475 strchr(line, ' ') ? "\t" : "");
1476 break;
1477 case DIFF_SYMBOL_FILEPAIR_MINUS:
1478 meta = diff_get_color_opt(o, DIFF_METAINFO);
1479 reset = diff_get_color_opt(o, DIFF_RESET);
1480 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1481 line, reset,
1482 strchr(line, ' ') ? "\t" : "");
1483 break;
1484 case DIFF_SYMBOL_BINARY_FILES:
1485 case DIFF_SYMBOL_HEADER:
1486 fprintf(o->file, "%s", line);
1487 break;
1488 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1489 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1490 break;
1491 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1492 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1493 break;
1494 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1495 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1496 break;
1497 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1498 fputs(diff_line_prefix(o), o->file);
1499 fputc('\n', o->file);
1500 break;
1501 case DIFF_SYMBOL_REWRITE_DIFF:
1502 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1503 reset = diff_get_color_opt(o, DIFF_RESET);
1504 emit_line(o, fraginfo, reset, line, len);
1505 break;
1506 case DIFF_SYMBOL_SUBMODULE_ADD:
1507 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1508 reset = diff_get_color_opt(o, DIFF_RESET);
1509 emit_line(o, set, reset, line, len);
1510 break;
1511 case DIFF_SYMBOL_SUBMODULE_DEL:
1512 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1513 reset = diff_get_color_opt(o, DIFF_RESET);
1514 emit_line(o, set, reset, line, len);
1515 break;
1516 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1517 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1518 diff_line_prefix(o), line);
1519 break;
1520 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1521 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1522 diff_line_prefix(o), line);
1523 break;
1524 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1525 emit_line(o, "", "", " 0 files changed\n",
1526 strlen(" 0 files changed\n"));
1527 break;
1528 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1529 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1530 break;
1531 case DIFF_SYMBOL_WORD_DIFF:
1532 fprintf(o->file, "%.*s", len, line);
1533 break;
1534 case DIFF_SYMBOL_STAT_SEP:
1535 fputs(o->stat_sep, o->file);
1536 break;
1537 default:
1538 BUG("unknown diff symbol");
1542 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1543 const char *line, int len, unsigned flags)
1545 struct emitted_diff_symbol e = {
1546 .line = line, .len = len, .flags = flags, .s = s
1549 if (o->emitted_symbols)
1550 append_emitted_diff_symbol(o, &e);
1551 else
1552 emit_diff_symbol_from_struct(o, &e);
1555 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1557 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1560 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1562 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1565 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1567 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1568 path, strlen(path), 0);
1571 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1573 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1574 path, strlen(path), 0);
1577 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1579 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1580 header, strlen(header), 0);
1583 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1585 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1588 void diff_emit_submodule_pipethrough(struct diff_options *o,
1589 const char *line, int len)
1591 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1594 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1596 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1597 ecbdata->blank_at_eof_in_preimage &&
1598 ecbdata->blank_at_eof_in_postimage &&
1599 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1600 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1601 return 0;
1602 return ws_blank_line(line, len);
1605 static void emit_add_line(struct emit_callback *ecbdata,
1606 const char *line, int len)
1608 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1609 if (new_blank_line_at_eof(ecbdata, line, len))
1610 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1612 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1615 static void emit_del_line(struct emit_callback *ecbdata,
1616 const char *line, int len)
1618 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1619 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1622 static void emit_context_line(struct emit_callback *ecbdata,
1623 const char *line, int len)
1625 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1626 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1629 static void emit_hunk_header(struct emit_callback *ecbdata,
1630 const char *line, int len)
1632 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1633 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1634 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1635 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1636 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1637 static const char atat[2] = { '@', '@' };
1638 const char *cp, *ep;
1639 struct strbuf msgbuf = STRBUF_INIT;
1640 int org_len = len;
1641 int i = 1;
1644 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1645 * it always is at least 10 bytes long.
1647 if (len < 10 ||
1648 memcmp(line, atat, 2) ||
1649 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1650 emit_diff_symbol(ecbdata->opt,
1651 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1652 return;
1654 ep += 2; /* skip over @@ */
1656 /* The hunk header in fraginfo color */
1657 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1658 strbuf_addstr(&msgbuf, reverse);
1659 strbuf_addstr(&msgbuf, frag);
1660 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1661 strbuf_add(&msgbuf, atat, sizeof(atat));
1662 else
1663 strbuf_add(&msgbuf, line, ep - line);
1664 strbuf_addstr(&msgbuf, reset);
1667 * trailing "\r\n"
1669 for ( ; i < 3; i++)
1670 if (line[len - i] == '\r' || line[len - i] == '\n')
1671 len--;
1673 /* blank before the func header */
1674 for (cp = ep; ep - line < len; ep++)
1675 if (*ep != ' ' && *ep != '\t')
1676 break;
1677 if (ep != cp) {
1678 strbuf_addstr(&msgbuf, context);
1679 strbuf_add(&msgbuf, cp, ep - cp);
1680 strbuf_addstr(&msgbuf, reset);
1683 if (ep < line + len) {
1684 strbuf_addstr(&msgbuf, func);
1685 strbuf_add(&msgbuf, ep, line + len - ep);
1686 strbuf_addstr(&msgbuf, reset);
1689 strbuf_add(&msgbuf, line + len, org_len - len);
1690 strbuf_complete_line(&msgbuf);
1691 emit_diff_symbol(ecbdata->opt,
1692 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1693 strbuf_release(&msgbuf);
1696 static struct diff_tempfile *claim_diff_tempfile(void)
1698 int i;
1699 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1700 if (!diff_temp[i].name)
1701 return diff_temp + i;
1702 BUG("diff is failing to clean up its tempfiles");
1705 static void remove_tempfile(void)
1707 int i;
1708 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1709 if (is_tempfile_active(diff_temp[i].tempfile))
1710 delete_tempfile(&diff_temp[i].tempfile);
1711 diff_temp[i].name = NULL;
1715 static void add_line_count(struct strbuf *out, int count)
1717 switch (count) {
1718 case 0:
1719 strbuf_addstr(out, "0,0");
1720 break;
1721 case 1:
1722 strbuf_addstr(out, "1");
1723 break;
1724 default:
1725 strbuf_addf(out, "1,%d", count);
1726 break;
1730 static void emit_rewrite_lines(struct emit_callback *ecb,
1731 int prefix, const char *data, int size)
1733 const char *endp = NULL;
1735 while (0 < size) {
1736 int len;
1738 endp = memchr(data, '\n', size);
1739 len = endp ? (endp - data + 1) : size;
1740 if (prefix != '+') {
1741 ecb->lno_in_preimage++;
1742 emit_del_line(ecb, data, len);
1743 } else {
1744 ecb->lno_in_postimage++;
1745 emit_add_line(ecb, data, len);
1747 size -= len;
1748 data += len;
1750 if (!endp)
1751 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1754 static void emit_rewrite_diff(const char *name_a,
1755 const char *name_b,
1756 struct diff_filespec *one,
1757 struct diff_filespec *two,
1758 struct userdiff_driver *textconv_one,
1759 struct userdiff_driver *textconv_two,
1760 struct diff_options *o)
1762 int lc_a, lc_b;
1763 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1764 const char *a_prefix, *b_prefix;
1765 char *data_one, *data_two;
1766 size_t size_one, size_two;
1767 struct emit_callback ecbdata;
1768 struct strbuf out = STRBUF_INIT;
1770 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1771 a_prefix = o->b_prefix;
1772 b_prefix = o->a_prefix;
1773 } else {
1774 a_prefix = o->a_prefix;
1775 b_prefix = o->b_prefix;
1778 name_a += (*name_a == '/');
1779 name_b += (*name_b == '/');
1781 strbuf_reset(&a_name);
1782 strbuf_reset(&b_name);
1783 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1784 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1786 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1787 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1789 memset(&ecbdata, 0, sizeof(ecbdata));
1790 ecbdata.color_diff = want_color(o->use_color);
1791 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1792 ecbdata.opt = o;
1793 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1794 mmfile_t mf1, mf2;
1795 mf1.ptr = (char *)data_one;
1796 mf2.ptr = (char *)data_two;
1797 mf1.size = size_one;
1798 mf2.size = size_two;
1799 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1801 ecbdata.lno_in_preimage = 1;
1802 ecbdata.lno_in_postimage = 1;
1804 lc_a = count_lines(data_one, size_one);
1805 lc_b = count_lines(data_two, size_two);
1807 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1808 a_name.buf, a_name.len, 0);
1809 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1810 b_name.buf, b_name.len, 0);
1812 strbuf_addstr(&out, "@@ -");
1813 if (!o->irreversible_delete)
1814 add_line_count(&out, lc_a);
1815 else
1816 strbuf_addstr(&out, "?,?");
1817 strbuf_addstr(&out, " +");
1818 add_line_count(&out, lc_b);
1819 strbuf_addstr(&out, " @@\n");
1820 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1821 strbuf_release(&out);
1823 if (lc_a && !o->irreversible_delete)
1824 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1825 if (lc_b)
1826 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1827 if (textconv_one)
1828 free((char *)data_one);
1829 if (textconv_two)
1830 free((char *)data_two);
1833 struct diff_words_buffer {
1834 mmfile_t text;
1835 unsigned long alloc;
1836 struct diff_words_orig {
1837 const char *begin, *end;
1838 } *orig;
1839 int orig_nr, orig_alloc;
1842 static void diff_words_append(char *line, unsigned long len,
1843 struct diff_words_buffer *buffer)
1845 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1846 line++;
1847 len--;
1848 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1849 buffer->text.size += len;
1850 buffer->text.ptr[buffer->text.size] = '\0';
1853 struct diff_words_style_elem {
1854 const char *prefix;
1855 const char *suffix;
1856 const char *color; /* NULL; filled in by the setup code if
1857 * color is enabled */
1860 struct diff_words_style {
1861 enum diff_words_type type;
1862 struct diff_words_style_elem new_word, old_word, ctx;
1863 const char *newline;
1866 static struct diff_words_style diff_words_styles[] = {
1867 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1868 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1869 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1872 struct diff_words_data {
1873 struct diff_words_buffer minus, plus;
1874 const char *current_plus;
1875 int last_minus;
1876 struct diff_options *opt;
1877 regex_t *word_regex;
1878 enum diff_words_type type;
1879 struct diff_words_style *style;
1882 static int fn_out_diff_words_write_helper(struct diff_options *o,
1883 struct diff_words_style_elem *st_el,
1884 const char *newline,
1885 size_t count, const char *buf)
1887 int print = 0;
1888 struct strbuf sb = STRBUF_INIT;
1890 while (count) {
1891 char *p = memchr(buf, '\n', count);
1892 if (print)
1893 strbuf_addstr(&sb, diff_line_prefix(o));
1895 if (p != buf) {
1896 const char *reset = st_el->color && *st_el->color ?
1897 GIT_COLOR_RESET : NULL;
1898 if (st_el->color && *st_el->color)
1899 strbuf_addstr(&sb, st_el->color);
1900 strbuf_addstr(&sb, st_el->prefix);
1901 strbuf_add(&sb, buf, p ? p - buf : count);
1902 strbuf_addstr(&sb, st_el->suffix);
1903 if (reset)
1904 strbuf_addstr(&sb, reset);
1906 if (!p)
1907 goto out;
1909 strbuf_addstr(&sb, newline);
1910 count -= p + 1 - buf;
1911 buf = p + 1;
1912 print = 1;
1913 if (count) {
1914 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1915 sb.buf, sb.len, 0);
1916 strbuf_reset(&sb);
1920 out:
1921 if (sb.len)
1922 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1923 sb.buf, sb.len, 0);
1924 strbuf_release(&sb);
1925 return 0;
1929 * '--color-words' algorithm can be described as:
1931 * 1. collect the minus/plus lines of a diff hunk, divided into
1932 * minus-lines and plus-lines;
1934 * 2. break both minus-lines and plus-lines into words and
1935 * place them into two mmfile_t with one word for each line;
1937 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1939 * And for the common parts of the both file, we output the plus side text.
1940 * diff_words->current_plus is used to trace the current position of the plus file
1941 * which printed. diff_words->last_minus is used to trace the last minus word
1942 * printed.
1944 * For '--graph' to work with '--color-words', we need to output the graph prefix
1945 * on each line of color words output. Generally, there are two conditions on
1946 * which we should output the prefix.
1948 * 1. diff_words->last_minus == 0 &&
1949 * diff_words->current_plus == diff_words->plus.text.ptr
1951 * that is: the plus text must start as a new line, and if there is no minus
1952 * word printed, a graph prefix must be printed.
1954 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1955 * *(diff_words->current_plus - 1) == '\n'
1957 * that is: a graph prefix must be printed following a '\n'
1959 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1961 if ((diff_words->last_minus == 0 &&
1962 diff_words->current_plus == diff_words->plus.text.ptr) ||
1963 (diff_words->current_plus > diff_words->plus.text.ptr &&
1964 *(diff_words->current_plus - 1) == '\n')) {
1965 return 1;
1966 } else {
1967 return 0;
1971 static void fn_out_diff_words_aux(void *priv,
1972 long minus_first, long minus_len,
1973 long plus_first, long plus_len,
1974 const char *func UNUSED, long funclen UNUSED)
1976 struct diff_words_data *diff_words = priv;
1977 struct diff_words_style *style = diff_words->style;
1978 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1979 struct diff_options *opt = diff_words->opt;
1980 const char *line_prefix;
1982 assert(opt);
1983 line_prefix = diff_line_prefix(opt);
1985 /* POSIX requires that first be decremented by one if len == 0... */
1986 if (minus_len) {
1987 minus_begin = diff_words->minus.orig[minus_first].begin;
1988 minus_end =
1989 diff_words->minus.orig[minus_first + minus_len - 1].end;
1990 } else
1991 minus_begin = minus_end =
1992 diff_words->minus.orig[minus_first].end;
1994 if (plus_len) {
1995 plus_begin = diff_words->plus.orig[plus_first].begin;
1996 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1997 } else
1998 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2000 if (color_words_output_graph_prefix(diff_words)) {
2001 fputs(line_prefix, diff_words->opt->file);
2003 if (diff_words->current_plus != plus_begin) {
2004 fn_out_diff_words_write_helper(diff_words->opt,
2005 &style->ctx, style->newline,
2006 plus_begin - diff_words->current_plus,
2007 diff_words->current_plus);
2009 if (minus_begin != minus_end) {
2010 fn_out_diff_words_write_helper(diff_words->opt,
2011 &style->old_word, style->newline,
2012 minus_end - minus_begin, minus_begin);
2014 if (plus_begin != plus_end) {
2015 fn_out_diff_words_write_helper(diff_words->opt,
2016 &style->new_word, style->newline,
2017 plus_end - plus_begin, plus_begin);
2020 diff_words->current_plus = plus_end;
2021 diff_words->last_minus = minus_first;
2024 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2025 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2026 int *begin, int *end)
2028 while (word_regex && *begin < buffer->size) {
2029 regmatch_t match[1];
2030 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2031 buffer->size - *begin, 1, match, 0)) {
2032 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2033 '\n', match[0].rm_eo - match[0].rm_so);
2034 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2035 *begin += match[0].rm_so;
2036 if (*begin == *end)
2037 (*begin)++;
2038 else
2039 return *begin > *end;
2040 } else {
2041 return -1;
2045 /* find the next word */
2046 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2047 (*begin)++;
2048 if (*begin >= buffer->size)
2049 return -1;
2051 /* find the end of the word */
2052 *end = *begin + 1;
2053 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2054 (*end)++;
2056 return 0;
2060 * This function splits the words in buffer->text, stores the list with
2061 * newline separator into out, and saves the offsets of the original words
2062 * in buffer->orig.
2064 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2065 regex_t *word_regex)
2067 int i, j;
2068 long alloc = 0;
2070 out->size = 0;
2071 out->ptr = NULL;
2073 /* fake an empty "0th" word */
2074 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2075 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2076 buffer->orig_nr = 1;
2078 for (i = 0; i < buffer->text.size; i++) {
2079 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2080 return;
2082 /* store original boundaries */
2083 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2084 buffer->orig_alloc);
2085 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2086 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2087 buffer->orig_nr++;
2089 /* store one word */
2090 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2091 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2092 out->ptr[out->size + j - i] = '\n';
2093 out->size += j - i + 1;
2095 i = j - 1;
2099 /* this executes the word diff on the accumulated buffers */
2100 static void diff_words_show(struct diff_words_data *diff_words)
2102 xpparam_t xpp;
2103 xdemitconf_t xecfg;
2104 mmfile_t minus, plus;
2105 struct diff_words_style *style = diff_words->style;
2107 struct diff_options *opt = diff_words->opt;
2108 const char *line_prefix;
2110 assert(opt);
2111 line_prefix = diff_line_prefix(opt);
2113 /* special case: only removal */
2114 if (!diff_words->plus.text.size) {
2115 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2116 line_prefix, strlen(line_prefix), 0);
2117 fn_out_diff_words_write_helper(diff_words->opt,
2118 &style->old_word, style->newline,
2119 diff_words->minus.text.size,
2120 diff_words->minus.text.ptr);
2121 diff_words->minus.text.size = 0;
2122 return;
2125 diff_words->current_plus = diff_words->plus.text.ptr;
2126 diff_words->last_minus = 0;
2128 memset(&xpp, 0, sizeof(xpp));
2129 memset(&xecfg, 0, sizeof(xecfg));
2130 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2131 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2132 xpp.flags = 0;
2133 /* as only the hunk header will be parsed, we need a 0-context */
2134 xecfg.ctxlen = 0;
2135 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2136 diff_words, &xpp, &xecfg))
2137 die("unable to generate word diff");
2138 free(minus.ptr);
2139 free(plus.ptr);
2140 if (diff_words->current_plus != diff_words->plus.text.ptr +
2141 diff_words->plus.text.size) {
2142 if (color_words_output_graph_prefix(diff_words))
2143 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2144 line_prefix, strlen(line_prefix), 0);
2145 fn_out_diff_words_write_helper(diff_words->opt,
2146 &style->ctx, style->newline,
2147 diff_words->plus.text.ptr + diff_words->plus.text.size
2148 - diff_words->current_plus, diff_words->current_plus);
2150 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2153 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2154 static void diff_words_flush(struct emit_callback *ecbdata)
2156 struct diff_options *wo = ecbdata->diff_words->opt;
2158 if (ecbdata->diff_words->minus.text.size ||
2159 ecbdata->diff_words->plus.text.size)
2160 diff_words_show(ecbdata->diff_words);
2162 if (wo->emitted_symbols) {
2163 struct diff_options *o = ecbdata->opt;
2164 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2165 int i;
2168 * NEEDSWORK:
2169 * Instead of appending each, concat all words to a line?
2171 for (i = 0; i < wol->nr; i++)
2172 append_emitted_diff_symbol(o, &wol->buf[i]);
2174 for (i = 0; i < wol->nr; i++)
2175 free((void *)wol->buf[i].line);
2177 wol->nr = 0;
2181 static void diff_filespec_load_driver(struct diff_filespec *one,
2182 struct index_state *istate)
2184 /* Use already-loaded driver */
2185 if (one->driver)
2186 return;
2188 if (S_ISREG(one->mode))
2189 one->driver = userdiff_find_by_path(istate, one->path);
2191 /* Fallback to default settings */
2192 if (!one->driver)
2193 one->driver = userdiff_find_by_name("default");
2196 static const char *userdiff_word_regex(struct diff_filespec *one,
2197 struct index_state *istate)
2199 diff_filespec_load_driver(one, istate);
2200 return one->driver->word_regex;
2203 static void init_diff_words_data(struct emit_callback *ecbdata,
2204 struct diff_options *orig_opts,
2205 struct diff_filespec *one,
2206 struct diff_filespec *two)
2208 int i;
2209 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2210 memcpy(o, orig_opts, sizeof(struct diff_options));
2212 CALLOC_ARRAY(ecbdata->diff_words, 1);
2213 ecbdata->diff_words->type = o->word_diff;
2214 ecbdata->diff_words->opt = o;
2216 if (orig_opts->emitted_symbols)
2217 CALLOC_ARRAY(o->emitted_symbols, 1);
2219 if (!o->word_regex)
2220 o->word_regex = userdiff_word_regex(one, o->repo->index);
2221 if (!o->word_regex)
2222 o->word_regex = userdiff_word_regex(two, o->repo->index);
2223 if (!o->word_regex)
2224 o->word_regex = diff_word_regex_cfg;
2225 if (o->word_regex) {
2226 ecbdata->diff_words->word_regex = (regex_t *)
2227 xmalloc(sizeof(regex_t));
2228 if (regcomp(ecbdata->diff_words->word_regex,
2229 o->word_regex,
2230 REG_EXTENDED | REG_NEWLINE))
2231 die("invalid regular expression: %s",
2232 o->word_regex);
2234 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2235 if (o->word_diff == diff_words_styles[i].type) {
2236 ecbdata->diff_words->style =
2237 &diff_words_styles[i];
2238 break;
2241 if (want_color(o->use_color)) {
2242 struct diff_words_style *st = ecbdata->diff_words->style;
2243 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2244 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2245 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2249 static void free_diff_words_data(struct emit_callback *ecbdata)
2251 if (ecbdata->diff_words) {
2252 diff_words_flush(ecbdata);
2253 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2254 free (ecbdata->diff_words->opt);
2255 free (ecbdata->diff_words->minus.text.ptr);
2256 free (ecbdata->diff_words->minus.orig);
2257 free (ecbdata->diff_words->plus.text.ptr);
2258 free (ecbdata->diff_words->plus.orig);
2259 if (ecbdata->diff_words->word_regex) {
2260 regfree(ecbdata->diff_words->word_regex);
2261 free(ecbdata->diff_words->word_regex);
2263 FREE_AND_NULL(ecbdata->diff_words);
2267 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2269 if (want_color(diff_use_color))
2270 return diff_colors[ix];
2271 return "";
2274 const char *diff_line_prefix(struct diff_options *opt)
2276 struct strbuf *msgbuf;
2277 if (!opt->output_prefix)
2278 return "";
2280 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2281 return msgbuf->buf;
2284 static unsigned long sane_truncate_line(char *line, unsigned long len)
2286 const char *cp;
2287 unsigned long allot;
2288 size_t l = len;
2290 cp = line;
2291 allot = l;
2292 while (0 < l) {
2293 (void) utf8_width(&cp, &l);
2294 if (!cp)
2295 break; /* truncated in the middle? */
2297 return allot - l;
2300 static void find_lno(const char *line, struct emit_callback *ecbdata)
2302 const char *p;
2303 ecbdata->lno_in_preimage = 0;
2304 ecbdata->lno_in_postimage = 0;
2305 p = strchr(line, '-');
2306 if (!p)
2307 return; /* cannot happen */
2308 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2309 p = strchr(p, '+');
2310 if (!p)
2311 return; /* cannot happen */
2312 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2315 static int fn_out_consume(void *priv, char *line, unsigned long len)
2317 struct emit_callback *ecbdata = priv;
2318 struct diff_options *o = ecbdata->opt;
2320 o->found_changes = 1;
2322 if (ecbdata->header) {
2323 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2324 ecbdata->header->buf, ecbdata->header->len, 0);
2325 strbuf_reset(ecbdata->header);
2326 ecbdata->header = NULL;
2329 if (ecbdata->label_path[0]) {
2330 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2331 ecbdata->label_path[0],
2332 strlen(ecbdata->label_path[0]), 0);
2333 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2334 ecbdata->label_path[1],
2335 strlen(ecbdata->label_path[1]), 0);
2336 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2339 if (diff_suppress_blank_empty
2340 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2341 line[0] = '\n';
2342 len = 1;
2345 if (line[0] == '@') {
2346 if (ecbdata->diff_words)
2347 diff_words_flush(ecbdata);
2348 len = sane_truncate_line(line, len);
2349 find_lno(line, ecbdata);
2350 emit_hunk_header(ecbdata, line, len);
2351 return 0;
2354 if (ecbdata->diff_words) {
2355 enum diff_symbol s =
2356 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2357 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2358 if (line[0] == '-') {
2359 diff_words_append(line, len,
2360 &ecbdata->diff_words->minus);
2361 return 0;
2362 } else if (line[0] == '+') {
2363 diff_words_append(line, len,
2364 &ecbdata->diff_words->plus);
2365 return 0;
2366 } else if (starts_with(line, "\\ ")) {
2368 * Eat the "no newline at eof" marker as if we
2369 * saw a "+" or "-" line with nothing on it,
2370 * and return without diff_words_flush() to
2371 * defer processing. If this is the end of
2372 * preimage, more "+" lines may come after it.
2374 return 0;
2376 diff_words_flush(ecbdata);
2377 emit_diff_symbol(o, s, line, len, 0);
2378 return 0;
2381 switch (line[0]) {
2382 case '+':
2383 ecbdata->lno_in_postimage++;
2384 emit_add_line(ecbdata, line + 1, len - 1);
2385 break;
2386 case '-':
2387 ecbdata->lno_in_preimage++;
2388 emit_del_line(ecbdata, line + 1, len - 1);
2389 break;
2390 case ' ':
2391 ecbdata->lno_in_postimage++;
2392 ecbdata->lno_in_preimage++;
2393 emit_context_line(ecbdata, line + 1, len - 1);
2394 break;
2395 default:
2396 /* incomplete line at the end */
2397 ecbdata->lno_in_preimage++;
2398 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2399 line, len, 0);
2400 break;
2402 return 0;
2405 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2407 const char *old_name = a;
2408 const char *new_name = b;
2409 int pfx_length, sfx_length;
2410 int pfx_adjust_for_slash;
2411 int len_a = strlen(a);
2412 int len_b = strlen(b);
2413 int a_midlen, b_midlen;
2414 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2415 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2417 if (qlen_a || qlen_b) {
2418 quote_c_style(a, name, NULL, 0);
2419 strbuf_addstr(name, " => ");
2420 quote_c_style(b, name, NULL, 0);
2421 return;
2424 /* Find common prefix */
2425 pfx_length = 0;
2426 while (*old_name && *new_name && *old_name == *new_name) {
2427 if (*old_name == '/')
2428 pfx_length = old_name - a + 1;
2429 old_name++;
2430 new_name++;
2433 /* Find common suffix */
2434 old_name = a + len_a;
2435 new_name = b + len_b;
2436 sfx_length = 0;
2438 * If there is a common prefix, it must end in a slash. In
2439 * that case we let this loop run 1 into the prefix to see the
2440 * same slash.
2442 * If there is no common prefix, we cannot do this as it would
2443 * underrun the input strings.
2445 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2446 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2447 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2448 *old_name == *new_name) {
2449 if (*old_name == '/')
2450 sfx_length = len_a - (old_name - a);
2451 old_name--;
2452 new_name--;
2456 * pfx{mid-a => mid-b}sfx
2457 * {pfx-a => pfx-b}sfx
2458 * pfx{sfx-a => sfx-b}
2459 * name-a => name-b
2461 a_midlen = len_a - pfx_length - sfx_length;
2462 b_midlen = len_b - pfx_length - sfx_length;
2463 if (a_midlen < 0)
2464 a_midlen = 0;
2465 if (b_midlen < 0)
2466 b_midlen = 0;
2468 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2469 if (pfx_length + sfx_length) {
2470 strbuf_add(name, a, pfx_length);
2471 strbuf_addch(name, '{');
2473 strbuf_add(name, a + pfx_length, a_midlen);
2474 strbuf_addstr(name, " => ");
2475 strbuf_add(name, b + pfx_length, b_midlen);
2476 if (pfx_length + sfx_length) {
2477 strbuf_addch(name, '}');
2478 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2482 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2483 const char *name_a,
2484 const char *name_b)
2486 struct diffstat_file *x;
2487 CALLOC_ARRAY(x, 1);
2488 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2489 diffstat->files[diffstat->nr++] = x;
2490 if (name_b) {
2491 x->from_name = xstrdup(name_a);
2492 x->name = xstrdup(name_b);
2493 x->is_renamed = 1;
2495 else {
2496 x->from_name = NULL;
2497 x->name = xstrdup(name_a);
2499 return x;
2502 static int diffstat_consume(void *priv, char *line, unsigned long len)
2504 struct diffstat_t *diffstat = priv;
2505 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2507 if (!len)
2508 BUG("xdiff fed us an empty line");
2510 if (line[0] == '+')
2511 x->added++;
2512 else if (line[0] == '-')
2513 x->deleted++;
2514 return 0;
2517 const char mime_boundary_leader[] = "------------";
2519 static int scale_linear(int it, int width, int max_change)
2521 if (!it)
2522 return 0;
2524 * make sure that at least one '-' or '+' is printed if
2525 * there is any change to this path. The easiest way is to
2526 * scale linearly as if the allotted width is one column shorter
2527 * than it is, and then add 1 to the result.
2529 return 1 + (it * (width - 1) / max_change);
2532 static void show_graph(struct strbuf *out, char ch, int cnt,
2533 const char *set, const char *reset)
2535 if (cnt <= 0)
2536 return;
2537 strbuf_addstr(out, set);
2538 strbuf_addchars(out, ch, cnt);
2539 strbuf_addstr(out, reset);
2542 static void fill_print_name(struct diffstat_file *file)
2544 struct strbuf pname = STRBUF_INIT;
2546 if (file->print_name)
2547 return;
2549 if (file->is_renamed)
2550 pprint_rename(&pname, file->from_name, file->name);
2551 else
2552 quote_c_style(file->name, &pname, NULL, 0);
2554 if (file->comments)
2555 strbuf_addf(&pname, " (%s)", file->comments);
2557 file->print_name = strbuf_detach(&pname, NULL);
2560 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2561 int files, int insertions, int deletions)
2563 struct strbuf sb = STRBUF_INIT;
2565 if (!files) {
2566 assert(insertions == 0 && deletions == 0);
2567 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2568 NULL, 0, 0);
2569 return;
2572 strbuf_addf(&sb,
2573 (files == 1) ? " %d file changed" : " %d files changed",
2574 files);
2577 * For binary diff, the caller may want to print "x files
2578 * changed" with insertions == 0 && deletions == 0.
2580 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2581 * is probably less confusing (i.e skip over "2 files changed
2582 * but nothing about added/removed lines? Is this a bug in Git?").
2584 if (insertions || deletions == 0) {
2585 strbuf_addf(&sb,
2586 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2587 insertions);
2590 if (deletions || insertions == 0) {
2591 strbuf_addf(&sb,
2592 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2593 deletions);
2595 strbuf_addch(&sb, '\n');
2596 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2597 sb.buf, sb.len, 0);
2598 strbuf_release(&sb);
2601 void print_stat_summary(FILE *fp, int files,
2602 int insertions, int deletions)
2604 struct diff_options o;
2605 memset(&o, 0, sizeof(o));
2606 o.file = fp;
2608 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2611 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2613 int i, len, add, del, adds = 0, dels = 0;
2614 uintmax_t max_change = 0, max_len = 0;
2615 int total_files = data->nr, count;
2616 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2617 const char *reset, *add_c, *del_c;
2618 int extra_shown = 0;
2619 const char *line_prefix = diff_line_prefix(options);
2620 struct strbuf out = STRBUF_INIT;
2622 if (data->nr == 0)
2623 return;
2625 count = options->stat_count ? options->stat_count : data->nr;
2627 reset = diff_get_color_opt(options, DIFF_RESET);
2628 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2629 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2632 * Find the longest filename and max number of changes
2634 for (i = 0; (i < count) && (i < data->nr); i++) {
2635 struct diffstat_file *file = data->files[i];
2636 uintmax_t change = file->added + file->deleted;
2638 if (!file->is_interesting && (change == 0)) {
2639 count++; /* not shown == room for one more */
2640 continue;
2642 fill_print_name(file);
2643 len = utf8_strwidth(file->print_name);
2644 if (max_len < len)
2645 max_len = len;
2647 if (file->is_unmerged) {
2648 /* "Unmerged" is 8 characters */
2649 bin_width = bin_width < 8 ? 8 : bin_width;
2650 continue;
2652 if (file->is_binary) {
2653 /* "Bin XXX -> YYY bytes" */
2654 int w = 14 + decimal_width(file->added)
2655 + decimal_width(file->deleted);
2656 bin_width = bin_width < w ? w : bin_width;
2657 /* Display change counts aligned with "Bin" */
2658 number_width = 3;
2659 continue;
2662 if (max_change < change)
2663 max_change = change;
2665 count = i; /* where we can stop scanning in data->files[] */
2668 * We have width = stat_width or term_columns() columns total.
2669 * We want a maximum of min(max_len, stat_name_width) for the name part.
2670 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2671 * We also need 1 for " " and 4 + decimal_width(max_change)
2672 * for " | NNNN " and one the empty column at the end, altogether
2673 * 6 + decimal_width(max_change).
2675 * If there's not enough space, we will use the smaller of
2676 * stat_name_width (if set) and 5/8*width for the filename,
2677 * and the rest for constant elements + graph part, but no more
2678 * than stat_graph_width for the graph part.
2679 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2680 * for the standard terminal size).
2682 * In other words: stat_width limits the maximum width, and
2683 * stat_name_width fixes the maximum width of the filename,
2684 * and is also used to divide available columns if there
2685 * aren't enough.
2687 * Binary files are displayed with "Bin XXX -> YYY bytes"
2688 * instead of the change count and graph. This part is treated
2689 * similarly to the graph part, except that it is not
2690 * "scaled". If total width is too small to accommodate the
2691 * guaranteed minimum width of the filename part and the
2692 * separators and this message, this message will "overflow"
2693 * making the line longer than the maximum width.
2697 * NEEDSWORK: line_prefix is often used for "log --graph" output
2698 * and contains ANSI-colored string. utf8_strnwidth() should be
2699 * used to correctly count the display width instead of strlen().
2701 if (options->stat_width == -1)
2702 width = term_columns() - strlen(line_prefix);
2703 else
2704 width = options->stat_width ? options->stat_width : 80;
2705 number_width = decimal_width(max_change) > number_width ?
2706 decimal_width(max_change) : number_width;
2708 if (options->stat_graph_width == -1)
2709 options->stat_graph_width = diff_stat_graph_width;
2712 * Guarantee 3/8*16==6 for the graph part
2713 * and 5/8*16==10 for the filename part
2715 if (width < 16 + 6 + number_width)
2716 width = 16 + 6 + number_width;
2719 * First assign sizes that are wanted, ignoring available width.
2720 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2721 * starting from "XXX" should fit in graph_width.
2723 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2724 if (options->stat_graph_width &&
2725 options->stat_graph_width < graph_width)
2726 graph_width = options->stat_graph_width;
2728 name_width = (options->stat_name_width > 0 &&
2729 options->stat_name_width < max_len) ?
2730 options->stat_name_width : max_len;
2733 * Adjust adjustable widths not to exceed maximum width
2735 if (name_width + number_width + 6 + graph_width > width) {
2736 if (graph_width > width * 3/8 - number_width - 6) {
2737 graph_width = width * 3/8 - number_width - 6;
2738 if (graph_width < 6)
2739 graph_width = 6;
2742 if (options->stat_graph_width &&
2743 graph_width > options->stat_graph_width)
2744 graph_width = options->stat_graph_width;
2745 if (name_width > width - number_width - 6 - graph_width)
2746 name_width = width - number_width - 6 - graph_width;
2747 else
2748 graph_width = width - number_width - 6 - name_width;
2752 * From here name_width is the width of the name area,
2753 * and graph_width is the width of the graph area.
2754 * max_change is used to scale graph properly.
2756 for (i = 0; i < count; i++) {
2757 const char *prefix = "";
2758 struct diffstat_file *file = data->files[i];
2759 char *name = file->print_name;
2760 uintmax_t added = file->added;
2761 uintmax_t deleted = file->deleted;
2762 int name_len, padding;
2764 if (!file->is_interesting && (added + deleted == 0))
2765 continue;
2768 * "scale" the filename
2770 len = name_width;
2771 name_len = utf8_strwidth(name);
2772 if (name_width < name_len) {
2773 char *slash;
2774 prefix = "...";
2775 len -= 3;
2777 * NEEDSWORK: (name_len - len) counts the display
2778 * width, which would be shorter than the byte
2779 * length of the corresponding substring.
2780 * Advancing "name" by that number of bytes does
2781 * *NOT* skip over that many columns, so it is
2782 * very likely that chomping the pathname at the
2783 * slash we will find starting from "name" will
2784 * leave the resulting string still too long.
2786 name += name_len - len;
2787 slash = strchr(name, '/');
2788 if (slash)
2789 name = slash;
2791 padding = len - utf8_strwidth(name);
2792 if (padding < 0)
2793 padding = 0;
2795 if (file->is_binary) {
2796 strbuf_addf(&out, " %s%s%*s | %*s",
2797 prefix, name, padding, "",
2798 number_width, "Bin");
2799 if (!added && !deleted) {
2800 strbuf_addch(&out, '\n');
2801 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2802 out.buf, out.len, 0);
2803 strbuf_reset(&out);
2804 continue;
2806 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2807 del_c, deleted, reset);
2808 strbuf_addstr(&out, " -> ");
2809 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2810 add_c, added, reset);
2811 strbuf_addstr(&out, " bytes\n");
2812 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2813 out.buf, out.len, 0);
2814 strbuf_reset(&out);
2815 continue;
2817 else if (file->is_unmerged) {
2818 strbuf_addf(&out, " %s%s%*s | %*s",
2819 prefix, name, padding, "",
2820 number_width, "Unmerged\n");
2821 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2822 out.buf, out.len, 0);
2823 strbuf_reset(&out);
2824 continue;
2828 * scale the add/delete
2830 add = added;
2831 del = deleted;
2833 if (graph_width <= max_change) {
2834 int total = scale_linear(add + del, graph_width, max_change);
2835 if (total < 2 && add && del)
2836 /* width >= 2 due to the sanity check */
2837 total = 2;
2838 if (add < del) {
2839 add = scale_linear(add, graph_width, max_change);
2840 del = total - add;
2841 } else {
2842 del = scale_linear(del, graph_width, max_change);
2843 add = total - del;
2846 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2847 prefix, name, padding, "",
2848 number_width, added + deleted,
2849 added + deleted ? " " : "");
2850 show_graph(&out, '+', add, add_c, reset);
2851 show_graph(&out, '-', del, del_c, reset);
2852 strbuf_addch(&out, '\n');
2853 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2854 out.buf, out.len, 0);
2855 strbuf_reset(&out);
2858 for (i = 0; i < data->nr; i++) {
2859 struct diffstat_file *file = data->files[i];
2860 uintmax_t added = file->added;
2861 uintmax_t deleted = file->deleted;
2863 if (file->is_unmerged ||
2864 (!file->is_interesting && (added + deleted == 0))) {
2865 total_files--;
2866 continue;
2869 if (!file->is_binary) {
2870 adds += added;
2871 dels += deleted;
2873 if (i < count)
2874 continue;
2875 if (!extra_shown)
2876 emit_diff_symbol(options,
2877 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2878 NULL, 0, 0);
2879 extra_shown = 1;
2882 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2883 strbuf_release(&out);
2886 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2888 int i, adds = 0, dels = 0, total_files = data->nr;
2890 if (data->nr == 0)
2891 return;
2893 for (i = 0; i < data->nr; i++) {
2894 int added = data->files[i]->added;
2895 int deleted = data->files[i]->deleted;
2897 if (data->files[i]->is_unmerged ||
2898 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2899 total_files--;
2900 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2901 adds += added;
2902 dels += deleted;
2905 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2908 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2910 int i;
2912 if (data->nr == 0)
2913 return;
2915 for (i = 0; i < data->nr; i++) {
2916 struct diffstat_file *file = data->files[i];
2918 fprintf(options->file, "%s", diff_line_prefix(options));
2920 if (file->is_binary)
2921 fprintf(options->file, "-\t-\t");
2922 else
2923 fprintf(options->file,
2924 "%"PRIuMAX"\t%"PRIuMAX"\t",
2925 file->added, file->deleted);
2926 if (options->line_termination) {
2927 fill_print_name(file);
2928 if (!file->is_renamed)
2929 write_name_quoted(file->name, options->file,
2930 options->line_termination);
2931 else {
2932 fputs(file->print_name, options->file);
2933 putc(options->line_termination, options->file);
2935 } else {
2936 if (file->is_renamed) {
2937 putc('\0', options->file);
2938 write_name_quoted(file->from_name, options->file, '\0');
2940 write_name_quoted(file->name, options->file, '\0');
2945 struct dirstat_file {
2946 const char *name;
2947 unsigned long changed;
2950 struct dirstat_dir {
2951 struct dirstat_file *files;
2952 int alloc, nr, permille, cumulative;
2955 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2956 unsigned long changed, const char *base, int baselen)
2958 unsigned long sum_changes = 0;
2959 unsigned int sources = 0;
2960 const char *line_prefix = diff_line_prefix(opt);
2962 while (dir->nr) {
2963 struct dirstat_file *f = dir->files;
2964 int namelen = strlen(f->name);
2965 unsigned long changes;
2966 char *slash;
2968 if (namelen < baselen)
2969 break;
2970 if (memcmp(f->name, base, baselen))
2971 break;
2972 slash = strchr(f->name + baselen, '/');
2973 if (slash) {
2974 int newbaselen = slash + 1 - f->name;
2975 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2976 sources++;
2977 } else {
2978 changes = f->changed;
2979 dir->files++;
2980 dir->nr--;
2981 sources += 2;
2983 sum_changes += changes;
2987 * We don't report dirstat's for
2988 * - the top level
2989 * - or cases where everything came from a single directory
2990 * under this directory (sources == 1).
2992 if (baselen && sources != 1) {
2993 if (sum_changes) {
2994 int permille = sum_changes * 1000 / changed;
2995 if (permille >= dir->permille) {
2996 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2997 permille / 10, permille % 10, baselen, base);
2998 if (!dir->cumulative)
2999 return 0;
3003 return sum_changes;
3006 static int dirstat_compare(const void *_a, const void *_b)
3008 const struct dirstat_file *a = _a;
3009 const struct dirstat_file *b = _b;
3010 return strcmp(a->name, b->name);
3013 static void conclude_dirstat(struct diff_options *options,
3014 struct dirstat_dir *dir,
3015 unsigned long changed)
3017 struct dirstat_file *to_free = dir->files;
3019 if (!changed) {
3020 /* This can happen even with many files, if everything was renames */
3022 } else {
3023 /* Show all directories with more than x% of the changes */
3024 QSORT(dir->files, dir->nr, dirstat_compare);
3025 gather_dirstat(options, dir, changed, "", 0);
3028 free(to_free);
3031 static void show_dirstat(struct diff_options *options)
3033 int i;
3034 unsigned long changed;
3035 struct dirstat_dir dir;
3036 struct diff_queue_struct *q = &diff_queued_diff;
3038 dir.files = NULL;
3039 dir.alloc = 0;
3040 dir.nr = 0;
3041 dir.permille = options->dirstat_permille;
3042 dir.cumulative = options->flags.dirstat_cumulative;
3044 changed = 0;
3045 for (i = 0; i < q->nr; i++) {
3046 struct diff_filepair *p = q->queue[i];
3047 const char *name;
3048 unsigned long copied, added, damage;
3049 struct diff_populate_filespec_options dpf_options = {
3050 .check_size_only = 1,
3053 name = p->two->path ? p->two->path : p->one->path;
3055 if (p->one->oid_valid && p->two->oid_valid &&
3056 oideq(&p->one->oid, &p->two->oid)) {
3058 * The SHA1 has not changed, so pre-/post-content is
3059 * identical. We can therefore skip looking at the
3060 * file contents altogether.
3062 damage = 0;
3063 goto found_damage;
3066 if (options->flags.dirstat_by_file) {
3068 * In --dirstat-by-file mode, we don't really need to
3069 * look at the actual file contents at all.
3070 * The fact that the SHA1 changed is enough for us to
3071 * add this file to the list of results
3072 * (with each file contributing equal damage).
3074 damage = 1;
3075 goto found_damage;
3078 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3079 diff_populate_filespec(options->repo, p->one, NULL);
3080 diff_populate_filespec(options->repo, p->two, NULL);
3081 diffcore_count_changes(options->repo,
3082 p->one, p->two, NULL, NULL,
3083 &copied, &added);
3084 diff_free_filespec_data(p->one);
3085 diff_free_filespec_data(p->two);
3086 } else if (DIFF_FILE_VALID(p->one)) {
3087 diff_populate_filespec(options->repo, p->one, &dpf_options);
3088 copied = added = 0;
3089 diff_free_filespec_data(p->one);
3090 } else if (DIFF_FILE_VALID(p->two)) {
3091 diff_populate_filespec(options->repo, p->two, &dpf_options);
3092 copied = 0;
3093 added = p->two->size;
3094 diff_free_filespec_data(p->two);
3095 } else
3096 continue;
3099 * Original minus copied is the removed material,
3100 * added is the new material. They are both damages
3101 * made to the preimage.
3102 * If the resulting damage is zero, we know that
3103 * diffcore_count_changes() considers the two entries to
3104 * be identical, but since the oid changed, we
3105 * know that there must have been _some_ kind of change,
3106 * so we force all entries to have damage > 0.
3108 damage = (p->one->size - copied) + added;
3109 if (!damage)
3110 damage = 1;
3112 found_damage:
3113 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3114 dir.files[dir.nr].name = name;
3115 dir.files[dir.nr].changed = damage;
3116 changed += damage;
3117 dir.nr++;
3120 conclude_dirstat(options, &dir, changed);
3123 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3125 int i;
3126 unsigned long changed;
3127 struct dirstat_dir dir;
3129 if (data->nr == 0)
3130 return;
3132 dir.files = NULL;
3133 dir.alloc = 0;
3134 dir.nr = 0;
3135 dir.permille = options->dirstat_permille;
3136 dir.cumulative = options->flags.dirstat_cumulative;
3138 changed = 0;
3139 for (i = 0; i < data->nr; i++) {
3140 struct diffstat_file *file = data->files[i];
3141 unsigned long damage = file->added + file->deleted;
3142 if (file->is_binary)
3144 * binary files counts bytes, not lines. Must find some
3145 * way to normalize binary bytes vs. textual lines.
3146 * The following heuristic assumes that there are 64
3147 * bytes per "line".
3148 * This is stupid and ugly, but very cheap...
3150 damage = DIV_ROUND_UP(damage, 64);
3151 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3152 dir.files[dir.nr].name = file->name;
3153 dir.files[dir.nr].changed = damage;
3154 changed += damage;
3155 dir.nr++;
3158 conclude_dirstat(options, &dir, changed);
3161 static void free_diffstat_file(struct diffstat_file *f)
3163 free(f->print_name);
3164 free(f->name);
3165 free(f->from_name);
3166 free(f);
3169 void free_diffstat_info(struct diffstat_t *diffstat)
3171 int i;
3172 for (i = 0; i < diffstat->nr; i++)
3173 free_diffstat_file(diffstat->files[i]);
3174 free(diffstat->files);
3177 struct checkdiff_t {
3178 const char *filename;
3179 int lineno;
3180 int conflict_marker_size;
3181 struct diff_options *o;
3182 unsigned ws_rule;
3183 unsigned status;
3186 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3188 char firstchar;
3189 int cnt;
3191 if (len < marker_size + 1)
3192 return 0;
3193 firstchar = line[0];
3194 switch (firstchar) {
3195 case '=': case '>': case '<': case '|':
3196 break;
3197 default:
3198 return 0;
3200 for (cnt = 1; cnt < marker_size; cnt++)
3201 if (line[cnt] != firstchar)
3202 return 0;
3203 /* line[1] through line[marker_size-1] are same as firstchar */
3204 if (len < marker_size + 1 || !isspace(line[marker_size]))
3205 return 0;
3206 return 1;
3209 static void checkdiff_consume_hunk(void *priv,
3210 long ob UNUSED, long on UNUSED,
3211 long nb, long nn UNUSED,
3212 const char *func UNUSED, long funclen UNUSED)
3215 struct checkdiff_t *data = priv;
3216 data->lineno = nb - 1;
3219 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3221 struct checkdiff_t *data = priv;
3222 int marker_size = data->conflict_marker_size;
3223 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3224 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3225 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3226 char *err;
3227 const char *line_prefix;
3229 assert(data->o);
3230 line_prefix = diff_line_prefix(data->o);
3232 if (line[0] == '+') {
3233 unsigned bad;
3234 data->lineno++;
3235 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3236 data->status |= 1;
3237 fprintf(data->o->file,
3238 "%s%s:%d: leftover conflict marker\n",
3239 line_prefix, data->filename, data->lineno);
3241 bad = ws_check(line + 1, len - 1, data->ws_rule);
3242 if (!bad)
3243 return 0;
3244 data->status |= bad;
3245 err = whitespace_error_string(bad);
3246 fprintf(data->o->file, "%s%s:%d: %s.\n",
3247 line_prefix, data->filename, data->lineno, err);
3248 free(err);
3249 emit_line(data->o, set, reset, line, 1);
3250 ws_check_emit(line + 1, len - 1, data->ws_rule,
3251 data->o->file, set, reset, ws);
3252 } else if (line[0] == ' ') {
3253 data->lineno++;
3255 return 0;
3258 static unsigned char *deflate_it(char *data,
3259 unsigned long size,
3260 unsigned long *result_size)
3262 int bound;
3263 unsigned char *deflated;
3264 git_zstream stream;
3266 git_deflate_init(&stream, zlib_compression_level);
3267 bound = git_deflate_bound(&stream, size);
3268 deflated = xmalloc(bound);
3269 stream.next_out = deflated;
3270 stream.avail_out = bound;
3272 stream.next_in = (unsigned char *)data;
3273 stream.avail_in = size;
3274 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3275 ; /* nothing */
3276 git_deflate_end(&stream);
3277 *result_size = stream.total_out;
3278 return deflated;
3281 static void emit_binary_diff_body(struct diff_options *o,
3282 mmfile_t *one, mmfile_t *two)
3284 void *cp;
3285 void *delta;
3286 void *deflated;
3287 void *data;
3288 unsigned long orig_size;
3289 unsigned long delta_size;
3290 unsigned long deflate_size;
3291 unsigned long data_size;
3293 /* We could do deflated delta, or we could do just deflated two,
3294 * whichever is smaller.
3296 delta = NULL;
3297 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3298 if (one->size && two->size) {
3299 delta = diff_delta(one->ptr, one->size,
3300 two->ptr, two->size,
3301 &delta_size, deflate_size);
3302 if (delta) {
3303 void *to_free = delta;
3304 orig_size = delta_size;
3305 delta = deflate_it(delta, delta_size, &delta_size);
3306 free(to_free);
3310 if (delta && delta_size < deflate_size) {
3311 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3312 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3313 s, strlen(s), 0);
3314 free(s);
3315 free(deflated);
3316 data = delta;
3317 data_size = delta_size;
3318 } else {
3319 char *s = xstrfmt("%lu", two->size);
3320 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3321 s, strlen(s), 0);
3322 free(s);
3323 free(delta);
3324 data = deflated;
3325 data_size = deflate_size;
3328 /* emit data encoded in base85 */
3329 cp = data;
3330 while (data_size) {
3331 int len;
3332 int bytes = (52 < data_size) ? 52 : data_size;
3333 char line[71];
3334 data_size -= bytes;
3335 if (bytes <= 26)
3336 line[0] = bytes + 'A' - 1;
3337 else
3338 line[0] = bytes - 26 + 'a' - 1;
3339 encode_85(line + 1, cp, bytes);
3340 cp = (char *) cp + bytes;
3342 len = strlen(line);
3343 line[len++] = '\n';
3344 line[len] = '\0';
3346 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3347 line, len, 0);
3349 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3350 free(data);
3353 static void emit_binary_diff(struct diff_options *o,
3354 mmfile_t *one, mmfile_t *two)
3356 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3357 emit_binary_diff_body(o, one, two);
3358 emit_binary_diff_body(o, two, one);
3361 int diff_filespec_is_binary(struct repository *r,
3362 struct diff_filespec *one)
3364 struct diff_populate_filespec_options dpf_options = {
3365 .check_binary = 1,
3368 if (one->is_binary == -1) {
3369 diff_filespec_load_driver(one, r->index);
3370 if (one->driver->binary != -1)
3371 one->is_binary = one->driver->binary;
3372 else {
3373 if (!one->data && DIFF_FILE_VALID(one))
3374 diff_populate_filespec(r, one, &dpf_options);
3375 if (one->is_binary == -1 && one->data)
3376 one->is_binary = buffer_is_binary(one->data,
3377 one->size);
3378 if (one->is_binary == -1)
3379 one->is_binary = 0;
3382 return one->is_binary;
3385 static const struct userdiff_funcname *
3386 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3388 diff_filespec_load_driver(one, o->repo->index);
3389 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3392 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3394 if (!options->a_prefix)
3395 options->a_prefix = a;
3396 if (!options->b_prefix)
3397 options->b_prefix = b;
3400 void diff_set_noprefix(struct diff_options *options)
3402 options->a_prefix = options->b_prefix = "";
3405 void diff_set_default_prefix(struct diff_options *options)
3407 options->a_prefix = "a/";
3408 options->b_prefix = "b/";
3411 struct userdiff_driver *get_textconv(struct repository *r,
3412 struct diff_filespec *one)
3414 if (!DIFF_FILE_VALID(one))
3415 return NULL;
3417 diff_filespec_load_driver(one, r->index);
3418 return userdiff_get_textconv(r, one->driver);
3421 static struct string_list *additional_headers(struct diff_options *o,
3422 const char *path)
3424 if (!o->additional_path_headers)
3425 return NULL;
3426 return strmap_get(o->additional_path_headers, path);
3429 static void add_formatted_header(struct strbuf *msg,
3430 const char *header,
3431 const char *line_prefix,
3432 const char *meta,
3433 const char *reset)
3435 const char *next, *newline;
3437 for (next = header; *next; next = newline) {
3438 newline = strchrnul(next, '\n');
3439 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3440 (int)(newline - next), next, reset);
3441 if (*newline)
3442 newline++;
3446 static void add_formatted_headers(struct strbuf *msg,
3447 struct string_list *more_headers,
3448 const char *line_prefix,
3449 const char *meta,
3450 const char *reset)
3452 int i;
3454 for (i = 0; i < more_headers->nr; i++)
3455 add_formatted_header(msg, more_headers->items[i].string,
3456 line_prefix, meta, reset);
3459 static int diff_filepair_is_phoney(struct diff_filespec *one,
3460 struct diff_filespec *two)
3463 * This function specifically looks for pairs injected by
3464 * create_filepairs_for_header_only_notifications(). Such
3465 * pairs are "phoney" in that they do not represent any
3466 * content or even mode difference, but were inserted because
3467 * diff_queued_diff previously had no pair associated with
3468 * that path but we needed some pair to avoid losing the
3469 * "remerge CONFLICT" header associated with the path.
3471 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3474 static int set_diff_algorithm(struct diff_options *opts,
3475 const char *alg)
3477 long value = parse_algorithm_value(alg);
3479 if (value < 0)
3480 return -1;
3482 /* clear out previous settings */
3483 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3484 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3485 opts->xdl_opts |= value;
3487 return 0;
3490 static void builtin_diff(const char *name_a,
3491 const char *name_b,
3492 struct diff_filespec *one,
3493 struct diff_filespec *two,
3494 const char *xfrm_msg,
3495 int must_show_header,
3496 struct diff_options *o,
3497 int complete_rewrite)
3499 mmfile_t mf1, mf2;
3500 const char *lbl[2];
3501 char *a_one, *b_two;
3502 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3503 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3504 const char *a_prefix, *b_prefix;
3505 struct userdiff_driver *textconv_one = NULL;
3506 struct userdiff_driver *textconv_two = NULL;
3507 struct strbuf header = STRBUF_INIT;
3508 const char *line_prefix = diff_line_prefix(o);
3510 diff_set_mnemonic_prefix(o, "a/", "b/");
3511 if (o->flags.reverse_diff) {
3512 a_prefix = o->b_prefix;
3513 b_prefix = o->a_prefix;
3514 } else {
3515 a_prefix = o->a_prefix;
3516 b_prefix = o->b_prefix;
3519 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3520 (!one->mode || S_ISGITLINK(one->mode)) &&
3521 (!two->mode || S_ISGITLINK(two->mode)) &&
3522 (!diff_filepair_is_phoney(one, two))) {
3523 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3524 &one->oid, &two->oid,
3525 two->dirty_submodule);
3526 return;
3527 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3528 (!one->mode || S_ISGITLINK(one->mode)) &&
3529 (!two->mode || S_ISGITLINK(two->mode)) &&
3530 (!diff_filepair_is_phoney(one, two))) {
3531 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3532 &one->oid, &two->oid,
3533 two->dirty_submodule);
3534 return;
3537 if (o->flags.allow_textconv) {
3538 textconv_one = get_textconv(o->repo, one);
3539 textconv_two = get_textconv(o->repo, two);
3542 /* Never use a non-valid filename anywhere if at all possible */
3543 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3544 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3546 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3547 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3548 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3549 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3550 if (diff_filepair_is_phoney(one, two)) {
3552 * We should only reach this point for pairs generated from
3553 * create_filepairs_for_header_only_notifications(). For
3554 * these, we want to avoid the "/dev/null" special casing
3555 * above, because we do not want such pairs shown as either
3556 * "new file" or "deleted file" below.
3558 lbl[0] = a_one;
3559 lbl[1] = b_two;
3561 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3562 if (lbl[0][0] == '/') {
3563 /* /dev/null */
3564 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3565 if (xfrm_msg)
3566 strbuf_addstr(&header, xfrm_msg);
3567 must_show_header = 1;
3569 else if (lbl[1][0] == '/') {
3570 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3571 if (xfrm_msg)
3572 strbuf_addstr(&header, xfrm_msg);
3573 must_show_header = 1;
3575 else {
3576 if (one->mode != two->mode) {
3577 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3578 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3579 must_show_header = 1;
3581 if (xfrm_msg)
3582 strbuf_addstr(&header, xfrm_msg);
3585 * we do not run diff between different kind
3586 * of objects.
3588 if ((one->mode ^ two->mode) & S_IFMT)
3589 goto free_ab_and_return;
3590 if (complete_rewrite &&
3591 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3592 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3593 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3594 header.buf, header.len, 0);
3595 strbuf_reset(&header);
3596 emit_rewrite_diff(name_a, name_b, one, two,
3597 textconv_one, textconv_two, o);
3598 o->found_changes = 1;
3599 goto free_ab_and_return;
3603 if (o->irreversible_delete && lbl[1][0] == '/') {
3604 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3605 header.len, 0);
3606 strbuf_reset(&header);
3607 goto free_ab_and_return;
3608 } else if (!o->flags.text &&
3609 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3610 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3611 struct strbuf sb = STRBUF_INIT;
3612 if (!one->data && !two->data &&
3613 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3614 !o->flags.binary) {
3615 if (oideq(&one->oid, &two->oid)) {
3616 if (must_show_header)
3617 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3618 header.buf, header.len,
3620 goto free_ab_and_return;
3622 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3623 header.buf, header.len, 0);
3624 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3625 diff_line_prefix(o), lbl[0], lbl[1]);
3626 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3627 sb.buf, sb.len, 0);
3628 strbuf_release(&sb);
3629 goto free_ab_and_return;
3631 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3632 fill_mmfile(o->repo, &mf2, two) < 0)
3633 die("unable to read files to diff");
3634 /* Quite common confusing case */
3635 if (mf1.size == mf2.size &&
3636 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3637 if (must_show_header)
3638 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3639 header.buf, header.len, 0);
3640 goto free_ab_and_return;
3642 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3643 strbuf_reset(&header);
3644 if (o->flags.binary)
3645 emit_binary_diff(o, &mf1, &mf2);
3646 else {
3647 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3648 diff_line_prefix(o), lbl[0], lbl[1]);
3649 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3650 sb.buf, sb.len, 0);
3651 strbuf_release(&sb);
3653 o->found_changes = 1;
3654 } else {
3655 /* Crazy xdl interfaces.. */
3656 const char *diffopts;
3657 const char *v;
3658 xpparam_t xpp;
3659 xdemitconf_t xecfg;
3660 struct emit_callback ecbdata;
3661 const struct userdiff_funcname *pe;
3663 if (must_show_header) {
3664 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3665 header.buf, header.len, 0);
3666 strbuf_reset(&header);
3669 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3670 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3672 pe = diff_funcname_pattern(o, one);
3673 if (!pe)
3674 pe = diff_funcname_pattern(o, two);
3676 memset(&xpp, 0, sizeof(xpp));
3677 memset(&xecfg, 0, sizeof(xecfg));
3678 memset(&ecbdata, 0, sizeof(ecbdata));
3679 if (o->flags.suppress_diff_headers)
3680 lbl[0] = NULL;
3681 ecbdata.label_path = lbl;
3682 ecbdata.color_diff = want_color(o->use_color);
3683 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3684 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3685 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3686 ecbdata.opt = o;
3687 if (header.len && !o->flags.suppress_diff_headers)
3688 ecbdata.header = &header;
3689 xpp.flags = o->xdl_opts;
3690 xpp.ignore_regex = o->ignore_regex;
3691 xpp.ignore_regex_nr = o->ignore_regex_nr;
3692 xpp.anchors = o->anchors;
3693 xpp.anchors_nr = o->anchors_nr;
3694 xecfg.ctxlen = o->context;
3695 xecfg.interhunkctxlen = o->interhunkcontext;
3696 xecfg.flags = XDL_EMIT_FUNCNAMES;
3697 if (o->flags.funccontext)
3698 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3699 if (pe)
3700 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3702 diffopts = getenv("GIT_DIFF_OPTS");
3703 if (!diffopts)
3705 else if (skip_prefix(diffopts, "--unified=", &v))
3706 xecfg.ctxlen = strtoul(v, NULL, 10);
3707 else if (skip_prefix(diffopts, "-u", &v))
3708 xecfg.ctxlen = strtoul(v, NULL, 10);
3710 if (o->word_diff)
3711 init_diff_words_data(&ecbdata, o, one, two);
3712 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3713 &ecbdata, &xpp, &xecfg))
3714 die("unable to generate diff for %s", one->path);
3715 if (o->word_diff)
3716 free_diff_words_data(&ecbdata);
3717 if (textconv_one)
3718 free(mf1.ptr);
3719 if (textconv_two)
3720 free(mf2.ptr);
3721 xdiff_clear_find_func(&xecfg);
3724 free_ab_and_return:
3725 strbuf_release(&header);
3726 diff_free_filespec_data(one);
3727 diff_free_filespec_data(two);
3728 free(a_one);
3729 free(b_two);
3730 return;
3733 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3735 if (!is_renamed) {
3736 if (p->status == DIFF_STATUS_ADDED) {
3737 if (S_ISLNK(p->two->mode))
3738 return "new +l";
3739 else if ((p->two->mode & 0777) == 0755)
3740 return "new +x";
3741 else
3742 return "new";
3743 } else if (p->status == DIFF_STATUS_DELETED)
3744 return "gone";
3746 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3747 return "mode -l";
3748 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3749 return "mode +l";
3750 else if ((p->one->mode & 0777) == 0644 &&
3751 (p->two->mode & 0777) == 0755)
3752 return "mode +x";
3753 else if ((p->one->mode & 0777) == 0755 &&
3754 (p->two->mode & 0777) == 0644)
3755 return "mode -x";
3756 return NULL;
3759 static void builtin_diffstat(const char *name_a, const char *name_b,
3760 struct diff_filespec *one,
3761 struct diff_filespec *two,
3762 struct diffstat_t *diffstat,
3763 struct diff_options *o,
3764 struct diff_filepair *p)
3766 mmfile_t mf1, mf2;
3767 struct diffstat_file *data;
3768 int may_differ;
3769 int complete_rewrite = 0;
3771 if (!DIFF_PAIR_UNMERGED(p)) {
3772 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3773 complete_rewrite = 1;
3776 data = diffstat_add(diffstat, name_a, name_b);
3777 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3778 if (o->flags.stat_with_summary)
3779 data->comments = get_compact_summary(p, data->is_renamed);
3781 if (!one || !two) {
3782 data->is_unmerged = 1;
3783 return;
3786 /* saves some reads if true, not a guarantee of diff outcome */
3787 may_differ = !(one->oid_valid && two->oid_valid &&
3788 oideq(&one->oid, &two->oid));
3790 if (diff_filespec_is_binary(o->repo, one) ||
3791 diff_filespec_is_binary(o->repo, two)) {
3792 data->is_binary = 1;
3793 if (!may_differ) {
3794 data->added = 0;
3795 data->deleted = 0;
3796 } else {
3797 data->added = diff_filespec_size(o->repo, two);
3798 data->deleted = diff_filespec_size(o->repo, one);
3802 else if (complete_rewrite) {
3803 diff_populate_filespec(o->repo, one, NULL);
3804 diff_populate_filespec(o->repo, two, NULL);
3805 data->deleted = count_lines(one->data, one->size);
3806 data->added = count_lines(two->data, two->size);
3809 else if (may_differ) {
3810 /* Crazy xdl interfaces.. */
3811 xpparam_t xpp;
3812 xdemitconf_t xecfg;
3814 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3815 fill_mmfile(o->repo, &mf2, two) < 0)
3816 die("unable to read files to diff");
3818 memset(&xpp, 0, sizeof(xpp));
3819 memset(&xecfg, 0, sizeof(xecfg));
3820 xpp.flags = o->xdl_opts;
3821 xpp.ignore_regex = o->ignore_regex;
3822 xpp.ignore_regex_nr = o->ignore_regex_nr;
3823 xpp.anchors = o->anchors;
3824 xpp.anchors_nr = o->anchors_nr;
3825 xecfg.ctxlen = o->context;
3826 xecfg.interhunkctxlen = o->interhunkcontext;
3827 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3828 if (xdi_diff_outf(&mf1, &mf2, NULL,
3829 diffstat_consume, diffstat, &xpp, &xecfg))
3830 die("unable to generate diffstat for %s", one->path);
3832 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3833 struct diffstat_file *file =
3834 diffstat->files[diffstat->nr - 1];
3836 * Omit diffstats of modified files where nothing changed.
3837 * Even if may_differ, this might be the case due to
3838 * ignoring whitespace changes, etc.
3840 * But note that we special-case additions, deletions,
3841 * renames, and mode changes as adding an empty file,
3842 * for example is still of interest.
3844 if ((p->status == DIFF_STATUS_MODIFIED)
3845 && !file->added
3846 && !file->deleted
3847 && one->mode == two->mode) {
3848 free_diffstat_file(file);
3849 diffstat->nr--;
3854 diff_free_filespec_data(one);
3855 diff_free_filespec_data(two);
3858 static void builtin_checkdiff(const char *name_a, const char *name_b,
3859 const char *attr_path,
3860 struct diff_filespec *one,
3861 struct diff_filespec *two,
3862 struct diff_options *o)
3864 mmfile_t mf1, mf2;
3865 struct checkdiff_t data;
3867 if (!two)
3868 return;
3870 memset(&data, 0, sizeof(data));
3871 data.filename = name_b ? name_b : name_a;
3872 data.lineno = 0;
3873 data.o = o;
3874 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3875 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3877 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3878 fill_mmfile(o->repo, &mf2, two) < 0)
3879 die("unable to read files to diff");
3882 * All the other codepaths check both sides, but not checking
3883 * the "old" side here is deliberate. We are checking the newly
3884 * introduced changes, and as long as the "new" side is text, we
3885 * can and should check what it introduces.
3887 if (diff_filespec_is_binary(o->repo, two))
3888 goto free_and_return;
3889 else {
3890 /* Crazy xdl interfaces.. */
3891 xpparam_t xpp;
3892 xdemitconf_t xecfg;
3894 memset(&xpp, 0, sizeof(xpp));
3895 memset(&xecfg, 0, sizeof(xecfg));
3896 xecfg.ctxlen = 1; /* at least one context line */
3897 xpp.flags = 0;
3898 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3899 checkdiff_consume, &data,
3900 &xpp, &xecfg))
3901 die("unable to generate checkdiff for %s", one->path);
3903 if (data.ws_rule & WS_BLANK_AT_EOF) {
3904 struct emit_callback ecbdata;
3905 int blank_at_eof;
3907 ecbdata.ws_rule = data.ws_rule;
3908 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3909 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3911 if (blank_at_eof) {
3912 static char *err;
3913 if (!err)
3914 err = whitespace_error_string(WS_BLANK_AT_EOF);
3915 fprintf(o->file, "%s:%d: %s.\n",
3916 data.filename, blank_at_eof, err);
3917 data.status = 1; /* report errors */
3921 free_and_return:
3922 diff_free_filespec_data(one);
3923 diff_free_filespec_data(two);
3924 if (data.status)
3925 o->flags.check_failed = 1;
3928 struct diff_filespec *alloc_filespec(const char *path)
3930 struct diff_filespec *spec;
3932 FLEXPTR_ALLOC_STR(spec, path, path);
3933 spec->count = 1;
3934 spec->is_binary = -1;
3935 return spec;
3938 void free_filespec(struct diff_filespec *spec)
3940 if (!--spec->count) {
3941 diff_free_filespec_data(spec);
3942 free(spec);
3946 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3947 int oid_valid, unsigned short mode)
3949 if (mode) {
3950 spec->mode = canon_mode(mode);
3951 oidcpy(&spec->oid, oid);
3952 spec->oid_valid = oid_valid;
3957 * Given a name and sha1 pair, if the index tells us the file in
3958 * the work tree has that object contents, return true, so that
3959 * prepare_temp_file() does not have to inflate and extract.
3961 static int reuse_worktree_file(struct index_state *istate,
3962 const char *name,
3963 const struct object_id *oid,
3964 int want_file)
3966 const struct cache_entry *ce;
3967 struct stat st;
3968 int pos, len;
3971 * We do not read the cache ourselves here, because the
3972 * benchmark with my previous version that always reads cache
3973 * shows that it makes things worse for diff-tree comparing
3974 * two linux-2.6 kernel trees in an already checked out work
3975 * tree. This is because most diff-tree comparisons deal with
3976 * only a small number of files, while reading the cache is
3977 * expensive for a large project, and its cost outweighs the
3978 * savings we get by not inflating the object to a temporary
3979 * file. Practically, this code only helps when we are used
3980 * by diff-cache --cached, which does read the cache before
3981 * calling us.
3983 if (!istate->cache)
3984 return 0;
3986 /* We want to avoid the working directory if our caller
3987 * doesn't need the data in a normal file, this system
3988 * is rather slow with its stat/open/mmap/close syscalls,
3989 * and the object is contained in a pack file. The pack
3990 * is probably already open and will be faster to obtain
3991 * the data through than the working directory. Loose
3992 * objects however would tend to be slower as they need
3993 * to be individually opened and inflated.
3995 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3996 return 0;
3999 * Similarly, if we'd have to convert the file contents anyway, that
4000 * makes the optimization not worthwhile.
4002 if (!want_file && would_convert_to_git(istate, name))
4003 return 0;
4006 * If this path does not match our sparse-checkout definition,
4007 * then the file will not be in the working directory.
4009 if (!path_in_sparse_checkout(name, istate))
4010 return 0;
4012 len = strlen(name);
4013 pos = index_name_pos(istate, name, len);
4014 if (pos < 0)
4015 return 0;
4016 ce = istate->cache[pos];
4019 * This is not the sha1 we are looking for, or
4020 * unreusable because it is not a regular file.
4022 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4023 return 0;
4026 * If ce is marked as "assume unchanged", there is no
4027 * guarantee that work tree matches what we are looking for.
4029 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4030 return 0;
4033 * If ce matches the file in the work tree, we can reuse it.
4035 if (ce_uptodate(ce) ||
4036 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4037 return 1;
4039 return 0;
4042 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4044 struct strbuf buf = STRBUF_INIT;
4045 char *dirty = "";
4047 /* Are we looking at the work tree? */
4048 if (s->dirty_submodule)
4049 dirty = "-dirty";
4051 strbuf_addf(&buf, "Subproject commit %s%s\n",
4052 oid_to_hex(&s->oid), dirty);
4053 s->size = buf.len;
4054 if (size_only) {
4055 s->data = NULL;
4056 strbuf_release(&buf);
4057 } else {
4058 s->data = strbuf_detach(&buf, NULL);
4059 s->should_free = 1;
4061 return 0;
4065 * While doing rename detection and pickaxe operation, we may need to
4066 * grab the data for the blob (or file) for our own in-core comparison.
4067 * diff_filespec has data and size fields for this purpose.
4069 int diff_populate_filespec(struct repository *r,
4070 struct diff_filespec *s,
4071 const struct diff_populate_filespec_options *options)
4073 int size_only = options ? options->check_size_only : 0;
4074 int check_binary = options ? options->check_binary : 0;
4075 int err = 0;
4076 int conv_flags = global_conv_flags_eol;
4078 * demote FAIL to WARN to allow inspecting the situation
4079 * instead of refusing.
4081 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4082 conv_flags = CONV_EOL_RNDTRP_WARN;
4084 if (!DIFF_FILE_VALID(s))
4085 die("internal error: asking to populate invalid file.");
4086 if (S_ISDIR(s->mode))
4087 return -1;
4089 if (s->data)
4090 return 0;
4092 if (size_only && 0 < s->size)
4093 return 0;
4095 if (S_ISGITLINK(s->mode))
4096 return diff_populate_gitlink(s, size_only);
4098 if (!s->oid_valid ||
4099 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4100 struct strbuf buf = STRBUF_INIT;
4101 struct stat st;
4102 int fd;
4104 if (lstat(s->path, &st) < 0) {
4105 err_empty:
4106 err = -1;
4107 empty:
4108 s->data = (char *)"";
4109 s->size = 0;
4110 return err;
4112 s->size = xsize_t(st.st_size);
4113 if (!s->size)
4114 goto empty;
4115 if (S_ISLNK(st.st_mode)) {
4116 struct strbuf sb = STRBUF_INIT;
4118 if (strbuf_readlink(&sb, s->path, s->size))
4119 goto err_empty;
4120 s->size = sb.len;
4121 s->data = strbuf_detach(&sb, NULL);
4122 s->should_free = 1;
4123 return 0;
4127 * Even if the caller would be happy with getting
4128 * only the size, we cannot return early at this
4129 * point if the path requires us to run the content
4130 * conversion.
4132 if (size_only && !would_convert_to_git(r->index, s->path))
4133 return 0;
4136 * Note: this check uses xsize_t(st.st_size) that may
4137 * not be the true size of the blob after it goes
4138 * through convert_to_git(). This may not strictly be
4139 * correct, but the whole point of big_file_threshold
4140 * and is_binary check being that we want to avoid
4141 * opening the file and inspecting the contents, this
4142 * is probably fine.
4144 if (check_binary &&
4145 s->size > big_file_threshold && s->is_binary == -1) {
4146 s->is_binary = 1;
4147 return 0;
4149 fd = open(s->path, O_RDONLY);
4150 if (fd < 0)
4151 goto err_empty;
4152 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4153 close(fd);
4154 s->should_munmap = 1;
4157 * Convert from working tree format to canonical git format
4159 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4160 size_t size = 0;
4161 munmap(s->data, s->size);
4162 s->should_munmap = 0;
4163 s->data = strbuf_detach(&buf, &size);
4164 s->size = size;
4165 s->should_free = 1;
4168 else {
4169 struct object_info info = {
4170 .sizep = &s->size
4173 if (!(size_only || check_binary))
4175 * Set contentp, since there is no chance that merely
4176 * the size is sufficient.
4178 info.contentp = &s->data;
4180 if (options && options->missing_object_cb) {
4181 if (!oid_object_info_extended(r, &s->oid, &info,
4182 OBJECT_INFO_LOOKUP_REPLACE |
4183 OBJECT_INFO_SKIP_FETCH_OBJECT))
4184 goto object_read;
4185 options->missing_object_cb(options->missing_object_data);
4187 if (oid_object_info_extended(r, &s->oid, &info,
4188 OBJECT_INFO_LOOKUP_REPLACE))
4189 die("unable to read %s", oid_to_hex(&s->oid));
4191 object_read:
4192 if (size_only || check_binary) {
4193 if (size_only)
4194 return 0;
4195 if (s->size > big_file_threshold && s->is_binary == -1) {
4196 s->is_binary = 1;
4197 return 0;
4200 if (!info.contentp) {
4201 info.contentp = &s->data;
4202 if (oid_object_info_extended(r, &s->oid, &info,
4203 OBJECT_INFO_LOOKUP_REPLACE))
4204 die("unable to read %s", oid_to_hex(&s->oid));
4206 s->should_free = 1;
4208 return 0;
4211 void diff_free_filespec_blob(struct diff_filespec *s)
4213 if (s->should_free)
4214 free(s->data);
4215 else if (s->should_munmap)
4216 munmap(s->data, s->size);
4218 if (s->should_free || s->should_munmap) {
4219 s->should_free = s->should_munmap = 0;
4220 s->data = NULL;
4224 void diff_free_filespec_data(struct diff_filespec *s)
4226 if (!s)
4227 return;
4229 diff_free_filespec_blob(s);
4230 FREE_AND_NULL(s->cnt_data);
4233 static void prep_temp_blob(struct index_state *istate,
4234 const char *path, struct diff_tempfile *temp,
4235 void *blob,
4236 unsigned long size,
4237 const struct object_id *oid,
4238 int mode)
4240 struct strbuf buf = STRBUF_INIT;
4241 char *path_dup = xstrdup(path);
4242 const char *base = basename(path_dup);
4243 struct checkout_metadata meta;
4245 init_checkout_metadata(&meta, NULL, NULL, oid);
4247 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4248 if (!temp->tempfile)
4249 die_errno("unable to create temp-file");
4250 if (convert_to_working_tree(istate, path,
4251 (const char *)blob, (size_t)size, &buf, &meta)) {
4252 blob = buf.buf;
4253 size = buf.len;
4255 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4256 close_tempfile_gently(temp->tempfile))
4257 die_errno("unable to write temp-file");
4258 temp->name = get_tempfile_path(temp->tempfile);
4259 oid_to_hex_r(temp->hex, oid);
4260 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4261 strbuf_release(&buf);
4262 free(path_dup);
4265 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4266 struct diff_filespec *one)
4268 struct diff_tempfile *temp = claim_diff_tempfile();
4270 if (!DIFF_FILE_VALID(one)) {
4271 not_a_valid_file:
4272 /* A '-' entry produces this for file-2, and
4273 * a '+' entry produces this for file-1.
4275 temp->name = "/dev/null";
4276 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4277 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4278 return temp;
4281 if (!S_ISGITLINK(one->mode) &&
4282 (!one->oid_valid ||
4283 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4284 struct stat st;
4285 if (lstat(one->path, &st) < 0) {
4286 if (errno == ENOENT)
4287 goto not_a_valid_file;
4288 die_errno("stat(%s)", one->path);
4290 if (S_ISLNK(st.st_mode)) {
4291 struct strbuf sb = STRBUF_INIT;
4292 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4293 die_errno("readlink(%s)", one->path);
4294 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4295 (one->oid_valid ?
4296 &one->oid : null_oid()),
4297 (one->oid_valid ?
4298 one->mode : S_IFLNK));
4299 strbuf_release(&sb);
4301 else {
4302 /* we can borrow from the file in the work tree */
4303 temp->name = one->path;
4304 if (!one->oid_valid)
4305 oid_to_hex_r(temp->hex, null_oid());
4306 else
4307 oid_to_hex_r(temp->hex, &one->oid);
4308 /* Even though we may sometimes borrow the
4309 * contents from the work tree, we always want
4310 * one->mode. mode is trustworthy even when
4311 * !(one->oid_valid), as long as
4312 * DIFF_FILE_VALID(one).
4314 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4316 return temp;
4318 else {
4319 if (diff_populate_filespec(r, one, NULL))
4320 die("cannot read data blob for %s", one->path);
4321 prep_temp_blob(r->index, one->path, temp,
4322 one->data, one->size,
4323 &one->oid, one->mode);
4325 return temp;
4328 static void add_external_diff_name(struct repository *r,
4329 struct strvec *argv,
4330 struct diff_filespec *df)
4332 struct diff_tempfile *temp = prepare_temp_file(r, df);
4333 strvec_push(argv, temp->name);
4334 strvec_push(argv, temp->hex);
4335 strvec_push(argv, temp->mode);
4338 /* An external diff command takes:
4340 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4341 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4344 static void run_external_diff(const char *pgm,
4345 const char *name,
4346 const char *other,
4347 struct diff_filespec *one,
4348 struct diff_filespec *two,
4349 const char *xfrm_msg,
4350 struct diff_options *o)
4352 struct child_process cmd = CHILD_PROCESS_INIT;
4353 struct diff_queue_struct *q = &diff_queued_diff;
4355 strvec_push(&cmd.args, pgm);
4356 strvec_push(&cmd.args, name);
4358 if (one && two) {
4359 add_external_diff_name(o->repo, &cmd.args, one);
4360 add_external_diff_name(o->repo, &cmd.args, two);
4361 if (other) {
4362 strvec_push(&cmd.args, other);
4363 strvec_push(&cmd.args, xfrm_msg);
4367 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4368 ++o->diff_path_counter);
4369 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4371 diff_free_filespec_data(one);
4372 diff_free_filespec_data(two);
4373 cmd.use_shell = 1;
4374 if (run_command(&cmd))
4375 die(_("external diff died, stopping at %s"), name);
4377 remove_tempfile();
4380 static int similarity_index(struct diff_filepair *p)
4382 return p->score * 100 / MAX_SCORE;
4385 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4387 if (startup_info->have_repository)
4388 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4389 else {
4390 char *hex = oid_to_hex(oid);
4391 if (abbrev < 0)
4392 abbrev = FALLBACK_DEFAULT_ABBREV;
4393 if (abbrev > the_hash_algo->hexsz)
4394 BUG("oid abbreviation out of range: %d", abbrev);
4395 if (abbrev)
4396 hex[abbrev] = '\0';
4397 return hex;
4401 static void fill_metainfo(struct strbuf *msg,
4402 const char *name,
4403 const char *other,
4404 struct diff_filespec *one,
4405 struct diff_filespec *two,
4406 struct diff_options *o,
4407 struct diff_filepair *p,
4408 int *must_show_header,
4409 int use_color)
4411 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4412 const char *reset = diff_get_color(use_color, DIFF_RESET);
4413 const char *line_prefix = diff_line_prefix(o);
4414 struct string_list *more_headers = NULL;
4416 *must_show_header = 1;
4417 strbuf_init(msg, PATH_MAX * 2 + 300);
4418 switch (p->status) {
4419 case DIFF_STATUS_COPIED:
4420 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4421 line_prefix, set, similarity_index(p));
4422 strbuf_addf(msg, "%s\n%s%scopy from ",
4423 reset, line_prefix, set);
4424 quote_c_style(name, msg, NULL, 0);
4425 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4426 quote_c_style(other, msg, NULL, 0);
4427 strbuf_addf(msg, "%s\n", reset);
4428 break;
4429 case DIFF_STATUS_RENAMED:
4430 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4431 line_prefix, set, similarity_index(p));
4432 strbuf_addf(msg, "%s\n%s%srename from ",
4433 reset, line_prefix, set);
4434 quote_c_style(name, msg, NULL, 0);
4435 strbuf_addf(msg, "%s\n%s%srename to ",
4436 reset, line_prefix, set);
4437 quote_c_style(other, msg, NULL, 0);
4438 strbuf_addf(msg, "%s\n", reset);
4439 break;
4440 case DIFF_STATUS_MODIFIED:
4441 if (p->score) {
4442 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4443 line_prefix,
4444 set, similarity_index(p), reset);
4445 break;
4447 /* fallthru */
4448 default:
4449 *must_show_header = 0;
4451 if ((more_headers = additional_headers(o, name))) {
4452 add_formatted_headers(msg, more_headers,
4453 line_prefix, set, reset);
4454 *must_show_header = 1;
4456 if (one && two && !oideq(&one->oid, &two->oid)) {
4457 const unsigned hexsz = the_hash_algo->hexsz;
4458 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4460 if (o->flags.full_index)
4461 abbrev = hexsz;
4463 if (o->flags.binary) {
4464 mmfile_t mf;
4465 if ((!fill_mmfile(o->repo, &mf, one) &&
4466 diff_filespec_is_binary(o->repo, one)) ||
4467 (!fill_mmfile(o->repo, &mf, two) &&
4468 diff_filespec_is_binary(o->repo, two)))
4469 abbrev = hexsz;
4471 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4472 diff_abbrev_oid(&one->oid, abbrev),
4473 diff_abbrev_oid(&two->oid, abbrev));
4474 if (one->mode == two->mode)
4475 strbuf_addf(msg, " %06o", one->mode);
4476 strbuf_addf(msg, "%s\n", reset);
4480 static void run_diff_cmd(const char *pgm,
4481 const char *name,
4482 const char *other,
4483 const char *attr_path,
4484 struct diff_filespec *one,
4485 struct diff_filespec *two,
4486 struct strbuf *msg,
4487 struct diff_options *o,
4488 struct diff_filepair *p)
4490 const char *xfrm_msg = NULL;
4491 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4492 int must_show_header = 0;
4493 struct userdiff_driver *drv = NULL;
4495 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4496 drv = userdiff_find_by_path(o->repo->index, attr_path);
4498 if (o->flags.allow_external && drv && drv->external)
4499 pgm = drv->external;
4501 if (msg) {
4503 * don't use colors when the header is intended for an
4504 * external diff driver
4506 fill_metainfo(msg, name, other, one, two, o, p,
4507 &must_show_header,
4508 want_color(o->use_color) && !pgm);
4509 xfrm_msg = msg->len ? msg->buf : NULL;
4512 if (pgm) {
4513 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4514 return;
4516 if (one && two) {
4517 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4518 set_diff_algorithm(o, drv->algorithm);
4520 builtin_diff(name, other ? other : name,
4521 one, two, xfrm_msg, must_show_header,
4522 o, complete_rewrite);
4523 } else {
4524 fprintf(o->file, "* Unmerged path %s\n", name);
4528 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4530 if (DIFF_FILE_VALID(one)) {
4531 if (!one->oid_valid) {
4532 struct stat st;
4533 if (one->is_stdin) {
4534 oidclr(&one->oid);
4535 return;
4537 if (lstat(one->path, &st) < 0)
4538 die_errno("stat '%s'", one->path);
4539 if (index_path(istate, &one->oid, one->path, &st, 0))
4540 die("cannot hash %s", one->path);
4543 else
4544 oidclr(&one->oid);
4547 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4549 /* Strip the prefix but do not molest /dev/null and absolute paths */
4550 if (*namep && !is_absolute_path(*namep)) {
4551 *namep += prefix_length;
4552 if (**namep == '/')
4553 ++*namep;
4555 if (*otherp && !is_absolute_path(*otherp)) {
4556 *otherp += prefix_length;
4557 if (**otherp == '/')
4558 ++*otherp;
4562 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4564 const char *pgm = external_diff();
4565 struct strbuf msg;
4566 struct diff_filespec *one = p->one;
4567 struct diff_filespec *two = p->two;
4568 const char *name;
4569 const char *other;
4570 const char *attr_path;
4572 name = one->path;
4573 other = (strcmp(name, two->path) ? two->path : NULL);
4574 attr_path = name;
4575 if (o->prefix_length)
4576 strip_prefix(o->prefix_length, &name, &other);
4578 if (!o->flags.allow_external)
4579 pgm = NULL;
4581 if (DIFF_PAIR_UNMERGED(p)) {
4582 run_diff_cmd(pgm, name, NULL, attr_path,
4583 NULL, NULL, NULL, o, p);
4584 return;
4587 diff_fill_oid_info(one, o->repo->index);
4588 diff_fill_oid_info(two, o->repo->index);
4590 if (!pgm &&
4591 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4592 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4594 * a filepair that changes between file and symlink
4595 * needs to be split into deletion and creation.
4597 struct diff_filespec *null = alloc_filespec(two->path);
4598 run_diff_cmd(NULL, name, other, attr_path,
4599 one, null, &msg,
4600 o, p);
4601 free(null);
4602 strbuf_release(&msg);
4604 null = alloc_filespec(one->path);
4605 run_diff_cmd(NULL, name, other, attr_path,
4606 null, two, &msg, o, p);
4607 free(null);
4609 else
4610 run_diff_cmd(pgm, name, other, attr_path,
4611 one, two, &msg, o, p);
4613 strbuf_release(&msg);
4616 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4617 struct diffstat_t *diffstat)
4619 const char *name;
4620 const char *other;
4622 if (!o->ignore_driver_algorithm) {
4623 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4624 p->one->path);
4626 if (drv && drv->algorithm)
4627 set_diff_algorithm(o, drv->algorithm);
4630 if (DIFF_PAIR_UNMERGED(p)) {
4631 /* unmerged */
4632 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4633 diffstat, o, p);
4634 return;
4637 name = p->one->path;
4638 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4640 if (o->prefix_length)
4641 strip_prefix(o->prefix_length, &name, &other);
4643 diff_fill_oid_info(p->one, o->repo->index);
4644 diff_fill_oid_info(p->two, o->repo->index);
4646 builtin_diffstat(name, other, p->one, p->two,
4647 diffstat, o, p);
4650 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4652 const char *name;
4653 const char *other;
4654 const char *attr_path;
4656 if (DIFF_PAIR_UNMERGED(p)) {
4657 /* unmerged */
4658 return;
4661 name = p->one->path;
4662 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4663 attr_path = other ? other : name;
4665 if (o->prefix_length)
4666 strip_prefix(o->prefix_length, &name, &other);
4668 diff_fill_oid_info(p->one, o->repo->index);
4669 diff_fill_oid_info(p->two, o->repo->index);
4671 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4674 void repo_diff_setup(struct repository *r, struct diff_options *options)
4676 memcpy(options, &default_diff_options, sizeof(*options));
4678 options->file = stdout;
4679 options->repo = r;
4681 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4682 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4683 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4684 options->abbrev = DEFAULT_ABBREV;
4685 options->line_termination = '\n';
4686 options->break_opt = -1;
4687 options->rename_limit = -1;
4688 options->dirstat_permille = diff_dirstat_permille_default;
4689 options->context = diff_context_default;
4690 options->interhunkcontext = diff_interhunk_context_default;
4691 options->ws_error_highlight = ws_error_highlight_default;
4692 options->flags.rename_empty = 1;
4693 options->flags.relative_name = diff_relative;
4694 options->objfind = NULL;
4696 /* pathchange left =NULL by default */
4697 options->change = diff_change;
4698 options->add_remove = diff_addremove;
4699 options->use_color = diff_use_color_default;
4700 options->detect_rename = diff_detect_rename_default;
4701 options->xdl_opts |= diff_algorithm;
4702 if (diff_indent_heuristic)
4703 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4705 options->orderfile = diff_order_file_cfg;
4707 if (!options->flags.ignore_submodule_set)
4708 options->flags.ignore_untracked_in_submodules = 1;
4710 if (diff_no_prefix) {
4711 diff_set_noprefix(options);
4712 } else if (!diff_mnemonic_prefix) {
4713 diff_set_default_prefix(options);
4716 options->color_moved = diff_color_moved_default;
4717 options->color_moved_ws_handling = diff_color_moved_ws_default;
4720 static const char diff_status_letters[] = {
4721 DIFF_STATUS_ADDED,
4722 DIFF_STATUS_COPIED,
4723 DIFF_STATUS_DELETED,
4724 DIFF_STATUS_MODIFIED,
4725 DIFF_STATUS_RENAMED,
4726 DIFF_STATUS_TYPE_CHANGED,
4727 DIFF_STATUS_UNKNOWN,
4728 DIFF_STATUS_UNMERGED,
4729 DIFF_STATUS_FILTER_AON,
4730 DIFF_STATUS_FILTER_BROKEN,
4731 '\0',
4734 static unsigned int filter_bit['Z' + 1];
4736 static void prepare_filter_bits(void)
4738 int i;
4740 if (!filter_bit[DIFF_STATUS_ADDED]) {
4741 for (i = 0; diff_status_letters[i]; i++)
4742 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4746 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4748 return opt->filter & filter_bit[(int) status];
4751 unsigned diff_filter_bit(char status)
4753 prepare_filter_bits();
4754 return filter_bit[(int) status];
4757 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4759 unsigned forbidden_magic;
4761 if (ps->nr != 1) {
4762 if (die_on_error)
4763 die(_("--follow requires exactly one pathspec"));
4764 return 0;
4767 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4768 PATHSPEC_LITERAL);
4769 if (forbidden_magic) {
4770 if (die_on_error) {
4771 struct strbuf sb = STRBUF_INIT;
4772 pathspec_magic_names(forbidden_magic, &sb);
4773 die(_("pathspec magic not supported by --follow: %s"),
4774 sb.buf);
4776 return 0;
4779 return 1;
4782 void diff_setup_done(struct diff_options *options)
4784 unsigned check_mask = DIFF_FORMAT_NAME |
4785 DIFF_FORMAT_NAME_STATUS |
4786 DIFF_FORMAT_CHECKDIFF |
4787 DIFF_FORMAT_NO_OUTPUT;
4789 * This must be signed because we're comparing against a potentially
4790 * negative value.
4792 const int hexsz = the_hash_algo->hexsz;
4794 if (options->set_default)
4795 options->set_default(options);
4797 if (HAS_MULTI_BITS(options->output_format & check_mask))
4798 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4799 "--name-only", "--name-status", "--check", "-s");
4801 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4802 die(_("options '%s', '%s', and '%s' cannot be used together"),
4803 "-G", "-S", "--find-object");
4805 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4806 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4807 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4809 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4810 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4811 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4814 * Most of the time we can say "there are changes"
4815 * only by checking if there are changed paths, but
4816 * --ignore-whitespace* options force us to look
4817 * inside contents.
4820 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4821 options->ignore_regex_nr)
4822 options->flags.diff_from_contents = 1;
4823 else
4824 options->flags.diff_from_contents = 0;
4826 if (options->flags.find_copies_harder)
4827 options->detect_rename = DIFF_DETECT_COPY;
4829 if (!options->flags.relative_name)
4830 options->prefix = NULL;
4831 if (options->prefix)
4832 options->prefix_length = strlen(options->prefix);
4833 else
4834 options->prefix_length = 0;
4836 if (options->output_format & (DIFF_FORMAT_NAME |
4837 DIFF_FORMAT_NAME_STATUS |
4838 DIFF_FORMAT_CHECKDIFF |
4839 DIFF_FORMAT_NO_OUTPUT))
4840 options->output_format &= ~(DIFF_FORMAT_RAW |
4841 DIFF_FORMAT_NUMSTAT |
4842 DIFF_FORMAT_DIFFSTAT |
4843 DIFF_FORMAT_SHORTSTAT |
4844 DIFF_FORMAT_DIRSTAT |
4845 DIFF_FORMAT_SUMMARY |
4846 DIFF_FORMAT_PATCH);
4849 * These cases always need recursive; we do not drop caller-supplied
4850 * recursive bits for other formats here.
4852 if (options->output_format & (DIFF_FORMAT_PATCH |
4853 DIFF_FORMAT_NUMSTAT |
4854 DIFF_FORMAT_DIFFSTAT |
4855 DIFF_FORMAT_SHORTSTAT |
4856 DIFF_FORMAT_DIRSTAT |
4857 DIFF_FORMAT_SUMMARY |
4858 DIFF_FORMAT_CHECKDIFF))
4859 options->flags.recursive = 1;
4861 * Also pickaxe would not work very well if you do not say recursive
4863 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4864 options->flags.recursive = 1;
4866 * When patches are generated, submodules diffed against the work tree
4867 * must be checked for dirtiness too so it can be shown in the output
4869 if (options->output_format & DIFF_FORMAT_PATCH)
4870 options->flags.dirty_submodules = 1;
4872 if (options->detect_rename && options->rename_limit < 0)
4873 options->rename_limit = diff_rename_limit_default;
4874 if (hexsz < options->abbrev)
4875 options->abbrev = hexsz; /* full */
4878 * It does not make sense to show the first hit we happened
4879 * to have found. It does not make sense not to return with
4880 * exit code in such a case either.
4882 if (options->flags.quick) {
4883 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4884 options->flags.exit_with_status = 1;
4887 options->diff_path_counter = 0;
4889 if (options->flags.follow_renames)
4890 diff_check_follow_pathspec(&options->pathspec, 1);
4892 if (!options->use_color || external_diff())
4893 options->color_moved = 0;
4895 if (options->filter_not) {
4896 if (!options->filter)
4897 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4898 options->filter &= ~options->filter_not;
4902 int parse_long_opt(const char *opt, const char **argv,
4903 const char **optarg)
4905 const char *arg = argv[0];
4906 if (!skip_prefix(arg, "--", &arg))
4907 return 0;
4908 if (!skip_prefix(arg, opt, &arg))
4909 return 0;
4910 if (*arg == '=') { /* stuck form: --option=value */
4911 *optarg = arg + 1;
4912 return 1;
4914 if (*arg != '\0')
4915 return 0;
4916 /* separate form: --option value */
4917 if (!argv[1])
4918 die("Option '--%s' requires a value", opt);
4919 *optarg = argv[1];
4920 return 2;
4923 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4925 struct diff_options *options = opt->value;
4926 int width = options->stat_width;
4927 int name_width = options->stat_name_width;
4928 int graph_width = options->stat_graph_width;
4929 int count = options->stat_count;
4930 char *end;
4932 BUG_ON_OPT_NEG(unset);
4934 if (!strcmp(opt->long_name, "stat")) {
4935 if (value) {
4936 width = strtoul(value, &end, 10);
4937 if (*end == ',')
4938 name_width = strtoul(end+1, &end, 10);
4939 if (*end == ',')
4940 count = strtoul(end+1, &end, 10);
4941 if (*end)
4942 return error(_("invalid --stat value: %s"), value);
4944 } else if (!strcmp(opt->long_name, "stat-width")) {
4945 width = strtoul(value, &end, 10);
4946 if (*end)
4947 return error(_("%s expects a numerical value"),
4948 opt->long_name);
4949 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4950 name_width = strtoul(value, &end, 10);
4951 if (*end)
4952 return error(_("%s expects a numerical value"),
4953 opt->long_name);
4954 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4955 graph_width = strtoul(value, &end, 10);
4956 if (*end)
4957 return error(_("%s expects a numerical value"),
4958 opt->long_name);
4959 } else if (!strcmp(opt->long_name, "stat-count")) {
4960 count = strtoul(value, &end, 10);
4961 if (*end)
4962 return error(_("%s expects a numerical value"),
4963 opt->long_name);
4964 } else
4965 BUG("%s should not get here", opt->long_name);
4967 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4968 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4969 options->stat_name_width = name_width;
4970 options->stat_graph_width = graph_width;
4971 options->stat_width = width;
4972 options->stat_count = count;
4973 return 0;
4976 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4978 struct strbuf errmsg = STRBUF_INIT;
4979 if (parse_dirstat_params(options, params, &errmsg))
4980 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4981 errmsg.buf);
4982 strbuf_release(&errmsg);
4984 * The caller knows a dirstat-related option is given from the command
4985 * line; allow it to say "return this_function();"
4987 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4988 options->output_format |= DIFF_FORMAT_DIRSTAT;
4989 return 1;
4992 static int diff_opt_diff_filter(const struct option *option,
4993 const char *optarg, int unset)
4995 struct diff_options *opt = option->value;
4996 int i, optch;
4998 BUG_ON_OPT_NEG(unset);
4999 prepare_filter_bits();
5001 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5002 unsigned int bit;
5003 int negate;
5005 if ('a' <= optch && optch <= 'z') {
5006 negate = 1;
5007 optch = toupper(optch);
5008 } else {
5009 negate = 0;
5012 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5013 if (!bit)
5014 return error(_("unknown change class '%c' in --diff-filter=%s"),
5015 optarg[i], optarg);
5016 if (negate)
5017 opt->filter_not |= bit;
5018 else
5019 opt->filter |= bit;
5021 return 0;
5024 static void enable_patch_output(int *fmt)
5026 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5027 *fmt |= DIFF_FORMAT_PATCH;
5030 static int diff_opt_ws_error_highlight(const struct option *option,
5031 const char *arg, int unset)
5033 struct diff_options *opt = option->value;
5034 int val = parse_ws_error_highlight(arg);
5036 BUG_ON_OPT_NEG(unset);
5037 if (val < 0)
5038 return error(_("unknown value after ws-error-highlight=%.*s"),
5039 -1 - val, arg);
5040 opt->ws_error_highlight = val;
5041 return 0;
5044 static int diff_opt_find_object(const struct option *option,
5045 const char *arg, int unset)
5047 struct diff_options *opt = option->value;
5048 struct object_id oid;
5050 BUG_ON_OPT_NEG(unset);
5051 if (repo_get_oid(the_repository, arg, &oid))
5052 return error(_("unable to resolve '%s'"), arg);
5054 if (!opt->objfind)
5055 CALLOC_ARRAY(opt->objfind, 1);
5057 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5058 opt->flags.recursive = 1;
5059 opt->flags.tree_in_recursive = 1;
5060 oidset_insert(opt->objfind, &oid);
5061 return 0;
5064 static int diff_opt_anchored(const struct option *opt,
5065 const char *arg, int unset)
5067 struct diff_options *options = opt->value;
5069 BUG_ON_OPT_NEG(unset);
5070 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5071 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5072 options->anchors_alloc);
5073 options->anchors[options->anchors_nr++] = xstrdup(arg);
5074 return 0;
5077 static int diff_opt_binary(const struct option *opt,
5078 const char *arg, int unset)
5080 struct diff_options *options = opt->value;
5082 BUG_ON_OPT_NEG(unset);
5083 BUG_ON_OPT_ARG(arg);
5084 enable_patch_output(&options->output_format);
5085 options->flags.binary = 1;
5086 return 0;
5089 static int diff_opt_break_rewrites(const struct option *opt,
5090 const char *arg, int unset)
5092 int *break_opt = opt->value;
5093 int opt1, opt2;
5095 BUG_ON_OPT_NEG(unset);
5096 if (!arg)
5097 arg = "";
5098 opt1 = parse_rename_score(&arg);
5099 if (*arg == 0)
5100 opt2 = 0;
5101 else if (*arg != '/')
5102 return error(_("%s expects <n>/<m> form"), opt->long_name);
5103 else {
5104 arg++;
5105 opt2 = parse_rename_score(&arg);
5107 if (*arg != 0)
5108 return error(_("%s expects <n>/<m> form"), opt->long_name);
5109 *break_opt = opt1 | (opt2 << 16);
5110 return 0;
5113 static int diff_opt_char(const struct option *opt,
5114 const char *arg, int unset)
5116 char *value = opt->value;
5118 BUG_ON_OPT_NEG(unset);
5119 if (arg[1])
5120 return error(_("%s expects a character, got '%s'"),
5121 opt->long_name, arg);
5122 *value = arg[0];
5123 return 0;
5126 static int diff_opt_color_moved(const struct option *opt,
5127 const char *arg, int unset)
5129 struct diff_options *options = opt->value;
5131 if (unset) {
5132 options->color_moved = COLOR_MOVED_NO;
5133 } else if (!arg) {
5134 if (diff_color_moved_default)
5135 options->color_moved = diff_color_moved_default;
5136 if (options->color_moved == COLOR_MOVED_NO)
5137 options->color_moved = COLOR_MOVED_DEFAULT;
5138 } else {
5139 int cm = parse_color_moved(arg);
5140 if (cm < 0)
5141 return error(_("bad --color-moved argument: %s"), arg);
5142 options->color_moved = cm;
5144 return 0;
5147 static int diff_opt_color_moved_ws(const struct option *opt,
5148 const char *arg, int unset)
5150 struct diff_options *options = opt->value;
5151 unsigned cm;
5153 if (unset) {
5154 options->color_moved_ws_handling = 0;
5155 return 0;
5158 cm = parse_color_moved_ws(arg);
5159 if (cm & COLOR_MOVED_WS_ERROR)
5160 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5161 options->color_moved_ws_handling = cm;
5162 return 0;
5165 static int diff_opt_color_words(const struct option *opt,
5166 const char *arg, int unset)
5168 struct diff_options *options = opt->value;
5170 BUG_ON_OPT_NEG(unset);
5171 options->use_color = 1;
5172 options->word_diff = DIFF_WORDS_COLOR;
5173 options->word_regex = arg;
5174 return 0;
5177 static int diff_opt_compact_summary(const struct option *opt,
5178 const char *arg, int unset)
5180 struct diff_options *options = opt->value;
5182 BUG_ON_OPT_ARG(arg);
5183 if (unset) {
5184 options->flags.stat_with_summary = 0;
5185 } else {
5186 options->flags.stat_with_summary = 1;
5187 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5188 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5190 return 0;
5193 static int diff_opt_diff_algorithm(const struct option *opt,
5194 const char *arg, int unset)
5196 struct diff_options *options = opt->value;
5198 BUG_ON_OPT_NEG(unset);
5200 if (set_diff_algorithm(options, arg))
5201 return error(_("option diff-algorithm accepts \"myers\", "
5202 "\"minimal\", \"patience\" and \"histogram\""));
5204 options->ignore_driver_algorithm = 1;
5206 return 0;
5209 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5210 const char *arg, int unset)
5212 struct diff_options *options = opt->value;
5214 BUG_ON_OPT_NEG(unset);
5215 BUG_ON_OPT_ARG(arg);
5217 if (set_diff_algorithm(options, opt->long_name))
5218 BUG("available diff algorithms include \"myers\", "
5219 "\"minimal\", \"patience\" and \"histogram\"");
5221 options->ignore_driver_algorithm = 1;
5223 return 0;
5226 static int diff_opt_dirstat(const struct option *opt,
5227 const char *arg, int unset)
5229 struct diff_options *options = opt->value;
5231 BUG_ON_OPT_NEG(unset);
5232 if (!strcmp(opt->long_name, "cumulative")) {
5233 if (arg)
5234 BUG("how come --cumulative take a value?");
5235 arg = "cumulative";
5236 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5237 parse_dirstat_opt(options, "files");
5238 parse_dirstat_opt(options, arg ? arg : "");
5239 return 0;
5242 static int diff_opt_find_copies(const struct option *opt,
5243 const char *arg, int unset)
5245 struct diff_options *options = opt->value;
5247 BUG_ON_OPT_NEG(unset);
5248 if (!arg)
5249 arg = "";
5250 options->rename_score = parse_rename_score(&arg);
5251 if (*arg != 0)
5252 return error(_("invalid argument to %s"), opt->long_name);
5254 if (options->detect_rename == DIFF_DETECT_COPY)
5255 options->flags.find_copies_harder = 1;
5256 else
5257 options->detect_rename = DIFF_DETECT_COPY;
5259 return 0;
5262 static int diff_opt_find_renames(const struct option *opt,
5263 const char *arg, int unset)
5265 struct diff_options *options = opt->value;
5267 BUG_ON_OPT_NEG(unset);
5268 if (!arg)
5269 arg = "";
5270 options->rename_score = parse_rename_score(&arg);
5271 if (*arg != 0)
5272 return error(_("invalid argument to %s"), opt->long_name);
5274 options->detect_rename = DIFF_DETECT_RENAME;
5275 return 0;
5278 static int diff_opt_follow(const struct option *opt,
5279 const char *arg, int unset)
5281 struct diff_options *options = opt->value;
5283 BUG_ON_OPT_ARG(arg);
5284 if (unset) {
5285 options->flags.follow_renames = 0;
5286 options->flags.default_follow_renames = 0;
5287 } else {
5288 options->flags.follow_renames = 1;
5290 return 0;
5293 static int diff_opt_ignore_submodules(const struct option *opt,
5294 const char *arg, int unset)
5296 struct diff_options *options = opt->value;
5298 BUG_ON_OPT_NEG(unset);
5299 if (!arg)
5300 arg = "all";
5301 options->flags.override_submodule_config = 1;
5302 handle_ignore_submodules_arg(options, arg);
5303 return 0;
5306 static int diff_opt_line_prefix(const struct option *opt,
5307 const char *optarg, int unset)
5309 struct diff_options *options = opt->value;
5311 BUG_ON_OPT_NEG(unset);
5312 options->line_prefix = optarg;
5313 options->line_prefix_length = strlen(options->line_prefix);
5314 graph_setup_line_prefix(options);
5315 return 0;
5318 static int diff_opt_no_prefix(const struct option *opt,
5319 const char *optarg, int unset)
5321 struct diff_options *options = opt->value;
5323 BUG_ON_OPT_NEG(unset);
5324 BUG_ON_OPT_ARG(optarg);
5325 diff_set_noprefix(options);
5326 return 0;
5329 static int diff_opt_default_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_default_prefix(options);
5337 return 0;
5340 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5341 const struct option *opt,
5342 const char *arg, int unset)
5344 struct diff_options *options = opt->value;
5345 char *path;
5347 BUG_ON_OPT_NEG(unset);
5348 path = prefix_filename(ctx->prefix, arg);
5349 options->file = xfopen(path, "w");
5350 options->close_file = 1;
5351 if (options->use_color != GIT_COLOR_ALWAYS)
5352 options->use_color = GIT_COLOR_NEVER;
5353 free(path);
5354 return 0;
5357 static int diff_opt_patience(const struct option *opt,
5358 const char *arg, int unset)
5360 struct diff_options *options = opt->value;
5361 int i;
5363 BUG_ON_OPT_NEG(unset);
5364 BUG_ON_OPT_ARG(arg);
5366 * Both --patience and --anchored use PATIENCE_DIFF
5367 * internally, so remove any anchors previously
5368 * specified.
5370 for (i = 0; i < options->anchors_nr; i++)
5371 free(options->anchors[i]);
5372 options->anchors_nr = 0;
5373 options->ignore_driver_algorithm = 1;
5375 return set_diff_algorithm(options, "patience");
5378 static int diff_opt_ignore_regex(const struct option *opt,
5379 const char *arg, int unset)
5381 struct diff_options *options = opt->value;
5382 regex_t *regex;
5384 BUG_ON_OPT_NEG(unset);
5385 regex = xmalloc(sizeof(*regex));
5386 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5387 return error(_("invalid regex given to -I: '%s'"), arg);
5388 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5389 options->ignore_regex_alloc);
5390 options->ignore_regex[options->ignore_regex_nr++] = regex;
5391 return 0;
5394 static int diff_opt_pickaxe_regex(const struct option *opt,
5395 const char *arg, int unset)
5397 struct diff_options *options = opt->value;
5399 BUG_ON_OPT_NEG(unset);
5400 options->pickaxe = arg;
5401 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5402 return 0;
5405 static int diff_opt_pickaxe_string(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_S;
5413 return 0;
5416 static int diff_opt_relative(const struct option *opt,
5417 const char *arg, int unset)
5419 struct diff_options *options = opt->value;
5421 options->flags.relative_name = !unset;
5422 if (arg)
5423 options->prefix = arg;
5424 return 0;
5427 static int diff_opt_submodule(const struct option *opt,
5428 const char *arg, int unset)
5430 struct diff_options *options = opt->value;
5432 BUG_ON_OPT_NEG(unset);
5433 if (!arg)
5434 arg = "log";
5435 if (parse_submodule_params(options, arg))
5436 return error(_("failed to parse --submodule option parameter: '%s'"),
5437 arg);
5438 return 0;
5441 static int diff_opt_textconv(const struct option *opt,
5442 const char *arg, int unset)
5444 struct diff_options *options = opt->value;
5446 BUG_ON_OPT_ARG(arg);
5447 if (unset) {
5448 options->flags.allow_textconv = 0;
5449 } else {
5450 options->flags.allow_textconv = 1;
5451 options->flags.textconv_set_via_cmdline = 1;
5453 return 0;
5456 static int diff_opt_unified(const struct option *opt,
5457 const char *arg, int unset)
5459 struct diff_options *options = opt->value;
5460 char *s;
5462 BUG_ON_OPT_NEG(unset);
5464 if (arg) {
5465 options->context = strtol(arg, &s, 10);
5466 if (*s)
5467 return error(_("%s expects a numerical value"), "--unified");
5469 enable_patch_output(&options->output_format);
5471 return 0;
5474 static int diff_opt_word_diff(const struct option *opt,
5475 const char *arg, int unset)
5477 struct diff_options *options = opt->value;
5479 BUG_ON_OPT_NEG(unset);
5480 if (arg) {
5481 if (!strcmp(arg, "plain"))
5482 options->word_diff = DIFF_WORDS_PLAIN;
5483 else if (!strcmp(arg, "color")) {
5484 options->use_color = 1;
5485 options->word_diff = DIFF_WORDS_COLOR;
5487 else if (!strcmp(arg, "porcelain"))
5488 options->word_diff = DIFF_WORDS_PORCELAIN;
5489 else if (!strcmp(arg, "none"))
5490 options->word_diff = DIFF_WORDS_NONE;
5491 else
5492 return error(_("bad --word-diff argument: %s"), arg);
5493 } else {
5494 if (options->word_diff == DIFF_WORDS_NONE)
5495 options->word_diff = DIFF_WORDS_PLAIN;
5497 return 0;
5500 static int diff_opt_word_diff_regex(const struct option *opt,
5501 const char *arg, int unset)
5503 struct diff_options *options = opt->value;
5505 BUG_ON_OPT_NEG(unset);
5506 if (options->word_diff == DIFF_WORDS_NONE)
5507 options->word_diff = DIFF_WORDS_PLAIN;
5508 options->word_regex = arg;
5509 return 0;
5512 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5514 struct diff_options *options = opt->value;
5516 BUG_ON_OPT_NEG(unset);
5517 if (!strcmp(opt->long_name, "skip-to"))
5518 options->skip_instead_of_rotate = 1;
5519 else
5520 options->skip_instead_of_rotate = 0;
5521 options->rotate_to = arg;
5522 return 0;
5525 struct option *add_diff_options(const struct option *opts,
5526 struct diff_options *options)
5528 struct option parseopts[] = {
5529 OPT_GROUP(N_("Diff output format options")),
5530 OPT_BITOP('p', "patch", &options->output_format,
5531 N_("generate patch"),
5532 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5533 OPT_SET_INT('s', "no-patch", &options->output_format,
5534 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5535 OPT_BITOP('u', NULL, &options->output_format,
5536 N_("generate patch"),
5537 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5538 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5539 N_("generate diffs with <n> lines context"),
5540 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5541 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5542 N_("generate diffs with <n> lines context")),
5543 OPT_BITOP(0, "raw", &options->output_format,
5544 N_("generate the diff in raw format"),
5545 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5546 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5547 N_("synonym for '-p --raw'"),
5548 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5549 DIFF_FORMAT_NO_OUTPUT),
5550 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5551 N_("synonym for '-p --stat'"),
5552 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5553 DIFF_FORMAT_NO_OUTPUT),
5554 OPT_BITOP(0, "numstat", &options->output_format,
5555 N_("machine friendly --stat"),
5556 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5557 OPT_BITOP(0, "shortstat", &options->output_format,
5558 N_("output only the last line of --stat"),
5559 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5560 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5561 N_("output the distribution of relative amount of changes for each sub-directory"),
5562 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5563 diff_opt_dirstat),
5564 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5565 N_("synonym for --dirstat=cumulative"),
5566 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5567 diff_opt_dirstat),
5568 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5569 N_("synonym for --dirstat=files,param1,param2..."),
5570 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5571 diff_opt_dirstat),
5572 OPT_BIT_F(0, "check", &options->output_format,
5573 N_("warn if changes introduce conflict markers or whitespace errors"),
5574 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5575 OPT_BITOP(0, "summary", &options->output_format,
5576 N_("condensed summary such as creations, renames and mode changes"),
5577 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5578 OPT_BIT_F(0, "name-only", &options->output_format,
5579 N_("show only names of changed files"),
5580 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5581 OPT_BIT_F(0, "name-status", &options->output_format,
5582 N_("show only names and status of changed files"),
5583 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5584 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5585 N_("generate diffstat"),
5586 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5587 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5588 N_("generate diffstat with a given width"),
5589 PARSE_OPT_NONEG, diff_opt_stat),
5590 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5591 N_("generate diffstat with a given name width"),
5592 PARSE_OPT_NONEG, diff_opt_stat),
5593 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5594 N_("generate diffstat with a given graph width"),
5595 PARSE_OPT_NONEG, diff_opt_stat),
5596 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5597 N_("generate diffstat with limited lines"),
5598 PARSE_OPT_NONEG, diff_opt_stat),
5599 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5600 N_("generate compact summary in diffstat"),
5601 PARSE_OPT_NOARG, diff_opt_compact_summary),
5602 OPT_CALLBACK_F(0, "binary", options, NULL,
5603 N_("output a binary diff that can be applied"),
5604 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5605 OPT_BOOL(0, "full-index", &options->flags.full_index,
5606 N_("show full pre- and post-image object names on the \"index\" lines")),
5607 OPT_COLOR_FLAG(0, "color", &options->use_color,
5608 N_("show colored diff")),
5609 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5610 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5611 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5612 OPT_SET_INT('z', NULL, &options->line_termination,
5613 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5615 OPT__ABBREV(&options->abbrev),
5616 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5617 N_("show the given source prefix instead of \"a/\""),
5618 PARSE_OPT_NONEG),
5619 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5620 N_("show the given destination prefix instead of \"b/\""),
5621 PARSE_OPT_NONEG),
5622 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5623 N_("prepend an additional prefix to every line of output"),
5624 PARSE_OPT_NONEG, diff_opt_line_prefix),
5625 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5626 N_("do not show any source or destination prefix"),
5627 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5628 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5629 N_("use default prefixes a/ and b/"),
5630 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5631 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5632 N_("show context between diff hunks up to the specified number of lines"),
5633 PARSE_OPT_NONEG),
5634 OPT_CALLBACK_F(0, "output-indicator-new",
5635 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5636 N_("<char>"),
5637 N_("specify the character to indicate a new line instead of '+'"),
5638 PARSE_OPT_NONEG, diff_opt_char),
5639 OPT_CALLBACK_F(0, "output-indicator-old",
5640 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5641 N_("<char>"),
5642 N_("specify the character to indicate an old line instead of '-'"),
5643 PARSE_OPT_NONEG, diff_opt_char),
5644 OPT_CALLBACK_F(0, "output-indicator-context",
5645 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5646 N_("<char>"),
5647 N_("specify the character to indicate a context instead of ' '"),
5648 PARSE_OPT_NONEG, diff_opt_char),
5650 OPT_GROUP(N_("Diff rename options")),
5651 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5652 N_("break complete rewrite changes into pairs of delete and create"),
5653 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5654 diff_opt_break_rewrites),
5655 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5656 N_("detect renames"),
5657 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5658 diff_opt_find_renames),
5659 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5660 N_("omit the preimage for deletes"),
5661 1, PARSE_OPT_NONEG),
5662 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5663 N_("detect copies"),
5664 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5665 diff_opt_find_copies),
5666 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5667 N_("use unmodified files as source to find copies")),
5668 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5669 N_("disable rename detection"),
5670 0, PARSE_OPT_NONEG),
5671 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5672 N_("use empty blobs as rename source")),
5673 OPT_CALLBACK_F(0, "follow", options, NULL,
5674 N_("continue listing the history of a file beyond renames"),
5675 PARSE_OPT_NOARG, diff_opt_follow),
5676 OPT_INTEGER('l', NULL, &options->rename_limit,
5677 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5679 OPT_GROUP(N_("Diff algorithm options")),
5680 OPT_CALLBACK_F(0, "minimal", options, NULL,
5681 N_("produce the smallest possible diff"),
5682 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5683 diff_opt_diff_algorithm_no_arg),
5684 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5685 N_("ignore whitespace when comparing lines"),
5686 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5687 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5688 N_("ignore changes in amount of whitespace"),
5689 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5690 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5691 N_("ignore changes in whitespace at EOL"),
5692 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5693 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5694 N_("ignore carrier-return at the end of line"),
5695 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5696 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5697 N_("ignore changes whose lines are all blank"),
5698 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5699 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5700 N_("ignore changes whose all lines match <regex>"),
5701 0, diff_opt_ignore_regex),
5702 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5703 N_("heuristic to shift diff hunk boundaries for easy reading"),
5704 XDF_INDENT_HEURISTIC),
5705 OPT_CALLBACK_F(0, "patience", options, NULL,
5706 N_("generate diff using the \"patience diff\" algorithm"),
5707 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5708 diff_opt_patience),
5709 OPT_CALLBACK_F(0, "histogram", options, NULL,
5710 N_("generate diff using the \"histogram diff\" algorithm"),
5711 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5712 diff_opt_diff_algorithm_no_arg),
5713 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5714 N_("choose a diff algorithm"),
5715 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5716 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5717 N_("generate diff using the \"anchored diff\" algorithm"),
5718 PARSE_OPT_NONEG, diff_opt_anchored),
5719 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5720 N_("show word diff, using <mode> to delimit changed words"),
5721 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5722 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5723 N_("use <regex> to decide what a word is"),
5724 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5725 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5726 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5727 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5728 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5729 N_("moved lines of code are colored differently"),
5730 PARSE_OPT_OPTARG, diff_opt_color_moved),
5731 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5732 N_("how white spaces are ignored in --color-moved"),
5733 0, diff_opt_color_moved_ws),
5735 OPT_GROUP(N_("Other diff options")),
5736 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5737 N_("when run from subdir, exclude changes outside and show relative paths"),
5738 PARSE_OPT_OPTARG,
5739 diff_opt_relative),
5740 OPT_BOOL('a', "text", &options->flags.text,
5741 N_("treat all files as text")),
5742 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5743 N_("swap two inputs, reverse the diff")),
5744 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5745 N_("exit with 1 if there were differences, 0 otherwise")),
5746 OPT_BOOL(0, "quiet", &options->flags.quick,
5747 N_("disable all output of the program")),
5748 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5749 N_("allow an external diff helper to be executed")),
5750 OPT_CALLBACK_F(0, "textconv", options, NULL,
5751 N_("run external text conversion filters when comparing binary files"),
5752 PARSE_OPT_NOARG, diff_opt_textconv),
5753 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5754 N_("ignore changes to submodules in the diff generation"),
5755 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5756 diff_opt_ignore_submodules),
5757 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5758 N_("specify how differences in submodules are shown"),
5759 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5760 diff_opt_submodule),
5761 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5762 N_("hide 'git add -N' entries from the index"),
5763 1, PARSE_OPT_NONEG),
5764 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5765 N_("treat 'git add -N' entries as real in the index"),
5766 0, PARSE_OPT_NONEG),
5767 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5768 N_("look for differences that change the number of occurrences of the specified string"),
5769 0, diff_opt_pickaxe_string),
5770 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5771 N_("look for differences that change the number of occurrences of the specified regex"),
5772 0, diff_opt_pickaxe_regex),
5773 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5774 N_("show all changes in the changeset with -S or -G"),
5775 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5776 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5777 N_("treat <string> in -S as extended POSIX regular expression"),
5778 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5779 OPT_FILENAME('O', NULL, &options->orderfile,
5780 N_("control the order in which files appear in the output")),
5781 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5782 N_("show the change in the specified path first"),
5783 PARSE_OPT_NONEG, diff_opt_rotate_to),
5784 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5785 N_("skip the output to the specified path"),
5786 PARSE_OPT_NONEG, diff_opt_rotate_to),
5787 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5788 N_("look for differences that change the number of occurrences of the specified object"),
5789 PARSE_OPT_NONEG, diff_opt_find_object),
5790 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5791 N_("select files by diff type"),
5792 PARSE_OPT_NONEG, diff_opt_diff_filter),
5793 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5794 N_("output to a specific file"),
5795 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5797 OPT_END()
5800 return parse_options_concat(opts, parseopts);
5803 int diff_opt_parse(struct diff_options *options,
5804 const char **av, int ac, const char *prefix)
5806 struct option no_options[] = { OPT_END() };
5807 struct option *parseopts = add_diff_options(no_options, options);
5809 if (!prefix)
5810 prefix = "";
5812 ac = parse_options(ac, av, prefix, parseopts, NULL,
5813 PARSE_OPT_KEEP_DASHDASH |
5814 PARSE_OPT_KEEP_UNKNOWN_OPT |
5815 PARSE_OPT_NO_INTERNAL_HELP |
5816 PARSE_OPT_ONE_SHOT |
5817 PARSE_OPT_STOP_AT_NON_OPTION);
5818 free(parseopts);
5820 return ac;
5823 int parse_rename_score(const char **cp_p)
5825 unsigned long num, scale;
5826 int ch, dot;
5827 const char *cp = *cp_p;
5829 num = 0;
5830 scale = 1;
5831 dot = 0;
5832 for (;;) {
5833 ch = *cp;
5834 if ( !dot && ch == '.' ) {
5835 scale = 1;
5836 dot = 1;
5837 } else if ( ch == '%' ) {
5838 scale = dot ? scale*100 : 100;
5839 cp++; /* % is always at the end */
5840 break;
5841 } else if ( ch >= '0' && ch <= '9' ) {
5842 if ( scale < 100000 ) {
5843 scale *= 10;
5844 num = (num*10) + (ch-'0');
5846 } else {
5847 break;
5849 cp++;
5851 *cp_p = cp;
5853 /* user says num divided by scale and we say internally that
5854 * is MAX_SCORE * num / scale.
5856 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5859 struct diff_queue_struct diff_queued_diff;
5861 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5863 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5864 queue->queue[queue->nr++] = dp;
5867 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5868 struct diff_filespec *one,
5869 struct diff_filespec *two)
5871 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5872 dp->one = one;
5873 dp->two = two;
5874 if (queue)
5875 diff_q(queue, dp);
5876 return dp;
5879 void diff_free_filepair(struct diff_filepair *p)
5881 free_filespec(p->one);
5882 free_filespec(p->two);
5883 free(p);
5886 void diff_free_queue(struct diff_queue_struct *q)
5888 for (int i = 0; i < q->nr; i++)
5889 diff_free_filepair(q->queue[i]);
5890 free(q->queue);
5893 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5895 int abblen;
5896 const char *abbrev;
5898 /* Do we want all 40 hex characters? */
5899 if (len == the_hash_algo->hexsz)
5900 return oid_to_hex(oid);
5902 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5903 abbrev = diff_abbrev_oid(oid, len);
5905 if (!print_sha1_ellipsis())
5906 return abbrev;
5908 abblen = strlen(abbrev);
5911 * In well-behaved cases, where the abbreviated result is the
5912 * same as the requested length, append three dots after the
5913 * abbreviation (hence the whole logic is limited to the case
5914 * where abblen < 37); when the actual abbreviated result is a
5915 * bit longer than the requested length, we reduce the number
5916 * of dots so that they match the well-behaved ones. However,
5917 * if the actual abbreviation is longer than the requested
5918 * length by more than three, we give up on aligning, and add
5919 * three dots anyway, to indicate that the output is not the
5920 * full object name. Yes, this may be suboptimal, but this
5921 * appears only in "diff --raw --abbrev" output and it is not
5922 * worth the effort to change it now. Note that this would
5923 * likely to work fine when the automatic sizing of default
5924 * abbreviation length is used--we would be fed -1 in "len" in
5925 * that case, and will end up always appending three-dots, but
5926 * the automatic sizing is supposed to give abblen that ensures
5927 * uniqueness across all objects (statistically speaking).
5929 if (abblen < the_hash_algo->hexsz - 3) {
5930 static char hex[GIT_MAX_HEXSZ + 1];
5931 if (len < abblen && abblen <= len + 2)
5932 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5933 else
5934 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5935 return hex;
5938 return oid_to_hex(oid);
5941 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5943 int line_termination = opt->line_termination;
5944 int inter_name_termination = line_termination ? '\t' : '\0';
5946 fprintf(opt->file, "%s", diff_line_prefix(opt));
5947 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5948 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5949 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5950 fprintf(opt->file, "%s ",
5951 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5953 if (p->score) {
5954 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5955 inter_name_termination);
5956 } else {
5957 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5960 if (p->status == DIFF_STATUS_COPIED ||
5961 p->status == DIFF_STATUS_RENAMED) {
5962 const char *name_a, *name_b;
5963 name_a = p->one->path;
5964 name_b = p->two->path;
5965 strip_prefix(opt->prefix_length, &name_a, &name_b);
5966 write_name_quoted(name_a, opt->file, inter_name_termination);
5967 write_name_quoted(name_b, opt->file, line_termination);
5968 } else {
5969 const char *name_a, *name_b;
5970 name_a = p->one->mode ? p->one->path : p->two->path;
5971 name_b = NULL;
5972 strip_prefix(opt->prefix_length, &name_a, &name_b);
5973 write_name_quoted(name_a, opt->file, line_termination);
5977 int diff_unmodified_pair(struct diff_filepair *p)
5979 /* This function is written stricter than necessary to support
5980 * the currently implemented transformers, but the idea is to
5981 * let transformers to produce diff_filepairs any way they want,
5982 * and filter and clean them up here before producing the output.
5984 struct diff_filespec *one = p->one, *two = p->two;
5986 if (DIFF_PAIR_UNMERGED(p))
5987 return 0; /* unmerged is interesting */
5989 /* deletion, addition, mode or type change
5990 * and rename are all interesting.
5992 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5993 DIFF_PAIR_MODE_CHANGED(p) ||
5994 strcmp(one->path, two->path))
5995 return 0;
5997 /* both are valid and point at the same path. that is, we are
5998 * dealing with a change.
6000 if (one->oid_valid && two->oid_valid &&
6001 oideq(&one->oid, &two->oid) &&
6002 !one->dirty_submodule && !two->dirty_submodule)
6003 return 1; /* no change */
6004 if (!one->oid_valid && !two->oid_valid)
6005 return 1; /* both look at the same file on the filesystem. */
6006 return 0;
6009 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6011 int include_conflict_headers =
6012 (additional_headers(o, p->one->path) &&
6013 !o->pickaxe_opts &&
6014 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6017 * Check if we can return early without showing a diff. Note that
6018 * diff_filepair only stores {oid, path, mode, is_valid}
6019 * information for each path, and thus diff_unmodified_pair() only
6020 * considers those bits of info. However, we do not want pairs
6021 * created by create_filepairs_for_header_only_notifications()
6022 * (which always look like unmodified pairs) to be ignored, so
6023 * return early if both p is unmodified AND we don't want to
6024 * include_conflict_headers.
6026 if (diff_unmodified_pair(p) && !include_conflict_headers)
6027 return;
6029 /* Actually, we can also return early to avoid showing tree diffs */
6030 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6031 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6032 return;
6034 run_diff(p, o);
6037 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6038 struct diffstat_t *diffstat)
6040 if (diff_unmodified_pair(p))
6041 return;
6043 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6044 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6045 return; /* no useful stat for tree diffs */
6047 run_diffstat(p, o, diffstat);
6050 static void diff_flush_checkdiff(struct diff_filepair *p,
6051 struct diff_options *o)
6053 if (diff_unmodified_pair(p))
6054 return;
6056 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6057 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6058 return; /* nothing to check in tree diffs */
6060 run_checkdiff(p, o);
6063 int diff_queue_is_empty(struct diff_options *o)
6065 struct diff_queue_struct *q = &diff_queued_diff;
6066 int i;
6067 int include_conflict_headers =
6068 (o->additional_path_headers &&
6069 strmap_get_size(o->additional_path_headers) &&
6070 !o->pickaxe_opts &&
6071 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6073 if (include_conflict_headers)
6074 return 0;
6076 for (i = 0; i < q->nr; i++)
6077 if (!diff_unmodified_pair(q->queue[i]))
6078 return 0;
6079 return 1;
6082 #if DIFF_DEBUG
6083 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6085 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6086 x, one ? one : "",
6087 s->path,
6088 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6089 s->mode,
6090 s->oid_valid ? oid_to_hex(&s->oid) : "");
6091 fprintf(stderr, "queue[%d] %s size %lu\n",
6092 x, one ? one : "",
6093 s->size);
6096 void diff_debug_filepair(const struct diff_filepair *p, int i)
6098 diff_debug_filespec(p->one, i, "one");
6099 diff_debug_filespec(p->two, i, "two");
6100 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6101 p->score, p->status ? p->status : '?',
6102 p->one->rename_used, p->broken_pair);
6105 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6107 int i;
6108 if (msg)
6109 fprintf(stderr, "%s\n", msg);
6110 fprintf(stderr, "q->nr = %d\n", q->nr);
6111 for (i = 0; i < q->nr; i++) {
6112 struct diff_filepair *p = q->queue[i];
6113 diff_debug_filepair(p, i);
6116 #endif
6118 static void diff_resolve_rename_copy(void)
6120 int i;
6121 struct diff_filepair *p;
6122 struct diff_queue_struct *q = &diff_queued_diff;
6124 diff_debug_queue("resolve-rename-copy", q);
6126 for (i = 0; i < q->nr; i++) {
6127 p = q->queue[i];
6128 p->status = 0; /* undecided */
6129 if (DIFF_PAIR_UNMERGED(p))
6130 p->status = DIFF_STATUS_UNMERGED;
6131 else if (!DIFF_FILE_VALID(p->one))
6132 p->status = DIFF_STATUS_ADDED;
6133 else if (!DIFF_FILE_VALID(p->two))
6134 p->status = DIFF_STATUS_DELETED;
6135 else if (DIFF_PAIR_TYPE_CHANGED(p))
6136 p->status = DIFF_STATUS_TYPE_CHANGED;
6138 /* from this point on, we are dealing with a pair
6139 * whose both sides are valid and of the same type, i.e.
6140 * either in-place edit or rename/copy edit.
6142 else if (DIFF_PAIR_RENAME(p)) {
6144 * A rename might have re-connected a broken
6145 * pair up, causing the pathnames to be the
6146 * same again. If so, that's not a rename at
6147 * all, just a modification..
6149 * Otherwise, see if this source was used for
6150 * multiple renames, in which case we decrement
6151 * the count, and call it a copy.
6153 if (!strcmp(p->one->path, p->two->path))
6154 p->status = DIFF_STATUS_MODIFIED;
6155 else if (--p->one->rename_used > 0)
6156 p->status = DIFF_STATUS_COPIED;
6157 else
6158 p->status = DIFF_STATUS_RENAMED;
6160 else if (!oideq(&p->one->oid, &p->two->oid) ||
6161 p->one->mode != p->two->mode ||
6162 p->one->dirty_submodule ||
6163 p->two->dirty_submodule ||
6164 is_null_oid(&p->one->oid))
6165 p->status = DIFF_STATUS_MODIFIED;
6166 else {
6167 /* This is a "no-change" entry and should not
6168 * happen anymore, but prepare for broken callers.
6170 error("feeding unmodified %s to diffcore",
6171 p->one->path);
6172 p->status = DIFF_STATUS_UNKNOWN;
6175 diff_debug_queue("resolve-rename-copy done", q);
6178 static int check_pair_status(struct diff_filepair *p)
6180 switch (p->status) {
6181 case DIFF_STATUS_UNKNOWN:
6182 return 0;
6183 case 0:
6184 die("internal error in diff-resolve-rename-copy");
6185 default:
6186 return 1;
6190 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6192 int fmt = opt->output_format;
6194 if (fmt & DIFF_FORMAT_CHECKDIFF)
6195 diff_flush_checkdiff(p, opt);
6196 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6197 diff_flush_raw(p, opt);
6198 else if (fmt & DIFF_FORMAT_NAME) {
6199 const char *name_a, *name_b;
6200 name_a = p->two->path;
6201 name_b = NULL;
6202 strip_prefix(opt->prefix_length, &name_a, &name_b);
6203 fprintf(opt->file, "%s", diff_line_prefix(opt));
6204 write_name_quoted(name_a, opt->file, opt->line_termination);
6208 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6210 struct strbuf sb = STRBUF_INIT;
6211 if (fs->mode)
6212 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6213 else
6214 strbuf_addf(&sb, " %s ", newdelete);
6216 quote_c_style(fs->path, &sb, NULL, 0);
6217 strbuf_addch(&sb, '\n');
6218 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6219 sb.buf, sb.len, 0);
6220 strbuf_release(&sb);
6223 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6224 int show_name)
6226 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6227 struct strbuf sb = STRBUF_INIT;
6228 strbuf_addf(&sb, " mode change %06o => %06o",
6229 p->one->mode, p->two->mode);
6230 if (show_name) {
6231 strbuf_addch(&sb, ' ');
6232 quote_c_style(p->two->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);
6241 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6242 struct diff_filepair *p)
6244 struct strbuf sb = STRBUF_INIT;
6245 struct strbuf names = STRBUF_INIT;
6247 pprint_rename(&names, p->one->path, p->two->path);
6248 strbuf_addf(&sb, " %s %s (%d%%)\n",
6249 renamecopy, names.buf, similarity_index(p));
6250 strbuf_release(&names);
6251 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6252 sb.buf, sb.len, 0);
6253 show_mode_change(opt, p, 0);
6254 strbuf_release(&sb);
6257 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6259 switch(p->status) {
6260 case DIFF_STATUS_DELETED:
6261 show_file_mode_name(opt, "delete", p->one);
6262 break;
6263 case DIFF_STATUS_ADDED:
6264 show_file_mode_name(opt, "create", p->two);
6265 break;
6266 case DIFF_STATUS_COPIED:
6267 show_rename_copy(opt, "copy", p);
6268 break;
6269 case DIFF_STATUS_RENAMED:
6270 show_rename_copy(opt, "rename", p);
6271 break;
6272 default:
6273 if (p->score) {
6274 struct strbuf sb = STRBUF_INIT;
6275 strbuf_addstr(&sb, " rewrite ");
6276 quote_c_style(p->two->path, &sb, NULL, 0);
6277 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6278 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6279 sb.buf, sb.len, 0);
6280 strbuf_release(&sb);
6282 show_mode_change(opt, p, !p->score);
6283 break;
6287 struct patch_id_t {
6288 git_hash_ctx *ctx;
6289 int patchlen;
6292 static int remove_space(char *line, int len)
6294 int i;
6295 char *dst = line;
6296 unsigned char c;
6298 for (i = 0; i < len; i++)
6299 if (!isspace((c = line[i])))
6300 *dst++ = c;
6302 return dst - line;
6305 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6307 unsigned char hash[GIT_MAX_RAWSZ];
6308 unsigned short carry = 0;
6309 int i;
6311 the_hash_algo->final_fn(hash, ctx);
6312 the_hash_algo->init_fn(ctx);
6313 /* 20-byte sum, with carry */
6314 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6315 carry += result->hash[i] + hash[i];
6316 result->hash[i] = carry;
6317 carry >>= 8;
6321 static int patch_id_consume(void *priv, char *line, unsigned long len)
6323 struct patch_id_t *data = priv;
6324 int new_len;
6326 if (len > 12 && starts_with(line, "\\ "))
6327 return 0;
6328 new_len = remove_space(line, len);
6330 the_hash_algo->update_fn(data->ctx, line, new_len);
6331 data->patchlen += new_len;
6332 return 0;
6335 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6337 the_hash_algo->update_fn(ctx, str, strlen(str));
6340 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6342 /* large enough for 2^32 in octal */
6343 char buf[12];
6344 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6345 the_hash_algo->update_fn(ctx, buf, len);
6348 /* returns 0 upon success, and writes result into oid */
6349 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6351 struct diff_queue_struct *q = &diff_queued_diff;
6352 int i;
6353 git_hash_ctx ctx;
6354 struct patch_id_t data;
6356 the_hash_algo->init_fn(&ctx);
6357 memset(&data, 0, sizeof(struct patch_id_t));
6358 data.ctx = &ctx;
6359 oidclr(oid);
6361 for (i = 0; i < q->nr; i++) {
6362 xpparam_t xpp;
6363 xdemitconf_t xecfg;
6364 mmfile_t mf1, mf2;
6365 struct diff_filepair *p = q->queue[i];
6366 int len1, len2;
6368 memset(&xpp, 0, sizeof(xpp));
6369 memset(&xecfg, 0, sizeof(xecfg));
6370 if (p->status == 0)
6371 return error("internal diff status error");
6372 if (p->status == DIFF_STATUS_UNKNOWN)
6373 continue;
6374 if (diff_unmodified_pair(p))
6375 continue;
6376 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6377 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6378 continue;
6379 if (DIFF_PAIR_UNMERGED(p))
6380 continue;
6382 diff_fill_oid_info(p->one, options->repo->index);
6383 diff_fill_oid_info(p->two, options->repo->index);
6385 len1 = remove_space(p->one->path, strlen(p->one->path));
6386 len2 = remove_space(p->two->path, strlen(p->two->path));
6387 patch_id_add_string(&ctx, "diff--git");
6388 patch_id_add_string(&ctx, "a/");
6389 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6390 patch_id_add_string(&ctx, "b/");
6391 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6393 if (p->one->mode == 0) {
6394 patch_id_add_string(&ctx, "newfilemode");
6395 patch_id_add_mode(&ctx, p->two->mode);
6396 } else if (p->two->mode == 0) {
6397 patch_id_add_string(&ctx, "deletedfilemode");
6398 patch_id_add_mode(&ctx, p->one->mode);
6399 } else if (p->one->mode != p->two->mode) {
6400 patch_id_add_string(&ctx, "oldmode");
6401 patch_id_add_mode(&ctx, p->one->mode);
6402 patch_id_add_string(&ctx, "newmode");
6403 patch_id_add_mode(&ctx, p->two->mode);
6406 if (diff_header_only) {
6407 /* don't do anything since we're only populating header info */
6408 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6409 diff_filespec_is_binary(options->repo, p->two)) {
6410 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6411 the_hash_algo->hexsz);
6412 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6413 the_hash_algo->hexsz);
6414 } else {
6415 if (p->one->mode == 0) {
6416 patch_id_add_string(&ctx, "---/dev/null");
6417 patch_id_add_string(&ctx, "+++b/");
6418 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6419 } else if (p->two->mode == 0) {
6420 patch_id_add_string(&ctx, "---a/");
6421 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6422 patch_id_add_string(&ctx, "+++/dev/null");
6423 } else {
6424 patch_id_add_string(&ctx, "---a/");
6425 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6426 patch_id_add_string(&ctx, "+++b/");
6427 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6430 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6431 fill_mmfile(options->repo, &mf2, p->two) < 0)
6432 return error("unable to read files to diff");
6433 xpp.flags = 0;
6434 xecfg.ctxlen = 3;
6435 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6436 if (xdi_diff_outf(&mf1, &mf2, NULL,
6437 patch_id_consume, &data, &xpp, &xecfg))
6438 return error("unable to generate patch-id diff for %s",
6439 p->one->path);
6441 flush_one_hunk(oid, &ctx);
6444 return 0;
6447 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6449 struct diff_queue_struct *q = &diff_queued_diff;
6450 int result = diff_get_patch_id(options, oid, diff_header_only);
6452 diff_free_queue(q);
6453 DIFF_QUEUE_CLEAR(q);
6455 return result;
6458 static int is_summary_empty(const struct diff_queue_struct *q)
6460 int i;
6462 for (i = 0; i < q->nr; i++) {
6463 const struct diff_filepair *p = q->queue[i];
6465 switch (p->status) {
6466 case DIFF_STATUS_DELETED:
6467 case DIFF_STATUS_ADDED:
6468 case DIFF_STATUS_COPIED:
6469 case DIFF_STATUS_RENAMED:
6470 return 0;
6471 default:
6472 if (p->score)
6473 return 0;
6474 if (p->one->mode && p->two->mode &&
6475 p->one->mode != p->two->mode)
6476 return 0;
6477 break;
6480 return 1;
6483 static const char rename_limit_warning[] =
6484 N_("exhaustive rename detection was skipped due to too many files.");
6486 static const char degrade_cc_to_c_warning[] =
6487 N_("only found copies from modified paths due to too many files.");
6489 static const char rename_limit_advice[] =
6490 N_("you may want to set your %s variable to at least "
6491 "%d and retry the command.");
6493 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6495 fflush(stdout);
6496 if (degraded_cc)
6497 warning(_(degrade_cc_to_c_warning));
6498 else if (needed)
6499 warning(_(rename_limit_warning));
6500 else
6501 return;
6502 if (0 < needed)
6503 warning(_(rename_limit_advice), varname, needed);
6506 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6508 struct strset present;
6509 struct diff_queue_struct *q = &diff_queued_diff;
6510 struct hashmap_iter iter;
6511 struct strmap_entry *e;
6512 int i;
6514 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6517 * Find out which paths exist in diff_queued_diff, preferring
6518 * one->path for any pair that has multiple paths.
6520 for (i = 0; i < q->nr; i++) {
6521 struct diff_filepair *p = q->queue[i];
6522 char *path = p->one->path ? p->one->path : p->two->path;
6524 if (strmap_contains(o->additional_path_headers, path))
6525 strset_add(&present, path);
6529 * Loop over paths in additional_path_headers; for each NOT already
6530 * in diff_queued_diff, create a synthetic filepair and insert that
6531 * into diff_queued_diff.
6533 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6534 if (!strset_contains(&present, e->key)) {
6535 struct diff_filespec *one, *two;
6536 struct diff_filepair *p;
6538 one = alloc_filespec(e->key);
6539 two = alloc_filespec(e->key);
6540 fill_filespec(one, null_oid(), 0, 0);
6541 fill_filespec(two, null_oid(), 0, 0);
6542 p = diff_queue(q, one, two);
6543 p->status = DIFF_STATUS_MODIFIED;
6547 /* Re-sort the filepairs */
6548 diffcore_fix_diff_index();
6550 /* Cleanup */
6551 strset_clear(&present);
6554 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6556 int i;
6557 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6558 struct diff_queue_struct *q = &diff_queued_diff;
6560 if (WSEH_NEW & WS_RULE_MASK)
6561 BUG("WS rules bit mask overlaps with diff symbol flags");
6563 if (o->color_moved)
6564 o->emitted_symbols = &esm;
6566 if (o->additional_path_headers)
6567 create_filepairs_for_header_only_notifications(o);
6569 for (i = 0; i < q->nr; i++) {
6570 struct diff_filepair *p = q->queue[i];
6571 if (check_pair_status(p))
6572 diff_flush_patch(p, o);
6575 if (o->emitted_symbols) {
6576 if (o->color_moved) {
6577 struct mem_pool entry_pool;
6578 struct moved_entry_list *entry_list;
6580 mem_pool_init(&entry_pool, 1024 * 1024);
6581 entry_list = add_lines_to_move_detection(o,
6582 &entry_pool);
6583 mark_color_as_moved(o, entry_list);
6584 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6585 dim_moved_lines(o);
6587 mem_pool_discard(&entry_pool, 0);
6588 free(entry_list);
6591 for (i = 0; i < esm.nr; i++)
6592 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6594 for (i = 0; i < esm.nr; i++)
6595 free((void *)esm.buf[i].line);
6596 esm.nr = 0;
6598 o->emitted_symbols = NULL;
6602 static void diff_free_file(struct diff_options *options)
6604 if (options->close_file)
6605 fclose(options->file);
6608 static void diff_free_ignore_regex(struct diff_options *options)
6610 int i;
6612 for (i = 0; i < options->ignore_regex_nr; i++) {
6613 regfree(options->ignore_regex[i]);
6614 free(options->ignore_regex[i]);
6616 free(options->ignore_regex);
6619 void diff_free(struct diff_options *options)
6621 if (options->no_free)
6622 return;
6624 diff_free_file(options);
6625 diff_free_ignore_regex(options);
6626 clear_pathspec(&options->pathspec);
6629 void diff_flush(struct diff_options *options)
6631 struct diff_queue_struct *q = &diff_queued_diff;
6632 int i, output_format = options->output_format;
6633 int separator = 0;
6634 int dirstat_by_line = 0;
6637 * Order: raw, stat, summary, patch
6638 * or: name/name-status/checkdiff (other bits clear)
6640 if (!q->nr && !options->additional_path_headers)
6641 goto free_queue;
6643 if (output_format & (DIFF_FORMAT_RAW |
6644 DIFF_FORMAT_NAME |
6645 DIFF_FORMAT_NAME_STATUS |
6646 DIFF_FORMAT_CHECKDIFF)) {
6647 for (i = 0; i < q->nr; i++) {
6648 struct diff_filepair *p = q->queue[i];
6649 if (check_pair_status(p))
6650 flush_one_pair(p, options);
6652 separator++;
6655 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6656 dirstat_by_line = 1;
6658 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6659 dirstat_by_line) {
6660 struct diffstat_t diffstat;
6662 compute_diffstat(options, &diffstat, q);
6663 if (output_format & DIFF_FORMAT_NUMSTAT)
6664 show_numstat(&diffstat, options);
6665 if (output_format & DIFF_FORMAT_DIFFSTAT)
6666 show_stats(&diffstat, options);
6667 if (output_format & DIFF_FORMAT_SHORTSTAT)
6668 show_shortstats(&diffstat, options);
6669 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6670 show_dirstat_by_line(&diffstat, options);
6671 free_diffstat_info(&diffstat);
6672 separator++;
6674 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6675 show_dirstat(options);
6677 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6678 for (i = 0; i < q->nr; i++) {
6679 diff_summary(options, q->queue[i]);
6681 separator++;
6684 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6685 options->flags.exit_with_status &&
6686 options->flags.diff_from_contents) {
6688 * run diff_flush_patch for the exit status. setting
6689 * options->file to /dev/null should be safe, because we
6690 * aren't supposed to produce any output anyway.
6692 diff_free_file(options);
6693 options->file = xfopen("/dev/null", "w");
6694 options->close_file = 1;
6695 options->color_moved = 0;
6696 for (i = 0; i < q->nr; i++) {
6697 struct diff_filepair *p = q->queue[i];
6698 if (check_pair_status(p))
6699 diff_flush_patch(p, options);
6700 if (options->found_changes)
6701 break;
6705 if (output_format & DIFF_FORMAT_PATCH) {
6706 if (separator) {
6707 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6708 if (options->stat_sep)
6709 /* attach patch instead of inline */
6710 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6711 NULL, 0, 0);
6714 diff_flush_patch_all_file_pairs(options);
6717 if (output_format & DIFF_FORMAT_CALLBACK)
6718 options->format_callback(q, options, options->format_callback_data);
6720 free_queue:
6721 diff_free_queue(q);
6722 DIFF_QUEUE_CLEAR(q);
6723 diff_free(options);
6726 * Report the content-level differences with HAS_CHANGES;
6727 * diff_addremove/diff_change does not set the bit when
6728 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6730 if (options->flags.diff_from_contents) {
6731 if (options->found_changes)
6732 options->flags.has_changes = 1;
6733 else
6734 options->flags.has_changes = 0;
6738 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6740 return (((p->status == DIFF_STATUS_MODIFIED) &&
6741 ((p->score &&
6742 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6743 (!p->score &&
6744 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6745 ((p->status != DIFF_STATUS_MODIFIED) &&
6746 filter_bit_tst(p->status, options)));
6749 static void diffcore_apply_filter(struct diff_options *options)
6751 int i;
6752 struct diff_queue_struct *q = &diff_queued_diff;
6753 struct diff_queue_struct outq;
6755 DIFF_QUEUE_CLEAR(&outq);
6757 if (!options->filter)
6758 return;
6760 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6761 int found;
6762 for (i = found = 0; !found && i < q->nr; i++) {
6763 if (match_filter(options, q->queue[i]))
6764 found++;
6766 if (found)
6767 return;
6769 /* otherwise we will clear the whole queue
6770 * by copying the empty outq at the end of this
6771 * function, but first clear the current entries
6772 * in the queue.
6774 for (i = 0; i < q->nr; i++)
6775 diff_free_filepair(q->queue[i]);
6777 else {
6778 /* Only the matching ones */
6779 for (i = 0; i < q->nr; i++) {
6780 struct diff_filepair *p = q->queue[i];
6781 if (match_filter(options, p))
6782 diff_q(&outq, p);
6783 else
6784 diff_free_filepair(p);
6787 free(q->queue);
6788 *q = outq;
6791 /* Check whether two filespecs with the same mode and size are identical */
6792 static int diff_filespec_is_identical(struct repository *r,
6793 struct diff_filespec *one,
6794 struct diff_filespec *two)
6796 if (S_ISGITLINK(one->mode))
6797 return 0;
6798 if (diff_populate_filespec(r, one, NULL))
6799 return 0;
6800 if (diff_populate_filespec(r, two, NULL))
6801 return 0;
6802 return !memcmp(one->data, two->data, one->size);
6805 static int diff_filespec_check_stat_unmatch(struct repository *r,
6806 struct diff_filepair *p)
6808 struct diff_populate_filespec_options dpf_options = {
6809 .check_size_only = 1,
6810 .missing_object_cb = diff_queued_diff_prefetch,
6811 .missing_object_data = r,
6814 if (p->done_skip_stat_unmatch)
6815 return p->skip_stat_unmatch_result;
6817 p->done_skip_stat_unmatch = 1;
6818 p->skip_stat_unmatch_result = 0;
6820 * 1. Entries that come from stat info dirtiness
6821 * always have both sides (iow, not create/delete),
6822 * one side of the object name is unknown, with
6823 * the same mode and size. Keep the ones that
6824 * do not match these criteria. They have real
6825 * differences.
6827 * 2. At this point, the file is known to be modified,
6828 * with the same mode and size, and the object
6829 * name of one side is unknown. Need to inspect
6830 * the identical contents.
6832 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6833 !DIFF_FILE_VALID(p->two) ||
6834 (p->one->oid_valid && p->two->oid_valid) ||
6835 (p->one->mode != p->two->mode) ||
6836 diff_populate_filespec(r, p->one, &dpf_options) ||
6837 diff_populate_filespec(r, p->two, &dpf_options) ||
6838 (p->one->size != p->two->size) ||
6839 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6840 p->skip_stat_unmatch_result = 1;
6841 return p->skip_stat_unmatch_result;
6844 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6846 int i;
6847 struct diff_queue_struct *q = &diff_queued_diff;
6848 struct diff_queue_struct outq;
6849 DIFF_QUEUE_CLEAR(&outq);
6851 for (i = 0; i < q->nr; i++) {
6852 struct diff_filepair *p = q->queue[i];
6854 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6855 diff_q(&outq, p);
6856 else {
6858 * The caller can subtract 1 from skip_stat_unmatch
6859 * to determine how many paths were dirty only
6860 * due to stat info mismatch.
6862 if (!diffopt->flags.no_index)
6863 diffopt->skip_stat_unmatch++;
6864 diff_free_filepair(p);
6867 free(q->queue);
6868 *q = outq;
6871 static int diffnamecmp(const void *a_, const void *b_)
6873 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6874 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6875 const char *name_a, *name_b;
6877 name_a = a->one ? a->one->path : a->two->path;
6878 name_b = b->one ? b->one->path : b->two->path;
6879 return strcmp(name_a, name_b);
6882 void diffcore_fix_diff_index(void)
6884 struct diff_queue_struct *q = &diff_queued_diff;
6885 QSORT(q->queue, q->nr, diffnamecmp);
6888 void diff_add_if_missing(struct repository *r,
6889 struct oid_array *to_fetch,
6890 const struct diff_filespec *filespec)
6892 if (filespec && filespec->oid_valid &&
6893 !S_ISGITLINK(filespec->mode) &&
6894 oid_object_info_extended(r, &filespec->oid, NULL,
6895 OBJECT_INFO_FOR_PREFETCH))
6896 oid_array_append(to_fetch, &filespec->oid);
6899 void diff_queued_diff_prefetch(void *repository)
6901 struct repository *repo = repository;
6902 int i;
6903 struct diff_queue_struct *q = &diff_queued_diff;
6904 struct oid_array to_fetch = OID_ARRAY_INIT;
6906 for (i = 0; i < q->nr; i++) {
6907 struct diff_filepair *p = q->queue[i];
6908 diff_add_if_missing(repo, &to_fetch, p->one);
6909 diff_add_if_missing(repo, &to_fetch, p->two);
6913 * NEEDSWORK: Consider deduplicating the OIDs sent.
6915 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6917 oid_array_clear(&to_fetch);
6920 void diffcore_std(struct diff_options *options)
6922 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6923 DIFF_FORMAT_NUMSTAT |
6924 DIFF_FORMAT_PATCH |
6925 DIFF_FORMAT_SHORTSTAT |
6926 DIFF_FORMAT_DIRSTAT;
6929 * Check if the user requested a blob-data-requiring diff output and/or
6930 * break-rewrite detection (which requires blob data). If yes, prefetch
6931 * the diff pairs.
6933 * If no prefetching occurs, diffcore_rename() will prefetch if it
6934 * decides that it needs inexact rename detection.
6936 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
6937 (options->output_format & output_formats_to_prefetch ||
6938 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6939 diff_queued_diff_prefetch(options->repo);
6941 /* NOTE please keep the following in sync with diff_tree_combined() */
6942 if (options->skip_stat_unmatch)
6943 diffcore_skip_stat_unmatch(options);
6944 if (!options->found_follow) {
6945 /* See try_to_follow_renames() in tree-diff.c */
6946 if (options->break_opt != -1)
6947 diffcore_break(options->repo,
6948 options->break_opt);
6949 if (options->detect_rename)
6950 diffcore_rename(options);
6951 if (options->break_opt != -1)
6952 diffcore_merge_broken();
6954 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6955 diffcore_pickaxe(options);
6956 if (options->orderfile)
6957 diffcore_order(options->orderfile);
6958 if (options->rotate_to)
6959 diffcore_rotate(options);
6960 if (!options->found_follow)
6961 /* See try_to_follow_renames() in tree-diff.c */
6962 diff_resolve_rename_copy();
6963 diffcore_apply_filter(options);
6965 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6966 options->flags.has_changes = 1;
6967 else
6968 options->flags.has_changes = 0;
6970 options->found_follow = 0;
6973 int diff_result_code(struct diff_options *opt, int status)
6975 int result = 0;
6977 diff_warn_rename_limit("diff.renameLimit",
6978 opt->needed_rename_limit,
6979 opt->degraded_cc_to_c);
6980 if (!opt->flags.exit_with_status &&
6981 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6982 return status;
6983 if (opt->flags.exit_with_status &&
6984 opt->flags.has_changes)
6985 result |= 01;
6986 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6987 opt->flags.check_failed)
6988 result |= 02;
6989 return result;
6992 int diff_can_quit_early(struct diff_options *opt)
6994 return (opt->flags.quick &&
6995 !opt->filter &&
6996 opt->flags.has_changes);
7000 * Shall changes to this submodule be ignored?
7002 * Submodule changes can be configured to be ignored separately for each path,
7003 * but that configuration can be overridden from the command line.
7005 static int is_submodule_ignored(const char *path, struct diff_options *options)
7007 int ignored = 0;
7008 struct diff_flags orig_flags = options->flags;
7009 if (!options->flags.override_submodule_config)
7010 set_diffopt_flags_from_submodule_config(options, path);
7011 if (options->flags.ignore_submodules)
7012 ignored = 1;
7013 options->flags = orig_flags;
7014 return ignored;
7017 void compute_diffstat(struct diff_options *options,
7018 struct diffstat_t *diffstat,
7019 struct diff_queue_struct *q)
7021 int i;
7023 memset(diffstat, 0, sizeof(struct diffstat_t));
7024 for (i = 0; i < q->nr; i++) {
7025 struct diff_filepair *p = q->queue[i];
7026 if (check_pair_status(p))
7027 diff_flush_stat(p, options, diffstat);
7031 void diff_addremove(struct diff_options *options,
7032 int addremove, unsigned mode,
7033 const struct object_id *oid,
7034 int oid_valid,
7035 const char *concatpath, unsigned dirty_submodule)
7037 struct diff_filespec *one, *two;
7039 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7040 return;
7042 /* This may look odd, but it is a preparation for
7043 * feeding "there are unchanged files which should
7044 * not produce diffs, but when you are doing copy
7045 * detection you would need them, so here they are"
7046 * entries to the diff-core. They will be prefixed
7047 * with something like '=' or '*' (I haven't decided
7048 * which but should not make any difference).
7049 * Feeding the same new and old to diff_change()
7050 * also has the same effect.
7051 * Before the final output happens, they are pruned after
7052 * merged into rename/copy pairs as appropriate.
7054 if (options->flags.reverse_diff)
7055 addremove = (addremove == '+' ? '-' :
7056 addremove == '-' ? '+' : addremove);
7058 if (options->prefix &&
7059 strncmp(concatpath, options->prefix, options->prefix_length))
7060 return;
7062 one = alloc_filespec(concatpath);
7063 two = alloc_filespec(concatpath);
7065 if (addremove != '+')
7066 fill_filespec(one, oid, oid_valid, mode);
7067 if (addremove != '-') {
7068 fill_filespec(two, oid, oid_valid, mode);
7069 two->dirty_submodule = dirty_submodule;
7072 diff_queue(&diff_queued_diff, one, two);
7073 if (!options->flags.diff_from_contents)
7074 options->flags.has_changes = 1;
7077 void diff_change(struct diff_options *options,
7078 unsigned old_mode, unsigned new_mode,
7079 const struct object_id *old_oid,
7080 const struct object_id *new_oid,
7081 int old_oid_valid, int new_oid_valid,
7082 const char *concatpath,
7083 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7085 struct diff_filespec *one, *two;
7086 struct diff_filepair *p;
7088 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7089 is_submodule_ignored(concatpath, options))
7090 return;
7092 if (options->flags.reverse_diff) {
7093 SWAP(old_mode, new_mode);
7094 SWAP(old_oid, new_oid);
7095 SWAP(old_oid_valid, new_oid_valid);
7096 SWAP(old_dirty_submodule, new_dirty_submodule);
7099 if (options->prefix &&
7100 strncmp(concatpath, options->prefix, options->prefix_length))
7101 return;
7103 one = alloc_filespec(concatpath);
7104 two = alloc_filespec(concatpath);
7105 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7106 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7107 one->dirty_submodule = old_dirty_submodule;
7108 two->dirty_submodule = new_dirty_submodule;
7109 p = diff_queue(&diff_queued_diff, one, two);
7111 if (options->flags.diff_from_contents)
7112 return;
7114 if (options->flags.quick && options->skip_stat_unmatch &&
7115 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7116 diff_free_filespec_data(p->one);
7117 diff_free_filespec_data(p->two);
7118 return;
7121 options->flags.has_changes = 1;
7124 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7126 struct diff_filepair *pair;
7127 struct diff_filespec *one, *two;
7129 if (options->prefix &&
7130 strncmp(path, options->prefix, options->prefix_length))
7131 return NULL;
7133 one = alloc_filespec(path);
7134 two = alloc_filespec(path);
7135 pair = diff_queue(&diff_queued_diff, one, two);
7136 pair->is_unmerged = 1;
7137 return pair;
7140 static char *run_textconv(struct repository *r,
7141 const char *pgm,
7142 struct diff_filespec *spec,
7143 size_t *outsize)
7145 struct diff_tempfile *temp;
7146 struct child_process child = CHILD_PROCESS_INIT;
7147 struct strbuf buf = STRBUF_INIT;
7148 int err = 0;
7150 temp = prepare_temp_file(r, spec);
7151 strvec_push(&child.args, pgm);
7152 strvec_push(&child.args, temp->name);
7154 child.use_shell = 1;
7155 child.out = -1;
7156 if (start_command(&child)) {
7157 remove_tempfile();
7158 return NULL;
7161 if (strbuf_read(&buf, child.out, 0) < 0)
7162 err = error("error reading from textconv command '%s'", pgm);
7163 close(child.out);
7165 if (finish_command(&child) || err) {
7166 strbuf_release(&buf);
7167 remove_tempfile();
7168 return NULL;
7170 remove_tempfile();
7172 return strbuf_detach(&buf, outsize);
7175 size_t fill_textconv(struct repository *r,
7176 struct userdiff_driver *driver,
7177 struct diff_filespec *df,
7178 char **outbuf)
7180 size_t size;
7182 if (!driver) {
7183 if (!DIFF_FILE_VALID(df)) {
7184 *outbuf = "";
7185 return 0;
7187 if (diff_populate_filespec(r, df, NULL))
7188 die("unable to read files to diff");
7189 *outbuf = df->data;
7190 return df->size;
7193 if (!driver->textconv)
7194 BUG("fill_textconv called with non-textconv driver");
7196 if (driver->textconv_cache && df->oid_valid) {
7197 *outbuf = notes_cache_get(driver->textconv_cache,
7198 &df->oid,
7199 &size);
7200 if (*outbuf)
7201 return size;
7204 *outbuf = run_textconv(r, driver->textconv, df, &size);
7205 if (!*outbuf)
7206 die("unable to read files to diff");
7208 if (driver->textconv_cache && df->oid_valid) {
7209 /* ignore errors, as we might be in a readonly repository */
7210 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7211 size);
7213 * we could save up changes and flush them all at the end,
7214 * but we would need an extra call after all diffing is done.
7215 * Since generating a cache entry is the slow path anyway,
7216 * this extra overhead probably isn't a big deal.
7218 notes_cache_write(driver->textconv_cache);
7221 return size;
7224 int textconv_object(struct repository *r,
7225 const char *path,
7226 unsigned mode,
7227 const struct object_id *oid,
7228 int oid_valid,
7229 char **buf,
7230 unsigned long *buf_size)
7232 struct diff_filespec *df;
7233 struct userdiff_driver *textconv;
7235 df = alloc_filespec(path);
7236 fill_filespec(df, oid, oid_valid, mode);
7237 textconv = get_textconv(r, df);
7238 if (!textconv) {
7239 free_filespec(df);
7240 return 0;
7243 *buf_size = fill_textconv(r, textconv, df, buf);
7244 free_filespec(df);
7245 return 1;
7248 void setup_diff_pager(struct diff_options *opt)
7251 * If the user asked for our exit code, then either they want --quiet
7252 * or --exit-code. We should definitely not bother with a pager in the
7253 * former case, as we will generate no output. Since we still properly
7254 * report our exit code even when a pager is run, we _could_ run a
7255 * pager with --exit-code. But since we have not done so historically,
7256 * and because it is easy to find people oneline advising "git diff
7257 * --exit-code" in hooks and other scripts, we do not do so.
7259 if (!opt->flags.exit_with_status &&
7260 check_pager_config("diff") != 0)
7261 setup_pager();