t5332-multi-pack-reuse.sh: demonstrate duplicate packing failure
[git/gitster.git] / diff.c
blob173cbe2bed35017a1577171732d1d1fc9d1cb4b8
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
5 #define USE_THE_REPOSITORY_VARIABLE
7 #include "git-compat-util.h"
8 #include "abspath.h"
9 #include "base85.h"
10 #include "config.h"
11 #include "convert.h"
12 #include "environment.h"
13 #include "gettext.h"
14 #include "tempfile.h"
15 #include "revision.h"
16 #include "quote.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "delta.h"
20 #include "hex.h"
21 #include "xdiff-interface.h"
22 #include "color.h"
23 #include "run-command.h"
24 #include "utf8.h"
25 #include "object-store-ll.h"
26 #include "userdiff.h"
27 #include "submodule.h"
28 #include "hashmap.h"
29 #include "mem-pool.h"
30 #include "merge-ll.h"
31 #include "string-list.h"
32 #include "strvec.h"
33 #include "tmp-objdir.h"
34 #include "graph.h"
35 #include "oid-array.h"
36 #include "packfile.h"
37 #include "pager.h"
38 #include "parse-options.h"
39 #include "help.h"
40 #include "promisor-remote.h"
41 #include "dir.h"
42 #include "object-file.h"
43 #include "object-name.h"
44 #include "read-cache-ll.h"
45 #include "setup.h"
46 #include "strmap.h"
47 #include "ws.h"
49 #ifdef NO_FAST_WORKING_DIRECTORY
50 #define FAST_WORKING_DIRECTORY 0
51 #else
52 #define FAST_WORKING_DIRECTORY 1
53 #endif
55 static int diff_detect_rename_default;
56 static int diff_indent_heuristic = 1;
57 static int diff_rename_limit_default = 1000;
58 static int diff_suppress_blank_empty;
59 static int diff_use_color_default = -1;
60 static int diff_color_moved_default;
61 static int diff_color_moved_ws_default;
62 static int diff_context_default = 3;
63 static int diff_interhunk_context_default;
64 static char *diff_word_regex_cfg;
65 static struct external_diff external_diff_cfg;
66 static char *diff_order_file_cfg;
67 int diff_auto_refresh_index = 1;
68 static int diff_mnemonic_prefix;
69 static int diff_no_prefix;
70 static char *diff_src_prefix;
71 static char *diff_dst_prefix;
72 static int diff_relative;
73 static int diff_stat_name_width;
74 static int diff_stat_graph_width;
75 static int diff_dirstat_permille_default = 30;
76 static struct diff_options default_diff_options;
77 static long diff_algorithm;
78 static unsigned ws_error_highlight_default = WSEH_NEW;
80 static char diff_colors[][COLOR_MAXLEN] = {
81 GIT_COLOR_RESET,
82 GIT_COLOR_NORMAL, /* CONTEXT */
83 GIT_COLOR_BOLD, /* METAINFO */
84 GIT_COLOR_CYAN, /* FRAGINFO */
85 GIT_COLOR_RED, /* OLD */
86 GIT_COLOR_GREEN, /* NEW */
87 GIT_COLOR_YELLOW, /* COMMIT */
88 GIT_COLOR_BG_RED, /* WHITESPACE */
89 GIT_COLOR_NORMAL, /* FUNCINFO */
90 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
91 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
92 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
93 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
94 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
95 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
96 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
97 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
98 GIT_COLOR_FAINT, /* CONTEXT_DIM */
99 GIT_COLOR_FAINT_RED, /* OLD_DIM */
100 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
101 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
102 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
103 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
106 static const char *color_diff_slots[] = {
107 [DIFF_CONTEXT] = "context",
108 [DIFF_METAINFO] = "meta",
109 [DIFF_FRAGINFO] = "frag",
110 [DIFF_FILE_OLD] = "old",
111 [DIFF_FILE_NEW] = "new",
112 [DIFF_COMMIT] = "commit",
113 [DIFF_WHITESPACE] = "whitespace",
114 [DIFF_FUNCINFO] = "func",
115 [DIFF_FILE_OLD_MOVED] = "oldMoved",
116 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
117 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
118 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
119 [DIFF_FILE_NEW_MOVED] = "newMoved",
120 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
121 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
122 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
123 [DIFF_CONTEXT_DIM] = "contextDimmed",
124 [DIFF_FILE_OLD_DIM] = "oldDimmed",
125 [DIFF_FILE_NEW_DIM] = "newDimmed",
126 [DIFF_CONTEXT_BOLD] = "contextBold",
127 [DIFF_FILE_OLD_BOLD] = "oldBold",
128 [DIFF_FILE_NEW_BOLD] = "newBold",
131 define_list_config_array_extra(color_diff_slots, {"plain"});
133 static int parse_diff_color_slot(const char *var)
135 if (!strcasecmp(var, "plain"))
136 return DIFF_CONTEXT;
137 return LOOKUP_CONFIG(color_diff_slots, var);
140 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
141 struct strbuf *errmsg)
143 char *params_copy = xstrdup(params_string);
144 struct string_list params = STRING_LIST_INIT_NODUP;
145 int ret = 0;
146 int i;
148 if (*params_copy)
149 string_list_split_in_place(&params, params_copy, ",", -1);
150 for (i = 0; i < params.nr; i++) {
151 const char *p = params.items[i].string;
152 if (!strcmp(p, "changes")) {
153 options->flags.dirstat_by_line = 0;
154 options->flags.dirstat_by_file = 0;
155 } else if (!strcmp(p, "lines")) {
156 options->flags.dirstat_by_line = 1;
157 options->flags.dirstat_by_file = 0;
158 } else if (!strcmp(p, "files")) {
159 options->flags.dirstat_by_line = 0;
160 options->flags.dirstat_by_file = 1;
161 } else if (!strcmp(p, "noncumulative")) {
162 options->flags.dirstat_cumulative = 0;
163 } else if (!strcmp(p, "cumulative")) {
164 options->flags.dirstat_cumulative = 1;
165 } else if (isdigit(*p)) {
166 char *end;
167 int permille = strtoul(p, &end, 10) * 10;
168 if (*end == '.' && isdigit(*++end)) {
169 /* only use first digit */
170 permille += *end - '0';
171 /* .. and ignore any further digits */
172 while (isdigit(*++end))
173 ; /* nothing */
175 if (!*end)
176 options->dirstat_permille = permille;
177 else {
178 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
180 ret++;
182 } else {
183 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
184 ret++;
188 string_list_clear(&params, 0);
189 free(params_copy);
190 return ret;
193 static int parse_submodule_params(struct diff_options *options, const char *value)
195 if (!strcmp(value, "log"))
196 options->submodule_format = DIFF_SUBMODULE_LOG;
197 else if (!strcmp(value, "short"))
198 options->submodule_format = DIFF_SUBMODULE_SHORT;
199 else if (!strcmp(value, "diff"))
200 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
202 * Please update $__git_diff_submodule_formats in
203 * git-completion.bash when you add new formats.
205 else
206 return -1;
207 return 0;
210 int git_config_rename(const char *var, const char *value)
212 if (!value)
213 return DIFF_DETECT_RENAME;
214 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
215 return DIFF_DETECT_COPY;
216 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
219 long parse_algorithm_value(const char *value)
221 if (!value)
222 return -1;
223 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
224 return 0;
225 else if (!strcasecmp(value, "minimal"))
226 return XDF_NEED_MINIMAL;
227 else if (!strcasecmp(value, "patience"))
228 return XDF_PATIENCE_DIFF;
229 else if (!strcasecmp(value, "histogram"))
230 return XDF_HISTOGRAM_DIFF;
232 * Please update $__git_diff_algorithms in git-completion.bash
233 * when you add new algorithms.
235 return -1;
238 static int parse_one_token(const char **arg, const char *token)
240 const char *rest;
241 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
242 *arg = rest;
243 return 1;
245 return 0;
248 static int parse_ws_error_highlight(const char *arg)
250 const char *orig_arg = arg;
251 unsigned val = 0;
253 while (*arg) {
254 if (parse_one_token(&arg, "none"))
255 val = 0;
256 else if (parse_one_token(&arg, "default"))
257 val = WSEH_NEW;
258 else if (parse_one_token(&arg, "all"))
259 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
260 else if (parse_one_token(&arg, "new"))
261 val |= WSEH_NEW;
262 else if (parse_one_token(&arg, "old"))
263 val |= WSEH_OLD;
264 else if (parse_one_token(&arg, "context"))
265 val |= WSEH_CONTEXT;
266 else {
267 return -1 - (int)(arg - orig_arg);
269 if (*arg)
270 arg++;
272 return val;
276 * These are to give UI layer defaults.
277 * The core-level commands such as git-diff-files should
278 * never be affected by the setting of diff.renames
279 * the user happens to have in the configuration file.
281 void init_diff_ui_defaults(void)
283 diff_detect_rename_default = DIFF_DETECT_RENAME;
286 int git_diff_heuristic_config(const char *var, const char *value,
287 void *cb UNUSED)
289 if (!strcmp(var, "diff.indentheuristic"))
290 diff_indent_heuristic = git_config_bool(var, value);
291 return 0;
294 static int parse_color_moved(const char *arg)
296 switch (git_parse_maybe_bool(arg)) {
297 case 0:
298 return COLOR_MOVED_NO;
299 case 1:
300 return COLOR_MOVED_DEFAULT;
301 default:
302 break;
305 if (!strcmp(arg, "no"))
306 return COLOR_MOVED_NO;
307 else if (!strcmp(arg, "plain"))
308 return COLOR_MOVED_PLAIN;
309 else if (!strcmp(arg, "blocks"))
310 return COLOR_MOVED_BLOCKS;
311 else if (!strcmp(arg, "zebra"))
312 return COLOR_MOVED_ZEBRA;
313 else if (!strcmp(arg, "default"))
314 return COLOR_MOVED_DEFAULT;
315 else if (!strcmp(arg, "dimmed-zebra"))
316 return COLOR_MOVED_ZEBRA_DIM;
317 else if (!strcmp(arg, "dimmed_zebra"))
318 return COLOR_MOVED_ZEBRA_DIM;
319 else
320 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
323 static unsigned parse_color_moved_ws(const char *arg)
325 int ret = 0;
326 struct string_list l = STRING_LIST_INIT_DUP;
327 struct string_list_item *i;
329 string_list_split(&l, arg, ',', -1);
331 for_each_string_list_item(i, &l) {
332 struct strbuf sb = STRBUF_INIT;
333 strbuf_addstr(&sb, i->string);
334 strbuf_trim(&sb);
336 if (!strcmp(sb.buf, "no"))
337 ret = 0;
338 else if (!strcmp(sb.buf, "ignore-space-change"))
339 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
340 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
341 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
342 else if (!strcmp(sb.buf, "ignore-all-space"))
343 ret |= XDF_IGNORE_WHITESPACE;
344 else if (!strcmp(sb.buf, "allow-indentation-change"))
345 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
346 else {
347 ret |= COLOR_MOVED_WS_ERROR;
348 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);
351 strbuf_release(&sb);
354 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
355 (ret & XDF_WHITESPACE_FLAGS)) {
356 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
357 ret |= COLOR_MOVED_WS_ERROR;
360 string_list_clear(&l, 0);
362 return ret;
365 int git_diff_ui_config(const char *var, const char *value,
366 const struct config_context *ctx, void *cb)
368 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
369 diff_use_color_default = git_config_colorbool(var, value);
370 return 0;
372 if (!strcmp(var, "diff.colormoved")) {
373 int cm = parse_color_moved(value);
374 if (cm < 0)
375 return -1;
376 diff_color_moved_default = cm;
377 return 0;
379 if (!strcmp(var, "diff.colormovedws")) {
380 unsigned cm;
381 if (!value)
382 return config_error_nonbool(var);
383 cm = parse_color_moved_ws(value);
384 if (cm & COLOR_MOVED_WS_ERROR)
385 return -1;
386 diff_color_moved_ws_default = cm;
387 return 0;
389 if (!strcmp(var, "diff.context")) {
390 diff_context_default = git_config_int(var, value, ctx->kvi);
391 if (diff_context_default < 0)
392 return -1;
393 return 0;
395 if (!strcmp(var, "diff.interhunkcontext")) {
396 diff_interhunk_context_default = git_config_int(var, value,
397 ctx->kvi);
398 if (diff_interhunk_context_default < 0)
399 return -1;
400 return 0;
402 if (!strcmp(var, "diff.renames")) {
403 diff_detect_rename_default = git_config_rename(var, value);
404 return 0;
406 if (!strcmp(var, "diff.autorefreshindex")) {
407 diff_auto_refresh_index = git_config_bool(var, value);
408 return 0;
410 if (!strcmp(var, "diff.mnemonicprefix")) {
411 diff_mnemonic_prefix = git_config_bool(var, value);
412 return 0;
414 if (!strcmp(var, "diff.noprefix")) {
415 diff_no_prefix = git_config_bool(var, value);
416 return 0;
418 if (!strcmp(var, "diff.srcprefix")) {
419 FREE_AND_NULL(diff_src_prefix);
420 return git_config_string(&diff_src_prefix, var, value);
422 if (!strcmp(var, "diff.dstprefix")) {
423 FREE_AND_NULL(diff_dst_prefix);
424 return git_config_string(&diff_dst_prefix, var, value);
426 if (!strcmp(var, "diff.relative")) {
427 diff_relative = git_config_bool(var, value);
428 return 0;
430 if (!strcmp(var, "diff.statnamewidth")) {
431 diff_stat_name_width = git_config_int(var, value, ctx->kvi);
432 return 0;
434 if (!strcmp(var, "diff.statgraphwidth")) {
435 diff_stat_graph_width = git_config_int(var, value, ctx->kvi);
436 return 0;
438 if (!strcmp(var, "diff.external"))
439 return git_config_string(&external_diff_cfg.cmd, var, value);
440 if (!strcmp(var, "diff.trustexitcode")) {
441 external_diff_cfg.trust_exit_code = git_config_bool(var, value);
442 return 0;
444 if (!strcmp(var, "diff.wordregex"))
445 return git_config_string(&diff_word_regex_cfg, var, value);
446 if (!strcmp(var, "diff.orderfile")) {
447 FREE_AND_NULL(diff_order_file_cfg);
448 return git_config_pathname(&diff_order_file_cfg, var, value);
451 if (!strcmp(var, "diff.ignoresubmodules")) {
452 if (!value)
453 return config_error_nonbool(var);
454 handle_ignore_submodules_arg(&default_diff_options, value);
457 if (!strcmp(var, "diff.submodule")) {
458 if (!value)
459 return config_error_nonbool(var);
460 if (parse_submodule_params(&default_diff_options, value))
461 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
462 value);
463 return 0;
466 if (!strcmp(var, "diff.algorithm")) {
467 if (!value)
468 return config_error_nonbool(var);
469 diff_algorithm = parse_algorithm_value(value);
470 if (diff_algorithm < 0)
471 return error(_("unknown value for config '%s': %s"),
472 var, value);
473 return 0;
476 if (git_color_config(var, value, cb) < 0)
477 return -1;
479 return git_diff_basic_config(var, value, ctx, cb);
482 int git_diff_basic_config(const char *var, const char *value,
483 const struct config_context *ctx, void *cb)
485 const char *name;
487 if (!strcmp(var, "diff.renamelimit")) {
488 diff_rename_limit_default = git_config_int(var, value, ctx->kvi);
489 return 0;
492 if (userdiff_config(var, value) < 0)
493 return -1;
495 if (skip_prefix(var, "diff.color.", &name) ||
496 skip_prefix(var, "color.diff.", &name)) {
497 int slot = parse_diff_color_slot(name);
498 if (slot < 0)
499 return 0;
500 if (!value)
501 return config_error_nonbool(var);
502 return color_parse(value, diff_colors[slot]);
505 if (!strcmp(var, "diff.wserrorhighlight")) {
506 int val;
507 if (!value)
508 return config_error_nonbool(var);
509 val = parse_ws_error_highlight(value);
510 if (val < 0)
511 return error(_("unknown value for config '%s': %s"),
512 var, value);
513 ws_error_highlight_default = val;
514 return 0;
517 /* like GNU diff's --suppress-blank-empty option */
518 if (!strcmp(var, "diff.suppressblankempty") ||
519 /* for backwards compatibility */
520 !strcmp(var, "diff.suppress-blank-empty")) {
521 diff_suppress_blank_empty = git_config_bool(var, value);
522 return 0;
525 if (!strcmp(var, "diff.dirstat")) {
526 struct strbuf errmsg = STRBUF_INIT;
527 if (!value)
528 return config_error_nonbool(var);
529 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
530 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
531 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
532 errmsg.buf);
533 strbuf_release(&errmsg);
534 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
535 return 0;
538 if (git_diff_heuristic_config(var, value, cb) < 0)
539 return -1;
541 return git_default_config(var, value, ctx, cb);
544 static char *quote_two(const char *one, const char *two)
546 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
547 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
548 struct strbuf res = STRBUF_INIT;
550 if (need_one + need_two) {
551 strbuf_addch(&res, '"');
552 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
553 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
554 strbuf_addch(&res, '"');
555 } else {
556 strbuf_addstr(&res, one);
557 strbuf_addstr(&res, two);
559 return strbuf_detach(&res, NULL);
562 static const struct external_diff *external_diff(void)
564 static struct external_diff external_diff_env, *external_diff_ptr;
565 static int done_preparing = 0;
567 if (done_preparing)
568 return external_diff_ptr;
569 external_diff_env.cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
570 if (git_env_bool("GIT_EXTERNAL_DIFF_TRUST_EXIT_CODE", 0))
571 external_diff_env.trust_exit_code = 1;
572 if (external_diff_env.cmd)
573 external_diff_ptr = &external_diff_env;
574 else if (external_diff_cfg.cmd)
575 external_diff_ptr = &external_diff_cfg;
576 done_preparing = 1;
577 return external_diff_ptr;
581 * Keep track of files used for diffing. Sometimes such an entry
582 * refers to a temporary file, sometimes to an existing file, and
583 * sometimes to "/dev/null".
585 static struct diff_tempfile {
587 * filename external diff should read from, or NULL if this
588 * entry is currently not in use:
590 const char *name;
592 char hex[GIT_MAX_HEXSZ + 1];
593 char mode[10];
596 * If this diff_tempfile instance refers to a temporary file,
597 * this tempfile object is used to manage its lifetime.
599 struct tempfile *tempfile;
600 } diff_temp[2];
602 struct emit_callback {
603 int color_diff;
604 unsigned ws_rule;
605 int blank_at_eof_in_preimage;
606 int blank_at_eof_in_postimage;
607 int lno_in_preimage;
608 int lno_in_postimage;
609 const char **label_path;
610 struct diff_words_data *diff_words;
611 struct diff_options *opt;
612 struct strbuf *header;
615 static int count_lines(const char *data, int size)
617 int count, ch, completely_empty = 1, nl_just_seen = 0;
618 count = 0;
619 while (0 < size--) {
620 ch = *data++;
621 if (ch == '\n') {
622 count++;
623 nl_just_seen = 1;
624 completely_empty = 0;
626 else {
627 nl_just_seen = 0;
628 completely_empty = 0;
631 if (completely_empty)
632 return 0;
633 if (!nl_just_seen)
634 count++; /* no trailing newline */
635 return count;
638 static int fill_mmfile(struct repository *r, mmfile_t *mf,
639 struct diff_filespec *one)
641 if (!DIFF_FILE_VALID(one)) {
642 mf->ptr = (char *)""; /* does not matter */
643 mf->size = 0;
644 return 0;
646 else if (diff_populate_filespec(r, one, NULL))
647 return -1;
649 mf->ptr = one->data;
650 mf->size = one->size;
651 return 0;
654 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
655 static unsigned long diff_filespec_size(struct repository *r,
656 struct diff_filespec *one)
658 struct diff_populate_filespec_options dpf_options = {
659 .check_size_only = 1,
662 if (!DIFF_FILE_VALID(one))
663 return 0;
664 diff_populate_filespec(r, one, &dpf_options);
665 return one->size;
668 static int count_trailing_blank(mmfile_t *mf)
670 char *ptr = mf->ptr;
671 long size = mf->size;
672 int cnt = 0;
674 if (!size)
675 return cnt;
676 ptr += size - 1; /* pointing at the very end */
677 if (*ptr != '\n')
678 ; /* incomplete line */
679 else
680 ptr--; /* skip the last LF */
681 while (mf->ptr < ptr) {
682 char *prev_eol;
683 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
684 if (*prev_eol == '\n')
685 break;
686 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol))
687 break;
688 cnt++;
689 ptr = prev_eol - 1;
691 return cnt;
694 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
695 struct emit_callback *ecbdata)
697 int l1, l2, at;
698 l1 = count_trailing_blank(mf1);
699 l2 = count_trailing_blank(mf2);
700 if (l2 <= l1) {
701 ecbdata->blank_at_eof_in_preimage = 0;
702 ecbdata->blank_at_eof_in_postimage = 0;
703 return;
705 at = count_lines(mf1->ptr, mf1->size);
706 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
708 at = count_lines(mf2->ptr, mf2->size);
709 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
712 static void emit_line_0(struct diff_options *o,
713 const char *set_sign, const char *set, unsigned reverse, const char *reset,
714 int first, const char *line, int len)
716 int has_trailing_newline, has_trailing_carriage_return;
717 int needs_reset = 0; /* at the end of the line */
718 FILE *file = o->file;
720 fputs(diff_line_prefix(o), file);
722 has_trailing_newline = (len > 0 && line[len-1] == '\n');
723 if (has_trailing_newline)
724 len--;
726 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
727 if (has_trailing_carriage_return)
728 len--;
730 if (!len && !first)
731 goto end_of_line;
733 if (reverse && want_color(o->use_color)) {
734 fputs(GIT_COLOR_REVERSE, file);
735 needs_reset = 1;
738 if (set_sign) {
739 fputs(set_sign, file);
740 needs_reset = 1;
743 if (first)
744 fputc(first, file);
746 if (!len)
747 goto end_of_line;
749 if (set) {
750 if (set_sign && set != set_sign)
751 fputs(reset, file);
752 fputs(set, file);
753 needs_reset = 1;
755 fwrite(line, len, 1, file);
756 needs_reset = 1; /* 'line' may contain color codes. */
758 end_of_line:
759 if (needs_reset)
760 fputs(reset, file);
761 if (has_trailing_carriage_return)
762 fputc('\r', file);
763 if (has_trailing_newline)
764 fputc('\n', file);
767 static void emit_line(struct diff_options *o, const char *set, const char *reset,
768 const char *line, int len)
770 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
773 enum diff_symbol {
774 DIFF_SYMBOL_BINARY_DIFF_HEADER,
775 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
776 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
777 DIFF_SYMBOL_BINARY_DIFF_BODY,
778 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
779 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
780 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
781 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
782 DIFF_SYMBOL_STATS_LINE,
783 DIFF_SYMBOL_WORD_DIFF,
784 DIFF_SYMBOL_STAT_SEP,
785 DIFF_SYMBOL_SUMMARY,
786 DIFF_SYMBOL_SUBMODULE_ADD,
787 DIFF_SYMBOL_SUBMODULE_DEL,
788 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
789 DIFF_SYMBOL_SUBMODULE_MODIFIED,
790 DIFF_SYMBOL_SUBMODULE_HEADER,
791 DIFF_SYMBOL_SUBMODULE_ERROR,
792 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
793 DIFF_SYMBOL_REWRITE_DIFF,
794 DIFF_SYMBOL_BINARY_FILES,
795 DIFF_SYMBOL_HEADER,
796 DIFF_SYMBOL_FILEPAIR_PLUS,
797 DIFF_SYMBOL_FILEPAIR_MINUS,
798 DIFF_SYMBOL_WORDS_PORCELAIN,
799 DIFF_SYMBOL_WORDS,
800 DIFF_SYMBOL_CONTEXT,
801 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
802 DIFF_SYMBOL_PLUS,
803 DIFF_SYMBOL_MINUS,
804 DIFF_SYMBOL_NO_LF_EOF,
805 DIFF_SYMBOL_CONTEXT_FRAGINFO,
806 DIFF_SYMBOL_CONTEXT_MARKER,
807 DIFF_SYMBOL_SEPARATOR
810 * Flags for content lines:
811 * 0..12 are whitespace rules
812 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
813 * 16 is marking if the line is blank at EOF
815 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
816 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
817 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
818 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
819 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
822 * This struct is used when we need to buffer the output of the diff output.
824 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
825 * into the pre/post image file. This pointer could be a union with the
826 * line pointer. By storing an offset into the file instead of the literal line,
827 * we can decrease the memory footprint for the buffered output. At first we
828 * may want to only have indirection for the content lines, but we could also
829 * enhance the state for emitting prefabricated lines, e.g. the similarity
830 * score line or hunk/file headers would only need to store a number or path
831 * and then the output can be constructed later on depending on state.
833 struct emitted_diff_symbol {
834 const char *line;
835 int len;
836 int flags;
837 int indent_off; /* Offset to first non-whitespace character */
838 int indent_width; /* The visual width of the indentation */
839 unsigned id;
840 enum diff_symbol s;
842 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
844 struct emitted_diff_symbols {
845 struct emitted_diff_symbol *buf;
846 int nr, alloc;
848 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
850 static void append_emitted_diff_symbol(struct diff_options *o,
851 struct emitted_diff_symbol *e)
853 struct emitted_diff_symbol *f;
855 ALLOC_GROW(o->emitted_symbols->buf,
856 o->emitted_symbols->nr + 1,
857 o->emitted_symbols->alloc);
858 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
860 memcpy(f, e, sizeof(struct emitted_diff_symbol));
861 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
864 static void free_emitted_diff_symbols(struct emitted_diff_symbols *e)
866 if (!e)
867 return;
868 free(e->buf);
869 free(e);
872 struct moved_entry {
873 const struct emitted_diff_symbol *es;
874 struct moved_entry *next_line;
875 struct moved_entry *next_match;
878 struct moved_block {
879 struct moved_entry *match;
880 int wsd; /* The whitespace delta of this block */
883 #define INDENT_BLANKLINE INT_MIN
885 static void fill_es_indent_data(struct emitted_diff_symbol *es)
887 unsigned int off = 0, i;
888 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
889 const char *s = es->line;
890 const int len = es->len;
892 /* skip any \v \f \r at start of indentation */
893 while (s[off] == '\f' || s[off] == '\v' ||
894 (s[off] == '\r' && off < len - 1))
895 off++;
897 /* calculate the visual width of indentation */
898 while(1) {
899 if (s[off] == ' ') {
900 width++;
901 off++;
902 } else if (s[off] == '\t') {
903 width += tab_width - (width % tab_width);
904 while (s[++off] == '\t')
905 width += tab_width;
906 } else {
907 break;
911 /* check if this line is blank */
912 for (i = off; i < len; i++)
913 if (!isspace(s[i]))
914 break;
916 if (i == len) {
917 es->indent_width = INDENT_BLANKLINE;
918 es->indent_off = len;
919 } else {
920 es->indent_off = off;
921 es->indent_width = width;
925 static int compute_ws_delta(const struct emitted_diff_symbol *a,
926 const struct emitted_diff_symbol *b)
928 int a_width = a->indent_width,
929 b_width = b->indent_width;
931 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
932 return INDENT_BLANKLINE;
934 return a_width - b_width;
937 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
938 const struct emitted_diff_symbol *l,
939 struct moved_block *pmb)
941 int a_width = cur->es->indent_width, b_width = l->indent_width;
942 int delta;
944 /* The text of each line must match */
945 if (cur->es->id != l->id)
946 return 1;
949 * If 'l' and 'cur' are both blank then we don't need to check the
950 * indent. We only need to check cur as we know the strings match.
951 * */
952 if (a_width == INDENT_BLANKLINE)
953 return 0;
956 * The indent changes of the block are known and stored in pmb->wsd;
957 * however we need to check if the indent changes of the current line
958 * match those of the current block.
960 delta = b_width - a_width;
963 * If the previous lines of this block were all blank then set its
964 * whitespace delta.
966 if (pmb->wsd == INDENT_BLANKLINE)
967 pmb->wsd = delta;
969 return delta != pmb->wsd;
972 struct interned_diff_symbol {
973 struct hashmap_entry ent;
974 struct emitted_diff_symbol *es;
977 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
978 const struct hashmap_entry *eptr,
979 const struct hashmap_entry *entry_or_key,
980 const void *keydata UNUSED)
982 const struct diff_options *diffopt = hashmap_cmp_fn_data;
983 const struct emitted_diff_symbol *a, *b;
984 unsigned flags = diffopt->color_moved_ws_handling
985 & XDF_WHITESPACE_FLAGS;
987 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
988 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
990 return !xdiff_compare_lines(a->line + a->indent_off,
991 a->len - a->indent_off,
992 b->line + b->indent_off,
993 b->len - b->indent_off, flags);
996 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
997 struct interned_diff_symbol *s)
999 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
1000 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
1001 l->len - l->indent_off, flags);
1003 hashmap_entry_init(&s->ent, hash);
1004 s->es = l;
1007 struct moved_entry_list {
1008 struct moved_entry *add, *del;
1011 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
1012 struct mem_pool *entry_mem_pool)
1014 struct moved_entry *prev_line = NULL;
1015 struct mem_pool interned_pool;
1016 struct hashmap interned_map;
1017 struct moved_entry_list *entry_list = NULL;
1018 size_t entry_list_alloc = 0;
1019 unsigned id = 0;
1020 int n;
1022 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
1023 mem_pool_init(&interned_pool, 1024 * 1024);
1025 for (n = 0; n < o->emitted_symbols->nr; n++) {
1026 struct interned_diff_symbol key;
1027 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1028 struct interned_diff_symbol *s;
1029 struct moved_entry *entry;
1031 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
1032 prev_line = NULL;
1033 continue;
1036 if (o->color_moved_ws_handling &
1037 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1038 fill_es_indent_data(l);
1040 prepare_entry(o, l, &key);
1041 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
1042 if (s) {
1043 l->id = s->es->id;
1044 } else {
1045 l->id = id;
1046 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
1047 hashmap_add(&interned_map,
1048 memcpy(mem_pool_alloc(&interned_pool,
1049 sizeof(key)),
1050 &key, sizeof(key)));
1052 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
1053 entry->es = l;
1054 entry->next_line = NULL;
1055 if (prev_line && prev_line->es->s == l->s)
1056 prev_line->next_line = entry;
1057 prev_line = entry;
1058 if (l->s == DIFF_SYMBOL_PLUS) {
1059 entry->next_match = entry_list[l->id].add;
1060 entry_list[l->id].add = entry;
1061 } else {
1062 entry->next_match = entry_list[l->id].del;
1063 entry_list[l->id].del = entry;
1067 hashmap_clear(&interned_map);
1068 mem_pool_discard(&interned_pool, 0);
1070 return entry_list;
1073 static void pmb_advance_or_null(struct diff_options *o,
1074 struct emitted_diff_symbol *l,
1075 struct moved_block *pmb,
1076 int *pmb_nr)
1078 int i, j;
1080 for (i = 0, j = 0; i < *pmb_nr; i++) {
1081 int match;
1082 struct moved_entry *prev = pmb[i].match;
1083 struct moved_entry *cur = (prev && prev->next_line) ?
1084 prev->next_line : NULL;
1086 if (o->color_moved_ws_handling &
1087 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1088 match = cur &&
1089 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1090 else
1091 match = cur && cur->es->id == l->id;
1093 if (match) {
1094 pmb[j] = pmb[i];
1095 pmb[j++].match = cur;
1098 *pmb_nr = j;
1101 static void fill_potential_moved_blocks(struct diff_options *o,
1102 struct moved_entry *match,
1103 struct emitted_diff_symbol *l,
1104 struct moved_block **pmb_p,
1105 int *pmb_alloc_p, int *pmb_nr_p)
1108 struct moved_block *pmb = *pmb_p;
1109 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1112 * The current line is the start of a new block.
1113 * Setup the set of potential blocks.
1115 for (; match; match = match->next_match) {
1116 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1117 if (o->color_moved_ws_handling &
1118 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1119 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1120 else
1121 pmb[pmb_nr].wsd = 0;
1122 pmb[pmb_nr++].match = match;
1125 *pmb_p = pmb;
1126 *pmb_alloc_p = pmb_alloc;
1127 *pmb_nr_p = pmb_nr;
1131 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1133 * Otherwise, if the last block has fewer alphanumeric characters than
1134 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1135 * that block.
1137 * The last block consists of the (n - block_length)'th line up to but not
1138 * including the nth line.
1140 * Returns 0 if the last block is empty or is unset by this function, non zero
1141 * otherwise.
1143 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1144 * Think of a way to unify them.
1146 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1147 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1148 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1150 int i, alnum_count = 0;
1151 if (o->color_moved == COLOR_MOVED_PLAIN)
1152 return block_length;
1153 for (i = 1; i < block_length + 1; i++) {
1154 const char *c = o->emitted_symbols->buf[n - i].line;
1155 for (; *c; c++) {
1156 if (!isalnum(*c))
1157 continue;
1158 alnum_count++;
1159 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1160 return 1;
1163 for (i = 1; i < block_length + 1; i++)
1164 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1165 return 0;
1168 /* Find blocks of moved code, delegate actual coloring decision to helper */
1169 static void mark_color_as_moved(struct diff_options *o,
1170 struct moved_entry_list *entry_list)
1172 struct moved_block *pmb = NULL; /* potentially moved blocks */
1173 int pmb_nr = 0, pmb_alloc = 0;
1174 int n, flipped_block = 0, block_length = 0;
1175 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1178 for (n = 0; n < o->emitted_symbols->nr; n++) {
1179 struct moved_entry *match = NULL;
1180 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1182 switch (l->s) {
1183 case DIFF_SYMBOL_PLUS:
1184 match = entry_list[l->id].del;
1185 break;
1186 case DIFF_SYMBOL_MINUS:
1187 match = entry_list[l->id].add;
1188 break;
1189 default:
1190 flipped_block = 0;
1193 if (pmb_nr && (!match || l->s != moved_symbol)) {
1194 if (!adjust_last_block(o, n, block_length) &&
1195 block_length > 1) {
1197 * Rewind in case there is another match
1198 * starting at the second line of the block
1200 match = NULL;
1201 n -= block_length;
1203 pmb_nr = 0;
1204 block_length = 0;
1205 flipped_block = 0;
1207 if (!match) {
1208 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1209 continue;
1212 if (o->color_moved == COLOR_MOVED_PLAIN) {
1213 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1214 continue;
1217 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1219 if (pmb_nr == 0) {
1220 int contiguous = adjust_last_block(o, n, block_length);
1222 if (!contiguous && block_length > 1)
1224 * Rewind in case there is another match
1225 * starting at the second line of the block
1227 n -= block_length;
1228 else
1229 fill_potential_moved_blocks(o, match, l,
1230 &pmb, &pmb_alloc,
1231 &pmb_nr);
1233 if (contiguous && pmb_nr && moved_symbol == l->s)
1234 flipped_block = (flipped_block + 1) % 2;
1235 else
1236 flipped_block = 0;
1238 if (pmb_nr)
1239 moved_symbol = l->s;
1240 else
1241 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1243 block_length = 0;
1246 if (pmb_nr) {
1247 block_length++;
1248 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1249 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1250 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1253 adjust_last_block(o, n, block_length);
1255 free(pmb);
1258 static void dim_moved_lines(struct diff_options *o)
1260 int n;
1261 for (n = 0; n < o->emitted_symbols->nr; n++) {
1262 struct emitted_diff_symbol *prev = (n != 0) ?
1263 &o->emitted_symbols->buf[n - 1] : NULL;
1264 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1265 struct emitted_diff_symbol *next =
1266 (n < o->emitted_symbols->nr - 1) ?
1267 &o->emitted_symbols->buf[n + 1] : NULL;
1269 /* Not a plus or minus line? */
1270 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1271 continue;
1273 /* Not a moved line? */
1274 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1275 continue;
1278 * If prev or next are not a plus or minus line,
1279 * pretend they don't exist
1281 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1282 prev->s != DIFF_SYMBOL_MINUS)
1283 prev = NULL;
1284 if (next && next->s != DIFF_SYMBOL_PLUS &&
1285 next->s != DIFF_SYMBOL_MINUS)
1286 next = NULL;
1288 /* Inside a block? */
1289 if ((prev &&
1290 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1291 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1292 (next &&
1293 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1294 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1295 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1296 continue;
1299 /* Check if we are at an interesting bound: */
1300 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1301 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1302 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1303 continue;
1304 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1305 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1306 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1307 continue;
1310 * The boundary to prev and next are not interesting,
1311 * so this line is not interesting as a whole
1313 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1317 static void emit_line_ws_markup(struct diff_options *o,
1318 const char *set_sign, const char *set,
1319 const char *reset,
1320 int sign_index, const char *line, int len,
1321 unsigned ws_rule, int blank_at_eof)
1323 const char *ws = NULL;
1324 int sign = o->output_indicators[sign_index];
1326 if (o->ws_error_highlight & ws_rule) {
1327 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1328 if (!*ws)
1329 ws = NULL;
1332 if (!ws && !set_sign)
1333 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1334 else if (!ws) {
1335 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1336 } else if (blank_at_eof)
1337 /* Blank line at EOF - paint '+' as well */
1338 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1339 else {
1340 /* Emit just the prefix, then the rest. */
1341 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1342 sign, "", 0);
1343 ws_check_emit(line, len, ws_rule,
1344 o->file, set, reset, ws);
1348 static void emit_diff_symbol_from_struct(struct diff_options *o,
1349 struct emitted_diff_symbol *eds)
1351 static const char *nneof = " No newline at end of file\n";
1352 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1354 enum diff_symbol s = eds->s;
1355 const char *line = eds->line;
1356 int len = eds->len;
1357 unsigned flags = eds->flags;
1359 switch (s) {
1360 case DIFF_SYMBOL_NO_LF_EOF:
1361 context = diff_get_color_opt(o, DIFF_CONTEXT);
1362 reset = diff_get_color_opt(o, DIFF_RESET);
1363 putc('\n', o->file);
1364 emit_line_0(o, context, NULL, 0, reset, '\\',
1365 nneof, strlen(nneof));
1366 break;
1367 case DIFF_SYMBOL_SUBMODULE_HEADER:
1368 case DIFF_SYMBOL_SUBMODULE_ERROR:
1369 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1370 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1371 case DIFF_SYMBOL_SUMMARY:
1372 case DIFF_SYMBOL_STATS_LINE:
1373 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1374 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1375 emit_line(o, "", "", line, len);
1376 break;
1377 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1378 case DIFF_SYMBOL_CONTEXT_MARKER:
1379 context = diff_get_color_opt(o, DIFF_CONTEXT);
1380 reset = diff_get_color_opt(o, DIFF_RESET);
1381 emit_line(o, context, reset, line, len);
1382 break;
1383 case DIFF_SYMBOL_SEPARATOR:
1384 fprintf(o->file, "%s%c",
1385 diff_line_prefix(o),
1386 o->line_termination);
1387 break;
1388 case DIFF_SYMBOL_CONTEXT:
1389 set = diff_get_color_opt(o, DIFF_CONTEXT);
1390 reset = diff_get_color_opt(o, DIFF_RESET);
1391 set_sign = NULL;
1392 if (o->flags.dual_color_diffed_diffs) {
1393 char c = !len ? 0 : line[0];
1395 if (c == '+')
1396 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1397 else if (c == '@')
1398 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1399 else if (c == '-')
1400 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1402 emit_line_ws_markup(o, set_sign, set, reset,
1403 OUTPUT_INDICATOR_CONTEXT, line, len,
1404 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1405 break;
1406 case DIFF_SYMBOL_PLUS:
1407 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1408 DIFF_SYMBOL_MOVED_LINE_ALT |
1409 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1410 case DIFF_SYMBOL_MOVED_LINE |
1411 DIFF_SYMBOL_MOVED_LINE_ALT |
1412 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1413 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1414 break;
1415 case DIFF_SYMBOL_MOVED_LINE |
1416 DIFF_SYMBOL_MOVED_LINE_ALT:
1417 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1418 break;
1419 case DIFF_SYMBOL_MOVED_LINE |
1420 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1421 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1422 break;
1423 case DIFF_SYMBOL_MOVED_LINE:
1424 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1425 break;
1426 default:
1427 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1429 reset = diff_get_color_opt(o, DIFF_RESET);
1430 if (!o->flags.dual_color_diffed_diffs)
1431 set_sign = NULL;
1432 else {
1433 char c = !len ? 0 : line[0];
1435 set_sign = set;
1436 if (c == '-')
1437 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1438 else if (c == '@')
1439 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1440 else if (c == '+')
1441 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1442 else
1443 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1444 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1446 emit_line_ws_markup(o, set_sign, set, reset,
1447 OUTPUT_INDICATOR_NEW, line, len,
1448 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1449 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1450 break;
1451 case DIFF_SYMBOL_MINUS:
1452 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1453 DIFF_SYMBOL_MOVED_LINE_ALT |
1454 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1455 case DIFF_SYMBOL_MOVED_LINE |
1456 DIFF_SYMBOL_MOVED_LINE_ALT |
1457 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1458 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1459 break;
1460 case DIFF_SYMBOL_MOVED_LINE |
1461 DIFF_SYMBOL_MOVED_LINE_ALT:
1462 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1463 break;
1464 case DIFF_SYMBOL_MOVED_LINE |
1465 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1466 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1467 break;
1468 case DIFF_SYMBOL_MOVED_LINE:
1469 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1470 break;
1471 default:
1472 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1474 reset = diff_get_color_opt(o, DIFF_RESET);
1475 if (!o->flags.dual_color_diffed_diffs)
1476 set_sign = NULL;
1477 else {
1478 char c = !len ? 0 : line[0];
1480 set_sign = set;
1481 if (c == '+')
1482 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1483 else if (c == '@')
1484 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1485 else if (c == '-')
1486 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1487 else
1488 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1490 emit_line_ws_markup(o, set_sign, set, reset,
1491 OUTPUT_INDICATOR_OLD, line, len,
1492 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1493 break;
1494 case DIFF_SYMBOL_WORDS_PORCELAIN:
1495 context = diff_get_color_opt(o, DIFF_CONTEXT);
1496 reset = diff_get_color_opt(o, DIFF_RESET);
1497 emit_line(o, context, reset, line, len);
1498 fputs("~\n", o->file);
1499 break;
1500 case DIFF_SYMBOL_WORDS:
1501 context = diff_get_color_opt(o, DIFF_CONTEXT);
1502 reset = diff_get_color_opt(o, DIFF_RESET);
1504 * Skip the prefix character, if any. With
1505 * diff_suppress_blank_empty, there may be
1506 * none.
1508 if (line[0] != '\n') {
1509 line++;
1510 len--;
1512 emit_line(o, context, reset, line, len);
1513 break;
1514 case DIFF_SYMBOL_FILEPAIR_PLUS:
1515 meta = diff_get_color_opt(o, DIFF_METAINFO);
1516 reset = diff_get_color_opt(o, DIFF_RESET);
1517 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1518 line, reset,
1519 strchr(line, ' ') ? "\t" : "");
1520 break;
1521 case DIFF_SYMBOL_FILEPAIR_MINUS:
1522 meta = diff_get_color_opt(o, DIFF_METAINFO);
1523 reset = diff_get_color_opt(o, DIFF_RESET);
1524 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1525 line, reset,
1526 strchr(line, ' ') ? "\t" : "");
1527 break;
1528 case DIFF_SYMBOL_BINARY_FILES:
1529 case DIFF_SYMBOL_HEADER:
1530 fprintf(o->file, "%s", line);
1531 break;
1532 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1533 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1534 break;
1535 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1536 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1537 break;
1538 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1539 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1540 break;
1541 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1542 fputs(diff_line_prefix(o), o->file);
1543 fputc('\n', o->file);
1544 break;
1545 case DIFF_SYMBOL_REWRITE_DIFF:
1546 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1547 reset = diff_get_color_opt(o, DIFF_RESET);
1548 emit_line(o, fraginfo, reset, line, len);
1549 break;
1550 case DIFF_SYMBOL_SUBMODULE_ADD:
1551 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1552 reset = diff_get_color_opt(o, DIFF_RESET);
1553 emit_line(o, set, reset, line, len);
1554 break;
1555 case DIFF_SYMBOL_SUBMODULE_DEL:
1556 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1557 reset = diff_get_color_opt(o, DIFF_RESET);
1558 emit_line(o, set, reset, line, len);
1559 break;
1560 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1561 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1562 diff_line_prefix(o), line);
1563 break;
1564 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1565 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1566 diff_line_prefix(o), line);
1567 break;
1568 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1569 emit_line(o, "", "", " 0 files changed\n",
1570 strlen(" 0 files changed\n"));
1571 break;
1572 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1573 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1574 break;
1575 case DIFF_SYMBOL_WORD_DIFF:
1576 fprintf(o->file, "%.*s", len, line);
1577 break;
1578 case DIFF_SYMBOL_STAT_SEP:
1579 fputs(o->stat_sep, o->file);
1580 break;
1581 default:
1582 BUG("unknown diff symbol");
1586 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1587 const char *line, int len, unsigned flags)
1589 struct emitted_diff_symbol e = {
1590 .line = line, .len = len, .flags = flags, .s = s
1593 if (o->emitted_symbols)
1594 append_emitted_diff_symbol(o, &e);
1595 else
1596 emit_diff_symbol_from_struct(o, &e);
1599 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1601 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1604 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1606 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1609 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1611 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1612 path, strlen(path), 0);
1615 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1617 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1618 path, strlen(path), 0);
1621 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1623 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1624 header, strlen(header), 0);
1627 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1629 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1632 void diff_emit_submodule_pipethrough(struct diff_options *o,
1633 const char *line, int len)
1635 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1638 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1640 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1641 ecbdata->blank_at_eof_in_preimage &&
1642 ecbdata->blank_at_eof_in_postimage &&
1643 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1644 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1645 return 0;
1646 return ws_blank_line(line, len);
1649 static void emit_add_line(struct emit_callback *ecbdata,
1650 const char *line, int len)
1652 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1653 if (new_blank_line_at_eof(ecbdata, line, len))
1654 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1656 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1659 static void emit_del_line(struct emit_callback *ecbdata,
1660 const char *line, int len)
1662 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1663 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1666 static void emit_context_line(struct emit_callback *ecbdata,
1667 const char *line, int len)
1669 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1670 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1673 static void emit_hunk_header(struct emit_callback *ecbdata,
1674 const char *line, int len)
1676 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1677 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1678 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1679 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1680 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1681 static const char atat[2] = { '@', '@' };
1682 const char *cp, *ep;
1683 struct strbuf msgbuf = STRBUF_INIT;
1684 int org_len = len;
1685 int i = 1;
1688 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1689 * it always is at least 10 bytes long.
1691 if (len < 10 ||
1692 memcmp(line, atat, 2) ||
1693 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1694 emit_diff_symbol(ecbdata->opt,
1695 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1696 return;
1698 ep += 2; /* skip over @@ */
1700 /* The hunk header in fraginfo color */
1701 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1702 strbuf_addstr(&msgbuf, reverse);
1703 strbuf_addstr(&msgbuf, frag);
1704 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1705 strbuf_add(&msgbuf, atat, sizeof(atat));
1706 else
1707 strbuf_add(&msgbuf, line, ep - line);
1708 strbuf_addstr(&msgbuf, reset);
1711 * trailing "\r\n"
1713 for ( ; i < 3; i++)
1714 if (line[len - i] == '\r' || line[len - i] == '\n')
1715 len--;
1717 /* blank before the func header */
1718 for (cp = ep; ep - line < len; ep++)
1719 if (*ep != ' ' && *ep != '\t')
1720 break;
1721 if (ep != cp) {
1722 strbuf_addstr(&msgbuf, context);
1723 strbuf_add(&msgbuf, cp, ep - cp);
1724 strbuf_addstr(&msgbuf, reset);
1727 if (ep < line + len) {
1728 strbuf_addstr(&msgbuf, func);
1729 strbuf_add(&msgbuf, ep, line + len - ep);
1730 strbuf_addstr(&msgbuf, reset);
1733 strbuf_add(&msgbuf, line + len, org_len - len);
1734 strbuf_complete_line(&msgbuf);
1735 emit_diff_symbol(ecbdata->opt,
1736 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1737 strbuf_release(&msgbuf);
1740 static struct diff_tempfile *claim_diff_tempfile(void)
1742 int i;
1743 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1744 if (!diff_temp[i].name)
1745 return diff_temp + i;
1746 BUG("diff is failing to clean up its tempfiles");
1749 static void remove_tempfile(void)
1751 int i;
1752 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1753 if (is_tempfile_active(diff_temp[i].tempfile))
1754 delete_tempfile(&diff_temp[i].tempfile);
1755 diff_temp[i].name = NULL;
1759 static void add_line_count(struct strbuf *out, int count)
1761 switch (count) {
1762 case 0:
1763 strbuf_addstr(out, "0,0");
1764 break;
1765 case 1:
1766 strbuf_addstr(out, "1");
1767 break;
1768 default:
1769 strbuf_addf(out, "1,%d", count);
1770 break;
1774 static void emit_rewrite_lines(struct emit_callback *ecb,
1775 int prefix, const char *data, int size)
1777 const char *endp = NULL;
1779 while (0 < size) {
1780 int len;
1782 endp = memchr(data, '\n', size);
1783 len = endp ? (endp - data + 1) : size;
1784 if (prefix != '+') {
1785 ecb->lno_in_preimage++;
1786 emit_del_line(ecb, data, len);
1787 } else {
1788 ecb->lno_in_postimage++;
1789 emit_add_line(ecb, data, len);
1791 size -= len;
1792 data += len;
1794 if (!endp)
1795 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1798 static void emit_rewrite_diff(const char *name_a,
1799 const char *name_b,
1800 struct diff_filespec *one,
1801 struct diff_filespec *two,
1802 struct userdiff_driver *textconv_one,
1803 struct userdiff_driver *textconv_two,
1804 struct diff_options *o)
1806 int lc_a, lc_b;
1807 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1808 const char *a_prefix, *b_prefix;
1809 char *data_one, *data_two;
1810 size_t size_one, size_two;
1811 struct emit_callback ecbdata;
1812 struct strbuf out = STRBUF_INIT;
1814 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1815 a_prefix = o->b_prefix;
1816 b_prefix = o->a_prefix;
1817 } else {
1818 a_prefix = o->a_prefix;
1819 b_prefix = o->b_prefix;
1822 name_a += (*name_a == '/');
1823 name_b += (*name_b == '/');
1825 strbuf_reset(&a_name);
1826 strbuf_reset(&b_name);
1827 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1828 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1830 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1831 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1833 memset(&ecbdata, 0, sizeof(ecbdata));
1834 ecbdata.color_diff = want_color(o->use_color);
1835 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1836 ecbdata.opt = o;
1837 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1838 mmfile_t mf1, mf2;
1839 mf1.ptr = (char *)data_one;
1840 mf2.ptr = (char *)data_two;
1841 mf1.size = size_one;
1842 mf2.size = size_two;
1843 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1845 ecbdata.lno_in_preimage = 1;
1846 ecbdata.lno_in_postimage = 1;
1848 lc_a = count_lines(data_one, size_one);
1849 lc_b = count_lines(data_two, size_two);
1851 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1852 a_name.buf, a_name.len, 0);
1853 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1854 b_name.buf, b_name.len, 0);
1856 strbuf_addstr(&out, "@@ -");
1857 if (!o->irreversible_delete)
1858 add_line_count(&out, lc_a);
1859 else
1860 strbuf_addstr(&out, "?,?");
1861 strbuf_addstr(&out, " +");
1862 add_line_count(&out, lc_b);
1863 strbuf_addstr(&out, " @@\n");
1864 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1865 strbuf_release(&out);
1867 if (lc_a && !o->irreversible_delete)
1868 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1869 if (lc_b)
1870 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1871 if (textconv_one)
1872 free((char *)data_one);
1873 if (textconv_two)
1874 free((char *)data_two);
1877 struct diff_words_buffer {
1878 mmfile_t text;
1879 unsigned long alloc;
1880 struct diff_words_orig {
1881 const char *begin, *end;
1882 } *orig;
1883 int orig_nr, orig_alloc;
1886 static void diff_words_append(char *line, unsigned long len,
1887 struct diff_words_buffer *buffer)
1889 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1890 line++;
1891 len--;
1892 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1893 buffer->text.size += len;
1894 buffer->text.ptr[buffer->text.size] = '\0';
1897 struct diff_words_style_elem {
1898 const char *prefix;
1899 const char *suffix;
1900 const char *color; /* NULL; filled in by the setup code if
1901 * color is enabled */
1904 struct diff_words_style {
1905 enum diff_words_type type;
1906 struct diff_words_style_elem new_word, old_word, ctx;
1907 const char *newline;
1910 static struct diff_words_style diff_words_styles[] = {
1911 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1912 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1913 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1916 struct diff_words_data {
1917 struct diff_words_buffer minus, plus;
1918 const char *current_plus;
1919 int last_minus;
1920 struct diff_options *opt;
1921 regex_t *word_regex;
1922 enum diff_words_type type;
1923 struct diff_words_style *style;
1926 static int fn_out_diff_words_write_helper(struct diff_options *o,
1927 struct diff_words_style_elem *st_el,
1928 const char *newline,
1929 size_t count, const char *buf)
1931 int print = 0;
1932 struct strbuf sb = STRBUF_INIT;
1934 while (count) {
1935 char *p = memchr(buf, '\n', count);
1936 if (print)
1937 strbuf_addstr(&sb, diff_line_prefix(o));
1939 if (p != buf) {
1940 const char *reset = st_el->color && *st_el->color ?
1941 GIT_COLOR_RESET : NULL;
1942 if (st_el->color && *st_el->color)
1943 strbuf_addstr(&sb, st_el->color);
1944 strbuf_addstr(&sb, st_el->prefix);
1945 strbuf_add(&sb, buf, p ? p - buf : count);
1946 strbuf_addstr(&sb, st_el->suffix);
1947 if (reset)
1948 strbuf_addstr(&sb, reset);
1950 if (!p)
1951 goto out;
1953 strbuf_addstr(&sb, newline);
1954 count -= p + 1 - buf;
1955 buf = p + 1;
1956 print = 1;
1957 if (count) {
1958 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1959 sb.buf, sb.len, 0);
1960 strbuf_reset(&sb);
1964 out:
1965 if (sb.len)
1966 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1967 sb.buf, sb.len, 0);
1968 strbuf_release(&sb);
1969 return 0;
1973 * '--color-words' algorithm can be described as:
1975 * 1. collect the minus/plus lines of a diff hunk, divided into
1976 * minus-lines and plus-lines;
1978 * 2. break both minus-lines and plus-lines into words and
1979 * place them into two mmfile_t with one word for each line;
1981 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1983 * And for the common parts of the both file, we output the plus side text.
1984 * diff_words->current_plus is used to trace the current position of the plus file
1985 * which printed. diff_words->last_minus is used to trace the last minus word
1986 * printed.
1988 * For '--graph' to work with '--color-words', we need to output the graph prefix
1989 * on each line of color words output. Generally, there are two conditions on
1990 * which we should output the prefix.
1992 * 1. diff_words->last_minus == 0 &&
1993 * diff_words->current_plus == diff_words->plus.text.ptr
1995 * that is: the plus text must start as a new line, and if there is no minus
1996 * word printed, a graph prefix must be printed.
1998 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1999 * *(diff_words->current_plus - 1) == '\n'
2001 * that is: a graph prefix must be printed following a '\n'
2003 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
2005 if ((diff_words->last_minus == 0 &&
2006 diff_words->current_plus == diff_words->plus.text.ptr) ||
2007 (diff_words->current_plus > diff_words->plus.text.ptr &&
2008 *(diff_words->current_plus - 1) == '\n')) {
2009 return 1;
2010 } else {
2011 return 0;
2015 static void fn_out_diff_words_aux(void *priv,
2016 long minus_first, long minus_len,
2017 long plus_first, long plus_len,
2018 const char *func UNUSED, long funclen UNUSED)
2020 struct diff_words_data *diff_words = priv;
2021 struct diff_words_style *style = diff_words->style;
2022 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2023 struct diff_options *opt = diff_words->opt;
2024 const char *line_prefix;
2026 assert(opt);
2027 line_prefix = diff_line_prefix(opt);
2029 /* POSIX requires that first be decremented by one if len == 0... */
2030 if (minus_len) {
2031 minus_begin = diff_words->minus.orig[minus_first].begin;
2032 minus_end =
2033 diff_words->minus.orig[minus_first + minus_len - 1].end;
2034 } else
2035 minus_begin = minus_end =
2036 diff_words->minus.orig[minus_first].end;
2038 if (plus_len) {
2039 plus_begin = diff_words->plus.orig[plus_first].begin;
2040 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2041 } else
2042 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2044 if (color_words_output_graph_prefix(diff_words)) {
2045 fputs(line_prefix, diff_words->opt->file);
2047 if (diff_words->current_plus != plus_begin) {
2048 fn_out_diff_words_write_helper(diff_words->opt,
2049 &style->ctx, style->newline,
2050 plus_begin - diff_words->current_plus,
2051 diff_words->current_plus);
2053 if (minus_begin != minus_end) {
2054 fn_out_diff_words_write_helper(diff_words->opt,
2055 &style->old_word, style->newline,
2056 minus_end - minus_begin, minus_begin);
2058 if (plus_begin != plus_end) {
2059 fn_out_diff_words_write_helper(diff_words->opt,
2060 &style->new_word, style->newline,
2061 plus_end - plus_begin, plus_begin);
2064 diff_words->current_plus = plus_end;
2065 diff_words->last_minus = minus_first;
2068 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2069 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2070 int *begin, int *end)
2072 while (word_regex && *begin < buffer->size) {
2073 regmatch_t match[1];
2074 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2075 buffer->size - *begin, 1, match, 0)) {
2076 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2077 '\n', match[0].rm_eo - match[0].rm_so);
2078 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2079 *begin += match[0].rm_so;
2080 if (*begin == *end)
2081 (*begin)++;
2082 else
2083 return *begin > *end;
2084 } else {
2085 return -1;
2089 /* find the next word */
2090 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2091 (*begin)++;
2092 if (*begin >= buffer->size)
2093 return -1;
2095 /* find the end of the word */
2096 *end = *begin + 1;
2097 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2098 (*end)++;
2100 return 0;
2104 * This function splits the words in buffer->text, stores the list with
2105 * newline separator into out, and saves the offsets of the original words
2106 * in buffer->orig.
2108 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2109 regex_t *word_regex)
2111 int i, j;
2112 long alloc = 0;
2114 out->size = 0;
2115 out->ptr = NULL;
2117 /* fake an empty "0th" word */
2118 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2119 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2120 buffer->orig_nr = 1;
2122 for (i = 0; i < buffer->text.size; i++) {
2123 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2124 return;
2126 /* store original boundaries */
2127 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2128 buffer->orig_alloc);
2129 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2130 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2131 buffer->orig_nr++;
2133 /* store one word */
2134 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2135 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2136 out->ptr[out->size + j - i] = '\n';
2137 out->size += j - i + 1;
2139 i = j - 1;
2143 /* this executes the word diff on the accumulated buffers */
2144 static void diff_words_show(struct diff_words_data *diff_words)
2146 xpparam_t xpp;
2147 xdemitconf_t xecfg;
2148 mmfile_t minus, plus;
2149 struct diff_words_style *style = diff_words->style;
2151 struct diff_options *opt = diff_words->opt;
2152 const char *line_prefix;
2154 assert(opt);
2155 line_prefix = diff_line_prefix(opt);
2157 /* special case: only removal */
2158 if (!diff_words->plus.text.size) {
2159 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2160 line_prefix, strlen(line_prefix), 0);
2161 fn_out_diff_words_write_helper(diff_words->opt,
2162 &style->old_word, style->newline,
2163 diff_words->minus.text.size,
2164 diff_words->minus.text.ptr);
2165 diff_words->minus.text.size = 0;
2166 return;
2169 diff_words->current_plus = diff_words->plus.text.ptr;
2170 diff_words->last_minus = 0;
2172 memset(&xpp, 0, sizeof(xpp));
2173 memset(&xecfg, 0, sizeof(xecfg));
2174 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2175 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2176 xpp.flags = 0;
2177 /* as only the hunk header will be parsed, we need a 0-context */
2178 xecfg.ctxlen = 0;
2179 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2180 diff_words, &xpp, &xecfg))
2181 die("unable to generate word diff");
2182 free(minus.ptr);
2183 free(plus.ptr);
2184 if (diff_words->current_plus != diff_words->plus.text.ptr +
2185 diff_words->plus.text.size) {
2186 if (color_words_output_graph_prefix(diff_words))
2187 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2188 line_prefix, strlen(line_prefix), 0);
2189 fn_out_diff_words_write_helper(diff_words->opt,
2190 &style->ctx, style->newline,
2191 diff_words->plus.text.ptr + diff_words->plus.text.size
2192 - diff_words->current_plus, diff_words->current_plus);
2194 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2197 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2198 static void diff_words_flush(struct emit_callback *ecbdata)
2200 struct diff_options *wo = ecbdata->diff_words->opt;
2202 if (ecbdata->diff_words->minus.text.size ||
2203 ecbdata->diff_words->plus.text.size)
2204 diff_words_show(ecbdata->diff_words);
2206 if (wo->emitted_symbols) {
2207 struct diff_options *o = ecbdata->opt;
2208 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2209 int i;
2212 * NEEDSWORK:
2213 * Instead of appending each, concat all words to a line?
2215 for (i = 0; i < wol->nr; i++)
2216 append_emitted_diff_symbol(o, &wol->buf[i]);
2218 for (i = 0; i < wol->nr; i++)
2219 free((void *)wol->buf[i].line);
2221 wol->nr = 0;
2225 static void diff_filespec_load_driver(struct diff_filespec *one,
2226 struct index_state *istate)
2228 /* Use already-loaded driver */
2229 if (one->driver)
2230 return;
2232 if (S_ISREG(one->mode))
2233 one->driver = userdiff_find_by_path(istate, one->path);
2235 /* Fallback to default settings */
2236 if (!one->driver)
2237 one->driver = userdiff_find_by_name("default");
2240 static const char *userdiff_word_regex(struct diff_filespec *one,
2241 struct index_state *istate)
2243 diff_filespec_load_driver(one, istate);
2244 return one->driver->word_regex;
2247 static void init_diff_words_data(struct emit_callback *ecbdata,
2248 struct diff_options *orig_opts,
2249 struct diff_filespec *one,
2250 struct diff_filespec *two)
2252 int i;
2253 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2254 memcpy(o, orig_opts, sizeof(struct diff_options));
2256 CALLOC_ARRAY(ecbdata->diff_words, 1);
2257 ecbdata->diff_words->type = o->word_diff;
2258 ecbdata->diff_words->opt = o;
2260 if (orig_opts->emitted_symbols)
2261 CALLOC_ARRAY(o->emitted_symbols, 1);
2263 if (!o->word_regex)
2264 o->word_regex = userdiff_word_regex(one, o->repo->index);
2265 if (!o->word_regex)
2266 o->word_regex = userdiff_word_regex(two, o->repo->index);
2267 if (!o->word_regex)
2268 o->word_regex = diff_word_regex_cfg;
2269 if (o->word_regex) {
2270 ecbdata->diff_words->word_regex = (regex_t *)
2271 xmalloc(sizeof(regex_t));
2272 if (regcomp(ecbdata->diff_words->word_regex,
2273 o->word_regex,
2274 REG_EXTENDED | REG_NEWLINE))
2275 die("invalid regular expression: %s",
2276 o->word_regex);
2278 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2279 if (o->word_diff == diff_words_styles[i].type) {
2280 ecbdata->diff_words->style =
2281 &diff_words_styles[i];
2282 break;
2285 if (want_color(o->use_color)) {
2286 struct diff_words_style *st = ecbdata->diff_words->style;
2287 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2288 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2289 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2293 static void free_diff_words_data(struct emit_callback *ecbdata)
2295 if (ecbdata->diff_words) {
2296 diff_words_flush(ecbdata);
2297 free_emitted_diff_symbols(ecbdata->diff_words->opt->emitted_symbols);
2298 free (ecbdata->diff_words->opt);
2299 free (ecbdata->diff_words->minus.text.ptr);
2300 free (ecbdata->diff_words->minus.orig);
2301 free (ecbdata->diff_words->plus.text.ptr);
2302 free (ecbdata->diff_words->plus.orig);
2303 if (ecbdata->diff_words->word_regex) {
2304 regfree(ecbdata->diff_words->word_regex);
2305 free(ecbdata->diff_words->word_regex);
2307 FREE_AND_NULL(ecbdata->diff_words);
2311 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2313 if (want_color(diff_use_color))
2314 return diff_colors[ix];
2315 return "";
2318 const char *diff_line_prefix(struct diff_options *opt)
2320 struct strbuf *msgbuf;
2321 if (!opt->output_prefix)
2322 return "";
2324 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2325 return msgbuf->buf;
2328 static unsigned long sane_truncate_line(char *line, unsigned long len)
2330 const char *cp;
2331 unsigned long allot;
2332 size_t l = len;
2334 cp = line;
2335 allot = l;
2336 while (0 < l) {
2337 (void) utf8_width(&cp, &l);
2338 if (!cp)
2339 break; /* truncated in the middle? */
2341 return allot - l;
2344 static void find_lno(const char *line, struct emit_callback *ecbdata)
2346 const char *p;
2347 ecbdata->lno_in_preimage = 0;
2348 ecbdata->lno_in_postimage = 0;
2349 p = strchr(line, '-');
2350 if (!p)
2351 return; /* cannot happen */
2352 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2353 p = strchr(p, '+');
2354 if (!p)
2355 return; /* cannot happen */
2356 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2359 static int fn_out_consume(void *priv, char *line, unsigned long len)
2361 struct emit_callback *ecbdata = priv;
2362 struct diff_options *o = ecbdata->opt;
2364 o->found_changes = 1;
2366 if (ecbdata->header) {
2367 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2368 ecbdata->header->buf, ecbdata->header->len, 0);
2369 strbuf_reset(ecbdata->header);
2370 ecbdata->header = NULL;
2373 if (ecbdata->label_path[0]) {
2374 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2375 ecbdata->label_path[0],
2376 strlen(ecbdata->label_path[0]), 0);
2377 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2378 ecbdata->label_path[1],
2379 strlen(ecbdata->label_path[1]), 0);
2380 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2383 if (diff_suppress_blank_empty
2384 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2385 line[0] = '\n';
2386 len = 1;
2389 if (line[0] == '@') {
2390 if (ecbdata->diff_words)
2391 diff_words_flush(ecbdata);
2392 len = sane_truncate_line(line, len);
2393 find_lno(line, ecbdata);
2394 emit_hunk_header(ecbdata, line, len);
2395 return 0;
2398 if (ecbdata->diff_words) {
2399 enum diff_symbol s =
2400 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2401 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2402 if (line[0] == '-') {
2403 diff_words_append(line, len,
2404 &ecbdata->diff_words->minus);
2405 return 0;
2406 } else if (line[0] == '+') {
2407 diff_words_append(line, len,
2408 &ecbdata->diff_words->plus);
2409 return 0;
2410 } else if (starts_with(line, "\\ ")) {
2412 * Eat the "no newline at eof" marker as if we
2413 * saw a "+" or "-" line with nothing on it,
2414 * and return without diff_words_flush() to
2415 * defer processing. If this is the end of
2416 * preimage, more "+" lines may come after it.
2418 return 0;
2420 diff_words_flush(ecbdata);
2421 emit_diff_symbol(o, s, line, len, 0);
2422 return 0;
2425 switch (line[0]) {
2426 case '+':
2427 ecbdata->lno_in_postimage++;
2428 emit_add_line(ecbdata, line + 1, len - 1);
2429 break;
2430 case '-':
2431 ecbdata->lno_in_preimage++;
2432 emit_del_line(ecbdata, line + 1, len - 1);
2433 break;
2434 case ' ':
2435 ecbdata->lno_in_postimage++;
2436 ecbdata->lno_in_preimage++;
2437 emit_context_line(ecbdata, line + 1, len - 1);
2438 break;
2439 default:
2440 /* incomplete line at the end */
2441 ecbdata->lno_in_preimage++;
2442 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2443 line, len, 0);
2444 break;
2446 return 0;
2449 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2451 const char *old_name = a;
2452 const char *new_name = b;
2453 int pfx_length, sfx_length;
2454 int pfx_adjust_for_slash;
2455 int len_a = strlen(a);
2456 int len_b = strlen(b);
2457 int a_midlen, b_midlen;
2458 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2459 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2461 if (qlen_a || qlen_b) {
2462 quote_c_style(a, name, NULL, 0);
2463 strbuf_addstr(name, " => ");
2464 quote_c_style(b, name, NULL, 0);
2465 return;
2468 /* Find common prefix */
2469 pfx_length = 0;
2470 while (*old_name && *new_name && *old_name == *new_name) {
2471 if (*old_name == '/')
2472 pfx_length = old_name - a + 1;
2473 old_name++;
2474 new_name++;
2477 /* Find common suffix */
2478 old_name = a + len_a;
2479 new_name = b + len_b;
2480 sfx_length = 0;
2482 * If there is a common prefix, it must end in a slash. In
2483 * that case we let this loop run 1 into the prefix to see the
2484 * same slash.
2486 * If there is no common prefix, we cannot do this as it would
2487 * underrun the input strings.
2489 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2490 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2491 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2492 *old_name == *new_name) {
2493 if (*old_name == '/')
2494 sfx_length = len_a - (old_name - a);
2495 old_name--;
2496 new_name--;
2500 * pfx{mid-a => mid-b}sfx
2501 * {pfx-a => pfx-b}sfx
2502 * pfx{sfx-a => sfx-b}
2503 * name-a => name-b
2505 a_midlen = len_a - pfx_length - sfx_length;
2506 b_midlen = len_b - pfx_length - sfx_length;
2507 if (a_midlen < 0)
2508 a_midlen = 0;
2509 if (b_midlen < 0)
2510 b_midlen = 0;
2512 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2513 if (pfx_length + sfx_length) {
2514 strbuf_add(name, a, pfx_length);
2515 strbuf_addch(name, '{');
2517 strbuf_add(name, a + pfx_length, a_midlen);
2518 strbuf_addstr(name, " => ");
2519 strbuf_add(name, b + pfx_length, b_midlen);
2520 if (pfx_length + sfx_length) {
2521 strbuf_addch(name, '}');
2522 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2526 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2527 const char *name_a,
2528 const char *name_b)
2530 struct diffstat_file *x;
2531 CALLOC_ARRAY(x, 1);
2532 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2533 diffstat->files[diffstat->nr++] = x;
2534 if (name_b) {
2535 x->from_name = xstrdup(name_a);
2536 x->name = xstrdup(name_b);
2537 x->is_renamed = 1;
2539 else {
2540 x->from_name = NULL;
2541 x->name = xstrdup(name_a);
2543 return x;
2546 static int diffstat_consume(void *priv, char *line, unsigned long len)
2548 struct diffstat_t *diffstat = priv;
2549 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2551 if (!len)
2552 BUG("xdiff fed us an empty line");
2554 if (line[0] == '+')
2555 x->added++;
2556 else if (line[0] == '-')
2557 x->deleted++;
2558 return 0;
2561 const char mime_boundary_leader[] = "------------";
2563 static int scale_linear(int it, int width, int max_change)
2565 if (!it)
2566 return 0;
2568 * make sure that at least one '-' or '+' is printed if
2569 * there is any change to this path. The easiest way is to
2570 * scale linearly as if the allotted width is one column shorter
2571 * than it is, and then add 1 to the result.
2573 return 1 + (it * (width - 1) / max_change);
2576 static void show_graph(struct strbuf *out, char ch, int cnt,
2577 const char *set, const char *reset)
2579 if (cnt <= 0)
2580 return;
2581 strbuf_addstr(out, set);
2582 strbuf_addchars(out, ch, cnt);
2583 strbuf_addstr(out, reset);
2586 static void fill_print_name(struct diffstat_file *file)
2588 struct strbuf pname = STRBUF_INIT;
2590 if (file->print_name)
2591 return;
2593 if (file->is_renamed)
2594 pprint_rename(&pname, file->from_name, file->name);
2595 else
2596 quote_c_style(file->name, &pname, NULL, 0);
2598 if (file->comments)
2599 strbuf_addf(&pname, " (%s)", file->comments);
2601 file->print_name = strbuf_detach(&pname, NULL);
2604 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2605 int files, int insertions, int deletions)
2607 struct strbuf sb = STRBUF_INIT;
2609 if (!files) {
2610 assert(insertions == 0 && deletions == 0);
2611 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2612 NULL, 0, 0);
2613 return;
2616 strbuf_addf(&sb,
2617 (files == 1) ? " %d file changed" : " %d files changed",
2618 files);
2621 * For binary diff, the caller may want to print "x files
2622 * changed" with insertions == 0 && deletions == 0.
2624 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2625 * is probably less confusing (i.e skip over "2 files changed
2626 * but nothing about added/removed lines? Is this a bug in Git?").
2628 if (insertions || deletions == 0) {
2629 strbuf_addf(&sb,
2630 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2631 insertions);
2634 if (deletions || insertions == 0) {
2635 strbuf_addf(&sb,
2636 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2637 deletions);
2639 strbuf_addch(&sb, '\n');
2640 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2641 sb.buf, sb.len, 0);
2642 strbuf_release(&sb);
2645 void print_stat_summary(FILE *fp, int files,
2646 int insertions, int deletions)
2648 struct diff_options o;
2649 memset(&o, 0, sizeof(o));
2650 o.file = fp;
2652 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2655 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2657 int i, len, add, del, adds = 0, dels = 0;
2658 uintmax_t max_change = 0, max_len = 0;
2659 int total_files = data->nr, count;
2660 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2661 const char *reset, *add_c, *del_c;
2662 int extra_shown = 0;
2663 const char *line_prefix = diff_line_prefix(options);
2664 struct strbuf out = STRBUF_INIT;
2666 if (data->nr == 0)
2667 return;
2669 count = options->stat_count ? options->stat_count : data->nr;
2671 reset = diff_get_color_opt(options, DIFF_RESET);
2672 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2673 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2676 * Find the longest filename and max number of changes
2678 for (i = 0; (i < count) && (i < data->nr); i++) {
2679 struct diffstat_file *file = data->files[i];
2680 uintmax_t change = file->added + file->deleted;
2682 if (!file->is_interesting && (change == 0)) {
2683 count++; /* not shown == room for one more */
2684 continue;
2686 fill_print_name(file);
2687 len = utf8_strwidth(file->print_name);
2688 if (max_len < len)
2689 max_len = len;
2691 if (file->is_unmerged) {
2692 /* "Unmerged" is 8 characters */
2693 bin_width = bin_width < 8 ? 8 : bin_width;
2694 continue;
2696 if (file->is_binary) {
2697 /* "Bin XXX -> YYY bytes" */
2698 int w = 14 + decimal_width(file->added)
2699 + decimal_width(file->deleted);
2700 bin_width = bin_width < w ? w : bin_width;
2701 /* Display change counts aligned with "Bin" */
2702 number_width = 3;
2703 continue;
2706 if (max_change < change)
2707 max_change = change;
2709 count = i; /* where we can stop scanning in data->files[] */
2712 * We have width = stat_width or term_columns() columns total.
2713 * We want a maximum of min(max_len, stat_name_width) for the name part.
2714 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2715 * We also need 1 for " " and 4 + decimal_width(max_change)
2716 * for " | NNNN " and one the empty column at the end, altogether
2717 * 6 + decimal_width(max_change).
2719 * If there's not enough space, we will use the smaller of
2720 * stat_name_width (if set) and 5/8*width for the filename,
2721 * and the rest for constant elements + graph part, but no more
2722 * than stat_graph_width for the graph part.
2723 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2724 * for the standard terminal size).
2726 * In other words: stat_width limits the maximum width, and
2727 * stat_name_width fixes the maximum width of the filename,
2728 * and is also used to divide available columns if there
2729 * aren't enough.
2731 * Binary files are displayed with "Bin XXX -> YYY bytes"
2732 * instead of the change count and graph. This part is treated
2733 * similarly to the graph part, except that it is not
2734 * "scaled". If total width is too small to accommodate the
2735 * guaranteed minimum width of the filename part and the
2736 * separators and this message, this message will "overflow"
2737 * making the line longer than the maximum width.
2741 * NEEDSWORK: line_prefix is often used for "log --graph" output
2742 * and contains ANSI-colored string. utf8_strnwidth() should be
2743 * used to correctly count the display width instead of strlen().
2745 if (options->stat_width == -1)
2746 width = term_columns() - strlen(line_prefix);
2747 else
2748 width = options->stat_width ? options->stat_width : 80;
2749 number_width = decimal_width(max_change) > number_width ?
2750 decimal_width(max_change) : number_width;
2752 if (options->stat_name_width == -1)
2753 options->stat_name_width = diff_stat_name_width;
2754 if (options->stat_graph_width == -1)
2755 options->stat_graph_width = diff_stat_graph_width;
2758 * Guarantee 3/8*16 == 6 for the graph part
2759 * and 5/8*16 == 10 for the filename part
2761 if (width < 16 + 6 + number_width)
2762 width = 16 + 6 + number_width;
2765 * First assign sizes that are wanted, ignoring available width.
2766 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2767 * starting from "XXX" should fit in graph_width.
2769 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2770 if (options->stat_graph_width &&
2771 options->stat_graph_width < graph_width)
2772 graph_width = options->stat_graph_width;
2774 name_width = (options->stat_name_width > 0 &&
2775 options->stat_name_width < max_len) ?
2776 options->stat_name_width : max_len;
2779 * Adjust adjustable widths not to exceed maximum width
2781 if (name_width + number_width + 6 + graph_width > width) {
2782 if (graph_width > width * 3/8 - number_width - 6) {
2783 graph_width = width * 3/8 - number_width - 6;
2784 if (graph_width < 6)
2785 graph_width = 6;
2788 if (options->stat_graph_width &&
2789 graph_width > options->stat_graph_width)
2790 graph_width = options->stat_graph_width;
2791 if (name_width > width - number_width - 6 - graph_width)
2792 name_width = width - number_width - 6 - graph_width;
2793 else
2794 graph_width = width - number_width - 6 - name_width;
2798 * From here name_width is the width of the name area,
2799 * and graph_width is the width of the graph area.
2800 * max_change is used to scale graph properly.
2802 for (i = 0; i < count; i++) {
2803 const char *prefix = "";
2804 struct diffstat_file *file = data->files[i];
2805 char *name = file->print_name;
2806 uintmax_t added = file->added;
2807 uintmax_t deleted = file->deleted;
2808 int name_len, padding;
2810 if (!file->is_interesting && (added + deleted == 0))
2811 continue;
2814 * "scale" the filename
2816 len = name_width;
2817 name_len = utf8_strwidth(name);
2818 if (name_width < name_len) {
2819 char *slash;
2820 prefix = "...";
2821 len -= 3;
2823 * NEEDSWORK: (name_len - len) counts the display
2824 * width, which would be shorter than the byte
2825 * length of the corresponding substring.
2826 * Advancing "name" by that number of bytes does
2827 * *NOT* skip over that many columns, so it is
2828 * very likely that chomping the pathname at the
2829 * slash we will find starting from "name" will
2830 * leave the resulting string still too long.
2832 name += name_len - len;
2833 slash = strchr(name, '/');
2834 if (slash)
2835 name = slash;
2837 padding = len - utf8_strwidth(name);
2838 if (padding < 0)
2839 padding = 0;
2841 if (file->is_binary) {
2842 strbuf_addf(&out, " %s%s%*s | %*s",
2843 prefix, name, padding, "",
2844 number_width, "Bin");
2845 if (!added && !deleted) {
2846 strbuf_addch(&out, '\n');
2847 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2848 out.buf, out.len, 0);
2849 strbuf_reset(&out);
2850 continue;
2852 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2853 del_c, deleted, reset);
2854 strbuf_addstr(&out, " -> ");
2855 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2856 add_c, added, reset);
2857 strbuf_addstr(&out, " bytes\n");
2858 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2859 out.buf, out.len, 0);
2860 strbuf_reset(&out);
2861 continue;
2863 else if (file->is_unmerged) {
2864 strbuf_addf(&out, " %s%s%*s | %*s",
2865 prefix, name, padding, "",
2866 number_width, "Unmerged\n");
2867 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2868 out.buf, out.len, 0);
2869 strbuf_reset(&out);
2870 continue;
2874 * scale the add/delete
2876 add = added;
2877 del = deleted;
2879 if (graph_width <= max_change) {
2880 int total = scale_linear(add + del, graph_width, max_change);
2881 if (total < 2 && add && del)
2882 /* width >= 2 due to the sanity check */
2883 total = 2;
2884 if (add < del) {
2885 add = scale_linear(add, graph_width, max_change);
2886 del = total - add;
2887 } else {
2888 del = scale_linear(del, graph_width, max_change);
2889 add = total - del;
2892 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2893 prefix, name, padding, "",
2894 number_width, added + deleted,
2895 added + deleted ? " " : "");
2896 show_graph(&out, '+', add, add_c, reset);
2897 show_graph(&out, '-', del, del_c, reset);
2898 strbuf_addch(&out, '\n');
2899 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2900 out.buf, out.len, 0);
2901 strbuf_reset(&out);
2904 for (i = 0; i < data->nr; i++) {
2905 struct diffstat_file *file = data->files[i];
2906 uintmax_t added = file->added;
2907 uintmax_t deleted = file->deleted;
2909 if (file->is_unmerged ||
2910 (!file->is_interesting && (added + deleted == 0))) {
2911 total_files--;
2912 continue;
2915 if (!file->is_binary) {
2916 adds += added;
2917 dels += deleted;
2919 if (i < count)
2920 continue;
2921 if (!extra_shown)
2922 emit_diff_symbol(options,
2923 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2924 NULL, 0, 0);
2925 extra_shown = 1;
2928 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2929 strbuf_release(&out);
2932 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2934 int i, adds = 0, dels = 0, total_files = data->nr;
2936 if (data->nr == 0)
2937 return;
2939 for (i = 0; i < data->nr; i++) {
2940 int added = data->files[i]->added;
2941 int deleted = data->files[i]->deleted;
2943 if (data->files[i]->is_unmerged ||
2944 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2945 total_files--;
2946 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2947 adds += added;
2948 dels += deleted;
2951 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2954 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2956 int i;
2958 if (data->nr == 0)
2959 return;
2961 for (i = 0; i < data->nr; i++) {
2962 struct diffstat_file *file = data->files[i];
2964 fprintf(options->file, "%s", diff_line_prefix(options));
2966 if (file->is_binary)
2967 fprintf(options->file, "-\t-\t");
2968 else
2969 fprintf(options->file,
2970 "%"PRIuMAX"\t%"PRIuMAX"\t",
2971 file->added, file->deleted);
2972 if (options->line_termination) {
2973 fill_print_name(file);
2974 if (!file->is_renamed)
2975 write_name_quoted(file->name, options->file,
2976 options->line_termination);
2977 else {
2978 fputs(file->print_name, options->file);
2979 putc(options->line_termination, options->file);
2981 } else {
2982 if (file->is_renamed) {
2983 putc('\0', options->file);
2984 write_name_quoted(file->from_name, options->file, '\0');
2986 write_name_quoted(file->name, options->file, '\0');
2991 struct dirstat_file {
2992 const char *name;
2993 unsigned long changed;
2996 struct dirstat_dir {
2997 struct dirstat_file *files;
2998 int alloc, nr, permille, cumulative;
3001 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
3002 unsigned long changed, const char *base, int baselen)
3004 unsigned long sum_changes = 0;
3005 unsigned int sources = 0;
3006 const char *line_prefix = diff_line_prefix(opt);
3008 while (dir->nr) {
3009 struct dirstat_file *f = dir->files;
3010 int namelen = strlen(f->name);
3011 unsigned long changes;
3012 char *slash;
3014 if (namelen < baselen)
3015 break;
3016 if (memcmp(f->name, base, baselen))
3017 break;
3018 slash = strchr(f->name + baselen, '/');
3019 if (slash) {
3020 int newbaselen = slash + 1 - f->name;
3021 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
3022 sources++;
3023 } else {
3024 changes = f->changed;
3025 dir->files++;
3026 dir->nr--;
3027 sources += 2;
3029 sum_changes += changes;
3033 * We don't report dirstat's for
3034 * - the top level
3035 * - or cases where everything came from a single directory
3036 * under this directory (sources == 1).
3038 if (baselen && sources != 1) {
3039 if (sum_changes) {
3040 int permille = sum_changes * 1000 / changed;
3041 if (permille >= dir->permille) {
3042 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3043 permille / 10, permille % 10, baselen, base);
3044 if (!dir->cumulative)
3045 return 0;
3049 return sum_changes;
3052 static int dirstat_compare(const void *_a, const void *_b)
3054 const struct dirstat_file *a = _a;
3055 const struct dirstat_file *b = _b;
3056 return strcmp(a->name, b->name);
3059 static void conclude_dirstat(struct diff_options *options,
3060 struct dirstat_dir *dir,
3061 unsigned long changed)
3063 struct dirstat_file *to_free = dir->files;
3065 if (!changed) {
3066 /* This can happen even with many files, if everything was renames */
3068 } else {
3069 /* Show all directories with more than x% of the changes */
3070 QSORT(dir->files, dir->nr, dirstat_compare);
3071 gather_dirstat(options, dir, changed, "", 0);
3074 free(to_free);
3077 static void show_dirstat(struct diff_options *options)
3079 int i;
3080 unsigned long changed;
3081 struct dirstat_dir dir;
3082 struct diff_queue_struct *q = &diff_queued_diff;
3084 dir.files = NULL;
3085 dir.alloc = 0;
3086 dir.nr = 0;
3087 dir.permille = options->dirstat_permille;
3088 dir.cumulative = options->flags.dirstat_cumulative;
3090 changed = 0;
3091 for (i = 0; i < q->nr; i++) {
3092 struct diff_filepair *p = q->queue[i];
3093 const char *name;
3094 unsigned long copied, added, damage;
3095 struct diff_populate_filespec_options dpf_options = {
3096 .check_size_only = 1,
3099 name = p->two->path ? p->two->path : p->one->path;
3101 if (p->one->oid_valid && p->two->oid_valid &&
3102 oideq(&p->one->oid, &p->two->oid)) {
3104 * The SHA1 has not changed, so pre-/post-content is
3105 * identical. We can therefore skip looking at the
3106 * file contents altogether.
3108 damage = 0;
3109 goto found_damage;
3112 if (options->flags.dirstat_by_file) {
3114 * In --dirstat-by-file mode, we don't really need to
3115 * look at the actual file contents at all.
3116 * The fact that the SHA1 changed is enough for us to
3117 * add this file to the list of results
3118 * (with each file contributing equal damage).
3120 damage = 1;
3121 goto found_damage;
3124 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3125 diff_populate_filespec(options->repo, p->one, NULL);
3126 diff_populate_filespec(options->repo, p->two, NULL);
3127 diffcore_count_changes(options->repo,
3128 p->one, p->two, NULL, NULL,
3129 &copied, &added);
3130 diff_free_filespec_data(p->one);
3131 diff_free_filespec_data(p->two);
3132 } else if (DIFF_FILE_VALID(p->one)) {
3133 diff_populate_filespec(options->repo, p->one, &dpf_options);
3134 copied = added = 0;
3135 diff_free_filespec_data(p->one);
3136 } else if (DIFF_FILE_VALID(p->two)) {
3137 diff_populate_filespec(options->repo, p->two, &dpf_options);
3138 copied = 0;
3139 added = p->two->size;
3140 diff_free_filespec_data(p->two);
3141 } else
3142 continue;
3145 * Original minus copied is the removed material,
3146 * added is the new material. They are both damages
3147 * made to the preimage.
3148 * If the resulting damage is zero, we know that
3149 * diffcore_count_changes() considers the two entries to
3150 * be identical, but since the oid changed, we
3151 * know that there must have been _some_ kind of change,
3152 * so we force all entries to have damage > 0.
3154 damage = (p->one->size - copied) + added;
3155 if (!damage)
3156 damage = 1;
3158 found_damage:
3159 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3160 dir.files[dir.nr].name = name;
3161 dir.files[dir.nr].changed = damage;
3162 changed += damage;
3163 dir.nr++;
3166 conclude_dirstat(options, &dir, changed);
3169 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3171 int i;
3172 unsigned long changed;
3173 struct dirstat_dir dir;
3175 if (data->nr == 0)
3176 return;
3178 dir.files = NULL;
3179 dir.alloc = 0;
3180 dir.nr = 0;
3181 dir.permille = options->dirstat_permille;
3182 dir.cumulative = options->flags.dirstat_cumulative;
3184 changed = 0;
3185 for (i = 0; i < data->nr; i++) {
3186 struct diffstat_file *file = data->files[i];
3187 unsigned long damage = file->added + file->deleted;
3188 if (file->is_binary)
3190 * binary files counts bytes, not lines. Must find some
3191 * way to normalize binary bytes vs. textual lines.
3192 * The following heuristic assumes that there are 64
3193 * bytes per "line".
3194 * This is stupid and ugly, but very cheap...
3196 damage = DIV_ROUND_UP(damage, 64);
3197 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3198 dir.files[dir.nr].name = file->name;
3199 dir.files[dir.nr].changed = damage;
3200 changed += damage;
3201 dir.nr++;
3204 conclude_dirstat(options, &dir, changed);
3207 static void free_diffstat_file(struct diffstat_file *f)
3209 free(f->print_name);
3210 free(f->name);
3211 free(f->from_name);
3212 free(f);
3215 void free_diffstat_info(struct diffstat_t *diffstat)
3217 int i;
3218 for (i = 0; i < diffstat->nr; i++)
3219 free_diffstat_file(diffstat->files[i]);
3220 free(diffstat->files);
3223 struct checkdiff_t {
3224 const char *filename;
3225 int lineno;
3226 int conflict_marker_size;
3227 struct diff_options *o;
3228 unsigned ws_rule;
3229 unsigned status;
3232 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3234 char firstchar;
3235 int cnt;
3237 if (len < marker_size + 1)
3238 return 0;
3239 firstchar = line[0];
3240 switch (firstchar) {
3241 case '=': case '>': case '<': case '|':
3242 break;
3243 default:
3244 return 0;
3246 for (cnt = 1; cnt < marker_size; cnt++)
3247 if (line[cnt] != firstchar)
3248 return 0;
3249 /* line[1] through line[marker_size-1] are same as firstchar */
3250 if (len < marker_size + 1 || !isspace(line[marker_size]))
3251 return 0;
3252 return 1;
3255 static void checkdiff_consume_hunk(void *priv,
3256 long ob UNUSED, long on UNUSED,
3257 long nb, long nn UNUSED,
3258 const char *func UNUSED, long funclen UNUSED)
3261 struct checkdiff_t *data = priv;
3262 data->lineno = nb - 1;
3265 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3267 struct checkdiff_t *data = priv;
3268 int marker_size = data->conflict_marker_size;
3269 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3270 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3271 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3272 char *err;
3273 const char *line_prefix;
3275 assert(data->o);
3276 line_prefix = diff_line_prefix(data->o);
3278 if (line[0] == '+') {
3279 unsigned bad;
3280 data->lineno++;
3281 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3282 data->status |= 1;
3283 fprintf(data->o->file,
3284 "%s%s:%d: leftover conflict marker\n",
3285 line_prefix, data->filename, data->lineno);
3287 bad = ws_check(line + 1, len - 1, data->ws_rule);
3288 if (!bad)
3289 return 0;
3290 data->status |= bad;
3291 err = whitespace_error_string(bad);
3292 fprintf(data->o->file, "%s%s:%d: %s.\n",
3293 line_prefix, data->filename, data->lineno, err);
3294 free(err);
3295 emit_line(data->o, set, reset, line, 1);
3296 ws_check_emit(line + 1, len - 1, data->ws_rule,
3297 data->o->file, set, reset, ws);
3298 } else if (line[0] == ' ') {
3299 data->lineno++;
3301 return 0;
3304 static unsigned char *deflate_it(char *data,
3305 unsigned long size,
3306 unsigned long *result_size)
3308 int bound;
3309 unsigned char *deflated;
3310 git_zstream stream;
3312 git_deflate_init(&stream, zlib_compression_level);
3313 bound = git_deflate_bound(&stream, size);
3314 deflated = xmalloc(bound);
3315 stream.next_out = deflated;
3316 stream.avail_out = bound;
3318 stream.next_in = (unsigned char *)data;
3319 stream.avail_in = size;
3320 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3321 ; /* nothing */
3322 git_deflate_end(&stream);
3323 *result_size = stream.total_out;
3324 return deflated;
3327 static void emit_binary_diff_body(struct diff_options *o,
3328 mmfile_t *one, mmfile_t *two)
3330 void *cp;
3331 void *delta;
3332 void *deflated;
3333 void *data;
3334 unsigned long orig_size;
3335 unsigned long delta_size;
3336 unsigned long deflate_size;
3337 unsigned long data_size;
3339 /* We could do deflated delta, or we could do just deflated two,
3340 * whichever is smaller.
3342 delta = NULL;
3343 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3344 if (one->size && two->size) {
3345 delta = diff_delta(one->ptr, one->size,
3346 two->ptr, two->size,
3347 &delta_size, deflate_size);
3348 if (delta) {
3349 void *to_free = delta;
3350 orig_size = delta_size;
3351 delta = deflate_it(delta, delta_size, &delta_size);
3352 free(to_free);
3356 if (delta && delta_size < deflate_size) {
3357 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3358 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3359 s, strlen(s), 0);
3360 free(s);
3361 free(deflated);
3362 data = delta;
3363 data_size = delta_size;
3364 } else {
3365 char *s = xstrfmt("%lu", two->size);
3366 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3367 s, strlen(s), 0);
3368 free(s);
3369 free(delta);
3370 data = deflated;
3371 data_size = deflate_size;
3374 /* emit data encoded in base85 */
3375 cp = data;
3376 while (data_size) {
3377 int len;
3378 int bytes = (52 < data_size) ? 52 : data_size;
3379 char line[71];
3380 data_size -= bytes;
3381 if (bytes <= 26)
3382 line[0] = bytes + 'A' - 1;
3383 else
3384 line[0] = bytes - 26 + 'a' - 1;
3385 encode_85(line + 1, cp, bytes);
3386 cp = (char *) cp + bytes;
3388 len = strlen(line);
3389 line[len++] = '\n';
3390 line[len] = '\0';
3392 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3393 line, len, 0);
3395 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3396 free(data);
3399 static void emit_binary_diff(struct diff_options *o,
3400 mmfile_t *one, mmfile_t *two)
3402 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3403 emit_binary_diff_body(o, one, two);
3404 emit_binary_diff_body(o, two, one);
3407 int diff_filespec_is_binary(struct repository *r,
3408 struct diff_filespec *one)
3410 struct diff_populate_filespec_options dpf_options = {
3411 .check_binary = 1,
3414 if (one->is_binary == -1) {
3415 diff_filespec_load_driver(one, r->index);
3416 if (one->driver->binary != -1)
3417 one->is_binary = one->driver->binary;
3418 else {
3419 if (!one->data && DIFF_FILE_VALID(one))
3420 diff_populate_filespec(r, one, &dpf_options);
3421 if (one->is_binary == -1 && one->data)
3422 one->is_binary = buffer_is_binary(one->data,
3423 one->size);
3424 if (one->is_binary == -1)
3425 one->is_binary = 0;
3428 return one->is_binary;
3431 static const struct userdiff_funcname *
3432 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3434 diff_filespec_load_driver(one, o->repo->index);
3435 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3438 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3440 if (!options->a_prefix)
3441 options->a_prefix = a;
3442 if (!options->b_prefix)
3443 options->b_prefix = b;
3446 void diff_set_noprefix(struct diff_options *options)
3448 options->a_prefix = options->b_prefix = "";
3451 void diff_set_default_prefix(struct diff_options *options)
3453 options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3454 options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3457 struct userdiff_driver *get_textconv(struct repository *r,
3458 struct diff_filespec *one)
3460 if (!DIFF_FILE_VALID(one))
3461 return NULL;
3463 diff_filespec_load_driver(one, r->index);
3464 return userdiff_get_textconv(r, one->driver);
3467 static struct string_list *additional_headers(struct diff_options *o,
3468 const char *path)
3470 if (!o->additional_path_headers)
3471 return NULL;
3472 return strmap_get(o->additional_path_headers, path);
3475 static void add_formatted_header(struct strbuf *msg,
3476 const char *header,
3477 const char *line_prefix,
3478 const char *meta,
3479 const char *reset)
3481 const char *next, *newline;
3483 for (next = header; *next; next = newline) {
3484 newline = strchrnul(next, '\n');
3485 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3486 (int)(newline - next), next, reset);
3487 if (*newline)
3488 newline++;
3492 static void add_formatted_headers(struct strbuf *msg,
3493 struct string_list *more_headers,
3494 const char *line_prefix,
3495 const char *meta,
3496 const char *reset)
3498 int i;
3500 for (i = 0; i < more_headers->nr; i++)
3501 add_formatted_header(msg, more_headers->items[i].string,
3502 line_prefix, meta, reset);
3505 static int diff_filepair_is_phoney(struct diff_filespec *one,
3506 struct diff_filespec *two)
3509 * This function specifically looks for pairs injected by
3510 * create_filepairs_for_header_only_notifications(). Such
3511 * pairs are "phoney" in that they do not represent any
3512 * content or even mode difference, but were inserted because
3513 * diff_queued_diff previously had no pair associated with
3514 * that path but we needed some pair to avoid losing the
3515 * "remerge CONFLICT" header associated with the path.
3517 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3520 static int set_diff_algorithm(struct diff_options *opts,
3521 const char *alg)
3523 long value = parse_algorithm_value(alg);
3525 if (value < 0)
3526 return -1;
3528 /* clear out previous settings */
3529 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3530 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3531 opts->xdl_opts |= value;
3533 return 0;
3536 static void builtin_diff(const char *name_a,
3537 const char *name_b,
3538 struct diff_filespec *one,
3539 struct diff_filespec *two,
3540 const char *xfrm_msg,
3541 int must_show_header,
3542 struct diff_options *o,
3543 int complete_rewrite)
3545 mmfile_t mf1, mf2;
3546 const char *lbl[2];
3547 char *a_one, *b_two;
3548 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3549 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3550 const char *a_prefix, *b_prefix;
3551 struct userdiff_driver *textconv_one = NULL;
3552 struct userdiff_driver *textconv_two = NULL;
3553 struct strbuf header = STRBUF_INIT;
3554 const char *line_prefix = diff_line_prefix(o);
3556 diff_set_mnemonic_prefix(o, "a/", "b/");
3557 if (o->flags.reverse_diff) {
3558 a_prefix = o->b_prefix;
3559 b_prefix = o->a_prefix;
3560 } else {
3561 a_prefix = o->a_prefix;
3562 b_prefix = o->b_prefix;
3565 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3566 (!one->mode || S_ISGITLINK(one->mode)) &&
3567 (!two->mode || S_ISGITLINK(two->mode)) &&
3568 (!diff_filepair_is_phoney(one, two))) {
3569 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3570 &one->oid, &two->oid,
3571 two->dirty_submodule);
3572 o->found_changes = 1;
3573 return;
3574 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3575 (!one->mode || S_ISGITLINK(one->mode)) &&
3576 (!two->mode || S_ISGITLINK(two->mode)) &&
3577 (!diff_filepair_is_phoney(one, two))) {
3578 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3579 &one->oid, &two->oid,
3580 two->dirty_submodule);
3581 o->found_changes = 1;
3582 return;
3585 if (o->flags.allow_textconv) {
3586 textconv_one = get_textconv(o->repo, one);
3587 textconv_two = get_textconv(o->repo, two);
3590 /* Never use a non-valid filename anywhere if at all possible */
3591 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3592 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3594 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3595 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3596 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3597 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3598 if (diff_filepair_is_phoney(one, two)) {
3600 * We should only reach this point for pairs generated from
3601 * create_filepairs_for_header_only_notifications(). For
3602 * these, we want to avoid the "/dev/null" special casing
3603 * above, because we do not want such pairs shown as either
3604 * "new file" or "deleted file" below.
3606 lbl[0] = a_one;
3607 lbl[1] = b_two;
3609 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3610 if (lbl[0][0] == '/') {
3611 /* /dev/null */
3612 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3613 if (xfrm_msg)
3614 strbuf_addstr(&header, xfrm_msg);
3615 o->found_changes = 1;
3616 must_show_header = 1;
3618 else if (lbl[1][0] == '/') {
3619 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3620 if (xfrm_msg)
3621 strbuf_addstr(&header, xfrm_msg);
3622 o->found_changes = 1;
3623 must_show_header = 1;
3625 else {
3626 if (one->mode != two->mode) {
3627 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3628 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3629 o->found_changes = 1;
3630 must_show_header = 1;
3632 if (xfrm_msg)
3633 strbuf_addstr(&header, xfrm_msg);
3636 * we do not run diff between different kind
3637 * of objects.
3639 if ((one->mode ^ two->mode) & S_IFMT)
3640 goto free_ab_and_return;
3641 if (complete_rewrite &&
3642 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3643 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3644 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3645 header.buf, header.len, 0);
3646 strbuf_reset(&header);
3647 emit_rewrite_diff(name_a, name_b, one, two,
3648 textconv_one, textconv_two, o);
3649 o->found_changes = 1;
3650 goto free_ab_and_return;
3654 if (o->irreversible_delete && lbl[1][0] == '/') {
3655 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3656 header.len, 0);
3657 strbuf_reset(&header);
3658 goto free_ab_and_return;
3659 } else if (!o->flags.text &&
3660 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3661 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3662 struct strbuf sb = STRBUF_INIT;
3663 if (!one->data && !two->data &&
3664 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3665 !o->flags.binary) {
3666 if (oideq(&one->oid, &two->oid)) {
3667 if (must_show_header)
3668 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3669 header.buf, header.len,
3671 goto free_ab_and_return;
3673 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3674 header.buf, header.len, 0);
3675 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3676 diff_line_prefix(o), lbl[0], lbl[1]);
3677 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3678 sb.buf, sb.len, 0);
3679 strbuf_release(&sb);
3680 o->found_changes = 1;
3681 goto free_ab_and_return;
3683 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3684 fill_mmfile(o->repo, &mf2, two) < 0)
3685 die("unable to read files to diff");
3686 /* Quite common confusing case */
3687 if (mf1.size == mf2.size &&
3688 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3689 if (must_show_header)
3690 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3691 header.buf, header.len, 0);
3692 goto free_ab_and_return;
3694 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3695 strbuf_reset(&header);
3696 if (o->flags.binary)
3697 emit_binary_diff(o, &mf1, &mf2);
3698 else {
3699 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3700 diff_line_prefix(o), lbl[0], lbl[1]);
3701 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3702 sb.buf, sb.len, 0);
3703 strbuf_release(&sb);
3705 o->found_changes = 1;
3706 } else {
3707 /* Crazy xdl interfaces.. */
3708 const char *diffopts;
3709 const char *v;
3710 xpparam_t xpp;
3711 xdemitconf_t xecfg;
3712 struct emit_callback ecbdata;
3713 const struct userdiff_funcname *pe;
3715 if (must_show_header) {
3716 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3717 header.buf, header.len, 0);
3718 strbuf_reset(&header);
3721 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3722 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3724 pe = diff_funcname_pattern(o, one);
3725 if (!pe)
3726 pe = diff_funcname_pattern(o, two);
3728 memset(&xpp, 0, sizeof(xpp));
3729 memset(&xecfg, 0, sizeof(xecfg));
3730 memset(&ecbdata, 0, sizeof(ecbdata));
3731 if (o->flags.suppress_diff_headers)
3732 lbl[0] = NULL;
3733 ecbdata.label_path = lbl;
3734 ecbdata.color_diff = want_color(o->use_color);
3735 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3736 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3737 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3738 ecbdata.opt = o;
3739 if (header.len && !o->flags.suppress_diff_headers)
3740 ecbdata.header = &header;
3741 xpp.flags = o->xdl_opts;
3742 xpp.ignore_regex = o->ignore_regex;
3743 xpp.ignore_regex_nr = o->ignore_regex_nr;
3744 xpp.anchors = o->anchors;
3745 xpp.anchors_nr = o->anchors_nr;
3746 xecfg.ctxlen = o->context;
3747 xecfg.interhunkctxlen = o->interhunkcontext;
3748 xecfg.flags = XDL_EMIT_FUNCNAMES;
3749 if (o->flags.funccontext)
3750 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3751 if (pe)
3752 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3754 diffopts = getenv("GIT_DIFF_OPTS");
3755 if (!diffopts)
3757 else if (skip_prefix(diffopts, "--unified=", &v))
3758 xecfg.ctxlen = strtoul(v, NULL, 10);
3759 else if (skip_prefix(diffopts, "-u", &v))
3760 xecfg.ctxlen = strtoul(v, NULL, 10);
3762 if (o->word_diff)
3763 init_diff_words_data(&ecbdata, o, one, two);
3764 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3765 &ecbdata, &xpp, &xecfg))
3766 die("unable to generate diff for %s", one->path);
3767 if (o->word_diff)
3768 free_diff_words_data(&ecbdata);
3769 if (textconv_one)
3770 free(mf1.ptr);
3771 if (textconv_two)
3772 free(mf2.ptr);
3773 xdiff_clear_find_func(&xecfg);
3776 free_ab_and_return:
3777 strbuf_release(&header);
3778 diff_free_filespec_data(one);
3779 diff_free_filespec_data(two);
3780 free(a_one);
3781 free(b_two);
3782 return;
3785 static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3787 if (!is_renamed) {
3788 if (p->status == DIFF_STATUS_ADDED) {
3789 if (S_ISLNK(p->two->mode))
3790 return "new +l";
3791 else if ((p->two->mode & 0777) == 0755)
3792 return "new +x";
3793 else
3794 return "new";
3795 } else if (p->status == DIFF_STATUS_DELETED)
3796 return "gone";
3798 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3799 return "mode -l";
3800 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3801 return "mode +l";
3802 else if ((p->one->mode & 0777) == 0644 &&
3803 (p->two->mode & 0777) == 0755)
3804 return "mode +x";
3805 else if ((p->one->mode & 0777) == 0755 &&
3806 (p->two->mode & 0777) == 0644)
3807 return "mode -x";
3808 return NULL;
3811 static void builtin_diffstat(const char *name_a, const char *name_b,
3812 struct diff_filespec *one,
3813 struct diff_filespec *two,
3814 struct diffstat_t *diffstat,
3815 struct diff_options *o,
3816 struct diff_filepair *p)
3818 mmfile_t mf1, mf2;
3819 struct diffstat_file *data;
3820 int may_differ;
3821 int complete_rewrite = 0;
3823 if (!DIFF_PAIR_UNMERGED(p)) {
3824 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3825 complete_rewrite = 1;
3828 data = diffstat_add(diffstat, name_a, name_b);
3829 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3830 if (o->flags.stat_with_summary)
3831 data->comments = get_compact_summary(p, data->is_renamed);
3833 if (!one || !two) {
3834 data->is_unmerged = 1;
3835 return;
3838 /* saves some reads if true, not a guarantee of diff outcome */
3839 may_differ = !(one->oid_valid && two->oid_valid &&
3840 oideq(&one->oid, &two->oid));
3842 if (diff_filespec_is_binary(o->repo, one) ||
3843 diff_filespec_is_binary(o->repo, two)) {
3844 data->is_binary = 1;
3845 if (!may_differ) {
3846 data->added = 0;
3847 data->deleted = 0;
3848 } else {
3849 data->added = diff_filespec_size(o->repo, two);
3850 data->deleted = diff_filespec_size(o->repo, one);
3854 else if (complete_rewrite) {
3855 diff_populate_filespec(o->repo, one, NULL);
3856 diff_populate_filespec(o->repo, two, NULL);
3857 data->deleted = count_lines(one->data, one->size);
3858 data->added = count_lines(two->data, two->size);
3861 else if (may_differ) {
3862 /* Crazy xdl interfaces.. */
3863 xpparam_t xpp;
3864 xdemitconf_t xecfg;
3866 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3867 fill_mmfile(o->repo, &mf2, two) < 0)
3868 die("unable to read files to diff");
3870 memset(&xpp, 0, sizeof(xpp));
3871 memset(&xecfg, 0, sizeof(xecfg));
3872 xpp.flags = o->xdl_opts;
3873 xpp.ignore_regex = o->ignore_regex;
3874 xpp.ignore_regex_nr = o->ignore_regex_nr;
3875 xpp.anchors = o->anchors;
3876 xpp.anchors_nr = o->anchors_nr;
3877 xecfg.ctxlen = o->context;
3878 xecfg.interhunkctxlen = o->interhunkcontext;
3879 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3880 if (xdi_diff_outf(&mf1, &mf2, NULL,
3881 diffstat_consume, diffstat, &xpp, &xecfg))
3882 die("unable to generate diffstat for %s", one->path);
3884 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3885 struct diffstat_file *file =
3886 diffstat->files[diffstat->nr - 1];
3888 * Omit diffstats of modified files where nothing changed.
3889 * Even if may_differ, this might be the case due to
3890 * ignoring whitespace changes, etc.
3892 * But note that we special-case additions, deletions,
3893 * renames, and mode changes as adding an empty file,
3894 * for example is still of interest.
3896 if ((p->status == DIFF_STATUS_MODIFIED)
3897 && !file->added
3898 && !file->deleted
3899 && one->mode == two->mode) {
3900 free_diffstat_file(file);
3901 diffstat->nr--;
3906 diff_free_filespec_data(one);
3907 diff_free_filespec_data(two);
3910 static void builtin_checkdiff(const char *name_a, const char *name_b,
3911 const char *attr_path,
3912 struct diff_filespec *one,
3913 struct diff_filespec *two,
3914 struct diff_options *o)
3916 mmfile_t mf1, mf2;
3917 struct checkdiff_t data;
3919 if (!two)
3920 return;
3922 memset(&data, 0, sizeof(data));
3923 data.filename = name_b ? name_b : name_a;
3924 data.lineno = 0;
3925 data.o = o;
3926 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3927 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3929 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3930 fill_mmfile(o->repo, &mf2, two) < 0)
3931 die("unable to read files to diff");
3934 * All the other codepaths check both sides, but not checking
3935 * the "old" side here is deliberate. We are checking the newly
3936 * introduced changes, and as long as the "new" side is text, we
3937 * can and should check what it introduces.
3939 if (diff_filespec_is_binary(o->repo, two))
3940 goto free_and_return;
3941 else {
3942 /* Crazy xdl interfaces.. */
3943 xpparam_t xpp;
3944 xdemitconf_t xecfg;
3946 memset(&xpp, 0, sizeof(xpp));
3947 memset(&xecfg, 0, sizeof(xecfg));
3948 xecfg.ctxlen = 1; /* at least one context line */
3949 xpp.flags = 0;
3950 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3951 checkdiff_consume, &data,
3952 &xpp, &xecfg))
3953 die("unable to generate checkdiff for %s", one->path);
3955 if (data.ws_rule & WS_BLANK_AT_EOF) {
3956 struct emit_callback ecbdata;
3957 int blank_at_eof;
3959 ecbdata.ws_rule = data.ws_rule;
3960 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3961 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3963 if (blank_at_eof) {
3964 static char *err;
3965 if (!err)
3966 err = whitespace_error_string(WS_BLANK_AT_EOF);
3967 fprintf(o->file, "%s:%d: %s.\n",
3968 data.filename, blank_at_eof, err);
3969 data.status = 1; /* report errors */
3973 free_and_return:
3974 diff_free_filespec_data(one);
3975 diff_free_filespec_data(two);
3976 if (data.status)
3977 o->flags.check_failed = 1;
3980 struct diff_filespec *alloc_filespec(const char *path)
3982 struct diff_filespec *spec;
3984 FLEXPTR_ALLOC_STR(spec, path, path);
3985 spec->count = 1;
3986 spec->is_binary = -1;
3987 return spec;
3990 void free_filespec(struct diff_filespec *spec)
3992 if (!--spec->count) {
3993 diff_free_filespec_data(spec);
3994 free(spec);
3998 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3999 int oid_valid, unsigned short mode)
4001 if (mode) {
4002 spec->mode = canon_mode(mode);
4003 oidcpy(&spec->oid, oid);
4004 spec->oid_valid = oid_valid;
4009 * Given a name and sha1 pair, if the index tells us the file in
4010 * the work tree has that object contents, return true, so that
4011 * prepare_temp_file() does not have to inflate and extract.
4013 static int reuse_worktree_file(struct index_state *istate,
4014 const char *name,
4015 const struct object_id *oid,
4016 int want_file)
4018 const struct cache_entry *ce;
4019 struct stat st;
4020 int pos, len;
4023 * We do not read the cache ourselves here, because the
4024 * benchmark with my previous version that always reads cache
4025 * shows that it makes things worse for diff-tree comparing
4026 * two linux-2.6 kernel trees in an already checked out work
4027 * tree. This is because most diff-tree comparisons deal with
4028 * only a small number of files, while reading the cache is
4029 * expensive for a large project, and its cost outweighs the
4030 * savings we get by not inflating the object to a temporary
4031 * file. Practically, this code only helps when we are used
4032 * by diff-cache --cached, which does read the cache before
4033 * calling us.
4035 if (!istate->cache)
4036 return 0;
4038 /* We want to avoid the working directory if our caller
4039 * doesn't need the data in a normal file, this system
4040 * is rather slow with its stat/open/mmap/close syscalls,
4041 * and the object is contained in a pack file. The pack
4042 * is probably already open and will be faster to obtain
4043 * the data through than the working directory. Loose
4044 * objects however would tend to be slower as they need
4045 * to be individually opened and inflated.
4047 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
4048 return 0;
4051 * Similarly, if we'd have to convert the file contents anyway, that
4052 * makes the optimization not worthwhile.
4054 if (!want_file && would_convert_to_git(istate, name))
4055 return 0;
4058 * If this path does not match our sparse-checkout definition,
4059 * then the file will not be in the working directory.
4061 if (!path_in_sparse_checkout(name, istate))
4062 return 0;
4064 len = strlen(name);
4065 pos = index_name_pos(istate, name, len);
4066 if (pos < 0)
4067 return 0;
4068 ce = istate->cache[pos];
4071 * This is not the sha1 we are looking for, or
4072 * unreusable because it is not a regular file.
4074 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4075 return 0;
4078 * If ce is marked as "assume unchanged", there is no
4079 * guarantee that work tree matches what we are looking for.
4081 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4082 return 0;
4085 * If ce matches the file in the work tree, we can reuse it.
4087 if (ce_uptodate(ce) ||
4088 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4089 return 1;
4091 return 0;
4094 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4096 struct strbuf buf = STRBUF_INIT;
4097 const char *dirty = "";
4099 /* Are we looking at the work tree? */
4100 if (s->dirty_submodule)
4101 dirty = "-dirty";
4103 strbuf_addf(&buf, "Subproject commit %s%s\n",
4104 oid_to_hex(&s->oid), dirty);
4105 s->size = buf.len;
4106 if (size_only) {
4107 s->data = NULL;
4108 strbuf_release(&buf);
4109 } else {
4110 s->data = strbuf_detach(&buf, NULL);
4111 s->should_free = 1;
4113 return 0;
4117 * While doing rename detection and pickaxe operation, we may need to
4118 * grab the data for the blob (or file) for our own in-core comparison.
4119 * diff_filespec has data and size fields for this purpose.
4121 int diff_populate_filespec(struct repository *r,
4122 struct diff_filespec *s,
4123 const struct diff_populate_filespec_options *options)
4125 int size_only = options ? options->check_size_only : 0;
4126 int check_binary = options ? options->check_binary : 0;
4127 int err = 0;
4128 int conv_flags = global_conv_flags_eol;
4130 * demote FAIL to WARN to allow inspecting the situation
4131 * instead of refusing.
4133 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4134 conv_flags = CONV_EOL_RNDTRP_WARN;
4136 if (!DIFF_FILE_VALID(s))
4137 die("internal error: asking to populate invalid file.");
4138 if (S_ISDIR(s->mode))
4139 return -1;
4141 if (s->data)
4142 return 0;
4144 if (size_only && 0 < s->size)
4145 return 0;
4147 if (S_ISGITLINK(s->mode))
4148 return diff_populate_gitlink(s, size_only);
4150 if (!s->oid_valid ||
4151 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4152 struct strbuf buf = STRBUF_INIT;
4153 struct stat st;
4154 int fd;
4156 if (lstat(s->path, &st) < 0) {
4157 err_empty:
4158 err = -1;
4159 empty:
4160 s->data = (char *)"";
4161 s->size = 0;
4162 return err;
4164 s->size = xsize_t(st.st_size);
4165 if (!s->size)
4166 goto empty;
4167 if (S_ISLNK(st.st_mode)) {
4168 struct strbuf sb = STRBUF_INIT;
4170 if (strbuf_readlink(&sb, s->path, s->size))
4171 goto err_empty;
4172 s->size = sb.len;
4173 s->data = strbuf_detach(&sb, NULL);
4174 s->should_free = 1;
4175 return 0;
4179 * Even if the caller would be happy with getting
4180 * only the size, we cannot return early at this
4181 * point if the path requires us to run the content
4182 * conversion.
4184 if (size_only && !would_convert_to_git(r->index, s->path))
4185 return 0;
4188 * Note: this check uses xsize_t(st.st_size) that may
4189 * not be the true size of the blob after it goes
4190 * through convert_to_git(). This may not strictly be
4191 * correct, but the whole point of big_file_threshold
4192 * and is_binary check being that we want to avoid
4193 * opening the file and inspecting the contents, this
4194 * is probably fine.
4196 if (check_binary &&
4197 s->size > big_file_threshold && s->is_binary == -1) {
4198 s->is_binary = 1;
4199 return 0;
4201 fd = open(s->path, O_RDONLY);
4202 if (fd < 0)
4203 goto err_empty;
4204 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4205 close(fd);
4206 s->should_munmap = 1;
4209 * Convert from working tree format to canonical git format
4211 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4212 size_t size = 0;
4213 munmap(s->data, s->size);
4214 s->should_munmap = 0;
4215 s->data = strbuf_detach(&buf, &size);
4216 s->size = size;
4217 s->should_free = 1;
4220 else {
4221 struct object_info info = {
4222 .sizep = &s->size
4225 if (!(size_only || check_binary))
4227 * Set contentp, since there is no chance that merely
4228 * the size is sufficient.
4230 info.contentp = &s->data;
4232 if (options && options->missing_object_cb) {
4233 if (!oid_object_info_extended(r, &s->oid, &info,
4234 OBJECT_INFO_LOOKUP_REPLACE |
4235 OBJECT_INFO_SKIP_FETCH_OBJECT))
4236 goto object_read;
4237 options->missing_object_cb(options->missing_object_data);
4239 if (oid_object_info_extended(r, &s->oid, &info,
4240 OBJECT_INFO_LOOKUP_REPLACE))
4241 die("unable to read %s", oid_to_hex(&s->oid));
4243 object_read:
4244 if (size_only || check_binary) {
4245 if (size_only)
4246 return 0;
4247 if (s->size > big_file_threshold && s->is_binary == -1) {
4248 s->is_binary = 1;
4249 return 0;
4252 if (!info.contentp) {
4253 info.contentp = &s->data;
4254 if (oid_object_info_extended(r, &s->oid, &info,
4255 OBJECT_INFO_LOOKUP_REPLACE))
4256 die("unable to read %s", oid_to_hex(&s->oid));
4258 s->should_free = 1;
4260 return 0;
4263 void diff_free_filespec_blob(struct diff_filespec *s)
4265 if (s->should_free)
4266 free(s->data);
4267 else if (s->should_munmap)
4268 munmap(s->data, s->size);
4270 if (s->should_free || s->should_munmap) {
4271 s->should_free = s->should_munmap = 0;
4272 s->data = NULL;
4276 void diff_free_filespec_data(struct diff_filespec *s)
4278 if (!s)
4279 return;
4281 diff_free_filespec_blob(s);
4282 FREE_AND_NULL(s->cnt_data);
4285 static void prep_temp_blob(struct index_state *istate,
4286 const char *path, struct diff_tempfile *temp,
4287 void *blob,
4288 unsigned long size,
4289 const struct object_id *oid,
4290 int mode)
4292 struct strbuf buf = STRBUF_INIT;
4293 char *path_dup = xstrdup(path);
4294 const char *base = basename(path_dup);
4295 struct checkout_metadata meta;
4297 init_checkout_metadata(&meta, NULL, NULL, oid);
4299 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4300 if (!temp->tempfile)
4301 die_errno("unable to create temp-file");
4302 if (convert_to_working_tree(istate, path,
4303 (const char *)blob, (size_t)size, &buf, &meta)) {
4304 blob = buf.buf;
4305 size = buf.len;
4307 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4308 close_tempfile_gently(temp->tempfile))
4309 die_errno("unable to write temp-file");
4310 temp->name = get_tempfile_path(temp->tempfile);
4311 oid_to_hex_r(temp->hex, oid);
4312 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4313 strbuf_release(&buf);
4314 free(path_dup);
4317 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4318 struct diff_filespec *one)
4320 struct diff_tempfile *temp = claim_diff_tempfile();
4322 if (!DIFF_FILE_VALID(one)) {
4323 not_a_valid_file:
4324 /* A '-' entry produces this for file-2, and
4325 * a '+' entry produces this for file-1.
4327 temp->name = "/dev/null";
4328 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4329 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4330 return temp;
4333 if (!S_ISGITLINK(one->mode) &&
4334 (!one->oid_valid ||
4335 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4336 struct stat st;
4337 if (lstat(one->path, &st) < 0) {
4338 if (errno == ENOENT)
4339 goto not_a_valid_file;
4340 die_errno("stat(%s)", one->path);
4342 if (S_ISLNK(st.st_mode)) {
4343 struct strbuf sb = STRBUF_INIT;
4344 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4345 die_errno("readlink(%s)", one->path);
4346 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4347 (one->oid_valid ?
4348 &one->oid : null_oid()),
4349 (one->oid_valid ?
4350 one->mode : S_IFLNK));
4351 strbuf_release(&sb);
4353 else {
4354 /* we can borrow from the file in the work tree */
4355 temp->name = one->path;
4356 if (!one->oid_valid)
4357 oid_to_hex_r(temp->hex, null_oid());
4358 else
4359 oid_to_hex_r(temp->hex, &one->oid);
4360 /* Even though we may sometimes borrow the
4361 * contents from the work tree, we always want
4362 * one->mode. mode is trustworthy even when
4363 * !(one->oid_valid), as long as
4364 * DIFF_FILE_VALID(one).
4366 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4368 return temp;
4370 else {
4371 if (diff_populate_filespec(r, one, NULL))
4372 die("cannot read data blob for %s", one->path);
4373 prep_temp_blob(r->index, one->path, temp,
4374 one->data, one->size,
4375 &one->oid, one->mode);
4377 return temp;
4380 static void add_external_diff_name(struct repository *r,
4381 struct strvec *argv,
4382 struct diff_filespec *df)
4384 struct diff_tempfile *temp = prepare_temp_file(r, df);
4385 strvec_push(argv, temp->name);
4386 strvec_push(argv, temp->hex);
4387 strvec_push(argv, temp->mode);
4390 /* An external diff command takes:
4392 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4393 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4396 static void run_external_diff(const struct external_diff *pgm,
4397 const char *name,
4398 const char *other,
4399 struct diff_filespec *one,
4400 struct diff_filespec *two,
4401 const char *xfrm_msg,
4402 struct diff_options *o)
4404 struct child_process cmd = CHILD_PROCESS_INIT;
4405 struct diff_queue_struct *q = &diff_queued_diff;
4406 int quiet = !(o->output_format & DIFF_FORMAT_PATCH);
4407 int rc;
4410 * Trivial equality is handled by diff_unmodified_pair() before
4411 * we get here. If we don't need to show the diff and the
4412 * external diff program lacks the ability to tell us whether
4413 * it's empty then we consider it non-empty without even asking.
4415 if (!pgm->trust_exit_code && quiet) {
4416 o->found_changes = 1;
4417 return;
4420 strvec_push(&cmd.args, pgm->cmd);
4421 strvec_push(&cmd.args, name);
4423 if (one && two) {
4424 add_external_diff_name(o->repo, &cmd.args, one);
4425 add_external_diff_name(o->repo, &cmd.args, two);
4426 if (other) {
4427 strvec_push(&cmd.args, other);
4428 if (xfrm_msg)
4429 strvec_push(&cmd.args, xfrm_msg);
4433 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4434 ++o->diff_path_counter);
4435 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4437 diff_free_filespec_data(one);
4438 diff_free_filespec_data(two);
4439 cmd.use_shell = 1;
4440 cmd.no_stdout = quiet;
4441 rc = run_command(&cmd);
4442 if (!pgm->trust_exit_code && rc == 0)
4443 o->found_changes = 1;
4444 else if (pgm->trust_exit_code && rc == 0)
4445 ; /* nothing */
4446 else if (pgm->trust_exit_code && rc == 1)
4447 o->found_changes = 1;
4448 else
4449 die(_("external diff died, stopping at %s"), name);
4451 remove_tempfile();
4454 static int similarity_index(struct diff_filepair *p)
4456 return p->score * 100 / MAX_SCORE;
4459 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4461 if (startup_info->have_repository)
4462 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4463 else {
4464 char *hex = oid_to_hex(oid);
4465 if (abbrev < 0)
4466 abbrev = FALLBACK_DEFAULT_ABBREV;
4467 if (abbrev > the_hash_algo->hexsz)
4468 BUG("oid abbreviation out of range: %d", abbrev);
4469 if (abbrev)
4470 hex[abbrev] = '\0';
4471 return hex;
4475 static void fill_metainfo(struct strbuf *msg,
4476 const char *name,
4477 const char *other,
4478 struct diff_filespec *one,
4479 struct diff_filespec *two,
4480 struct diff_options *o,
4481 struct diff_filepair *p,
4482 int *must_show_header,
4483 int use_color)
4485 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4486 const char *reset = diff_get_color(use_color, DIFF_RESET);
4487 const char *line_prefix = diff_line_prefix(o);
4488 struct string_list *more_headers = NULL;
4490 *must_show_header = 1;
4491 strbuf_init(msg, PATH_MAX * 2 + 300);
4492 switch (p->status) {
4493 case DIFF_STATUS_COPIED:
4494 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4495 line_prefix, set, similarity_index(p));
4496 strbuf_addf(msg, "%s\n%s%scopy from ",
4497 reset, line_prefix, set);
4498 quote_c_style(name, msg, NULL, 0);
4499 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4500 quote_c_style(other, msg, NULL, 0);
4501 strbuf_addf(msg, "%s\n", reset);
4502 break;
4503 case DIFF_STATUS_RENAMED:
4504 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4505 line_prefix, set, similarity_index(p));
4506 strbuf_addf(msg, "%s\n%s%srename from ",
4507 reset, line_prefix, set);
4508 quote_c_style(name, msg, NULL, 0);
4509 strbuf_addf(msg, "%s\n%s%srename to ",
4510 reset, line_prefix, set);
4511 quote_c_style(other, msg, NULL, 0);
4512 strbuf_addf(msg, "%s\n", reset);
4513 break;
4514 case DIFF_STATUS_MODIFIED:
4515 if (p->score) {
4516 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4517 line_prefix,
4518 set, similarity_index(p), reset);
4519 break;
4521 /* fallthru */
4522 default:
4523 *must_show_header = 0;
4525 if ((more_headers = additional_headers(o, name))) {
4526 add_formatted_headers(msg, more_headers,
4527 line_prefix, set, reset);
4528 *must_show_header = 1;
4530 if (one && two && !oideq(&one->oid, &two->oid)) {
4531 const unsigned hexsz = the_hash_algo->hexsz;
4532 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4534 if (o->flags.full_index)
4535 abbrev = hexsz;
4537 if (o->flags.binary) {
4538 mmfile_t mf;
4539 if ((!fill_mmfile(o->repo, &mf, one) &&
4540 diff_filespec_is_binary(o->repo, one)) ||
4541 (!fill_mmfile(o->repo, &mf, two) &&
4542 diff_filespec_is_binary(o->repo, two)))
4543 abbrev = hexsz;
4545 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4546 diff_abbrev_oid(&one->oid, abbrev),
4547 diff_abbrev_oid(&two->oid, abbrev));
4548 if (one->mode == two->mode)
4549 strbuf_addf(msg, " %06o", one->mode);
4550 strbuf_addf(msg, "%s\n", reset);
4554 static void run_diff_cmd(const struct external_diff *pgm,
4555 const char *name,
4556 const char *other,
4557 const char *attr_path,
4558 struct diff_filespec *one,
4559 struct diff_filespec *two,
4560 struct strbuf *msg,
4561 struct diff_options *o,
4562 struct diff_filepair *p)
4564 const char *xfrm_msg = NULL;
4565 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4566 int must_show_header = 0;
4567 struct userdiff_driver *drv = NULL;
4569 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4570 drv = userdiff_find_by_path(o->repo->index, attr_path);
4572 if (o->flags.allow_external && drv && drv->external.cmd)
4573 pgm = &drv->external;
4575 if (msg) {
4577 * don't use colors when the header is intended for an
4578 * external diff driver
4580 fill_metainfo(msg, name, other, one, two, o, p,
4581 &must_show_header,
4582 want_color(o->use_color) && !pgm);
4583 xfrm_msg = msg->len ? msg->buf : NULL;
4586 if (pgm) {
4587 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4588 return;
4590 if (one && two) {
4591 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4592 set_diff_algorithm(o, drv->algorithm);
4594 builtin_diff(name, other ? other : name,
4595 one, two, xfrm_msg, must_show_header,
4596 o, complete_rewrite);
4597 if (p->status == DIFF_STATUS_COPIED ||
4598 p->status == DIFF_STATUS_RENAMED)
4599 o->found_changes = 1;
4600 } else {
4601 fprintf(o->file, "* Unmerged path %s\n", name);
4602 o->found_changes = 1;
4606 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4608 if (DIFF_FILE_VALID(one)) {
4609 if (!one->oid_valid) {
4610 struct stat st;
4611 if (one->is_stdin) {
4612 oidclr(&one->oid, the_repository->hash_algo);
4613 return;
4615 if (lstat(one->path, &st) < 0)
4616 die_errno("stat '%s'", one->path);
4617 if (index_path(istate, &one->oid, one->path, &st, 0))
4618 die("cannot hash %s", one->path);
4621 else
4622 oidclr(&one->oid, the_repository->hash_algo);
4625 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4627 /* Strip the prefix but do not molest /dev/null and absolute paths */
4628 if (*namep && !is_absolute_path(*namep)) {
4629 *namep += prefix_length;
4630 if (**namep == '/')
4631 ++*namep;
4633 if (*otherp && !is_absolute_path(*otherp)) {
4634 *otherp += prefix_length;
4635 if (**otherp == '/')
4636 ++*otherp;
4640 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4642 const struct external_diff *pgm = external_diff();
4643 struct strbuf msg;
4644 struct diff_filespec *one = p->one;
4645 struct diff_filespec *two = p->two;
4646 const char *name;
4647 const char *other;
4648 const char *attr_path;
4650 name = one->path;
4651 other = (strcmp(name, two->path) ? two->path : NULL);
4652 attr_path = name;
4653 if (o->prefix_length)
4654 strip_prefix(o->prefix_length, &name, &other);
4656 if (!o->flags.allow_external)
4657 pgm = NULL;
4659 if (DIFF_PAIR_UNMERGED(p)) {
4660 run_diff_cmd(pgm, name, NULL, attr_path,
4661 NULL, NULL, NULL, o, p);
4662 return;
4665 diff_fill_oid_info(one, o->repo->index);
4666 diff_fill_oid_info(two, o->repo->index);
4668 if (!pgm &&
4669 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4670 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4672 * a filepair that changes between file and symlink
4673 * needs to be split into deletion and creation.
4675 struct diff_filespec *null = alloc_filespec(two->path);
4676 run_diff_cmd(NULL, name, other, attr_path,
4677 one, null, &msg,
4678 o, p);
4679 free(null);
4680 strbuf_release(&msg);
4682 null = alloc_filespec(one->path);
4683 run_diff_cmd(NULL, name, other, attr_path,
4684 null, two, &msg, o, p);
4685 free(null);
4687 else
4688 run_diff_cmd(pgm, name, other, attr_path,
4689 one, two, &msg, o, p);
4691 strbuf_release(&msg);
4694 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4695 struct diffstat_t *diffstat)
4697 const char *name;
4698 const char *other;
4700 if (!o->ignore_driver_algorithm) {
4701 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4702 p->one->path);
4704 if (drv && drv->algorithm)
4705 set_diff_algorithm(o, drv->algorithm);
4708 if (DIFF_PAIR_UNMERGED(p)) {
4709 /* unmerged */
4710 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4711 diffstat, o, p);
4712 return;
4715 name = p->one->path;
4716 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4718 if (o->prefix_length)
4719 strip_prefix(o->prefix_length, &name, &other);
4721 diff_fill_oid_info(p->one, o->repo->index);
4722 diff_fill_oid_info(p->two, o->repo->index);
4724 builtin_diffstat(name, other, p->one, p->two,
4725 diffstat, o, p);
4728 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4730 const char *name;
4731 const char *other;
4732 const char *attr_path;
4734 if (DIFF_PAIR_UNMERGED(p)) {
4735 /* unmerged */
4736 return;
4739 name = p->one->path;
4740 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4741 attr_path = other ? other : name;
4743 if (o->prefix_length)
4744 strip_prefix(o->prefix_length, &name, &other);
4746 diff_fill_oid_info(p->one, o->repo->index);
4747 diff_fill_oid_info(p->two, o->repo->index);
4749 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4752 void repo_diff_setup(struct repository *r, struct diff_options *options)
4754 memcpy(options, &default_diff_options, sizeof(*options));
4756 options->file = stdout;
4757 options->repo = r;
4759 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4760 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4761 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4762 options->abbrev = DEFAULT_ABBREV;
4763 options->line_termination = '\n';
4764 options->break_opt = -1;
4765 options->rename_limit = -1;
4766 options->dirstat_permille = diff_dirstat_permille_default;
4767 options->context = diff_context_default;
4768 options->interhunkcontext = diff_interhunk_context_default;
4769 options->ws_error_highlight = ws_error_highlight_default;
4770 options->flags.rename_empty = 1;
4771 options->flags.relative_name = diff_relative;
4772 options->objfind = NULL;
4774 /* pathchange left =NULL by default */
4775 options->change = diff_change;
4776 options->add_remove = diff_addremove;
4777 options->use_color = diff_use_color_default;
4778 options->detect_rename = diff_detect_rename_default;
4779 options->xdl_opts |= diff_algorithm;
4780 if (diff_indent_heuristic)
4781 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4783 options->orderfile = xstrdup_or_null(diff_order_file_cfg);
4785 if (!options->flags.ignore_submodule_set)
4786 options->flags.ignore_untracked_in_submodules = 1;
4788 if (diff_no_prefix) {
4789 diff_set_noprefix(options);
4790 } else if (!diff_mnemonic_prefix) {
4791 diff_set_default_prefix(options);
4794 options->color_moved = diff_color_moved_default;
4795 options->color_moved_ws_handling = diff_color_moved_ws_default;
4798 static const char diff_status_letters[] = {
4799 DIFF_STATUS_ADDED,
4800 DIFF_STATUS_COPIED,
4801 DIFF_STATUS_DELETED,
4802 DIFF_STATUS_MODIFIED,
4803 DIFF_STATUS_RENAMED,
4804 DIFF_STATUS_TYPE_CHANGED,
4805 DIFF_STATUS_UNKNOWN,
4806 DIFF_STATUS_UNMERGED,
4807 DIFF_STATUS_FILTER_AON,
4808 DIFF_STATUS_FILTER_BROKEN,
4809 '\0',
4812 static unsigned int filter_bit['Z' + 1];
4814 static void prepare_filter_bits(void)
4816 int i;
4818 if (!filter_bit[DIFF_STATUS_ADDED]) {
4819 for (i = 0; diff_status_letters[i]; i++)
4820 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4824 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4826 return opt->filter & filter_bit[(int) status];
4829 unsigned diff_filter_bit(char status)
4831 prepare_filter_bits();
4832 return filter_bit[(int) status];
4835 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4837 unsigned forbidden_magic;
4839 if (ps->nr != 1) {
4840 if (die_on_error)
4841 die(_("--follow requires exactly one pathspec"));
4842 return 0;
4845 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4846 PATHSPEC_LITERAL);
4847 if (forbidden_magic) {
4848 if (die_on_error) {
4849 struct strbuf sb = STRBUF_INIT;
4850 pathspec_magic_names(forbidden_magic, &sb);
4851 die(_("pathspec magic not supported by --follow: %s"),
4852 sb.buf);
4854 return 0;
4857 return 1;
4860 void diff_setup_done(struct diff_options *options)
4862 unsigned check_mask = DIFF_FORMAT_NAME |
4863 DIFF_FORMAT_NAME_STATUS |
4864 DIFF_FORMAT_CHECKDIFF |
4865 DIFF_FORMAT_NO_OUTPUT;
4867 * This must be signed because we're comparing against a potentially
4868 * negative value.
4870 const int hexsz = the_hash_algo->hexsz;
4872 if (options->set_default)
4873 options->set_default(options);
4875 if (HAS_MULTI_BITS(options->output_format & check_mask))
4876 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4877 "--name-only", "--name-status", "--check", "-s");
4879 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4880 die(_("options '%s', '%s', and '%s' cannot be used together"),
4881 "-G", "-S", "--find-object");
4883 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4884 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4885 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4887 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4888 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4889 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4892 * Most of the time we can say "there are changes"
4893 * only by checking if there are changed paths, but
4894 * --ignore-whitespace* options force us to look
4895 * inside contents.
4898 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4899 options->ignore_regex_nr)
4900 options->flags.diff_from_contents = 1;
4901 else
4902 options->flags.diff_from_contents = 0;
4904 if (options->flags.find_copies_harder)
4905 options->detect_rename = DIFF_DETECT_COPY;
4907 if (!options->flags.relative_name)
4908 options->prefix = NULL;
4909 if (options->prefix)
4910 options->prefix_length = strlen(options->prefix);
4911 else
4912 options->prefix_length = 0;
4915 * --name-only, --name-status, --checkdiff, and -s
4916 * turn other output format off.
4918 if (options->output_format & (DIFF_FORMAT_NAME |
4919 DIFF_FORMAT_NAME_STATUS |
4920 DIFF_FORMAT_CHECKDIFF |
4921 DIFF_FORMAT_NO_OUTPUT))
4922 options->output_format &= ~(DIFF_FORMAT_RAW |
4923 DIFF_FORMAT_NUMSTAT |
4924 DIFF_FORMAT_DIFFSTAT |
4925 DIFF_FORMAT_SHORTSTAT |
4926 DIFF_FORMAT_DIRSTAT |
4927 DIFF_FORMAT_SUMMARY |
4928 DIFF_FORMAT_PATCH);
4931 * These cases always need recursive; we do not drop caller-supplied
4932 * recursive bits for other formats here.
4934 if (options->output_format & (DIFF_FORMAT_PATCH |
4935 DIFF_FORMAT_NUMSTAT |
4936 DIFF_FORMAT_DIFFSTAT |
4937 DIFF_FORMAT_SHORTSTAT |
4938 DIFF_FORMAT_DIRSTAT |
4939 DIFF_FORMAT_SUMMARY |
4940 DIFF_FORMAT_CHECKDIFF))
4941 options->flags.recursive = 1;
4943 * Also pickaxe would not work very well if you do not say recursive
4945 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4946 options->flags.recursive = 1;
4948 * When patches are generated, submodules diffed against the work tree
4949 * must be checked for dirtiness too so it can be shown in the output
4951 if (options->output_format & DIFF_FORMAT_PATCH)
4952 options->flags.dirty_submodules = 1;
4954 if (options->detect_rename && options->rename_limit < 0)
4955 options->rename_limit = diff_rename_limit_default;
4956 if (hexsz < options->abbrev)
4957 options->abbrev = hexsz; /* full */
4960 * It does not make sense to show the first hit we happened
4961 * to have found. It does not make sense not to return with
4962 * exit code in such a case either.
4964 if (options->flags.quick) {
4965 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4966 options->flags.exit_with_status = 1;
4970 * External diffs could declare non-identical contents equal
4971 * (think diff --ignore-space-change).
4973 if (options->flags.allow_external && options->flags.exit_with_status)
4974 options->flags.diff_from_contents = 1;
4976 options->diff_path_counter = 0;
4978 if (options->flags.follow_renames)
4979 diff_check_follow_pathspec(&options->pathspec, 1);
4981 if (!options->use_color ||
4982 (options->flags.allow_external && external_diff()))
4983 options->color_moved = 0;
4985 if (options->filter_not) {
4986 if (!options->filter)
4987 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4988 options->filter &= ~options->filter_not;
4992 int parse_long_opt(const char *opt, const char **argv,
4993 const char **optarg)
4995 const char *arg = argv[0];
4996 if (!skip_prefix(arg, "--", &arg))
4997 return 0;
4998 if (!skip_prefix(arg, opt, &arg))
4999 return 0;
5000 if (*arg == '=') { /* stuck form: --option=value */
5001 *optarg = arg + 1;
5002 return 1;
5004 if (*arg != '\0')
5005 return 0;
5006 /* separate form: --option value */
5007 if (!argv[1])
5008 die("Option '--%s' requires a value", opt);
5009 *optarg = argv[1];
5010 return 2;
5013 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5015 struct diff_options *options = opt->value;
5016 int width = options->stat_width;
5017 int name_width = options->stat_name_width;
5018 int graph_width = options->stat_graph_width;
5019 int count = options->stat_count;
5020 char *end;
5022 BUG_ON_OPT_NEG(unset);
5024 if (!strcmp(opt->long_name, "stat")) {
5025 if (value) {
5026 width = strtoul(value, &end, 10);
5027 if (*end == ',')
5028 name_width = strtoul(end+1, &end, 10);
5029 if (*end == ',')
5030 count = strtoul(end+1, &end, 10);
5031 if (*end)
5032 return error(_("invalid --stat value: %s"), value);
5034 } else if (!strcmp(opt->long_name, "stat-width")) {
5035 width = strtoul(value, &end, 10);
5036 if (*end)
5037 return error(_("%s expects a numerical value"),
5038 opt->long_name);
5039 } else if (!strcmp(opt->long_name, "stat-name-width")) {
5040 name_width = strtoul(value, &end, 10);
5041 if (*end)
5042 return error(_("%s expects a numerical value"),
5043 opt->long_name);
5044 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5045 graph_width = strtoul(value, &end, 10);
5046 if (*end)
5047 return error(_("%s expects a numerical value"),
5048 opt->long_name);
5049 } else if (!strcmp(opt->long_name, "stat-count")) {
5050 count = strtoul(value, &end, 10);
5051 if (*end)
5052 return error(_("%s expects a numerical value"),
5053 opt->long_name);
5054 } else
5055 BUG("%s should not get here", opt->long_name);
5057 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5058 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5059 options->stat_name_width = name_width;
5060 options->stat_graph_width = graph_width;
5061 options->stat_width = width;
5062 options->stat_count = count;
5063 return 0;
5066 static int parse_dirstat_opt(struct diff_options *options, const char *params)
5068 struct strbuf errmsg = STRBUF_INIT;
5069 if (parse_dirstat_params(options, params, &errmsg))
5070 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5071 errmsg.buf);
5072 strbuf_release(&errmsg);
5074 * The caller knows a dirstat-related option is given from the command
5075 * line; allow it to say "return this_function();"
5077 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5078 options->output_format |= DIFF_FORMAT_DIRSTAT;
5079 return 1;
5082 static int diff_opt_diff_filter(const struct option *option,
5083 const char *optarg, int unset)
5085 struct diff_options *opt = option->value;
5086 int i, optch;
5088 BUG_ON_OPT_NEG(unset);
5089 prepare_filter_bits();
5091 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5092 unsigned int bit;
5093 int negate;
5095 if ('a' <= optch && optch <= 'z') {
5096 negate = 1;
5097 optch = toupper(optch);
5098 } else {
5099 negate = 0;
5102 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5103 if (!bit)
5104 return error(_("unknown change class '%c' in --diff-filter=%s"),
5105 optarg[i], optarg);
5106 if (negate)
5107 opt->filter_not |= bit;
5108 else
5109 opt->filter |= bit;
5111 return 0;
5114 static void enable_patch_output(int *fmt)
5116 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5117 *fmt |= DIFF_FORMAT_PATCH;
5120 static int diff_opt_ws_error_highlight(const struct option *option,
5121 const char *arg, int unset)
5123 struct diff_options *opt = option->value;
5124 int val = parse_ws_error_highlight(arg);
5126 BUG_ON_OPT_NEG(unset);
5127 if (val < 0)
5128 return error(_("unknown value after ws-error-highlight=%.*s"),
5129 -1 - val, arg);
5130 opt->ws_error_highlight = val;
5131 return 0;
5134 static int diff_opt_find_object(const struct option *option,
5135 const char *arg, int unset)
5137 struct diff_options *opt = option->value;
5138 struct object_id oid;
5140 BUG_ON_OPT_NEG(unset);
5141 if (repo_get_oid(the_repository, arg, &oid))
5142 return error(_("unable to resolve '%s'"), arg);
5144 if (!opt->objfind)
5145 CALLOC_ARRAY(opt->objfind, 1);
5147 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5148 opt->flags.recursive = 1;
5149 opt->flags.tree_in_recursive = 1;
5150 oidset_insert(opt->objfind, &oid);
5151 return 0;
5154 static int diff_opt_anchored(const struct option *opt,
5155 const char *arg, int unset)
5157 struct diff_options *options = opt->value;
5159 BUG_ON_OPT_NEG(unset);
5160 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5161 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5162 options->anchors_alloc);
5163 options->anchors[options->anchors_nr++] = xstrdup(arg);
5164 return 0;
5167 static int diff_opt_binary(const struct option *opt,
5168 const char *arg, int unset)
5170 struct diff_options *options = opt->value;
5172 BUG_ON_OPT_NEG(unset);
5173 BUG_ON_OPT_ARG(arg);
5174 enable_patch_output(&options->output_format);
5175 options->flags.binary = 1;
5176 return 0;
5179 static int diff_opt_break_rewrites(const struct option *opt,
5180 const char *arg, int unset)
5182 int *break_opt = opt->value;
5183 int opt1, opt2;
5185 BUG_ON_OPT_NEG(unset);
5186 if (!arg)
5187 arg = "";
5188 opt1 = parse_rename_score(&arg);
5189 if (*arg == 0)
5190 opt2 = 0;
5191 else if (*arg != '/')
5192 return error(_("%s expects <n>/<m> form"), opt->long_name);
5193 else {
5194 arg++;
5195 opt2 = parse_rename_score(&arg);
5197 if (*arg != 0)
5198 return error(_("%s expects <n>/<m> form"), opt->long_name);
5199 *break_opt = opt1 | (opt2 << 16);
5200 return 0;
5203 static int diff_opt_char(const struct option *opt,
5204 const char *arg, int unset)
5206 char *value = opt->value;
5208 BUG_ON_OPT_NEG(unset);
5209 if (arg[1])
5210 return error(_("%s expects a character, got '%s'"),
5211 opt->long_name, arg);
5212 *value = arg[0];
5213 return 0;
5216 static int diff_opt_color_moved(const struct option *opt,
5217 const char *arg, int unset)
5219 struct diff_options *options = opt->value;
5221 if (unset) {
5222 options->color_moved = COLOR_MOVED_NO;
5223 } else if (!arg) {
5224 if (diff_color_moved_default)
5225 options->color_moved = diff_color_moved_default;
5226 if (options->color_moved == COLOR_MOVED_NO)
5227 options->color_moved = COLOR_MOVED_DEFAULT;
5228 } else {
5229 int cm = parse_color_moved(arg);
5230 if (cm < 0)
5231 return error(_("bad --color-moved argument: %s"), arg);
5232 options->color_moved = cm;
5234 return 0;
5237 static int diff_opt_color_moved_ws(const struct option *opt,
5238 const char *arg, int unset)
5240 struct diff_options *options = opt->value;
5241 unsigned cm;
5243 if (unset) {
5244 options->color_moved_ws_handling = 0;
5245 return 0;
5248 cm = parse_color_moved_ws(arg);
5249 if (cm & COLOR_MOVED_WS_ERROR)
5250 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5251 options->color_moved_ws_handling = cm;
5252 return 0;
5255 static int diff_opt_color_words(const struct option *opt,
5256 const char *arg, int unset)
5258 struct diff_options *options = opt->value;
5260 BUG_ON_OPT_NEG(unset);
5261 options->use_color = 1;
5262 options->word_diff = DIFF_WORDS_COLOR;
5263 options->word_regex = arg;
5264 return 0;
5267 static int diff_opt_compact_summary(const struct option *opt,
5268 const char *arg, int unset)
5270 struct diff_options *options = opt->value;
5272 BUG_ON_OPT_ARG(arg);
5273 if (unset) {
5274 options->flags.stat_with_summary = 0;
5275 } else {
5276 options->flags.stat_with_summary = 1;
5277 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5278 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5280 return 0;
5283 static int diff_opt_diff_algorithm(const struct option *opt,
5284 const char *arg, int unset)
5286 struct diff_options *options = opt->value;
5288 BUG_ON_OPT_NEG(unset);
5290 if (set_diff_algorithm(options, arg))
5291 return error(_("option diff-algorithm accepts \"myers\", "
5292 "\"minimal\", \"patience\" and \"histogram\""));
5294 options->ignore_driver_algorithm = 1;
5296 return 0;
5299 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5300 const char *arg, int unset)
5302 struct diff_options *options = opt->value;
5304 BUG_ON_OPT_NEG(unset);
5305 BUG_ON_OPT_ARG(arg);
5307 if (set_diff_algorithm(options, opt->long_name))
5308 BUG("available diff algorithms include \"myers\", "
5309 "\"minimal\", \"patience\" and \"histogram\"");
5311 options->ignore_driver_algorithm = 1;
5313 return 0;
5316 static int diff_opt_dirstat(const struct option *opt,
5317 const char *arg, int unset)
5319 struct diff_options *options = opt->value;
5321 BUG_ON_OPT_NEG(unset);
5322 if (!strcmp(opt->long_name, "cumulative")) {
5323 if (arg)
5324 BUG("how come --cumulative take a value?");
5325 arg = "cumulative";
5326 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5327 parse_dirstat_opt(options, "files");
5328 parse_dirstat_opt(options, arg ? arg : "");
5329 return 0;
5332 static int diff_opt_find_copies(const struct option *opt,
5333 const char *arg, int unset)
5335 struct diff_options *options = opt->value;
5337 BUG_ON_OPT_NEG(unset);
5338 if (!arg)
5339 arg = "";
5340 options->rename_score = parse_rename_score(&arg);
5341 if (*arg != 0)
5342 return error(_("invalid argument to %s"), opt->long_name);
5344 if (options->detect_rename == DIFF_DETECT_COPY)
5345 options->flags.find_copies_harder = 1;
5346 else
5347 options->detect_rename = DIFF_DETECT_COPY;
5349 return 0;
5352 static int diff_opt_find_renames(const struct option *opt,
5353 const char *arg, int unset)
5355 struct diff_options *options = opt->value;
5357 BUG_ON_OPT_NEG(unset);
5358 if (!arg)
5359 arg = "";
5360 options->rename_score = parse_rename_score(&arg);
5361 if (*arg != 0)
5362 return error(_("invalid argument to %s"), opt->long_name);
5364 options->detect_rename = DIFF_DETECT_RENAME;
5365 return 0;
5368 static int diff_opt_follow(const struct option *opt,
5369 const char *arg, int unset)
5371 struct diff_options *options = opt->value;
5373 BUG_ON_OPT_ARG(arg);
5374 if (unset) {
5375 options->flags.follow_renames = 0;
5376 options->flags.default_follow_renames = 0;
5377 } else {
5378 options->flags.follow_renames = 1;
5380 return 0;
5383 static int diff_opt_ignore_submodules(const struct option *opt,
5384 const char *arg, int unset)
5386 struct diff_options *options = opt->value;
5388 BUG_ON_OPT_NEG(unset);
5389 if (!arg)
5390 arg = "all";
5391 options->flags.override_submodule_config = 1;
5392 handle_ignore_submodules_arg(options, arg);
5393 return 0;
5396 static int diff_opt_line_prefix(const struct option *opt,
5397 const char *optarg, int unset)
5399 struct diff_options *options = opt->value;
5401 BUG_ON_OPT_NEG(unset);
5402 options->line_prefix = optarg;
5403 options->line_prefix_length = strlen(options->line_prefix);
5404 graph_setup_line_prefix(options);
5405 return 0;
5408 static int diff_opt_no_prefix(const struct option *opt,
5409 const char *optarg, int unset)
5411 struct diff_options *options = opt->value;
5413 BUG_ON_OPT_NEG(unset);
5414 BUG_ON_OPT_ARG(optarg);
5415 diff_set_noprefix(options);
5416 return 0;
5419 static int diff_opt_default_prefix(const struct option *opt,
5420 const char *optarg, int unset)
5422 struct diff_options *options = opt->value;
5424 BUG_ON_OPT_NEG(unset);
5425 BUG_ON_OPT_ARG(optarg);
5426 FREE_AND_NULL(diff_src_prefix);
5427 FREE_AND_NULL(diff_dst_prefix);
5428 diff_set_default_prefix(options);
5429 return 0;
5432 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5433 const struct option *opt,
5434 const char *arg, int unset)
5436 struct diff_options *options = opt->value;
5437 char *path;
5439 BUG_ON_OPT_NEG(unset);
5440 path = prefix_filename(ctx->prefix, arg);
5441 options->file = xfopen(path, "w");
5442 options->close_file = 1;
5443 if (options->use_color != GIT_COLOR_ALWAYS)
5444 options->use_color = GIT_COLOR_NEVER;
5445 free(path);
5446 return 0;
5449 static int diff_opt_patience(const struct option *opt,
5450 const char *arg, int unset)
5452 struct diff_options *options = opt->value;
5453 int i;
5455 BUG_ON_OPT_NEG(unset);
5456 BUG_ON_OPT_ARG(arg);
5458 * Both --patience and --anchored use PATIENCE_DIFF
5459 * internally, so remove any anchors previously
5460 * specified.
5462 for (i = 0; i < options->anchors_nr; i++)
5463 free(options->anchors[i]);
5464 options->anchors_nr = 0;
5465 options->ignore_driver_algorithm = 1;
5467 return set_diff_algorithm(options, "patience");
5470 static int diff_opt_ignore_regex(const struct option *opt,
5471 const char *arg, int unset)
5473 struct diff_options *options = opt->value;
5474 regex_t *regex;
5476 BUG_ON_OPT_NEG(unset);
5478 regex = xmalloc(sizeof(*regex));
5479 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE)) {
5480 free(regex);
5481 return error(_("invalid regex given to -I: '%s'"), arg);
5484 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5485 options->ignore_regex_alloc);
5486 options->ignore_regex[options->ignore_regex_nr++] = regex;
5487 return 0;
5490 static int diff_opt_pickaxe_regex(const struct option *opt,
5491 const char *arg, int unset)
5493 struct diff_options *options = opt->value;
5495 BUG_ON_OPT_NEG(unset);
5496 options->pickaxe = arg;
5497 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5498 return 0;
5501 static int diff_opt_pickaxe_string(const struct option *opt,
5502 const char *arg, int unset)
5504 struct diff_options *options = opt->value;
5506 BUG_ON_OPT_NEG(unset);
5507 options->pickaxe = arg;
5508 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5509 return 0;
5512 static int diff_opt_relative(const struct option *opt,
5513 const char *arg, int unset)
5515 struct diff_options *options = opt->value;
5517 options->flags.relative_name = !unset;
5518 if (arg)
5519 options->prefix = arg;
5520 return 0;
5523 static int diff_opt_submodule(const struct option *opt,
5524 const char *arg, int unset)
5526 struct diff_options *options = opt->value;
5528 BUG_ON_OPT_NEG(unset);
5529 if (!arg)
5530 arg = "log";
5531 if (parse_submodule_params(options, arg))
5532 return error(_("failed to parse --submodule option parameter: '%s'"),
5533 arg);
5534 return 0;
5537 static int diff_opt_textconv(const struct option *opt,
5538 const char *arg, int unset)
5540 struct diff_options *options = opt->value;
5542 BUG_ON_OPT_ARG(arg);
5543 if (unset) {
5544 options->flags.allow_textconv = 0;
5545 } else {
5546 options->flags.allow_textconv = 1;
5547 options->flags.textconv_set_via_cmdline = 1;
5549 return 0;
5552 static int diff_opt_unified(const struct option *opt,
5553 const char *arg, int unset)
5555 struct diff_options *options = opt->value;
5556 char *s;
5558 BUG_ON_OPT_NEG(unset);
5560 if (arg) {
5561 options->context = strtol(arg, &s, 10);
5562 if (*s)
5563 return error(_("%s expects a numerical value"), "--unified");
5565 enable_patch_output(&options->output_format);
5567 return 0;
5570 static int diff_opt_word_diff(const struct option *opt,
5571 const char *arg, int unset)
5573 struct diff_options *options = opt->value;
5575 BUG_ON_OPT_NEG(unset);
5576 if (arg) {
5577 if (!strcmp(arg, "plain"))
5578 options->word_diff = DIFF_WORDS_PLAIN;
5579 else if (!strcmp(arg, "color")) {
5580 options->use_color = 1;
5581 options->word_diff = DIFF_WORDS_COLOR;
5583 else if (!strcmp(arg, "porcelain"))
5584 options->word_diff = DIFF_WORDS_PORCELAIN;
5585 else if (!strcmp(arg, "none"))
5586 options->word_diff = DIFF_WORDS_NONE;
5587 else
5588 return error(_("bad --word-diff argument: %s"), arg);
5589 } else {
5590 if (options->word_diff == DIFF_WORDS_NONE)
5591 options->word_diff = DIFF_WORDS_PLAIN;
5593 return 0;
5596 static int diff_opt_word_diff_regex(const struct option *opt,
5597 const char *arg, int unset)
5599 struct diff_options *options = opt->value;
5601 BUG_ON_OPT_NEG(unset);
5602 if (options->word_diff == DIFF_WORDS_NONE)
5603 options->word_diff = DIFF_WORDS_PLAIN;
5604 options->word_regex = arg;
5605 return 0;
5608 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5610 struct diff_options *options = opt->value;
5612 BUG_ON_OPT_NEG(unset);
5613 if (!strcmp(opt->long_name, "skip-to"))
5614 options->skip_instead_of_rotate = 1;
5615 else
5616 options->skip_instead_of_rotate = 0;
5617 options->rotate_to = arg;
5618 return 0;
5622 * Consider adding new flags to __git_diff_common_options
5623 * in contrib/completion/git-completion.bash
5625 struct option *add_diff_options(const struct option *opts,
5626 struct diff_options *options)
5628 struct option parseopts[] = {
5629 OPT_GROUP(N_("Diff output format options")),
5630 OPT_BITOP('p', "patch", &options->output_format,
5631 N_("generate patch"),
5632 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5633 OPT_SET_INT('s', "no-patch", &options->output_format,
5634 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5635 OPT_BITOP('u', NULL, &options->output_format,
5636 N_("generate patch"),
5637 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5638 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5639 N_("generate diffs with <n> lines context"),
5640 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5641 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5642 N_("generate diffs with <n> lines context")),
5643 OPT_BITOP(0, "raw", &options->output_format,
5644 N_("generate the diff in raw format"),
5645 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5646 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5647 N_("synonym for '-p --raw'"),
5648 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5649 DIFF_FORMAT_NO_OUTPUT),
5650 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5651 N_("synonym for '-p --stat'"),
5652 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5653 DIFF_FORMAT_NO_OUTPUT),
5654 OPT_BITOP(0, "numstat", &options->output_format,
5655 N_("machine friendly --stat"),
5656 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5657 OPT_BITOP(0, "shortstat", &options->output_format,
5658 N_("output only the last line of --stat"),
5659 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5660 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
5661 N_("output the distribution of relative amount of changes for each sub-directory"),
5662 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5663 diff_opt_dirstat),
5664 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5665 N_("synonym for --dirstat=cumulative"),
5666 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5667 diff_opt_dirstat),
5668 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
5669 N_("synonym for --dirstat=files,<param1>,<param2>..."),
5670 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5671 diff_opt_dirstat),
5672 OPT_BIT_F(0, "check", &options->output_format,
5673 N_("warn if changes introduce conflict markers or whitespace errors"),
5674 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5675 OPT_BITOP(0, "summary", &options->output_format,
5676 N_("condensed summary such as creations, renames and mode changes"),
5677 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5678 OPT_BIT_F(0, "name-only", &options->output_format,
5679 N_("show only names of changed files"),
5680 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5681 OPT_BIT_F(0, "name-status", &options->output_format,
5682 N_("show only names and status of changed files"),
5683 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5684 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5685 N_("generate diffstat"),
5686 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5687 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5688 N_("generate diffstat with a given width"),
5689 PARSE_OPT_NONEG, diff_opt_stat),
5690 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5691 N_("generate diffstat with a given name width"),
5692 PARSE_OPT_NONEG, diff_opt_stat),
5693 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5694 N_("generate diffstat with a given graph width"),
5695 PARSE_OPT_NONEG, diff_opt_stat),
5696 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5697 N_("generate diffstat with limited lines"),
5698 PARSE_OPT_NONEG, diff_opt_stat),
5699 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5700 N_("generate compact summary in diffstat"),
5701 PARSE_OPT_NOARG, diff_opt_compact_summary),
5702 OPT_CALLBACK_F(0, "binary", options, NULL,
5703 N_("output a binary diff that can be applied"),
5704 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5705 OPT_BOOL(0, "full-index", &options->flags.full_index,
5706 N_("show full pre- and post-image object names on the \"index\" lines")),
5707 OPT_COLOR_FLAG(0, "color", &options->use_color,
5708 N_("show colored diff")),
5709 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5710 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5711 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5712 OPT_SET_INT('z', NULL, &options->line_termination,
5713 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5715 OPT__ABBREV(&options->abbrev),
5716 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5717 N_("show the given source prefix instead of \"a/\""),
5718 PARSE_OPT_NONEG),
5719 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5720 N_("show the given destination prefix instead of \"b/\""),
5721 PARSE_OPT_NONEG),
5722 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5723 N_("prepend an additional prefix to every line of output"),
5724 PARSE_OPT_NONEG, diff_opt_line_prefix),
5725 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5726 N_("do not show any source or destination prefix"),
5727 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5728 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5729 N_("use default prefixes a/ and b/"),
5730 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5731 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5732 N_("show context between diff hunks up to the specified number of lines"),
5733 PARSE_OPT_NONEG),
5734 OPT_CALLBACK_F(0, "output-indicator-new",
5735 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5736 N_("<char>"),
5737 N_("specify the character to indicate a new line instead of '+'"),
5738 PARSE_OPT_NONEG, diff_opt_char),
5739 OPT_CALLBACK_F(0, "output-indicator-old",
5740 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5741 N_("<char>"),
5742 N_("specify the character to indicate an old line instead of '-'"),
5743 PARSE_OPT_NONEG, diff_opt_char),
5744 OPT_CALLBACK_F(0, "output-indicator-context",
5745 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5746 N_("<char>"),
5747 N_("specify the character to indicate a context instead of ' '"),
5748 PARSE_OPT_NONEG, diff_opt_char),
5750 OPT_GROUP(N_("Diff rename options")),
5751 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5752 N_("break complete rewrite changes into pairs of delete and create"),
5753 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5754 diff_opt_break_rewrites),
5755 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5756 N_("detect renames"),
5757 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5758 diff_opt_find_renames),
5759 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5760 N_("omit the preimage for deletes"),
5761 1, PARSE_OPT_NONEG),
5762 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5763 N_("detect copies"),
5764 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5765 diff_opt_find_copies),
5766 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5767 N_("use unmodified files as source to find copies")),
5768 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5769 N_("disable rename detection"),
5770 0, PARSE_OPT_NONEG),
5771 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5772 N_("use empty blobs as rename source")),
5773 OPT_CALLBACK_F(0, "follow", options, NULL,
5774 N_("continue listing the history of a file beyond renames"),
5775 PARSE_OPT_NOARG, diff_opt_follow),
5776 OPT_INTEGER('l', NULL, &options->rename_limit,
5777 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5779 OPT_GROUP(N_("Diff algorithm options")),
5780 OPT_CALLBACK_F(0, "minimal", options, NULL,
5781 N_("produce the smallest possible diff"),
5782 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5783 diff_opt_diff_algorithm_no_arg),
5784 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5785 N_("ignore whitespace when comparing lines"),
5786 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5787 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5788 N_("ignore changes in amount of whitespace"),
5789 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5790 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5791 N_("ignore changes in whitespace at EOL"),
5792 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5793 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5794 N_("ignore carrier-return at the end of line"),
5795 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5796 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5797 N_("ignore changes whose lines are all blank"),
5798 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5799 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5800 N_("ignore changes whose all lines match <regex>"),
5801 0, diff_opt_ignore_regex),
5802 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5803 N_("heuristic to shift diff hunk boundaries for easy reading"),
5804 XDF_INDENT_HEURISTIC),
5805 OPT_CALLBACK_F(0, "patience", options, NULL,
5806 N_("generate diff using the \"patience diff\" algorithm"),
5807 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5808 diff_opt_patience),
5809 OPT_CALLBACK_F(0, "histogram", options, NULL,
5810 N_("generate diff using the \"histogram diff\" algorithm"),
5811 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5812 diff_opt_diff_algorithm_no_arg),
5813 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5814 N_("choose a diff algorithm"),
5815 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5816 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5817 N_("generate diff using the \"anchored diff\" algorithm"),
5818 PARSE_OPT_NONEG, diff_opt_anchored),
5819 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5820 N_("show word diff, using <mode> to delimit changed words"),
5821 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5822 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5823 N_("use <regex> to decide what a word is"),
5824 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5825 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5826 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5827 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5828 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5829 N_("moved lines of code are colored differently"),
5830 PARSE_OPT_OPTARG, diff_opt_color_moved),
5831 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5832 N_("how white spaces are ignored in --color-moved"),
5833 0, diff_opt_color_moved_ws),
5835 OPT_GROUP(N_("Other diff options")),
5836 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5837 N_("when run from subdir, exclude changes outside and show relative paths"),
5838 PARSE_OPT_OPTARG,
5839 diff_opt_relative),
5840 OPT_BOOL('a', "text", &options->flags.text,
5841 N_("treat all files as text")),
5842 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5843 N_("swap two inputs, reverse the diff")),
5844 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5845 N_("exit with 1 if there were differences, 0 otherwise")),
5846 OPT_BOOL(0, "quiet", &options->flags.quick,
5847 N_("disable all output of the program")),
5848 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5849 N_("allow an external diff helper to be executed")),
5850 OPT_CALLBACK_F(0, "textconv", options, NULL,
5851 N_("run external text conversion filters when comparing binary files"),
5852 PARSE_OPT_NOARG, diff_opt_textconv),
5853 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5854 N_("ignore changes to submodules in the diff generation"),
5855 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5856 diff_opt_ignore_submodules),
5857 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5858 N_("specify how differences in submodules are shown"),
5859 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5860 diff_opt_submodule),
5861 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5862 N_("hide 'git add -N' entries from the index"),
5863 1, PARSE_OPT_NONEG),
5864 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5865 N_("treat 'git add -N' entries as real in the index"),
5866 0, PARSE_OPT_NONEG),
5867 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5868 N_("look for differences that change the number of occurrences of the specified string"),
5869 0, diff_opt_pickaxe_string),
5870 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5871 N_("look for differences that change the number of occurrences of the specified regex"),
5872 0, diff_opt_pickaxe_regex),
5873 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5874 N_("show all changes in the changeset with -S or -G"),
5875 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5876 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5877 N_("treat <string> in -S as extended POSIX regular expression"),
5878 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5879 OPT_FILENAME('O', NULL, &options->orderfile,
5880 N_("control the order in which files appear in the output")),
5881 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5882 N_("show the change in the specified path first"),
5883 PARSE_OPT_NONEG, diff_opt_rotate_to),
5884 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5885 N_("skip the output to the specified path"),
5886 PARSE_OPT_NONEG, diff_opt_rotate_to),
5887 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5888 N_("look for differences that change the number of occurrences of the specified object"),
5889 PARSE_OPT_NONEG, diff_opt_find_object),
5890 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5891 N_("select files by diff type"),
5892 PARSE_OPT_NONEG, diff_opt_diff_filter),
5893 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5894 N_("output to a specific file"),
5895 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5897 OPT_END()
5900 return parse_options_concat(opts, parseopts);
5903 int diff_opt_parse(struct diff_options *options,
5904 const char **av, int ac, const char *prefix)
5906 struct option no_options[] = { OPT_END() };
5907 struct option *parseopts = add_diff_options(no_options, options);
5909 if (!prefix)
5910 prefix = "";
5912 ac = parse_options(ac, av, prefix, parseopts, NULL,
5913 PARSE_OPT_KEEP_DASHDASH |
5914 PARSE_OPT_KEEP_UNKNOWN_OPT |
5915 PARSE_OPT_NO_INTERNAL_HELP |
5916 PARSE_OPT_ONE_SHOT |
5917 PARSE_OPT_STOP_AT_NON_OPTION);
5918 free(parseopts);
5920 return ac;
5923 int parse_rename_score(const char **cp_p)
5925 unsigned long num, scale;
5926 int ch, dot;
5927 const char *cp = *cp_p;
5929 num = 0;
5930 scale = 1;
5931 dot = 0;
5932 for (;;) {
5933 ch = *cp;
5934 if ( !dot && ch == '.' ) {
5935 scale = 1;
5936 dot = 1;
5937 } else if ( ch == '%' ) {
5938 scale = dot ? scale*100 : 100;
5939 cp++; /* % is always at the end */
5940 break;
5941 } else if ( ch >= '0' && ch <= '9' ) {
5942 if ( scale < 100000 ) {
5943 scale *= 10;
5944 num = (num*10) + (ch-'0');
5946 } else {
5947 break;
5949 cp++;
5951 *cp_p = cp;
5953 /* user says num divided by scale and we say internally that
5954 * is MAX_SCORE * num / scale.
5956 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5959 struct diff_queue_struct diff_queued_diff;
5961 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5963 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5964 queue->queue[queue->nr++] = dp;
5967 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5968 struct diff_filespec *one,
5969 struct diff_filespec *two)
5971 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5972 dp->one = one;
5973 dp->two = two;
5974 if (queue)
5975 diff_q(queue, dp);
5976 return dp;
5979 void diff_free_filepair(struct diff_filepair *p)
5981 free_filespec(p->one);
5982 free_filespec(p->two);
5983 free(p);
5986 void diff_free_queue(struct diff_queue_struct *q)
5988 for (int i = 0; i < q->nr; i++)
5989 diff_free_filepair(q->queue[i]);
5990 free(q->queue);
5993 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5995 int abblen;
5996 const char *abbrev;
5998 /* Do we want all 40 hex characters? */
5999 if (len == the_hash_algo->hexsz)
6000 return oid_to_hex(oid);
6002 /* An abbreviated value is fine, possibly followed by an ellipsis. */
6003 abbrev = diff_abbrev_oid(oid, len);
6005 if (!print_sha1_ellipsis())
6006 return abbrev;
6008 abblen = strlen(abbrev);
6011 * In well-behaved cases, where the abbreviated result is the
6012 * same as the requested length, append three dots after the
6013 * abbreviation (hence the whole logic is limited to the case
6014 * where abblen < 37); when the actual abbreviated result is a
6015 * bit longer than the requested length, we reduce the number
6016 * of dots so that they match the well-behaved ones. However,
6017 * if the actual abbreviation is longer than the requested
6018 * length by more than three, we give up on aligning, and add
6019 * three dots anyway, to indicate that the output is not the
6020 * full object name. Yes, this may be suboptimal, but this
6021 * appears only in "diff --raw --abbrev" output and it is not
6022 * worth the effort to change it now. Note that this would
6023 * likely to work fine when the automatic sizing of default
6024 * abbreviation length is used--we would be fed -1 in "len" in
6025 * that case, and will end up always appending three-dots, but
6026 * the automatic sizing is supposed to give abblen that ensures
6027 * uniqueness across all objects (statistically speaking).
6029 if (abblen < the_hash_algo->hexsz - 3) {
6030 static char hex[GIT_MAX_HEXSZ + 1];
6031 if (len < abblen && abblen <= len + 2)
6032 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6033 else
6034 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6035 return hex;
6038 return oid_to_hex(oid);
6041 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6043 int line_termination = opt->line_termination;
6044 int inter_name_termination = line_termination ? '\t' : '\0';
6046 fprintf(opt->file, "%s", diff_line_prefix(opt));
6047 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6048 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6049 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6050 fprintf(opt->file, "%s ",
6051 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6053 if (p->score) {
6054 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6055 inter_name_termination);
6056 } else {
6057 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6060 if (p->status == DIFF_STATUS_COPIED ||
6061 p->status == DIFF_STATUS_RENAMED) {
6062 const char *name_a, *name_b;
6063 name_a = p->one->path;
6064 name_b = p->two->path;
6065 strip_prefix(opt->prefix_length, &name_a, &name_b);
6066 write_name_quoted(name_a, opt->file, inter_name_termination);
6067 write_name_quoted(name_b, opt->file, line_termination);
6068 } else {
6069 const char *name_a, *name_b;
6070 name_a = p->one->mode ? p->one->path : p->two->path;
6071 name_b = NULL;
6072 strip_prefix(opt->prefix_length, &name_a, &name_b);
6073 write_name_quoted(name_a, opt->file, line_termination);
6077 int diff_unmodified_pair(struct diff_filepair *p)
6079 /* This function is written stricter than necessary to support
6080 * the currently implemented transformers, but the idea is to
6081 * let transformers to produce diff_filepairs any way they want,
6082 * and filter and clean them up here before producing the output.
6084 struct diff_filespec *one = p->one, *two = p->two;
6086 if (DIFF_PAIR_UNMERGED(p))
6087 return 0; /* unmerged is interesting */
6089 /* deletion, addition, mode or type change
6090 * and rename are all interesting.
6092 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6093 DIFF_PAIR_MODE_CHANGED(p) ||
6094 strcmp(one->path, two->path))
6095 return 0;
6097 /* both are valid and point at the same path. that is, we are
6098 * dealing with a change.
6100 if (one->oid_valid && two->oid_valid &&
6101 oideq(&one->oid, &two->oid) &&
6102 !one->dirty_submodule && !two->dirty_submodule)
6103 return 1; /* no change */
6104 if (!one->oid_valid && !two->oid_valid)
6105 return 1; /* both look at the same file on the filesystem. */
6106 return 0;
6109 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6111 int include_conflict_headers =
6112 (additional_headers(o, p->one->path) &&
6113 !o->pickaxe_opts &&
6114 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6117 * Check if we can return early without showing a diff. Note that
6118 * diff_filepair only stores {oid, path, mode, is_valid}
6119 * information for each path, and thus diff_unmodified_pair() only
6120 * considers those bits of info. However, we do not want pairs
6121 * created by create_filepairs_for_header_only_notifications()
6122 * (which always look like unmodified pairs) to be ignored, so
6123 * return early if both p is unmodified AND we don't want to
6124 * include_conflict_headers.
6126 if (diff_unmodified_pair(p) && !include_conflict_headers)
6127 return;
6129 /* Actually, we can also return early to avoid showing tree diffs */
6130 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6131 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6132 return;
6134 run_diff(p, o);
6137 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6138 struct diffstat_t *diffstat)
6140 if (diff_unmodified_pair(p))
6141 return;
6143 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6144 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6145 return; /* no useful stat for tree diffs */
6147 run_diffstat(p, o, diffstat);
6150 static void diff_flush_checkdiff(struct diff_filepair *p,
6151 struct diff_options *o)
6153 if (diff_unmodified_pair(p))
6154 return;
6156 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6157 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6158 return; /* nothing to check in tree diffs */
6160 run_checkdiff(p, o);
6163 int diff_queue_is_empty(struct diff_options *o)
6165 struct diff_queue_struct *q = &diff_queued_diff;
6166 int i;
6167 int include_conflict_headers =
6168 (o->additional_path_headers &&
6169 strmap_get_size(o->additional_path_headers) &&
6170 !o->pickaxe_opts &&
6171 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6173 if (include_conflict_headers)
6174 return 0;
6176 for (i = 0; i < q->nr; i++)
6177 if (!diff_unmodified_pair(q->queue[i]))
6178 return 0;
6179 return 1;
6182 #if DIFF_DEBUG
6183 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6185 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6186 x, one ? one : "",
6187 s->path,
6188 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6189 s->mode,
6190 s->oid_valid ? oid_to_hex(&s->oid) : "");
6191 fprintf(stderr, "queue[%d] %s size %lu\n",
6192 x, one ? one : "",
6193 s->size);
6196 void diff_debug_filepair(const struct diff_filepair *p, int i)
6198 diff_debug_filespec(p->one, i, "one");
6199 diff_debug_filespec(p->two, i, "two");
6200 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6201 p->score, p->status ? p->status : '?',
6202 p->one->rename_used, p->broken_pair);
6205 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6207 int i;
6208 if (msg)
6209 fprintf(stderr, "%s\n", msg);
6210 fprintf(stderr, "q->nr = %d\n", q->nr);
6211 for (i = 0; i < q->nr; i++) {
6212 struct diff_filepair *p = q->queue[i];
6213 diff_debug_filepair(p, i);
6216 #endif
6218 static void diff_resolve_rename_copy(void)
6220 int i;
6221 struct diff_filepair *p;
6222 struct diff_queue_struct *q = &diff_queued_diff;
6224 diff_debug_queue("resolve-rename-copy", q);
6226 for (i = 0; i < q->nr; i++) {
6227 p = q->queue[i];
6228 p->status = 0; /* undecided */
6229 if (DIFF_PAIR_UNMERGED(p))
6230 p->status = DIFF_STATUS_UNMERGED;
6231 else if (!DIFF_FILE_VALID(p->one))
6232 p->status = DIFF_STATUS_ADDED;
6233 else if (!DIFF_FILE_VALID(p->two))
6234 p->status = DIFF_STATUS_DELETED;
6235 else if (DIFF_PAIR_TYPE_CHANGED(p))
6236 p->status = DIFF_STATUS_TYPE_CHANGED;
6238 /* from this point on, we are dealing with a pair
6239 * whose both sides are valid and of the same type, i.e.
6240 * either in-place edit or rename/copy edit.
6242 else if (DIFF_PAIR_RENAME(p)) {
6244 * A rename might have re-connected a broken
6245 * pair up, causing the pathnames to be the
6246 * same again. If so, that's not a rename at
6247 * all, just a modification..
6249 * Otherwise, see if this source was used for
6250 * multiple renames, in which case we decrement
6251 * the count, and call it a copy.
6253 if (!strcmp(p->one->path, p->two->path))
6254 p->status = DIFF_STATUS_MODIFIED;
6255 else if (--p->one->rename_used > 0)
6256 p->status = DIFF_STATUS_COPIED;
6257 else
6258 p->status = DIFF_STATUS_RENAMED;
6260 else if (!oideq(&p->one->oid, &p->two->oid) ||
6261 p->one->mode != p->two->mode ||
6262 p->one->dirty_submodule ||
6263 p->two->dirty_submodule ||
6264 is_null_oid(&p->one->oid))
6265 p->status = DIFF_STATUS_MODIFIED;
6266 else {
6267 /* This is a "no-change" entry and should not
6268 * happen anymore, but prepare for broken callers.
6270 error("feeding unmodified %s to diffcore",
6271 p->one->path);
6272 p->status = DIFF_STATUS_UNKNOWN;
6275 diff_debug_queue("resolve-rename-copy done", q);
6278 static int check_pair_status(struct diff_filepair *p)
6280 switch (p->status) {
6281 case DIFF_STATUS_UNKNOWN:
6282 return 0;
6283 case 0:
6284 die("internal error in diff-resolve-rename-copy");
6285 default:
6286 return 1;
6290 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6292 int fmt = opt->output_format;
6294 if (fmt & DIFF_FORMAT_CHECKDIFF)
6295 diff_flush_checkdiff(p, opt);
6296 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6297 diff_flush_raw(p, opt);
6298 else if (fmt & DIFF_FORMAT_NAME) {
6299 const char *name_a, *name_b;
6300 name_a = p->two->path;
6301 name_b = NULL;
6302 strip_prefix(opt->prefix_length, &name_a, &name_b);
6303 fprintf(opt->file, "%s", diff_line_prefix(opt));
6304 write_name_quoted(name_a, opt->file, opt->line_termination);
6307 opt->found_changes = 1;
6310 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6312 struct strbuf sb = STRBUF_INIT;
6313 if (fs->mode)
6314 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6315 else
6316 strbuf_addf(&sb, " %s ", newdelete);
6318 quote_c_style(fs->path, &sb, NULL, 0);
6319 strbuf_addch(&sb, '\n');
6320 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6321 sb.buf, sb.len, 0);
6322 strbuf_release(&sb);
6325 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6326 int show_name)
6328 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6329 struct strbuf sb = STRBUF_INIT;
6330 strbuf_addf(&sb, " mode change %06o => %06o",
6331 p->one->mode, p->two->mode);
6332 if (show_name) {
6333 strbuf_addch(&sb, ' ');
6334 quote_c_style(p->two->path, &sb, NULL, 0);
6336 strbuf_addch(&sb, '\n');
6337 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6338 sb.buf, sb.len, 0);
6339 strbuf_release(&sb);
6343 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6344 struct diff_filepair *p)
6346 struct strbuf sb = STRBUF_INIT;
6347 struct strbuf names = STRBUF_INIT;
6349 pprint_rename(&names, p->one->path, p->two->path);
6350 strbuf_addf(&sb, " %s %s (%d%%)\n",
6351 renamecopy, names.buf, similarity_index(p));
6352 strbuf_release(&names);
6353 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6354 sb.buf, sb.len, 0);
6355 show_mode_change(opt, p, 0);
6356 strbuf_release(&sb);
6359 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6361 switch(p->status) {
6362 case DIFF_STATUS_DELETED:
6363 show_file_mode_name(opt, "delete", p->one);
6364 break;
6365 case DIFF_STATUS_ADDED:
6366 show_file_mode_name(opt, "create", p->two);
6367 break;
6368 case DIFF_STATUS_COPIED:
6369 show_rename_copy(opt, "copy", p);
6370 break;
6371 case DIFF_STATUS_RENAMED:
6372 show_rename_copy(opt, "rename", p);
6373 break;
6374 default:
6375 if (p->score) {
6376 struct strbuf sb = STRBUF_INIT;
6377 strbuf_addstr(&sb, " rewrite ");
6378 quote_c_style(p->two->path, &sb, NULL, 0);
6379 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6380 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6381 sb.buf, sb.len, 0);
6382 strbuf_release(&sb);
6384 show_mode_change(opt, p, !p->score);
6385 break;
6389 struct patch_id_t {
6390 git_hash_ctx *ctx;
6391 int patchlen;
6394 static int remove_space(char *line, int len)
6396 int i;
6397 char *dst = line;
6398 unsigned char c;
6400 for (i = 0; i < len; i++)
6401 if (!isspace((c = line[i])))
6402 *dst++ = c;
6404 return dst - line;
6407 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6409 unsigned char hash[GIT_MAX_RAWSZ];
6410 unsigned short carry = 0;
6411 int i;
6413 the_hash_algo->final_fn(hash, ctx);
6414 the_hash_algo->init_fn(ctx);
6415 /* 20-byte sum, with carry */
6416 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6417 carry += result->hash[i] + hash[i];
6418 result->hash[i] = carry;
6419 carry >>= 8;
6423 static int patch_id_consume(void *priv, char *line, unsigned long len)
6425 struct patch_id_t *data = priv;
6426 int new_len;
6428 if (len > 12 && starts_with(line, "\\ "))
6429 return 0;
6430 new_len = remove_space(line, len);
6432 the_hash_algo->update_fn(data->ctx, line, new_len);
6433 data->patchlen += new_len;
6434 return 0;
6437 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6439 the_hash_algo->update_fn(ctx, str, strlen(str));
6442 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6444 /* large enough for 2^32 in octal */
6445 char buf[12];
6446 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6447 the_hash_algo->update_fn(ctx, buf, len);
6450 /* returns 0 upon success, and writes result into oid */
6451 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6453 struct diff_queue_struct *q = &diff_queued_diff;
6454 int i;
6455 git_hash_ctx ctx;
6456 struct patch_id_t data;
6458 the_hash_algo->init_fn(&ctx);
6459 memset(&data, 0, sizeof(struct patch_id_t));
6460 data.ctx = &ctx;
6461 oidclr(oid, the_repository->hash_algo);
6463 for (i = 0; i < q->nr; i++) {
6464 xpparam_t xpp;
6465 xdemitconf_t xecfg;
6466 mmfile_t mf1, mf2;
6467 struct diff_filepair *p = q->queue[i];
6468 int len1, len2;
6470 memset(&xpp, 0, sizeof(xpp));
6471 memset(&xecfg, 0, sizeof(xecfg));
6472 if (p->status == 0)
6473 return error("internal diff status error");
6474 if (p->status == DIFF_STATUS_UNKNOWN)
6475 continue;
6476 if (diff_unmodified_pair(p))
6477 continue;
6478 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6479 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6480 continue;
6481 if (DIFF_PAIR_UNMERGED(p))
6482 continue;
6484 diff_fill_oid_info(p->one, options->repo->index);
6485 diff_fill_oid_info(p->two, options->repo->index);
6487 len1 = remove_space(p->one->path, strlen(p->one->path));
6488 len2 = remove_space(p->two->path, strlen(p->two->path));
6489 patch_id_add_string(&ctx, "diff--git");
6490 patch_id_add_string(&ctx, "a/");
6491 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6492 patch_id_add_string(&ctx, "b/");
6493 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6495 if (p->one->mode == 0) {
6496 patch_id_add_string(&ctx, "newfilemode");
6497 patch_id_add_mode(&ctx, p->two->mode);
6498 } else if (p->two->mode == 0) {
6499 patch_id_add_string(&ctx, "deletedfilemode");
6500 patch_id_add_mode(&ctx, p->one->mode);
6501 } else if (p->one->mode != p->two->mode) {
6502 patch_id_add_string(&ctx, "oldmode");
6503 patch_id_add_mode(&ctx, p->one->mode);
6504 patch_id_add_string(&ctx, "newmode");
6505 patch_id_add_mode(&ctx, p->two->mode);
6508 if (diff_header_only) {
6509 /* don't do anything since we're only populating header info */
6510 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6511 diff_filespec_is_binary(options->repo, p->two)) {
6512 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6513 the_hash_algo->hexsz);
6514 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6515 the_hash_algo->hexsz);
6516 } else {
6517 if (p->one->mode == 0) {
6518 patch_id_add_string(&ctx, "---/dev/null");
6519 patch_id_add_string(&ctx, "+++b/");
6520 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6521 } else if (p->two->mode == 0) {
6522 patch_id_add_string(&ctx, "---a/");
6523 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6524 patch_id_add_string(&ctx, "+++/dev/null");
6525 } else {
6526 patch_id_add_string(&ctx, "---a/");
6527 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6528 patch_id_add_string(&ctx, "+++b/");
6529 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6532 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6533 fill_mmfile(options->repo, &mf2, p->two) < 0)
6534 return error("unable to read files to diff");
6535 xpp.flags = 0;
6536 xecfg.ctxlen = 3;
6537 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6538 if (xdi_diff_outf(&mf1, &mf2, NULL,
6539 patch_id_consume, &data, &xpp, &xecfg))
6540 return error("unable to generate patch-id diff for %s",
6541 p->one->path);
6543 flush_one_hunk(oid, &ctx);
6546 return 0;
6549 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6551 struct diff_queue_struct *q = &diff_queued_diff;
6552 int result = diff_get_patch_id(options, oid, diff_header_only);
6554 diff_free_queue(q);
6555 DIFF_QUEUE_CLEAR(q);
6557 return result;
6560 static int is_summary_empty(const struct diff_queue_struct *q)
6562 int i;
6564 for (i = 0; i < q->nr; i++) {
6565 const struct diff_filepair *p = q->queue[i];
6567 switch (p->status) {
6568 case DIFF_STATUS_DELETED:
6569 case DIFF_STATUS_ADDED:
6570 case DIFF_STATUS_COPIED:
6571 case DIFF_STATUS_RENAMED:
6572 return 0;
6573 default:
6574 if (p->score)
6575 return 0;
6576 if (p->one->mode && p->two->mode &&
6577 p->one->mode != p->two->mode)
6578 return 0;
6579 break;
6582 return 1;
6585 static const char rename_limit_warning[] =
6586 N_("exhaustive rename detection was skipped due to too many files.");
6588 static const char degrade_cc_to_c_warning[] =
6589 N_("only found copies from modified paths due to too many files.");
6591 static const char rename_limit_advice[] =
6592 N_("you may want to set your %s variable to at least "
6593 "%d and retry the command.");
6595 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6597 fflush(stdout);
6598 if (degraded_cc)
6599 warning(_(degrade_cc_to_c_warning));
6600 else if (needed)
6601 warning(_(rename_limit_warning));
6602 else
6603 return;
6604 if (0 < needed)
6605 warning(_(rename_limit_advice), varname, needed);
6608 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6610 struct strset present;
6611 struct diff_queue_struct *q = &diff_queued_diff;
6612 struct hashmap_iter iter;
6613 struct strmap_entry *e;
6614 int i;
6616 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6619 * Find out which paths exist in diff_queued_diff, preferring
6620 * one->path for any pair that has multiple paths.
6622 for (i = 0; i < q->nr; i++) {
6623 struct diff_filepair *p = q->queue[i];
6624 char *path = p->one->path ? p->one->path : p->two->path;
6626 if (strmap_contains(o->additional_path_headers, path))
6627 strset_add(&present, path);
6631 * Loop over paths in additional_path_headers; for each NOT already
6632 * in diff_queued_diff, create a synthetic filepair and insert that
6633 * into diff_queued_diff.
6635 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6636 if (!strset_contains(&present, e->key)) {
6637 struct diff_filespec *one, *two;
6638 struct diff_filepair *p;
6640 one = alloc_filespec(e->key);
6641 two = alloc_filespec(e->key);
6642 fill_filespec(one, null_oid(), 0, 0);
6643 fill_filespec(two, null_oid(), 0, 0);
6644 p = diff_queue(q, one, two);
6645 p->status = DIFF_STATUS_MODIFIED;
6649 /* Re-sort the filepairs */
6650 diffcore_fix_diff_index();
6652 /* Cleanup */
6653 strset_clear(&present);
6656 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6658 int i;
6659 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6660 struct diff_queue_struct *q = &diff_queued_diff;
6662 if (WSEH_NEW & WS_RULE_MASK)
6663 BUG("WS rules bit mask overlaps with diff symbol flags");
6665 if (o->color_moved)
6666 o->emitted_symbols = &esm;
6668 if (o->additional_path_headers)
6669 create_filepairs_for_header_only_notifications(o);
6671 for (i = 0; i < q->nr; i++) {
6672 struct diff_filepair *p = q->queue[i];
6673 if (check_pair_status(p))
6674 diff_flush_patch(p, o);
6677 if (o->emitted_symbols) {
6678 if (o->color_moved) {
6679 struct mem_pool entry_pool;
6680 struct moved_entry_list *entry_list;
6682 mem_pool_init(&entry_pool, 1024 * 1024);
6683 entry_list = add_lines_to_move_detection(o,
6684 &entry_pool);
6685 mark_color_as_moved(o, entry_list);
6686 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6687 dim_moved_lines(o);
6689 mem_pool_discard(&entry_pool, 0);
6690 free(entry_list);
6693 for (i = 0; i < esm.nr; i++)
6694 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6696 for (i = 0; i < esm.nr; i++)
6697 free((void *)esm.buf[i].line);
6698 esm.nr = 0;
6700 o->emitted_symbols = NULL;
6704 static void diff_free_file(struct diff_options *options)
6706 if (options->close_file && options->file) {
6707 fclose(options->file);
6708 options->file = NULL;
6712 static void diff_free_ignore_regex(struct diff_options *options)
6714 int i;
6716 for (i = 0; i < options->ignore_regex_nr; i++) {
6717 regfree(options->ignore_regex[i]);
6718 free(options->ignore_regex[i]);
6721 FREE_AND_NULL(options->ignore_regex);
6722 options->ignore_regex_nr = 0;
6725 void diff_free(struct diff_options *options)
6727 if (options->no_free)
6728 return;
6730 if (options->objfind) {
6731 oidset_clear(options->objfind);
6732 FREE_AND_NULL(options->objfind);
6735 FREE_AND_NULL(options->orderfile);
6736 for (size_t i = 0; i < options->anchors_nr; i++)
6737 free(options->anchors[i]);
6738 FREE_AND_NULL(options->anchors);
6739 options->anchors_nr = options->anchors_alloc = 0;
6741 diff_free_file(options);
6742 diff_free_ignore_regex(options);
6743 clear_pathspec(&options->pathspec);
6746 void diff_flush(struct diff_options *options)
6748 struct diff_queue_struct *q = &diff_queued_diff;
6749 int i, output_format = options->output_format;
6750 int separator = 0;
6751 int dirstat_by_line = 0;
6754 * Order: raw, stat, summary, patch
6755 * or: name/name-status/checkdiff (other bits clear)
6757 if (!q->nr && !options->additional_path_headers)
6758 goto free_queue;
6760 if (output_format & (DIFF_FORMAT_RAW |
6761 DIFF_FORMAT_NAME |
6762 DIFF_FORMAT_NAME_STATUS |
6763 DIFF_FORMAT_CHECKDIFF)) {
6764 for (i = 0; i < q->nr; i++) {
6765 struct diff_filepair *p = q->queue[i];
6766 if (check_pair_status(p))
6767 flush_one_pair(p, options);
6769 separator++;
6772 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6773 dirstat_by_line = 1;
6775 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6776 dirstat_by_line) {
6777 struct diffstat_t diffstat;
6779 compute_diffstat(options, &diffstat, q);
6780 if (output_format & DIFF_FORMAT_NUMSTAT)
6781 show_numstat(&diffstat, options);
6782 if (output_format & DIFF_FORMAT_DIFFSTAT)
6783 show_stats(&diffstat, options);
6784 if (output_format & DIFF_FORMAT_SHORTSTAT)
6785 show_shortstats(&diffstat, options);
6786 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6787 show_dirstat_by_line(&diffstat, options);
6788 free_diffstat_info(&diffstat);
6789 separator++;
6791 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6792 show_dirstat(options);
6794 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6795 for (i = 0; i < q->nr; i++) {
6796 diff_summary(options, q->queue[i]);
6798 separator++;
6801 if (output_format & DIFF_FORMAT_PATCH) {
6802 if (separator) {
6803 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6804 if (options->stat_sep)
6805 /* attach patch instead of inline */
6806 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6807 NULL, 0, 0);
6810 diff_flush_patch_all_file_pairs(options);
6813 if (output_format & DIFF_FORMAT_CALLBACK)
6814 options->format_callback(q, options, options->format_callback_data);
6816 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6817 options->flags.exit_with_status &&
6818 options->flags.diff_from_contents) {
6820 * run diff_flush_patch for the exit status. setting
6821 * options->file to /dev/null should be safe, because we
6822 * aren't supposed to produce any output anyway.
6824 diff_free_file(options);
6825 options->file = xfopen("/dev/null", "w");
6826 options->close_file = 1;
6827 options->color_moved = 0;
6828 for (i = 0; i < q->nr; i++) {
6829 struct diff_filepair *p = q->queue[i];
6830 if (check_pair_status(p))
6831 diff_flush_patch(p, options);
6832 if (options->found_changes)
6833 break;
6837 free_queue:
6838 diff_free_queue(q);
6839 DIFF_QUEUE_CLEAR(q);
6840 diff_free(options);
6843 * Report the content-level differences with HAS_CHANGES;
6844 * diff_addremove/diff_change does not set the bit when
6845 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6847 if (options->flags.diff_from_contents) {
6848 if (options->found_changes)
6849 options->flags.has_changes = 1;
6850 else
6851 options->flags.has_changes = 0;
6855 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6857 return (((p->status == DIFF_STATUS_MODIFIED) &&
6858 ((p->score &&
6859 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6860 (!p->score &&
6861 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6862 ((p->status != DIFF_STATUS_MODIFIED) &&
6863 filter_bit_tst(p->status, options)));
6866 static void diffcore_apply_filter(struct diff_options *options)
6868 int i;
6869 struct diff_queue_struct *q = &diff_queued_diff;
6870 struct diff_queue_struct outq;
6872 DIFF_QUEUE_CLEAR(&outq);
6874 if (!options->filter)
6875 return;
6877 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6878 int found;
6879 for (i = found = 0; !found && i < q->nr; i++) {
6880 if (match_filter(options, q->queue[i]))
6881 found++;
6883 if (found)
6884 return;
6886 /* otherwise we will clear the whole queue
6887 * by copying the empty outq at the end of this
6888 * function, but first clear the current entries
6889 * in the queue.
6891 for (i = 0; i < q->nr; i++)
6892 diff_free_filepair(q->queue[i]);
6894 else {
6895 /* Only the matching ones */
6896 for (i = 0; i < q->nr; i++) {
6897 struct diff_filepair *p = q->queue[i];
6898 if (match_filter(options, p))
6899 diff_q(&outq, p);
6900 else
6901 diff_free_filepair(p);
6904 free(q->queue);
6905 *q = outq;
6908 /* Check whether two filespecs with the same mode and size are identical */
6909 static int diff_filespec_is_identical(struct repository *r,
6910 struct diff_filespec *one,
6911 struct diff_filespec *two)
6913 if (S_ISGITLINK(one->mode))
6914 return 0;
6915 if (diff_populate_filespec(r, one, NULL))
6916 return 0;
6917 if (diff_populate_filespec(r, two, NULL))
6918 return 0;
6919 return !memcmp(one->data, two->data, one->size);
6922 static int diff_filespec_check_stat_unmatch(struct repository *r,
6923 struct diff_filepair *p)
6925 struct diff_populate_filespec_options dpf_options = {
6926 .check_size_only = 1,
6927 .missing_object_cb = diff_queued_diff_prefetch,
6928 .missing_object_data = r,
6931 if (p->done_skip_stat_unmatch)
6932 return p->skip_stat_unmatch_result;
6934 p->done_skip_stat_unmatch = 1;
6935 p->skip_stat_unmatch_result = 0;
6937 * 1. Entries that come from stat info dirtiness
6938 * always have both sides (iow, not create/delete),
6939 * one side of the object name is unknown, with
6940 * the same mode and size. Keep the ones that
6941 * do not match these criteria. They have real
6942 * differences.
6944 * 2. At this point, the file is known to be modified,
6945 * with the same mode and size, and the object
6946 * name of one side is unknown. Need to inspect
6947 * the identical contents.
6949 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6950 !DIFF_FILE_VALID(p->two) ||
6951 (p->one->oid_valid && p->two->oid_valid) ||
6952 (p->one->mode != p->two->mode) ||
6953 diff_populate_filespec(r, p->one, &dpf_options) ||
6954 diff_populate_filespec(r, p->two, &dpf_options) ||
6955 (p->one->size != p->two->size) ||
6956 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6957 p->skip_stat_unmatch_result = 1;
6958 return p->skip_stat_unmatch_result;
6961 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6963 int i;
6964 struct diff_queue_struct *q = &diff_queued_diff;
6965 struct diff_queue_struct outq;
6966 DIFF_QUEUE_CLEAR(&outq);
6968 for (i = 0; i < q->nr; i++) {
6969 struct diff_filepair *p = q->queue[i];
6971 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6972 diff_q(&outq, p);
6973 else {
6975 * The caller can subtract 1 from skip_stat_unmatch
6976 * to determine how many paths were dirty only
6977 * due to stat info mismatch.
6979 if (!diffopt->flags.no_index)
6980 diffopt->skip_stat_unmatch++;
6981 diff_free_filepair(p);
6984 free(q->queue);
6985 *q = outq;
6988 static int diffnamecmp(const void *a_, const void *b_)
6990 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6991 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6992 const char *name_a, *name_b;
6994 name_a = a->one ? a->one->path : a->two->path;
6995 name_b = b->one ? b->one->path : b->two->path;
6996 return strcmp(name_a, name_b);
6999 void diffcore_fix_diff_index(void)
7001 struct diff_queue_struct *q = &diff_queued_diff;
7002 QSORT(q->queue, q->nr, diffnamecmp);
7005 void diff_add_if_missing(struct repository *r,
7006 struct oid_array *to_fetch,
7007 const struct diff_filespec *filespec)
7009 if (filespec && filespec->oid_valid &&
7010 !S_ISGITLINK(filespec->mode) &&
7011 oid_object_info_extended(r, &filespec->oid, NULL,
7012 OBJECT_INFO_FOR_PREFETCH))
7013 oid_array_append(to_fetch, &filespec->oid);
7016 void diff_queued_diff_prefetch(void *repository)
7018 struct repository *repo = repository;
7019 int i;
7020 struct diff_queue_struct *q = &diff_queued_diff;
7021 struct oid_array to_fetch = OID_ARRAY_INIT;
7023 for (i = 0; i < q->nr; i++) {
7024 struct diff_filepair *p = q->queue[i];
7025 diff_add_if_missing(repo, &to_fetch, p->one);
7026 diff_add_if_missing(repo, &to_fetch, p->two);
7030 * NEEDSWORK: Consider deduplicating the OIDs sent.
7032 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7034 oid_array_clear(&to_fetch);
7037 void init_diffstat_widths(struct diff_options *options)
7039 options->stat_width = -1; /* use full terminal width */
7040 options->stat_name_width = -1; /* respect diff.statNameWidth config */
7041 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
7044 void diffcore_std(struct diff_options *options)
7046 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7047 DIFF_FORMAT_NUMSTAT |
7048 DIFF_FORMAT_PATCH |
7049 DIFF_FORMAT_SHORTSTAT |
7050 DIFF_FORMAT_DIRSTAT;
7053 * Check if the user requested a blob-data-requiring diff output and/or
7054 * break-rewrite detection (which requires blob data). If yes, prefetch
7055 * the diff pairs.
7057 * If no prefetching occurs, diffcore_rename() will prefetch if it
7058 * decides that it needs inexact rename detection.
7060 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
7061 (options->output_format & output_formats_to_prefetch ||
7062 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7063 diff_queued_diff_prefetch(options->repo);
7065 /* NOTE please keep the following in sync with diff_tree_combined() */
7066 if (options->skip_stat_unmatch)
7067 diffcore_skip_stat_unmatch(options);
7068 if (!options->found_follow) {
7069 /* See try_to_follow_renames() in tree-diff.c */
7070 if (options->break_opt != -1)
7071 diffcore_break(options->repo,
7072 options->break_opt);
7073 if (options->detect_rename)
7074 diffcore_rename(options);
7075 if (options->break_opt != -1)
7076 diffcore_merge_broken();
7078 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7079 diffcore_pickaxe(options);
7080 if (options->orderfile)
7081 diffcore_order(options->orderfile);
7082 if (options->rotate_to)
7083 diffcore_rotate(options);
7084 if (!options->found_follow)
7085 /* See try_to_follow_renames() in tree-diff.c */
7086 diff_resolve_rename_copy();
7087 diffcore_apply_filter(options);
7089 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7090 options->flags.has_changes = 1;
7091 else
7092 options->flags.has_changes = 0;
7094 options->found_follow = 0;
7097 int diff_result_code(struct rev_info *revs)
7099 struct diff_options *opt = &revs->diffopt;
7100 int result = 0;
7102 if (revs->remerge_diff) {
7103 tmp_objdir_destroy(revs->remerge_objdir);
7104 revs->remerge_objdir = NULL;
7107 diff_warn_rename_limit("diff.renameLimit",
7108 opt->needed_rename_limit,
7109 opt->degraded_cc_to_c);
7111 if (opt->flags.exit_with_status &&
7112 opt->flags.has_changes)
7113 result |= 01;
7114 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7115 opt->flags.check_failed)
7116 result |= 02;
7117 return result;
7120 int diff_can_quit_early(struct diff_options *opt)
7122 return (opt->flags.quick &&
7123 !opt->filter &&
7124 opt->flags.has_changes);
7128 * Shall changes to this submodule be ignored?
7130 * Submodule changes can be configured to be ignored separately for each path,
7131 * but that configuration can be overridden from the command line.
7133 static int is_submodule_ignored(const char *path, struct diff_options *options)
7135 int ignored = 0;
7136 struct diff_flags orig_flags = options->flags;
7137 if (!options->flags.override_submodule_config)
7138 set_diffopt_flags_from_submodule_config(options, path);
7139 if (options->flags.ignore_submodules)
7140 ignored = 1;
7141 options->flags = orig_flags;
7142 return ignored;
7145 void compute_diffstat(struct diff_options *options,
7146 struct diffstat_t *diffstat,
7147 struct diff_queue_struct *q)
7149 int i;
7151 memset(diffstat, 0, sizeof(struct diffstat_t));
7152 for (i = 0; i < q->nr; i++) {
7153 struct diff_filepair *p = q->queue[i];
7154 if (check_pair_status(p))
7155 diff_flush_stat(p, options, diffstat);
7157 options->found_changes = !!diffstat->nr;
7160 void diff_addremove(struct diff_options *options,
7161 int addremove, unsigned mode,
7162 const struct object_id *oid,
7163 int oid_valid,
7164 const char *concatpath, unsigned dirty_submodule)
7166 struct diff_filespec *one, *two;
7168 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7169 return;
7171 /* This may look odd, but it is a preparation for
7172 * feeding "there are unchanged files which should
7173 * not produce diffs, but when you are doing copy
7174 * detection you would need them, so here they are"
7175 * entries to the diff-core. They will be prefixed
7176 * with something like '=' or '*' (I haven't decided
7177 * which but should not make any difference).
7178 * Feeding the same new and old to diff_change()
7179 * also has the same effect.
7180 * Before the final output happens, they are pruned after
7181 * merged into rename/copy pairs as appropriate.
7183 if (options->flags.reverse_diff)
7184 addremove = (addremove == '+' ? '-' :
7185 addremove == '-' ? '+' : addremove);
7187 if (options->prefix &&
7188 strncmp(concatpath, options->prefix, options->prefix_length))
7189 return;
7191 one = alloc_filespec(concatpath);
7192 two = alloc_filespec(concatpath);
7194 if (addremove != '+')
7195 fill_filespec(one, oid, oid_valid, mode);
7196 if (addremove != '-') {
7197 fill_filespec(two, oid, oid_valid, mode);
7198 two->dirty_submodule = dirty_submodule;
7201 diff_queue(&diff_queued_diff, one, two);
7202 if (!options->flags.diff_from_contents)
7203 options->flags.has_changes = 1;
7206 void diff_change(struct diff_options *options,
7207 unsigned old_mode, unsigned new_mode,
7208 const struct object_id *old_oid,
7209 const struct object_id *new_oid,
7210 int old_oid_valid, int new_oid_valid,
7211 const char *concatpath,
7212 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7214 struct diff_filespec *one, *two;
7215 struct diff_filepair *p;
7217 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7218 is_submodule_ignored(concatpath, options))
7219 return;
7221 if (options->flags.reverse_diff) {
7222 SWAP(old_mode, new_mode);
7223 SWAP(old_oid, new_oid);
7224 SWAP(old_oid_valid, new_oid_valid);
7225 SWAP(old_dirty_submodule, new_dirty_submodule);
7228 if (options->prefix &&
7229 strncmp(concatpath, options->prefix, options->prefix_length))
7230 return;
7232 one = alloc_filespec(concatpath);
7233 two = alloc_filespec(concatpath);
7234 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7235 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7236 one->dirty_submodule = old_dirty_submodule;
7237 two->dirty_submodule = new_dirty_submodule;
7238 p = diff_queue(&diff_queued_diff, one, two);
7240 if (options->flags.diff_from_contents)
7241 return;
7243 if (options->flags.quick && options->skip_stat_unmatch &&
7244 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7245 diff_free_filespec_data(p->one);
7246 diff_free_filespec_data(p->two);
7247 return;
7250 options->flags.has_changes = 1;
7253 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7255 struct diff_filepair *pair;
7256 struct diff_filespec *one, *two;
7258 if (options->prefix &&
7259 strncmp(path, options->prefix, options->prefix_length))
7260 return NULL;
7262 one = alloc_filespec(path);
7263 two = alloc_filespec(path);
7264 pair = diff_queue(&diff_queued_diff, one, two);
7265 pair->is_unmerged = 1;
7266 return pair;
7269 static char *run_textconv(struct repository *r,
7270 const char *pgm,
7271 struct diff_filespec *spec,
7272 size_t *outsize)
7274 struct diff_tempfile *temp;
7275 struct child_process child = CHILD_PROCESS_INIT;
7276 struct strbuf buf = STRBUF_INIT;
7277 int err = 0;
7279 temp = prepare_temp_file(r, spec);
7280 strvec_push(&child.args, pgm);
7281 strvec_push(&child.args, temp->name);
7283 child.use_shell = 1;
7284 child.out = -1;
7285 if (start_command(&child)) {
7286 remove_tempfile();
7287 return NULL;
7290 if (strbuf_read(&buf, child.out, 0) < 0)
7291 err = error("error reading from textconv command '%s'", pgm);
7292 close(child.out);
7294 if (finish_command(&child) || err) {
7295 strbuf_release(&buf);
7296 remove_tempfile();
7297 return NULL;
7299 remove_tempfile();
7301 return strbuf_detach(&buf, outsize);
7304 size_t fill_textconv(struct repository *r,
7305 struct userdiff_driver *driver,
7306 struct diff_filespec *df,
7307 char **outbuf)
7309 size_t size;
7311 if (!driver) {
7312 if (!DIFF_FILE_VALID(df)) {
7313 *outbuf = (char *) "";
7314 return 0;
7316 if (diff_populate_filespec(r, df, NULL))
7317 die("unable to read files to diff");
7318 *outbuf = df->data;
7319 return df->size;
7322 if (!driver->textconv)
7323 BUG("fill_textconv called with non-textconv driver");
7325 if (driver->textconv_cache && df->oid_valid) {
7326 *outbuf = notes_cache_get(driver->textconv_cache,
7327 &df->oid,
7328 &size);
7329 if (*outbuf)
7330 return size;
7333 *outbuf = run_textconv(r, driver->textconv, df, &size);
7334 if (!*outbuf)
7335 die("unable to read files to diff");
7337 if (driver->textconv_cache && df->oid_valid) {
7338 /* ignore errors, as we might be in a readonly repository */
7339 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7340 size);
7342 * we could save up changes and flush them all at the end,
7343 * but we would need an extra call after all diffing is done.
7344 * Since generating a cache entry is the slow path anyway,
7345 * this extra overhead probably isn't a big deal.
7347 notes_cache_write(driver->textconv_cache);
7350 return size;
7353 int textconv_object(struct repository *r,
7354 const char *path,
7355 unsigned mode,
7356 const struct object_id *oid,
7357 int oid_valid,
7358 char **buf,
7359 unsigned long *buf_size)
7361 struct diff_filespec *df;
7362 struct userdiff_driver *textconv;
7364 df = alloc_filespec(path);
7365 fill_filespec(df, oid, oid_valid, mode);
7366 textconv = get_textconv(r, df);
7367 if (!textconv) {
7368 free_filespec(df);
7369 return 0;
7372 *buf_size = fill_textconv(r, textconv, df, buf);
7373 free_filespec(df);
7374 return 1;
7377 void setup_diff_pager(struct diff_options *opt)
7380 * If the user asked for our exit code, then either they want --quiet
7381 * or --exit-code. We should definitely not bother with a pager in the
7382 * former case, as we will generate no output. Since we still properly
7383 * report our exit code even when a pager is run, we _could_ run a
7384 * pager with --exit-code. But since we have not done so historically,
7385 * and because it is easy to find people oneline advising "git diff
7386 * --exit-code" in hooks and other scripts, we do not do so.
7388 if (!opt->flags.exit_with_status &&
7389 check_pager_config("diff") != 0)
7390 setup_pager();