The eleventh batch
[git/gitster.git] / diff.c
blobdceac20d18f03dfb72632f4466ed5a8a8e51bc14
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 return opt->output_prefix ?
2321 opt->output_prefix(opt, opt->output_prefix_data) :
2325 static unsigned long sane_truncate_line(char *line, unsigned long len)
2327 const char *cp;
2328 unsigned long allot;
2329 size_t l = len;
2331 cp = line;
2332 allot = l;
2333 while (0 < l) {
2334 (void) utf8_width(&cp, &l);
2335 if (!cp)
2336 break; /* truncated in the middle? */
2338 return allot - l;
2341 static void find_lno(const char *line, struct emit_callback *ecbdata)
2343 const char *p;
2344 ecbdata->lno_in_preimage = 0;
2345 ecbdata->lno_in_postimage = 0;
2346 p = strchr(line, '-');
2347 if (!p)
2348 return; /* cannot happen */
2349 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2350 p = strchr(p, '+');
2351 if (!p)
2352 return; /* cannot happen */
2353 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2356 static int fn_out_consume(void *priv, char *line, unsigned long len)
2358 struct emit_callback *ecbdata = priv;
2359 struct diff_options *o = ecbdata->opt;
2361 o->found_changes = 1;
2363 if (ecbdata->header) {
2364 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2365 ecbdata->header->buf, ecbdata->header->len, 0);
2366 strbuf_reset(ecbdata->header);
2367 ecbdata->header = NULL;
2370 if (ecbdata->label_path[0]) {
2371 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2372 ecbdata->label_path[0],
2373 strlen(ecbdata->label_path[0]), 0);
2374 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2375 ecbdata->label_path[1],
2376 strlen(ecbdata->label_path[1]), 0);
2377 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2380 if (diff_suppress_blank_empty
2381 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2382 line[0] = '\n';
2383 len = 1;
2386 if (line[0] == '@') {
2387 if (ecbdata->diff_words)
2388 diff_words_flush(ecbdata);
2389 len = sane_truncate_line(line, len);
2390 find_lno(line, ecbdata);
2391 emit_hunk_header(ecbdata, line, len);
2392 return 0;
2395 if (ecbdata->diff_words) {
2396 enum diff_symbol s =
2397 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2398 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2399 if (line[0] == '-') {
2400 diff_words_append(line, len,
2401 &ecbdata->diff_words->minus);
2402 return 0;
2403 } else if (line[0] == '+') {
2404 diff_words_append(line, len,
2405 &ecbdata->diff_words->plus);
2406 return 0;
2407 } else if (starts_with(line, "\\ ")) {
2409 * Eat the "no newline at eof" marker as if we
2410 * saw a "+" or "-" line with nothing on it,
2411 * and return without diff_words_flush() to
2412 * defer processing. If this is the end of
2413 * preimage, more "+" lines may come after it.
2415 return 0;
2417 diff_words_flush(ecbdata);
2418 emit_diff_symbol(o, s, line, len, 0);
2419 return 0;
2422 switch (line[0]) {
2423 case '+':
2424 ecbdata->lno_in_postimage++;
2425 emit_add_line(ecbdata, line + 1, len - 1);
2426 break;
2427 case '-':
2428 ecbdata->lno_in_preimage++;
2429 emit_del_line(ecbdata, line + 1, len - 1);
2430 break;
2431 case ' ':
2432 ecbdata->lno_in_postimage++;
2433 ecbdata->lno_in_preimage++;
2434 emit_context_line(ecbdata, line + 1, len - 1);
2435 break;
2436 default:
2437 /* incomplete line at the end */
2438 ecbdata->lno_in_preimage++;
2439 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2440 line, len, 0);
2441 break;
2443 return 0;
2446 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2448 const char *old_name = a;
2449 const char *new_name = b;
2450 int pfx_length, sfx_length;
2451 int pfx_adjust_for_slash;
2452 int len_a = strlen(a);
2453 int len_b = strlen(b);
2454 int a_midlen, b_midlen;
2455 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2456 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2458 if (qlen_a || qlen_b) {
2459 quote_c_style(a, name, NULL, 0);
2460 strbuf_addstr(name, " => ");
2461 quote_c_style(b, name, NULL, 0);
2462 return;
2465 /* Find common prefix */
2466 pfx_length = 0;
2467 while (*old_name && *new_name && *old_name == *new_name) {
2468 if (*old_name == '/')
2469 pfx_length = old_name - a + 1;
2470 old_name++;
2471 new_name++;
2474 /* Find common suffix */
2475 old_name = a + len_a;
2476 new_name = b + len_b;
2477 sfx_length = 0;
2479 * If there is a common prefix, it must end in a slash. In
2480 * that case we let this loop run 1 into the prefix to see the
2481 * same slash.
2483 * If there is no common prefix, we cannot do this as it would
2484 * underrun the input strings.
2486 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2487 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2488 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2489 *old_name == *new_name) {
2490 if (*old_name == '/')
2491 sfx_length = len_a - (old_name - a);
2492 old_name--;
2493 new_name--;
2497 * pfx{mid-a => mid-b}sfx
2498 * {pfx-a => pfx-b}sfx
2499 * pfx{sfx-a => sfx-b}
2500 * name-a => name-b
2502 a_midlen = len_a - pfx_length - sfx_length;
2503 b_midlen = len_b - pfx_length - sfx_length;
2504 if (a_midlen < 0)
2505 a_midlen = 0;
2506 if (b_midlen < 0)
2507 b_midlen = 0;
2509 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2510 if (pfx_length + sfx_length) {
2511 strbuf_add(name, a, pfx_length);
2512 strbuf_addch(name, '{');
2514 strbuf_add(name, a + pfx_length, a_midlen);
2515 strbuf_addstr(name, " => ");
2516 strbuf_add(name, b + pfx_length, b_midlen);
2517 if (pfx_length + sfx_length) {
2518 strbuf_addch(name, '}');
2519 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2523 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2524 const char *name_a,
2525 const char *name_b)
2527 struct diffstat_file *x;
2528 CALLOC_ARRAY(x, 1);
2529 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2530 diffstat->files[diffstat->nr++] = x;
2531 if (name_b) {
2532 x->from_name = xstrdup(name_a);
2533 x->name = xstrdup(name_b);
2534 x->is_renamed = 1;
2536 else {
2537 x->from_name = NULL;
2538 x->name = xstrdup(name_a);
2540 return x;
2543 static int diffstat_consume(void *priv, char *line, unsigned long len)
2545 struct diffstat_t *diffstat = priv;
2546 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2548 if (!len)
2549 BUG("xdiff fed us an empty line");
2551 if (line[0] == '+')
2552 x->added++;
2553 else if (line[0] == '-')
2554 x->deleted++;
2555 return 0;
2558 const char mime_boundary_leader[] = "------------";
2560 static int scale_linear(int it, int width, int max_change)
2562 if (!it)
2563 return 0;
2565 * make sure that at least one '-' or '+' is printed if
2566 * there is any change to this path. The easiest way is to
2567 * scale linearly as if the allotted width is one column shorter
2568 * than it is, and then add 1 to the result.
2570 return 1 + (it * (width - 1) / max_change);
2573 static void show_graph(struct strbuf *out, char ch, int cnt,
2574 const char *set, const char *reset)
2576 if (cnt <= 0)
2577 return;
2578 strbuf_addstr(out, set);
2579 strbuf_addchars(out, ch, cnt);
2580 strbuf_addstr(out, reset);
2583 static void fill_print_name(struct diffstat_file *file)
2585 struct strbuf pname = STRBUF_INIT;
2587 if (file->print_name)
2588 return;
2590 if (file->is_renamed)
2591 pprint_rename(&pname, file->from_name, file->name);
2592 else
2593 quote_c_style(file->name, &pname, NULL, 0);
2595 if (file->comments)
2596 strbuf_addf(&pname, " (%s)", file->comments);
2598 file->print_name = strbuf_detach(&pname, NULL);
2601 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2602 int files, int insertions, int deletions)
2604 struct strbuf sb = STRBUF_INIT;
2606 if (!files) {
2607 assert(insertions == 0 && deletions == 0);
2608 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2609 NULL, 0, 0);
2610 return;
2613 strbuf_addf(&sb,
2614 (files == 1) ? " %d file changed" : " %d files changed",
2615 files);
2618 * For binary diff, the caller may want to print "x files
2619 * changed" with insertions == 0 && deletions == 0.
2621 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2622 * is probably less confusing (i.e skip over "2 files changed
2623 * but nothing about added/removed lines? Is this a bug in Git?").
2625 if (insertions || deletions == 0) {
2626 strbuf_addf(&sb,
2627 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2628 insertions);
2631 if (deletions || insertions == 0) {
2632 strbuf_addf(&sb,
2633 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2634 deletions);
2636 strbuf_addch(&sb, '\n');
2637 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2638 sb.buf, sb.len, 0);
2639 strbuf_release(&sb);
2642 void print_stat_summary(FILE *fp, int files,
2643 int insertions, int deletions)
2645 struct diff_options o;
2646 memset(&o, 0, sizeof(o));
2647 o.file = fp;
2649 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2652 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2654 int i, len, add, del, adds = 0, dels = 0;
2655 uintmax_t max_change = 0, max_len = 0;
2656 int total_files = data->nr, count;
2657 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2658 const char *reset, *add_c, *del_c;
2659 int extra_shown = 0;
2660 const char *line_prefix = diff_line_prefix(options);
2661 struct strbuf out = STRBUF_INIT;
2663 if (data->nr == 0)
2664 return;
2666 count = options->stat_count ? options->stat_count : data->nr;
2668 reset = diff_get_color_opt(options, DIFF_RESET);
2669 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2670 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2673 * Find the longest filename and max number of changes
2675 for (i = 0; (i < count) && (i < data->nr); i++) {
2676 struct diffstat_file *file = data->files[i];
2677 uintmax_t change = file->added + file->deleted;
2679 if (!file->is_interesting && (change == 0)) {
2680 count++; /* not shown == room for one more */
2681 continue;
2683 fill_print_name(file);
2684 len = utf8_strwidth(file->print_name);
2685 if (max_len < len)
2686 max_len = len;
2688 if (file->is_unmerged) {
2689 /* "Unmerged" is 8 characters */
2690 bin_width = bin_width < 8 ? 8 : bin_width;
2691 continue;
2693 if (file->is_binary) {
2694 /* "Bin XXX -> YYY bytes" */
2695 int w = 14 + decimal_width(file->added)
2696 + decimal_width(file->deleted);
2697 bin_width = bin_width < w ? w : bin_width;
2698 /* Display change counts aligned with "Bin" */
2699 number_width = 3;
2700 continue;
2703 if (max_change < change)
2704 max_change = change;
2706 count = i; /* where we can stop scanning in data->files[] */
2709 * We have width = stat_width or term_columns() columns total.
2710 * We want a maximum of min(max_len, stat_name_width) for the name part.
2711 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2712 * We also need 1 for " " and 4 + decimal_width(max_change)
2713 * for " | NNNN " and one the empty column at the end, altogether
2714 * 6 + decimal_width(max_change).
2716 * If there's not enough space, we will use the smaller of
2717 * stat_name_width (if set) and 5/8*width for the filename,
2718 * and the rest for constant elements + graph part, but no more
2719 * than stat_graph_width for the graph part.
2720 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2721 * for the standard terminal size).
2723 * In other words: stat_width limits the maximum width, and
2724 * stat_name_width fixes the maximum width of the filename,
2725 * and is also used to divide available columns if there
2726 * aren't enough.
2728 * Binary files are displayed with "Bin XXX -> YYY bytes"
2729 * instead of the change count and graph. This part is treated
2730 * similarly to the graph part, except that it is not
2731 * "scaled". If total width is too small to accommodate the
2732 * guaranteed minimum width of the filename part and the
2733 * separators and this message, this message will "overflow"
2734 * making the line longer than the maximum width.
2738 * NEEDSWORK: line_prefix is often used for "log --graph" output
2739 * and contains ANSI-colored string. utf8_strnwidth() should be
2740 * used to correctly count the display width instead of strlen().
2742 if (options->stat_width == -1)
2743 width = term_columns() - strlen(line_prefix);
2744 else
2745 width = options->stat_width ? options->stat_width : 80;
2746 number_width = decimal_width(max_change) > number_width ?
2747 decimal_width(max_change) : number_width;
2749 if (options->stat_name_width == -1)
2750 options->stat_name_width = diff_stat_name_width;
2751 if (options->stat_graph_width == -1)
2752 options->stat_graph_width = diff_stat_graph_width;
2755 * Guarantee 3/8*16 == 6 for the graph part
2756 * and 5/8*16 == 10 for the filename part
2758 if (width < 16 + 6 + number_width)
2759 width = 16 + 6 + number_width;
2762 * First assign sizes that are wanted, ignoring available width.
2763 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2764 * starting from "XXX" should fit in graph_width.
2766 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2767 if (options->stat_graph_width &&
2768 options->stat_graph_width < graph_width)
2769 graph_width = options->stat_graph_width;
2771 name_width = (options->stat_name_width > 0 &&
2772 options->stat_name_width < max_len) ?
2773 options->stat_name_width : max_len;
2776 * Adjust adjustable widths not to exceed maximum width
2778 if (name_width + number_width + 6 + graph_width > width) {
2779 if (graph_width > width * 3/8 - number_width - 6) {
2780 graph_width = width * 3/8 - number_width - 6;
2781 if (graph_width < 6)
2782 graph_width = 6;
2785 if (options->stat_graph_width &&
2786 graph_width > options->stat_graph_width)
2787 graph_width = options->stat_graph_width;
2788 if (name_width > width - number_width - 6 - graph_width)
2789 name_width = width - number_width - 6 - graph_width;
2790 else
2791 graph_width = width - number_width - 6 - name_width;
2795 * From here name_width is the width of the name area,
2796 * and graph_width is the width of the graph area.
2797 * max_change is used to scale graph properly.
2799 for (i = 0; i < count; i++) {
2800 const char *prefix = "";
2801 struct diffstat_file *file = data->files[i];
2802 char *name = file->print_name;
2803 uintmax_t added = file->added;
2804 uintmax_t deleted = file->deleted;
2805 int name_len, padding;
2807 if (!file->is_interesting && (added + deleted == 0))
2808 continue;
2811 * "scale" the filename
2813 len = name_width;
2814 name_len = utf8_strwidth(name);
2815 if (name_width < name_len) {
2816 char *slash;
2817 prefix = "...";
2818 len -= 3;
2820 * NEEDSWORK: (name_len - len) counts the display
2821 * width, which would be shorter than the byte
2822 * length of the corresponding substring.
2823 * Advancing "name" by that number of bytes does
2824 * *NOT* skip over that many columns, so it is
2825 * very likely that chomping the pathname at the
2826 * slash we will find starting from "name" will
2827 * leave the resulting string still too long.
2829 name += name_len - len;
2830 slash = strchr(name, '/');
2831 if (slash)
2832 name = slash;
2834 padding = len - utf8_strwidth(name);
2835 if (padding < 0)
2836 padding = 0;
2838 if (file->is_binary) {
2839 strbuf_addf(&out, " %s%s%*s | %*s",
2840 prefix, name, padding, "",
2841 number_width, "Bin");
2842 if (!added && !deleted) {
2843 strbuf_addch(&out, '\n');
2844 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2845 out.buf, out.len, 0);
2846 strbuf_reset(&out);
2847 continue;
2849 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2850 del_c, deleted, reset);
2851 strbuf_addstr(&out, " -> ");
2852 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2853 add_c, added, reset);
2854 strbuf_addstr(&out, " bytes\n");
2855 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2856 out.buf, out.len, 0);
2857 strbuf_reset(&out);
2858 continue;
2860 else if (file->is_unmerged) {
2861 strbuf_addf(&out, " %s%s%*s | %*s",
2862 prefix, name, padding, "",
2863 number_width, "Unmerged\n");
2864 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2865 out.buf, out.len, 0);
2866 strbuf_reset(&out);
2867 continue;
2871 * scale the add/delete
2873 add = added;
2874 del = deleted;
2876 if (graph_width <= max_change) {
2877 int total = scale_linear(add + del, graph_width, max_change);
2878 if (total < 2 && add && del)
2879 /* width >= 2 due to the sanity check */
2880 total = 2;
2881 if (add < del) {
2882 add = scale_linear(add, graph_width, max_change);
2883 del = total - add;
2884 } else {
2885 del = scale_linear(del, graph_width, max_change);
2886 add = total - del;
2889 strbuf_addf(&out, " %s%s%*s | %*"PRIuMAX"%s",
2890 prefix, name, padding, "",
2891 number_width, added + deleted,
2892 added + deleted ? " " : "");
2893 show_graph(&out, '+', add, add_c, reset);
2894 show_graph(&out, '-', del, del_c, reset);
2895 strbuf_addch(&out, '\n');
2896 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2897 out.buf, out.len, 0);
2898 strbuf_reset(&out);
2901 for (i = 0; i < data->nr; i++) {
2902 struct diffstat_file *file = data->files[i];
2903 uintmax_t added = file->added;
2904 uintmax_t deleted = file->deleted;
2906 if (file->is_unmerged ||
2907 (!file->is_interesting && (added + deleted == 0))) {
2908 total_files--;
2909 continue;
2912 if (!file->is_binary) {
2913 adds += added;
2914 dels += deleted;
2916 if (i < count)
2917 continue;
2918 if (!extra_shown)
2919 emit_diff_symbol(options,
2920 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2921 NULL, 0, 0);
2922 extra_shown = 1;
2925 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2926 strbuf_release(&out);
2929 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2931 int i, adds = 0, dels = 0, total_files = data->nr;
2933 if (data->nr == 0)
2934 return;
2936 for (i = 0; i < data->nr; i++) {
2937 int added = data->files[i]->added;
2938 int deleted = data->files[i]->deleted;
2940 if (data->files[i]->is_unmerged ||
2941 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2942 total_files--;
2943 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2944 adds += added;
2945 dels += deleted;
2948 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2951 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2953 int i;
2955 if (data->nr == 0)
2956 return;
2958 for (i = 0; i < data->nr; i++) {
2959 struct diffstat_file *file = data->files[i];
2961 fprintf(options->file, "%s", diff_line_prefix(options));
2963 if (file->is_binary)
2964 fprintf(options->file, "-\t-\t");
2965 else
2966 fprintf(options->file,
2967 "%"PRIuMAX"\t%"PRIuMAX"\t",
2968 file->added, file->deleted);
2969 if (options->line_termination) {
2970 fill_print_name(file);
2971 if (!file->is_renamed)
2972 write_name_quoted(file->name, options->file,
2973 options->line_termination);
2974 else {
2975 fputs(file->print_name, options->file);
2976 putc(options->line_termination, options->file);
2978 } else {
2979 if (file->is_renamed) {
2980 putc('\0', options->file);
2981 write_name_quoted(file->from_name, options->file, '\0');
2983 write_name_quoted(file->name, options->file, '\0');
2988 struct dirstat_file {
2989 const char *name;
2990 unsigned long changed;
2993 struct dirstat_dir {
2994 struct dirstat_file *files;
2995 int alloc, nr, permille, cumulative;
2998 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2999 unsigned long changed, const char *base, int baselen)
3001 unsigned long sum_changes = 0;
3002 unsigned int sources = 0;
3003 const char *line_prefix = diff_line_prefix(opt);
3005 while (dir->nr) {
3006 struct dirstat_file *f = dir->files;
3007 int namelen = strlen(f->name);
3008 unsigned long changes;
3009 char *slash;
3011 if (namelen < baselen)
3012 break;
3013 if (memcmp(f->name, base, baselen))
3014 break;
3015 slash = strchr(f->name + baselen, '/');
3016 if (slash) {
3017 int newbaselen = slash + 1 - f->name;
3018 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
3019 sources++;
3020 } else {
3021 changes = f->changed;
3022 dir->files++;
3023 dir->nr--;
3024 sources += 2;
3026 sum_changes += changes;
3030 * We don't report dirstat's for
3031 * - the top level
3032 * - or cases where everything came from a single directory
3033 * under this directory (sources == 1).
3035 if (baselen && sources != 1) {
3036 if (sum_changes) {
3037 int permille = sum_changes * 1000 / changed;
3038 if (permille >= dir->permille) {
3039 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
3040 permille / 10, permille % 10, baselen, base);
3041 if (!dir->cumulative)
3042 return 0;
3046 return sum_changes;
3049 static int dirstat_compare(const void *_a, const void *_b)
3051 const struct dirstat_file *a = _a;
3052 const struct dirstat_file *b = _b;
3053 return strcmp(a->name, b->name);
3056 static void conclude_dirstat(struct diff_options *options,
3057 struct dirstat_dir *dir,
3058 unsigned long changed)
3060 struct dirstat_file *to_free = dir->files;
3062 if (!changed) {
3063 /* This can happen even with many files, if everything was renames */
3065 } else {
3066 /* Show all directories with more than x% of the changes */
3067 QSORT(dir->files, dir->nr, dirstat_compare);
3068 gather_dirstat(options, dir, changed, "", 0);
3071 free(to_free);
3074 static void show_dirstat(struct diff_options *options)
3076 int i;
3077 unsigned long changed;
3078 struct dirstat_dir dir;
3079 struct diff_queue_struct *q = &diff_queued_diff;
3081 dir.files = NULL;
3082 dir.alloc = 0;
3083 dir.nr = 0;
3084 dir.permille = options->dirstat_permille;
3085 dir.cumulative = options->flags.dirstat_cumulative;
3087 changed = 0;
3088 for (i = 0; i < q->nr; i++) {
3089 struct diff_filepair *p = q->queue[i];
3090 const char *name;
3091 unsigned long copied, added, damage;
3092 struct diff_populate_filespec_options dpf_options = {
3093 .check_size_only = 1,
3096 name = p->two->path ? p->two->path : p->one->path;
3098 if (p->one->oid_valid && p->two->oid_valid &&
3099 oideq(&p->one->oid, &p->two->oid)) {
3101 * The SHA1 has not changed, so pre-/post-content is
3102 * identical. We can therefore skip looking at the
3103 * file contents altogether.
3105 damage = 0;
3106 goto found_damage;
3109 if (options->flags.dirstat_by_file) {
3111 * In --dirstat-by-file mode, we don't really need to
3112 * look at the actual file contents at all.
3113 * The fact that the SHA1 changed is enough for us to
3114 * add this file to the list of results
3115 * (with each file contributing equal damage).
3117 damage = 1;
3118 goto found_damage;
3121 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3122 diff_populate_filespec(options->repo, p->one, NULL);
3123 diff_populate_filespec(options->repo, p->two, NULL);
3124 diffcore_count_changes(options->repo,
3125 p->one, p->two, NULL, NULL,
3126 &copied, &added);
3127 diff_free_filespec_data(p->one);
3128 diff_free_filespec_data(p->two);
3129 } else if (DIFF_FILE_VALID(p->one)) {
3130 diff_populate_filespec(options->repo, p->one, &dpf_options);
3131 copied = added = 0;
3132 diff_free_filespec_data(p->one);
3133 } else if (DIFF_FILE_VALID(p->two)) {
3134 diff_populate_filespec(options->repo, p->two, &dpf_options);
3135 copied = 0;
3136 added = p->two->size;
3137 diff_free_filespec_data(p->two);
3138 } else
3139 continue;
3142 * Original minus copied is the removed material,
3143 * added is the new material. They are both damages
3144 * made to the preimage.
3145 * If the resulting damage is zero, we know that
3146 * diffcore_count_changes() considers the two entries to
3147 * be identical, but since the oid changed, we
3148 * know that there must have been _some_ kind of change,
3149 * so we force all entries to have damage > 0.
3151 damage = (p->one->size - copied) + added;
3152 if (!damage)
3153 damage = 1;
3155 found_damage:
3156 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3157 dir.files[dir.nr].name = name;
3158 dir.files[dir.nr].changed = damage;
3159 changed += damage;
3160 dir.nr++;
3163 conclude_dirstat(options, &dir, changed);
3166 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3168 int i;
3169 unsigned long changed;
3170 struct dirstat_dir dir;
3172 if (data->nr == 0)
3173 return;
3175 dir.files = NULL;
3176 dir.alloc = 0;
3177 dir.nr = 0;
3178 dir.permille = options->dirstat_permille;
3179 dir.cumulative = options->flags.dirstat_cumulative;
3181 changed = 0;
3182 for (i = 0; i < data->nr; i++) {
3183 struct diffstat_file *file = data->files[i];
3184 unsigned long damage = file->added + file->deleted;
3185 if (file->is_binary)
3187 * binary files counts bytes, not lines. Must find some
3188 * way to normalize binary bytes vs. textual lines.
3189 * The following heuristic assumes that there are 64
3190 * bytes per "line".
3191 * This is stupid and ugly, but very cheap...
3193 damage = DIV_ROUND_UP(damage, 64);
3194 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3195 dir.files[dir.nr].name = file->name;
3196 dir.files[dir.nr].changed = damage;
3197 changed += damage;
3198 dir.nr++;
3201 conclude_dirstat(options, &dir, changed);
3204 static void free_diffstat_file(struct diffstat_file *f)
3206 free(f->print_name);
3207 free(f->name);
3208 free(f->from_name);
3209 free(f);
3212 void free_diffstat_info(struct diffstat_t *diffstat)
3214 int i;
3215 for (i = 0; i < diffstat->nr; i++)
3216 free_diffstat_file(diffstat->files[i]);
3217 free(diffstat->files);
3220 struct checkdiff_t {
3221 const char *filename;
3222 int lineno;
3223 int conflict_marker_size;
3224 struct diff_options *o;
3225 unsigned ws_rule;
3226 unsigned status;
3229 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3231 char firstchar;
3232 int cnt;
3234 if (len < marker_size + 1)
3235 return 0;
3236 firstchar = line[0];
3237 switch (firstchar) {
3238 case '=': case '>': case '<': case '|':
3239 break;
3240 default:
3241 return 0;
3243 for (cnt = 1; cnt < marker_size; cnt++)
3244 if (line[cnt] != firstchar)
3245 return 0;
3246 /* line[1] through line[marker_size-1] are same as firstchar */
3247 if (len < marker_size + 1 || !isspace(line[marker_size]))
3248 return 0;
3249 return 1;
3252 static void checkdiff_consume_hunk(void *priv,
3253 long ob UNUSED, long on UNUSED,
3254 long nb, long nn UNUSED,
3255 const char *func UNUSED, long funclen UNUSED)
3258 struct checkdiff_t *data = priv;
3259 data->lineno = nb - 1;
3262 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3264 struct checkdiff_t *data = priv;
3265 int marker_size = data->conflict_marker_size;
3266 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3267 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3268 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3269 char *err;
3270 const char *line_prefix;
3272 assert(data->o);
3273 line_prefix = diff_line_prefix(data->o);
3275 if (line[0] == '+') {
3276 unsigned bad;
3277 data->lineno++;
3278 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3279 data->status |= 1;
3280 fprintf(data->o->file,
3281 "%s%s:%d: leftover conflict marker\n",
3282 line_prefix, data->filename, data->lineno);
3284 bad = ws_check(line + 1, len - 1, data->ws_rule);
3285 if (!bad)
3286 return 0;
3287 data->status |= bad;
3288 err = whitespace_error_string(bad);
3289 fprintf(data->o->file, "%s%s:%d: %s.\n",
3290 line_prefix, data->filename, data->lineno, err);
3291 free(err);
3292 emit_line(data->o, set, reset, line, 1);
3293 ws_check_emit(line + 1, len - 1, data->ws_rule,
3294 data->o->file, set, reset, ws);
3295 } else if (line[0] == ' ') {
3296 data->lineno++;
3298 return 0;
3301 static unsigned char *deflate_it(char *data,
3302 unsigned long size,
3303 unsigned long *result_size)
3305 int bound;
3306 unsigned char *deflated;
3307 git_zstream stream;
3309 git_deflate_init(&stream, zlib_compression_level);
3310 bound = git_deflate_bound(&stream, size);
3311 deflated = xmalloc(bound);
3312 stream.next_out = deflated;
3313 stream.avail_out = bound;
3315 stream.next_in = (unsigned char *)data;
3316 stream.avail_in = size;
3317 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3318 ; /* nothing */
3319 git_deflate_end(&stream);
3320 *result_size = stream.total_out;
3321 return deflated;
3324 static void emit_binary_diff_body(struct diff_options *o,
3325 mmfile_t *one, mmfile_t *two)
3327 void *cp;
3328 void *delta;
3329 void *deflated;
3330 void *data;
3331 unsigned long orig_size;
3332 unsigned long delta_size;
3333 unsigned long deflate_size;
3334 unsigned long data_size;
3336 /* We could do deflated delta, or we could do just deflated two,
3337 * whichever is smaller.
3339 delta = NULL;
3340 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3341 if (one->size && two->size) {
3342 delta = diff_delta(one->ptr, one->size,
3343 two->ptr, two->size,
3344 &delta_size, deflate_size);
3345 if (delta) {
3346 void *to_free = delta;
3347 orig_size = delta_size;
3348 delta = deflate_it(delta, delta_size, &delta_size);
3349 free(to_free);
3353 if (delta && delta_size < deflate_size) {
3354 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3355 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3356 s, strlen(s), 0);
3357 free(s);
3358 free(deflated);
3359 data = delta;
3360 data_size = delta_size;
3361 } else {
3362 char *s = xstrfmt("%lu", two->size);
3363 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3364 s, strlen(s), 0);
3365 free(s);
3366 free(delta);
3367 data = deflated;
3368 data_size = deflate_size;
3371 /* emit data encoded in base85 */
3372 cp = data;
3373 while (data_size) {
3374 int len;
3375 int bytes = (52 < data_size) ? 52 : data_size;
3376 char line[71];
3377 data_size -= bytes;
3378 if (bytes <= 26)
3379 line[0] = bytes + 'A' - 1;
3380 else
3381 line[0] = bytes - 26 + 'a' - 1;
3382 encode_85(line + 1, cp, bytes);
3383 cp = (char *) cp + bytes;
3385 len = strlen(line);
3386 line[len++] = '\n';
3387 line[len] = '\0';
3389 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3390 line, len, 0);
3392 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3393 free(data);
3396 static void emit_binary_diff(struct diff_options *o,
3397 mmfile_t *one, mmfile_t *two)
3399 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3400 emit_binary_diff_body(o, one, two);
3401 emit_binary_diff_body(o, two, one);
3404 int diff_filespec_is_binary(struct repository *r,
3405 struct diff_filespec *one)
3407 struct diff_populate_filespec_options dpf_options = {
3408 .check_binary = 1,
3411 if (one->is_binary == -1) {
3412 diff_filespec_load_driver(one, r->index);
3413 if (one->driver->binary != -1)
3414 one->is_binary = one->driver->binary;
3415 else {
3416 if (!one->data && DIFF_FILE_VALID(one))
3417 diff_populate_filespec(r, one, &dpf_options);
3418 if (one->is_binary == -1 && one->data)
3419 one->is_binary = buffer_is_binary(one->data,
3420 one->size);
3421 if (one->is_binary == -1)
3422 one->is_binary = 0;
3425 return one->is_binary;
3428 static const struct userdiff_funcname *
3429 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3431 diff_filespec_load_driver(one, o->repo->index);
3432 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3435 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3437 if (!options->a_prefix)
3438 options->a_prefix = a;
3439 if (!options->b_prefix)
3440 options->b_prefix = b;
3443 void diff_set_noprefix(struct diff_options *options)
3445 options->a_prefix = options->b_prefix = "";
3448 void diff_set_default_prefix(struct diff_options *options)
3450 options->a_prefix = diff_src_prefix ? diff_src_prefix : "a/";
3451 options->b_prefix = diff_dst_prefix ? diff_dst_prefix : "b/";
3454 struct userdiff_driver *get_textconv(struct repository *r,
3455 struct diff_filespec *one)
3457 if (!DIFF_FILE_VALID(one))
3458 return NULL;
3460 diff_filespec_load_driver(one, r->index);
3461 return userdiff_get_textconv(r, one->driver);
3464 static struct string_list *additional_headers(struct diff_options *o,
3465 const char *path)
3467 if (!o->additional_path_headers)
3468 return NULL;
3469 return strmap_get(o->additional_path_headers, path);
3472 static void add_formatted_header(struct strbuf *msg,
3473 const char *header,
3474 const char *line_prefix,
3475 const char *meta,
3476 const char *reset)
3478 const char *next, *newline;
3480 for (next = header; *next; next = newline) {
3481 newline = strchrnul(next, '\n');
3482 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3483 (int)(newline - next), next, reset);
3484 if (*newline)
3485 newline++;
3489 static void add_formatted_headers(struct strbuf *msg,
3490 struct string_list *more_headers,
3491 const char *line_prefix,
3492 const char *meta,
3493 const char *reset)
3495 int i;
3497 for (i = 0; i < more_headers->nr; i++)
3498 add_formatted_header(msg, more_headers->items[i].string,
3499 line_prefix, meta, reset);
3502 static int diff_filepair_is_phoney(struct diff_filespec *one,
3503 struct diff_filespec *two)
3506 * This function specifically looks for pairs injected by
3507 * create_filepairs_for_header_only_notifications(). Such
3508 * pairs are "phoney" in that they do not represent any
3509 * content or even mode difference, but were inserted because
3510 * diff_queued_diff previously had no pair associated with
3511 * that path but we needed some pair to avoid losing the
3512 * "remerge CONFLICT" header associated with the path.
3514 return !DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two);
3517 static int set_diff_algorithm(struct diff_options *opts,
3518 const char *alg)
3520 long value = parse_algorithm_value(alg);
3522 if (value < 0)
3523 return -1;
3525 /* clear out previous settings */
3526 DIFF_XDL_CLR(opts, NEED_MINIMAL);
3527 opts->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3528 opts->xdl_opts |= value;
3530 return 0;
3533 static void builtin_diff(const char *name_a,
3534 const char *name_b,
3535 struct diff_filespec *one,
3536 struct diff_filespec *two,
3537 const char *xfrm_msg,
3538 int must_show_header,
3539 struct diff_options *o,
3540 int complete_rewrite)
3542 mmfile_t mf1, mf2;
3543 const char *lbl[2];
3544 char *a_one, *b_two;
3545 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3546 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3547 const char *a_prefix, *b_prefix;
3548 struct userdiff_driver *textconv_one = NULL;
3549 struct userdiff_driver *textconv_two = NULL;
3550 struct strbuf header = STRBUF_INIT;
3551 const char *line_prefix = diff_line_prefix(o);
3553 diff_set_mnemonic_prefix(o, "a/", "b/");
3554 if (o->flags.reverse_diff) {
3555 a_prefix = o->b_prefix;
3556 b_prefix = o->a_prefix;
3557 } else {
3558 a_prefix = o->a_prefix;
3559 b_prefix = o->b_prefix;
3562 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3563 (!one->mode || S_ISGITLINK(one->mode)) &&
3564 (!two->mode || S_ISGITLINK(two->mode)) &&
3565 (!diff_filepair_is_phoney(one, two))) {
3566 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3567 &one->oid, &two->oid,
3568 two->dirty_submodule);
3569 o->found_changes = 1;
3570 return;
3571 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3572 (!one->mode || S_ISGITLINK(one->mode)) &&
3573 (!two->mode || S_ISGITLINK(two->mode)) &&
3574 (!diff_filepair_is_phoney(one, two))) {
3575 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3576 &one->oid, &two->oid,
3577 two->dirty_submodule);
3578 o->found_changes = 1;
3579 return;
3582 if (o->flags.allow_textconv) {
3583 textconv_one = get_textconv(o->repo, one);
3584 textconv_two = get_textconv(o->repo, two);
3587 /* Never use a non-valid filename anywhere if at all possible */
3588 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3589 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3591 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3592 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3593 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3594 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3595 if (diff_filepair_is_phoney(one, two)) {
3597 * We should only reach this point for pairs generated from
3598 * create_filepairs_for_header_only_notifications(). For
3599 * these, we want to avoid the "/dev/null" special casing
3600 * above, because we do not want such pairs shown as either
3601 * "new file" or "deleted file" below.
3603 lbl[0] = a_one;
3604 lbl[1] = b_two;
3606 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3607 if (lbl[0][0] == '/') {
3608 /* /dev/null */
3609 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3610 if (xfrm_msg)
3611 strbuf_addstr(&header, xfrm_msg);
3612 o->found_changes = 1;
3613 must_show_header = 1;
3615 else if (lbl[1][0] == '/') {
3616 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3617 if (xfrm_msg)
3618 strbuf_addstr(&header, xfrm_msg);
3619 o->found_changes = 1;
3620 must_show_header = 1;
3622 else {
3623 if (one->mode != two->mode) {
3624 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3625 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3626 o->found_changes = 1;
3627 must_show_header = 1;
3629 if (xfrm_msg)
3630 strbuf_addstr(&header, xfrm_msg);
3633 * we do not run diff between different kind
3634 * of objects.
3636 if ((one->mode ^ two->mode) & S_IFMT)
3637 goto free_ab_and_return;
3638 if (complete_rewrite &&
3639 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3640 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3641 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3642 header.buf, header.len, 0);
3643 strbuf_reset(&header);
3644 emit_rewrite_diff(name_a, name_b, one, two,
3645 textconv_one, textconv_two, o);
3646 o->found_changes = 1;
3647 goto free_ab_and_return;
3651 if (o->irreversible_delete && lbl[1][0] == '/') {
3652 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3653 header.len, 0);
3654 strbuf_reset(&header);
3655 goto free_ab_and_return;
3656 } else if (!o->flags.text &&
3657 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3658 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3659 struct strbuf sb = STRBUF_INIT;
3660 if (!one->data && !two->data &&
3661 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3662 !o->flags.binary) {
3663 if (oideq(&one->oid, &two->oid)) {
3664 if (must_show_header)
3665 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3666 header.buf, header.len,
3668 goto free_ab_and_return;
3670 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3671 header.buf, header.len, 0);
3672 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3673 diff_line_prefix(o), lbl[0], lbl[1]);
3674 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3675 sb.buf, sb.len, 0);
3676 strbuf_release(&sb);
3677 o->found_changes = 1;
3678 goto free_ab_and_return;
3680 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3681 fill_mmfile(o->repo, &mf2, two) < 0)
3682 die("unable to read files to diff");
3683 /* Quite common confusing case */
3684 if (mf1.size == mf2.size &&
3685 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3686 if (must_show_header)
3687 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3688 header.buf, header.len, 0);
3689 goto free_ab_and_return;
3691 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3692 strbuf_reset(&header);
3693 if (o->flags.binary)
3694 emit_binary_diff(o, &mf1, &mf2);
3695 else {
3696 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3697 diff_line_prefix(o), lbl[0], lbl[1]);
3698 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3699 sb.buf, sb.len, 0);
3700 strbuf_release(&sb);
3702 o->found_changes = 1;
3703 } else {
3704 /* Crazy xdl interfaces.. */
3705 const char *diffopts;
3706 const char *v;
3707 xpparam_t xpp;
3708 xdemitconf_t xecfg;
3709 struct emit_callback ecbdata;
3710 const struct userdiff_funcname *pe;
3712 if (must_show_header) {
3713 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3714 header.buf, header.len, 0);
3715 strbuf_reset(&header);
3718 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3719 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3721 pe = diff_funcname_pattern(o, one);
3722 if (!pe)
3723 pe = diff_funcname_pattern(o, two);
3725 memset(&xpp, 0, sizeof(xpp));
3726 memset(&xecfg, 0, sizeof(xecfg));
3727 memset(&ecbdata, 0, sizeof(ecbdata));
3728 if (o->flags.suppress_diff_headers)
3729 lbl[0] = NULL;
3730 ecbdata.label_path = lbl;
3731 ecbdata.color_diff = want_color(o->use_color);
3732 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3733 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3734 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3735 ecbdata.opt = o;
3736 if (header.len && !o->flags.suppress_diff_headers)
3737 ecbdata.header = &header;
3738 xpp.flags = o->xdl_opts;
3739 xpp.ignore_regex = o->ignore_regex;
3740 xpp.ignore_regex_nr = o->ignore_regex_nr;
3741 xpp.anchors = o->anchors;
3742 xpp.anchors_nr = o->anchors_nr;
3743 xecfg.ctxlen = o->context;
3744 xecfg.interhunkctxlen = o->interhunkcontext;
3745 xecfg.flags = XDL_EMIT_FUNCNAMES;
3746 if (o->flags.funccontext)
3747 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3748 if (pe)
3749 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3751 diffopts = getenv("GIT_DIFF_OPTS");
3752 if (!diffopts)
3754 else if (skip_prefix(diffopts, "--unified=", &v))
3755 xecfg.ctxlen = strtoul(v, NULL, 10);
3756 else if (skip_prefix(diffopts, "-u", &v))
3757 xecfg.ctxlen = strtoul(v, NULL, 10);
3759 if (o->word_diff)
3760 init_diff_words_data(&ecbdata, o, one, two);
3761 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3762 &ecbdata, &xpp, &xecfg))
3763 die("unable to generate diff for %s", one->path);
3764 if (o->word_diff)
3765 free_diff_words_data(&ecbdata);
3766 if (textconv_one)
3767 free(mf1.ptr);
3768 if (textconv_two)
3769 free(mf2.ptr);
3770 xdiff_clear_find_func(&xecfg);
3773 free_ab_and_return:
3774 strbuf_release(&header);
3775 diff_free_filespec_data(one);
3776 diff_free_filespec_data(two);
3777 free(a_one);
3778 free(b_two);
3779 return;
3782 static const char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3784 if (!is_renamed) {
3785 if (p->status == DIFF_STATUS_ADDED) {
3786 if (S_ISLNK(p->two->mode))
3787 return "new +l";
3788 else if ((p->two->mode & 0777) == 0755)
3789 return "new +x";
3790 else
3791 return "new";
3792 } else if (p->status == DIFF_STATUS_DELETED)
3793 return "gone";
3795 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3796 return "mode -l";
3797 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3798 return "mode +l";
3799 else if ((p->one->mode & 0777) == 0644 &&
3800 (p->two->mode & 0777) == 0755)
3801 return "mode +x";
3802 else if ((p->one->mode & 0777) == 0755 &&
3803 (p->two->mode & 0777) == 0644)
3804 return "mode -x";
3805 return NULL;
3808 static void builtin_diffstat(const char *name_a, const char *name_b,
3809 struct diff_filespec *one,
3810 struct diff_filespec *two,
3811 struct diffstat_t *diffstat,
3812 struct diff_options *o,
3813 struct diff_filepair *p)
3815 mmfile_t mf1, mf2;
3816 struct diffstat_file *data;
3817 int may_differ;
3818 int complete_rewrite = 0;
3820 if (!DIFF_PAIR_UNMERGED(p)) {
3821 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3822 complete_rewrite = 1;
3825 data = diffstat_add(diffstat, name_a, name_b);
3826 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3827 if (o->flags.stat_with_summary)
3828 data->comments = get_compact_summary(p, data->is_renamed);
3830 if (!one || !two) {
3831 data->is_unmerged = 1;
3832 return;
3835 /* saves some reads if true, not a guarantee of diff outcome */
3836 may_differ = !(one->oid_valid && two->oid_valid &&
3837 oideq(&one->oid, &two->oid));
3839 if (diff_filespec_is_binary(o->repo, one) ||
3840 diff_filespec_is_binary(o->repo, two)) {
3841 data->is_binary = 1;
3842 if (!may_differ) {
3843 data->added = 0;
3844 data->deleted = 0;
3845 } else {
3846 data->added = diff_filespec_size(o->repo, two);
3847 data->deleted = diff_filespec_size(o->repo, one);
3851 else if (complete_rewrite) {
3852 diff_populate_filespec(o->repo, one, NULL);
3853 diff_populate_filespec(o->repo, two, NULL);
3854 data->deleted = count_lines(one->data, one->size);
3855 data->added = count_lines(two->data, two->size);
3858 else if (may_differ) {
3859 /* Crazy xdl interfaces.. */
3860 xpparam_t xpp;
3861 xdemitconf_t xecfg;
3863 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3864 fill_mmfile(o->repo, &mf2, two) < 0)
3865 die("unable to read files to diff");
3867 memset(&xpp, 0, sizeof(xpp));
3868 memset(&xecfg, 0, sizeof(xecfg));
3869 xpp.flags = o->xdl_opts;
3870 xpp.ignore_regex = o->ignore_regex;
3871 xpp.ignore_regex_nr = o->ignore_regex_nr;
3872 xpp.anchors = o->anchors;
3873 xpp.anchors_nr = o->anchors_nr;
3874 xecfg.ctxlen = o->context;
3875 xecfg.interhunkctxlen = o->interhunkcontext;
3876 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3877 if (xdi_diff_outf(&mf1, &mf2, NULL,
3878 diffstat_consume, diffstat, &xpp, &xecfg))
3879 die("unable to generate diffstat for %s", one->path);
3881 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3882 struct diffstat_file *file =
3883 diffstat->files[diffstat->nr - 1];
3885 * Omit diffstats of modified files where nothing changed.
3886 * Even if may_differ, this might be the case due to
3887 * ignoring whitespace changes, etc.
3889 * But note that we special-case additions, deletions,
3890 * renames, and mode changes as adding an empty file,
3891 * for example is still of interest.
3893 if ((p->status == DIFF_STATUS_MODIFIED)
3894 && !file->added
3895 && !file->deleted
3896 && one->mode == two->mode) {
3897 free_diffstat_file(file);
3898 diffstat->nr--;
3903 diff_free_filespec_data(one);
3904 diff_free_filespec_data(two);
3907 static void builtin_checkdiff(const char *name_a, const char *name_b,
3908 const char *attr_path,
3909 struct diff_filespec *one,
3910 struct diff_filespec *two,
3911 struct diff_options *o)
3913 mmfile_t mf1, mf2;
3914 struct checkdiff_t data;
3916 if (!two)
3917 return;
3919 memset(&data, 0, sizeof(data));
3920 data.filename = name_b ? name_b : name_a;
3921 data.lineno = 0;
3922 data.o = o;
3923 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3924 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3926 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3927 fill_mmfile(o->repo, &mf2, two) < 0)
3928 die("unable to read files to diff");
3931 * All the other codepaths check both sides, but not checking
3932 * the "old" side here is deliberate. We are checking the newly
3933 * introduced changes, and as long as the "new" side is text, we
3934 * can and should check what it introduces.
3936 if (diff_filespec_is_binary(o->repo, two))
3937 goto free_and_return;
3938 else {
3939 /* Crazy xdl interfaces.. */
3940 xpparam_t xpp;
3941 xdemitconf_t xecfg;
3943 memset(&xpp, 0, sizeof(xpp));
3944 memset(&xecfg, 0, sizeof(xecfg));
3945 xecfg.ctxlen = 1; /* at least one context line */
3946 xpp.flags = 0;
3947 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3948 checkdiff_consume, &data,
3949 &xpp, &xecfg))
3950 die("unable to generate checkdiff for %s", one->path);
3952 if (data.ws_rule & WS_BLANK_AT_EOF) {
3953 struct emit_callback ecbdata;
3954 int blank_at_eof;
3956 ecbdata.ws_rule = data.ws_rule;
3957 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3958 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3960 if (blank_at_eof) {
3961 static char *err;
3962 if (!err)
3963 err = whitespace_error_string(WS_BLANK_AT_EOF);
3964 fprintf(o->file, "%s:%d: %s.\n",
3965 data.filename, blank_at_eof, err);
3966 data.status = 1; /* report errors */
3970 free_and_return:
3971 diff_free_filespec_data(one);
3972 diff_free_filespec_data(two);
3973 if (data.status)
3974 o->flags.check_failed = 1;
3977 struct diff_filespec *alloc_filespec(const char *path)
3979 struct diff_filespec *spec;
3981 FLEXPTR_ALLOC_STR(spec, path, path);
3982 spec->count = 1;
3983 spec->is_binary = -1;
3984 return spec;
3987 void free_filespec(struct diff_filespec *spec)
3989 if (!--spec->count) {
3990 diff_free_filespec_data(spec);
3991 free(spec);
3995 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3996 int oid_valid, unsigned short mode)
3998 if (mode) {
3999 spec->mode = canon_mode(mode);
4000 oidcpy(&spec->oid, oid);
4001 spec->oid_valid = oid_valid;
4006 * Given a name and sha1 pair, if the index tells us the file in
4007 * the work tree has that object contents, return true, so that
4008 * prepare_temp_file() does not have to inflate and extract.
4010 static int reuse_worktree_file(struct index_state *istate,
4011 const char *name,
4012 const struct object_id *oid,
4013 int want_file)
4015 const struct cache_entry *ce;
4016 struct stat st;
4017 int pos, len;
4020 * We do not read the cache ourselves here, because the
4021 * benchmark with my previous version that always reads cache
4022 * shows that it makes things worse for diff-tree comparing
4023 * two linux-2.6 kernel trees in an already checked out work
4024 * tree. This is because most diff-tree comparisons deal with
4025 * only a small number of files, while reading the cache is
4026 * expensive for a large project, and its cost outweighs the
4027 * savings we get by not inflating the object to a temporary
4028 * file. Practically, this code only helps when we are used
4029 * by diff-cache --cached, which does read the cache before
4030 * calling us.
4032 if (!istate->cache)
4033 return 0;
4035 /* We want to avoid the working directory if our caller
4036 * doesn't need the data in a normal file, this system
4037 * is rather slow with its stat/open/mmap/close syscalls,
4038 * and the object is contained in a pack file. The pack
4039 * is probably already open and will be faster to obtain
4040 * the data through than the working directory. Loose
4041 * objects however would tend to be slower as they need
4042 * to be individually opened and inflated.
4044 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
4045 return 0;
4048 * Similarly, if we'd have to convert the file contents anyway, that
4049 * makes the optimization not worthwhile.
4051 if (!want_file && would_convert_to_git(istate, name))
4052 return 0;
4055 * If this path does not match our sparse-checkout definition,
4056 * then the file will not be in the working directory.
4058 if (!path_in_sparse_checkout(name, istate))
4059 return 0;
4061 len = strlen(name);
4062 pos = index_name_pos(istate, name, len);
4063 if (pos < 0)
4064 return 0;
4065 ce = istate->cache[pos];
4068 * This is not the sha1 we are looking for, or
4069 * unreusable because it is not a regular file.
4071 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
4072 return 0;
4075 * If ce is marked as "assume unchanged", there is no
4076 * guarantee that work tree matches what we are looking for.
4078 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
4079 return 0;
4082 * If ce matches the file in the work tree, we can reuse it.
4084 if (ce_uptodate(ce) ||
4085 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
4086 return 1;
4088 return 0;
4091 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4093 struct strbuf buf = STRBUF_INIT;
4094 const char *dirty = "";
4096 /* Are we looking at the work tree? */
4097 if (s->dirty_submodule)
4098 dirty = "-dirty";
4100 strbuf_addf(&buf, "Subproject commit %s%s\n",
4101 oid_to_hex(&s->oid), dirty);
4102 s->size = buf.len;
4103 if (size_only) {
4104 s->data = NULL;
4105 strbuf_release(&buf);
4106 } else {
4107 s->data = strbuf_detach(&buf, NULL);
4108 s->should_free = 1;
4110 return 0;
4114 * While doing rename detection and pickaxe operation, we may need to
4115 * grab the data for the blob (or file) for our own in-core comparison.
4116 * diff_filespec has data and size fields for this purpose.
4118 int diff_populate_filespec(struct repository *r,
4119 struct diff_filespec *s,
4120 const struct diff_populate_filespec_options *options)
4122 int size_only = options ? options->check_size_only : 0;
4123 int check_binary = options ? options->check_binary : 0;
4124 int err = 0;
4125 int conv_flags = global_conv_flags_eol;
4127 * demote FAIL to WARN to allow inspecting the situation
4128 * instead of refusing.
4130 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4131 conv_flags = CONV_EOL_RNDTRP_WARN;
4133 if (!DIFF_FILE_VALID(s))
4134 die("internal error: asking to populate invalid file.");
4135 if (S_ISDIR(s->mode))
4136 return -1;
4138 if (s->data)
4139 return 0;
4141 if (size_only && 0 < s->size)
4142 return 0;
4144 if (S_ISGITLINK(s->mode))
4145 return diff_populate_gitlink(s, size_only);
4147 if (!s->oid_valid ||
4148 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
4149 struct strbuf buf = STRBUF_INIT;
4150 struct stat st;
4151 int fd;
4153 if (lstat(s->path, &st) < 0) {
4154 err_empty:
4155 err = -1;
4156 empty:
4157 s->data = (char *)"";
4158 s->size = 0;
4159 return err;
4161 s->size = xsize_t(st.st_size);
4162 if (!s->size)
4163 goto empty;
4164 if (S_ISLNK(st.st_mode)) {
4165 struct strbuf sb = STRBUF_INIT;
4167 if (strbuf_readlink(&sb, s->path, s->size))
4168 goto err_empty;
4169 s->size = sb.len;
4170 s->data = strbuf_detach(&sb, NULL);
4171 s->should_free = 1;
4172 return 0;
4176 * Even if the caller would be happy with getting
4177 * only the size, we cannot return early at this
4178 * point if the path requires us to run the content
4179 * conversion.
4181 if (size_only && !would_convert_to_git(r->index, s->path))
4182 return 0;
4185 * Note: this check uses xsize_t(st.st_size) that may
4186 * not be the true size of the blob after it goes
4187 * through convert_to_git(). This may not strictly be
4188 * correct, but the whole point of big_file_threshold
4189 * and is_binary check being that we want to avoid
4190 * opening the file and inspecting the contents, this
4191 * is probably fine.
4193 if (check_binary &&
4194 s->size > big_file_threshold && s->is_binary == -1) {
4195 s->is_binary = 1;
4196 return 0;
4198 fd = open(s->path, O_RDONLY);
4199 if (fd < 0)
4200 goto err_empty;
4201 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4202 close(fd);
4203 s->should_munmap = 1;
4206 * Convert from working tree format to canonical git format
4208 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4209 size_t size = 0;
4210 munmap(s->data, s->size);
4211 s->should_munmap = 0;
4212 s->data = strbuf_detach(&buf, &size);
4213 s->size = size;
4214 s->should_free = 1;
4217 else {
4218 struct object_info info = {
4219 .sizep = &s->size
4222 if (!(size_only || check_binary))
4224 * Set contentp, since there is no chance that merely
4225 * the size is sufficient.
4227 info.contentp = &s->data;
4229 if (options && options->missing_object_cb) {
4230 if (!oid_object_info_extended(r, &s->oid, &info,
4231 OBJECT_INFO_LOOKUP_REPLACE |
4232 OBJECT_INFO_SKIP_FETCH_OBJECT))
4233 goto object_read;
4234 options->missing_object_cb(options->missing_object_data);
4236 if (oid_object_info_extended(r, &s->oid, &info,
4237 OBJECT_INFO_LOOKUP_REPLACE))
4238 die("unable to read %s", oid_to_hex(&s->oid));
4240 object_read:
4241 if (size_only || check_binary) {
4242 if (size_only)
4243 return 0;
4244 if (s->size > big_file_threshold && s->is_binary == -1) {
4245 s->is_binary = 1;
4246 return 0;
4249 if (!info.contentp) {
4250 info.contentp = &s->data;
4251 if (oid_object_info_extended(r, &s->oid, &info,
4252 OBJECT_INFO_LOOKUP_REPLACE))
4253 die("unable to read %s", oid_to_hex(&s->oid));
4255 s->should_free = 1;
4257 return 0;
4260 void diff_free_filespec_blob(struct diff_filespec *s)
4262 if (s->should_free)
4263 free(s->data);
4264 else if (s->should_munmap)
4265 munmap(s->data, s->size);
4267 if (s->should_free || s->should_munmap) {
4268 s->should_free = s->should_munmap = 0;
4269 s->data = NULL;
4273 void diff_free_filespec_data(struct diff_filespec *s)
4275 if (!s)
4276 return;
4278 diff_free_filespec_blob(s);
4279 FREE_AND_NULL(s->cnt_data);
4282 static void prep_temp_blob(struct index_state *istate,
4283 const char *path, struct diff_tempfile *temp,
4284 void *blob,
4285 unsigned long size,
4286 const struct object_id *oid,
4287 int mode)
4289 struct strbuf buf = STRBUF_INIT;
4290 char *path_dup = xstrdup(path);
4291 const char *base = basename(path_dup);
4292 struct checkout_metadata meta;
4294 init_checkout_metadata(&meta, NULL, NULL, oid);
4296 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
4297 if (!temp->tempfile)
4298 die_errno("unable to create temp-file");
4299 if (convert_to_working_tree(istate, path,
4300 (const char *)blob, (size_t)size, &buf, &meta)) {
4301 blob = buf.buf;
4302 size = buf.len;
4304 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4305 close_tempfile_gently(temp->tempfile))
4306 die_errno("unable to write temp-file");
4307 temp->name = get_tempfile_path(temp->tempfile);
4308 oid_to_hex_r(temp->hex, oid);
4309 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4310 strbuf_release(&buf);
4311 free(path_dup);
4314 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4315 struct diff_filespec *one)
4317 struct diff_tempfile *temp = claim_diff_tempfile();
4319 if (!DIFF_FILE_VALID(one)) {
4320 not_a_valid_file:
4321 /* A '-' entry produces this for file-2, and
4322 * a '+' entry produces this for file-1.
4324 temp->name = "/dev/null";
4325 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4326 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4327 return temp;
4330 if (!S_ISGITLINK(one->mode) &&
4331 (!one->oid_valid ||
4332 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
4333 struct stat st;
4334 if (lstat(one->path, &st) < 0) {
4335 if (errno == ENOENT)
4336 goto not_a_valid_file;
4337 die_errno("stat(%s)", one->path);
4339 if (S_ISLNK(st.st_mode)) {
4340 struct strbuf sb = STRBUF_INIT;
4341 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4342 die_errno("readlink(%s)", one->path);
4343 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
4344 (one->oid_valid ?
4345 &one->oid : null_oid()),
4346 (one->oid_valid ?
4347 one->mode : S_IFLNK));
4348 strbuf_release(&sb);
4350 else {
4351 /* we can borrow from the file in the work tree */
4352 temp->name = one->path;
4353 if (!one->oid_valid)
4354 oid_to_hex_r(temp->hex, null_oid());
4355 else
4356 oid_to_hex_r(temp->hex, &one->oid);
4357 /* Even though we may sometimes borrow the
4358 * contents from the work tree, we always want
4359 * one->mode. mode is trustworthy even when
4360 * !(one->oid_valid), as long as
4361 * DIFF_FILE_VALID(one).
4363 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4365 return temp;
4367 else {
4368 if (diff_populate_filespec(r, one, NULL))
4369 die("cannot read data blob for %s", one->path);
4370 prep_temp_blob(r->index, one->path, temp,
4371 one->data, one->size,
4372 &one->oid, one->mode);
4374 return temp;
4377 static void add_external_diff_name(struct repository *r,
4378 struct strvec *argv,
4379 struct diff_filespec *df)
4381 struct diff_tempfile *temp = prepare_temp_file(r, df);
4382 strvec_push(argv, temp->name);
4383 strvec_push(argv, temp->hex);
4384 strvec_push(argv, temp->mode);
4387 /* An external diff command takes:
4389 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4390 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4393 static void run_external_diff(const struct external_diff *pgm,
4394 const char *name,
4395 const char *other,
4396 struct diff_filespec *one,
4397 struct diff_filespec *two,
4398 const char *xfrm_msg,
4399 struct diff_options *o)
4401 struct child_process cmd = CHILD_PROCESS_INIT;
4402 struct diff_queue_struct *q = &diff_queued_diff;
4403 int quiet = !(o->output_format & DIFF_FORMAT_PATCH);
4404 int rc;
4407 * Trivial equality is handled by diff_unmodified_pair() before
4408 * we get here. If we don't need to show the diff and the
4409 * external diff program lacks the ability to tell us whether
4410 * it's empty then we consider it non-empty without even asking.
4412 if (!pgm->trust_exit_code && quiet) {
4413 o->found_changes = 1;
4414 return;
4417 strvec_push(&cmd.args, pgm->cmd);
4418 strvec_push(&cmd.args, name);
4420 if (one && two) {
4421 add_external_diff_name(o->repo, &cmd.args, one);
4422 add_external_diff_name(o->repo, &cmd.args, two);
4423 if (other) {
4424 strvec_push(&cmd.args, other);
4425 if (xfrm_msg)
4426 strvec_push(&cmd.args, xfrm_msg);
4430 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4431 ++o->diff_path_counter);
4432 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4434 diff_free_filespec_data(one);
4435 diff_free_filespec_data(two);
4436 cmd.use_shell = 1;
4437 cmd.no_stdout = quiet;
4438 rc = run_command(&cmd);
4439 if (!pgm->trust_exit_code && rc == 0)
4440 o->found_changes = 1;
4441 else if (pgm->trust_exit_code && rc == 0)
4442 ; /* nothing */
4443 else if (pgm->trust_exit_code && rc == 1)
4444 o->found_changes = 1;
4445 else
4446 die(_("external diff died, stopping at %s"), name);
4448 remove_tempfile();
4451 static int similarity_index(struct diff_filepair *p)
4453 return p->score * 100 / MAX_SCORE;
4456 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4458 if (startup_info->have_repository)
4459 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4460 else {
4461 char *hex = oid_to_hex(oid);
4462 if (abbrev < 0)
4463 abbrev = FALLBACK_DEFAULT_ABBREV;
4464 if (abbrev > the_hash_algo->hexsz)
4465 BUG("oid abbreviation out of range: %d", abbrev);
4466 if (abbrev)
4467 hex[abbrev] = '\0';
4468 return hex;
4472 static void fill_metainfo(struct strbuf *msg,
4473 const char *name,
4474 const char *other,
4475 struct diff_filespec *one,
4476 struct diff_filespec *two,
4477 struct diff_options *o,
4478 struct diff_filepair *p,
4479 int *must_show_header,
4480 int use_color)
4482 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4483 const char *reset = diff_get_color(use_color, DIFF_RESET);
4484 const char *line_prefix = diff_line_prefix(o);
4485 struct string_list *more_headers = NULL;
4487 *must_show_header = 1;
4488 strbuf_init(msg, PATH_MAX * 2 + 300);
4489 switch (p->status) {
4490 case DIFF_STATUS_COPIED:
4491 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4492 line_prefix, set, similarity_index(p));
4493 strbuf_addf(msg, "%s\n%s%scopy from ",
4494 reset, line_prefix, set);
4495 quote_c_style(name, msg, NULL, 0);
4496 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4497 quote_c_style(other, msg, NULL, 0);
4498 strbuf_addf(msg, "%s\n", reset);
4499 break;
4500 case DIFF_STATUS_RENAMED:
4501 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4502 line_prefix, set, similarity_index(p));
4503 strbuf_addf(msg, "%s\n%s%srename from ",
4504 reset, line_prefix, set);
4505 quote_c_style(name, msg, NULL, 0);
4506 strbuf_addf(msg, "%s\n%s%srename to ",
4507 reset, line_prefix, set);
4508 quote_c_style(other, msg, NULL, 0);
4509 strbuf_addf(msg, "%s\n", reset);
4510 break;
4511 case DIFF_STATUS_MODIFIED:
4512 if (p->score) {
4513 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4514 line_prefix,
4515 set, similarity_index(p), reset);
4516 break;
4518 /* fallthru */
4519 default:
4520 *must_show_header = 0;
4522 if ((more_headers = additional_headers(o, name))) {
4523 add_formatted_headers(msg, more_headers,
4524 line_prefix, set, reset);
4525 *must_show_header = 1;
4527 if (one && two && !oideq(&one->oid, &two->oid)) {
4528 const unsigned hexsz = the_hash_algo->hexsz;
4529 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4531 if (o->flags.full_index)
4532 abbrev = hexsz;
4534 if (o->flags.binary) {
4535 mmfile_t mf;
4536 if ((!fill_mmfile(o->repo, &mf, one) &&
4537 diff_filespec_is_binary(o->repo, one)) ||
4538 (!fill_mmfile(o->repo, &mf, two) &&
4539 diff_filespec_is_binary(o->repo, two)))
4540 abbrev = hexsz;
4542 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4543 diff_abbrev_oid(&one->oid, abbrev),
4544 diff_abbrev_oid(&two->oid, abbrev));
4545 if (one->mode == two->mode)
4546 strbuf_addf(msg, " %06o", one->mode);
4547 strbuf_addf(msg, "%s\n", reset);
4551 static void run_diff_cmd(const struct external_diff *pgm,
4552 const char *name,
4553 const char *other,
4554 const char *attr_path,
4555 struct diff_filespec *one,
4556 struct diff_filespec *two,
4557 struct strbuf *msg,
4558 struct diff_options *o,
4559 struct diff_filepair *p)
4561 const char *xfrm_msg = NULL;
4562 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4563 int must_show_header = 0;
4564 struct userdiff_driver *drv = NULL;
4566 if (o->flags.allow_external || !o->ignore_driver_algorithm)
4567 drv = userdiff_find_by_path(o->repo->index, attr_path);
4569 if (o->flags.allow_external && drv && drv->external.cmd)
4570 pgm = &drv->external;
4572 if (msg) {
4574 * don't use colors when the header is intended for an
4575 * external diff driver
4577 fill_metainfo(msg, name, other, one, two, o, p,
4578 &must_show_header,
4579 want_color(o->use_color) && !pgm);
4580 xfrm_msg = msg->len ? msg->buf : NULL;
4583 if (pgm) {
4584 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4585 return;
4587 if (one && two) {
4588 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4589 set_diff_algorithm(o, drv->algorithm);
4591 builtin_diff(name, other ? other : name,
4592 one, two, xfrm_msg, must_show_header,
4593 o, complete_rewrite);
4594 if (p->status == DIFF_STATUS_COPIED ||
4595 p->status == DIFF_STATUS_RENAMED)
4596 o->found_changes = 1;
4597 } else {
4598 fprintf(o->file, "* Unmerged path %s\n", name);
4599 o->found_changes = 1;
4603 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4605 if (DIFF_FILE_VALID(one)) {
4606 if (!one->oid_valid) {
4607 struct stat st;
4608 if (one->is_stdin) {
4609 oidclr(&one->oid, the_repository->hash_algo);
4610 return;
4612 if (lstat(one->path, &st) < 0)
4613 die_errno("stat '%s'", one->path);
4614 if (index_path(istate, &one->oid, one->path, &st, 0))
4615 die("cannot hash %s", one->path);
4618 else
4619 oidclr(&one->oid, the_repository->hash_algo);
4622 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4624 /* Strip the prefix but do not molest /dev/null and absolute paths */
4625 if (*namep && !is_absolute_path(*namep)) {
4626 *namep += prefix_length;
4627 if (**namep == '/')
4628 ++*namep;
4630 if (*otherp && !is_absolute_path(*otherp)) {
4631 *otherp += prefix_length;
4632 if (**otherp == '/')
4633 ++*otherp;
4637 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4639 const struct external_diff *pgm = external_diff();
4640 struct strbuf msg;
4641 struct diff_filespec *one = p->one;
4642 struct diff_filespec *two = p->two;
4643 const char *name;
4644 const char *other;
4645 const char *attr_path;
4647 name = one->path;
4648 other = (strcmp(name, two->path) ? two->path : NULL);
4649 attr_path = name;
4650 if (o->prefix_length)
4651 strip_prefix(o->prefix_length, &name, &other);
4653 if (!o->flags.allow_external)
4654 pgm = NULL;
4656 if (DIFF_PAIR_UNMERGED(p)) {
4657 run_diff_cmd(pgm, name, NULL, attr_path,
4658 NULL, NULL, NULL, o, p);
4659 return;
4662 diff_fill_oid_info(one, o->repo->index);
4663 diff_fill_oid_info(two, o->repo->index);
4665 if (!pgm &&
4666 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4667 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4669 * a filepair that changes between file and symlink
4670 * needs to be split into deletion and creation.
4672 struct diff_filespec *null = alloc_filespec(two->path);
4673 run_diff_cmd(NULL, name, other, attr_path,
4674 one, null, &msg,
4675 o, p);
4676 free(null);
4677 strbuf_release(&msg);
4679 null = alloc_filespec(one->path);
4680 run_diff_cmd(NULL, name, other, attr_path,
4681 null, two, &msg, o, p);
4682 free(null);
4684 else
4685 run_diff_cmd(pgm, name, other, attr_path,
4686 one, two, &msg, o, p);
4688 strbuf_release(&msg);
4691 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4692 struct diffstat_t *diffstat)
4694 const char *name;
4695 const char *other;
4697 if (!o->ignore_driver_algorithm) {
4698 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4699 p->one->path);
4701 if (drv && drv->algorithm)
4702 set_diff_algorithm(o, drv->algorithm);
4705 if (DIFF_PAIR_UNMERGED(p)) {
4706 /* unmerged */
4707 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4708 diffstat, o, p);
4709 return;
4712 name = p->one->path;
4713 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4715 if (o->prefix_length)
4716 strip_prefix(o->prefix_length, &name, &other);
4718 diff_fill_oid_info(p->one, o->repo->index);
4719 diff_fill_oid_info(p->two, o->repo->index);
4721 builtin_diffstat(name, other, p->one, p->two,
4722 diffstat, o, p);
4725 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4727 const char *name;
4728 const char *other;
4729 const char *attr_path;
4731 if (DIFF_PAIR_UNMERGED(p)) {
4732 /* unmerged */
4733 return;
4736 name = p->one->path;
4737 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4738 attr_path = other ? other : name;
4740 if (o->prefix_length)
4741 strip_prefix(o->prefix_length, &name, &other);
4743 diff_fill_oid_info(p->one, o->repo->index);
4744 diff_fill_oid_info(p->two, o->repo->index);
4746 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4749 void repo_diff_setup(struct repository *r, struct diff_options *options)
4751 memcpy(options, &default_diff_options, sizeof(*options));
4753 options->file = stdout;
4754 options->repo = r;
4756 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4757 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4758 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4759 options->abbrev = DEFAULT_ABBREV;
4760 options->line_termination = '\n';
4761 options->break_opt = -1;
4762 options->rename_limit = -1;
4763 options->dirstat_permille = diff_dirstat_permille_default;
4764 options->context = diff_context_default;
4765 options->interhunkcontext = diff_interhunk_context_default;
4766 options->ws_error_highlight = ws_error_highlight_default;
4767 options->flags.rename_empty = 1;
4768 options->flags.relative_name = diff_relative;
4769 options->objfind = NULL;
4771 /* pathchange left =NULL by default */
4772 options->change = diff_change;
4773 options->add_remove = diff_addremove;
4774 options->use_color = diff_use_color_default;
4775 options->detect_rename = diff_detect_rename_default;
4776 options->xdl_opts |= diff_algorithm;
4777 if (diff_indent_heuristic)
4778 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4780 options->orderfile = xstrdup_or_null(diff_order_file_cfg);
4782 if (!options->flags.ignore_submodule_set)
4783 options->flags.ignore_untracked_in_submodules = 1;
4785 if (diff_no_prefix) {
4786 diff_set_noprefix(options);
4787 } else if (!diff_mnemonic_prefix) {
4788 diff_set_default_prefix(options);
4791 options->color_moved = diff_color_moved_default;
4792 options->color_moved_ws_handling = diff_color_moved_ws_default;
4795 static const char diff_status_letters[] = {
4796 DIFF_STATUS_ADDED,
4797 DIFF_STATUS_COPIED,
4798 DIFF_STATUS_DELETED,
4799 DIFF_STATUS_MODIFIED,
4800 DIFF_STATUS_RENAMED,
4801 DIFF_STATUS_TYPE_CHANGED,
4802 DIFF_STATUS_UNKNOWN,
4803 DIFF_STATUS_UNMERGED,
4804 DIFF_STATUS_FILTER_AON,
4805 DIFF_STATUS_FILTER_BROKEN,
4806 '\0',
4809 static unsigned int filter_bit['Z' + 1];
4811 static void prepare_filter_bits(void)
4813 int i;
4815 if (!filter_bit[DIFF_STATUS_ADDED]) {
4816 for (i = 0; diff_status_letters[i]; i++)
4817 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4821 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4823 return opt->filter & filter_bit[(int) status];
4826 unsigned diff_filter_bit(char status)
4828 prepare_filter_bits();
4829 return filter_bit[(int) status];
4832 int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4834 unsigned forbidden_magic;
4836 if (ps->nr != 1) {
4837 if (die_on_error)
4838 die(_("--follow requires exactly one pathspec"));
4839 return 0;
4842 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4843 PATHSPEC_LITERAL);
4844 if (forbidden_magic) {
4845 if (die_on_error) {
4846 struct strbuf sb = STRBUF_INIT;
4847 pathspec_magic_names(forbidden_magic, &sb);
4848 die(_("pathspec magic not supported by --follow: %s"),
4849 sb.buf);
4851 return 0;
4854 return 1;
4857 void diff_setup_done(struct diff_options *options)
4859 unsigned check_mask = DIFF_FORMAT_NAME |
4860 DIFF_FORMAT_NAME_STATUS |
4861 DIFF_FORMAT_CHECKDIFF |
4862 DIFF_FORMAT_NO_OUTPUT;
4864 * This must be signed because we're comparing against a potentially
4865 * negative value.
4867 const int hexsz = the_hash_algo->hexsz;
4869 if (options->set_default)
4870 options->set_default(options);
4872 if (HAS_MULTI_BITS(options->output_format & check_mask))
4873 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4874 "--name-only", "--name-status", "--check", "-s");
4876 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4877 die(_("options '%s', '%s', and '%s' cannot be used together"),
4878 "-G", "-S", "--find-object");
4880 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4881 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4882 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4884 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4885 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4886 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4889 * Most of the time we can say "there are changes"
4890 * only by checking if there are changed paths, but
4891 * --ignore-whitespace* options force us to look
4892 * inside contents.
4895 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4896 options->ignore_regex_nr)
4897 options->flags.diff_from_contents = 1;
4898 else
4899 options->flags.diff_from_contents = 0;
4901 if (options->flags.find_copies_harder)
4902 options->detect_rename = DIFF_DETECT_COPY;
4904 if (!options->flags.relative_name)
4905 options->prefix = NULL;
4906 if (options->prefix)
4907 options->prefix_length = strlen(options->prefix);
4908 else
4909 options->prefix_length = 0;
4912 * --name-only, --name-status, --checkdiff, and -s
4913 * turn other output format off.
4915 if (options->output_format & (DIFF_FORMAT_NAME |
4916 DIFF_FORMAT_NAME_STATUS |
4917 DIFF_FORMAT_CHECKDIFF |
4918 DIFF_FORMAT_NO_OUTPUT))
4919 options->output_format &= ~(DIFF_FORMAT_RAW |
4920 DIFF_FORMAT_NUMSTAT |
4921 DIFF_FORMAT_DIFFSTAT |
4922 DIFF_FORMAT_SHORTSTAT |
4923 DIFF_FORMAT_DIRSTAT |
4924 DIFF_FORMAT_SUMMARY |
4925 DIFF_FORMAT_PATCH);
4928 * These cases always need recursive; we do not drop caller-supplied
4929 * recursive bits for other formats here.
4931 if (options->output_format & (DIFF_FORMAT_PATCH |
4932 DIFF_FORMAT_NUMSTAT |
4933 DIFF_FORMAT_DIFFSTAT |
4934 DIFF_FORMAT_SHORTSTAT |
4935 DIFF_FORMAT_DIRSTAT |
4936 DIFF_FORMAT_SUMMARY |
4937 DIFF_FORMAT_CHECKDIFF))
4938 options->flags.recursive = 1;
4940 * Also pickaxe would not work very well if you do not say recursive
4942 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4943 options->flags.recursive = 1;
4945 * When patches are generated, submodules diffed against the work tree
4946 * must be checked for dirtiness too so it can be shown in the output
4948 if (options->output_format & DIFF_FORMAT_PATCH)
4949 options->flags.dirty_submodules = 1;
4951 if (options->detect_rename && options->rename_limit < 0)
4952 options->rename_limit = diff_rename_limit_default;
4953 if (hexsz < options->abbrev)
4954 options->abbrev = hexsz; /* full */
4957 * It does not make sense to show the first hit we happened
4958 * to have found. It does not make sense not to return with
4959 * exit code in such a case either.
4961 if (options->flags.quick) {
4962 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4963 options->flags.exit_with_status = 1;
4967 * External diffs could declare non-identical contents equal
4968 * (think diff --ignore-space-change).
4970 if (options->flags.allow_external && options->flags.exit_with_status)
4971 options->flags.diff_from_contents = 1;
4973 options->diff_path_counter = 0;
4975 if (options->flags.follow_renames)
4976 diff_check_follow_pathspec(&options->pathspec, 1);
4978 if (!options->use_color ||
4979 (options->flags.allow_external && external_diff()))
4980 options->color_moved = 0;
4982 if (options->filter_not) {
4983 if (!options->filter)
4984 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4985 options->filter &= ~options->filter_not;
4989 int parse_long_opt(const char *opt, const char **argv,
4990 const char **optarg)
4992 const char *arg = argv[0];
4993 if (!skip_prefix(arg, "--", &arg))
4994 return 0;
4995 if (!skip_prefix(arg, opt, &arg))
4996 return 0;
4997 if (*arg == '=') { /* stuck form: --option=value */
4998 *optarg = arg + 1;
4999 return 1;
5001 if (*arg != '\0')
5002 return 0;
5003 /* separate form: --option value */
5004 if (!argv[1])
5005 die("Option '--%s' requires a value", opt);
5006 *optarg = argv[1];
5007 return 2;
5010 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
5012 struct diff_options *options = opt->value;
5013 int width = options->stat_width;
5014 int name_width = options->stat_name_width;
5015 int graph_width = options->stat_graph_width;
5016 int count = options->stat_count;
5017 char *end;
5019 BUG_ON_OPT_NEG(unset);
5021 if (!strcmp(opt->long_name, "stat")) {
5022 if (value) {
5023 width = strtoul(value, &end, 10);
5024 if (*end == ',')
5025 name_width = strtoul(end+1, &end, 10);
5026 if (*end == ',')
5027 count = strtoul(end+1, &end, 10);
5028 if (*end)
5029 return error(_("invalid --stat value: %s"), value);
5031 } else if (!strcmp(opt->long_name, "stat-width")) {
5032 width = strtoul(value, &end, 10);
5033 if (*end)
5034 return error(_("%s expects a numerical value"),
5035 opt->long_name);
5036 } else if (!strcmp(opt->long_name, "stat-name-width")) {
5037 name_width = strtoul(value, &end, 10);
5038 if (*end)
5039 return error(_("%s expects a numerical value"),
5040 opt->long_name);
5041 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
5042 graph_width = strtoul(value, &end, 10);
5043 if (*end)
5044 return error(_("%s expects a numerical value"),
5045 opt->long_name);
5046 } else if (!strcmp(opt->long_name, "stat-count")) {
5047 count = strtoul(value, &end, 10);
5048 if (*end)
5049 return error(_("%s expects a numerical value"),
5050 opt->long_name);
5051 } else
5052 BUG("%s should not get here", opt->long_name);
5054 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5055 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5056 options->stat_name_width = name_width;
5057 options->stat_graph_width = graph_width;
5058 options->stat_width = width;
5059 options->stat_count = count;
5060 return 0;
5063 static int parse_dirstat_opt(struct diff_options *options, const char *params)
5065 struct strbuf errmsg = STRBUF_INIT;
5066 if (parse_dirstat_params(options, params, &errmsg))
5067 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
5068 errmsg.buf);
5069 strbuf_release(&errmsg);
5071 * The caller knows a dirstat-related option is given from the command
5072 * line; allow it to say "return this_function();"
5074 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5075 options->output_format |= DIFF_FORMAT_DIRSTAT;
5076 return 1;
5079 static int diff_opt_diff_filter(const struct option *option,
5080 const char *optarg, int unset)
5082 struct diff_options *opt = option->value;
5083 int i, optch;
5085 BUG_ON_OPT_NEG(unset);
5086 prepare_filter_bits();
5088 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5089 unsigned int bit;
5090 int negate;
5092 if ('a' <= optch && optch <= 'z') {
5093 negate = 1;
5094 optch = toupper(optch);
5095 } else {
5096 negate = 0;
5099 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5100 if (!bit)
5101 return error(_("unknown change class '%c' in --diff-filter=%s"),
5102 optarg[i], optarg);
5103 if (negate)
5104 opt->filter_not |= bit;
5105 else
5106 opt->filter |= bit;
5108 return 0;
5111 static void enable_patch_output(int *fmt)
5113 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5114 *fmt |= DIFF_FORMAT_PATCH;
5117 static int diff_opt_ws_error_highlight(const struct option *option,
5118 const char *arg, int unset)
5120 struct diff_options *opt = option->value;
5121 int val = parse_ws_error_highlight(arg);
5123 BUG_ON_OPT_NEG(unset);
5124 if (val < 0)
5125 return error(_("unknown value after ws-error-highlight=%.*s"),
5126 -1 - val, arg);
5127 opt->ws_error_highlight = val;
5128 return 0;
5131 static int diff_opt_find_object(const struct option *option,
5132 const char *arg, int unset)
5134 struct diff_options *opt = option->value;
5135 struct object_id oid;
5137 BUG_ON_OPT_NEG(unset);
5138 if (repo_get_oid(the_repository, arg, &oid))
5139 return error(_("unable to resolve '%s'"), arg);
5141 if (!opt->objfind)
5142 CALLOC_ARRAY(opt->objfind, 1);
5144 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5145 opt->flags.recursive = 1;
5146 opt->flags.tree_in_recursive = 1;
5147 oidset_insert(opt->objfind, &oid);
5148 return 0;
5151 static int diff_opt_anchored(const struct option *opt,
5152 const char *arg, int unset)
5154 struct diff_options *options = opt->value;
5156 BUG_ON_OPT_NEG(unset);
5157 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5158 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5159 options->anchors_alloc);
5160 options->anchors[options->anchors_nr++] = xstrdup(arg);
5161 return 0;
5164 static int diff_opt_binary(const struct option *opt,
5165 const char *arg, int unset)
5167 struct diff_options *options = opt->value;
5169 BUG_ON_OPT_NEG(unset);
5170 BUG_ON_OPT_ARG(arg);
5171 enable_patch_output(&options->output_format);
5172 options->flags.binary = 1;
5173 return 0;
5176 static int diff_opt_break_rewrites(const struct option *opt,
5177 const char *arg, int unset)
5179 int *break_opt = opt->value;
5180 int opt1, opt2;
5182 BUG_ON_OPT_NEG(unset);
5183 if (!arg)
5184 arg = "";
5185 opt1 = parse_rename_score(&arg);
5186 if (*arg == 0)
5187 opt2 = 0;
5188 else if (*arg != '/')
5189 return error(_("%s expects <n>/<m> form"), opt->long_name);
5190 else {
5191 arg++;
5192 opt2 = parse_rename_score(&arg);
5194 if (*arg != 0)
5195 return error(_("%s expects <n>/<m> form"), opt->long_name);
5196 *break_opt = opt1 | (opt2 << 16);
5197 return 0;
5200 static int diff_opt_char(const struct option *opt,
5201 const char *arg, int unset)
5203 char *value = opt->value;
5205 BUG_ON_OPT_NEG(unset);
5206 if (arg[1])
5207 return error(_("%s expects a character, got '%s'"),
5208 opt->long_name, arg);
5209 *value = arg[0];
5210 return 0;
5213 static int diff_opt_color_moved(const struct option *opt,
5214 const char *arg, int unset)
5216 struct diff_options *options = opt->value;
5218 if (unset) {
5219 options->color_moved = COLOR_MOVED_NO;
5220 } else if (!arg) {
5221 if (diff_color_moved_default)
5222 options->color_moved = diff_color_moved_default;
5223 if (options->color_moved == COLOR_MOVED_NO)
5224 options->color_moved = COLOR_MOVED_DEFAULT;
5225 } else {
5226 int cm = parse_color_moved(arg);
5227 if (cm < 0)
5228 return error(_("bad --color-moved argument: %s"), arg);
5229 options->color_moved = cm;
5231 return 0;
5234 static int diff_opt_color_moved_ws(const struct option *opt,
5235 const char *arg, int unset)
5237 struct diff_options *options = opt->value;
5238 unsigned cm;
5240 if (unset) {
5241 options->color_moved_ws_handling = 0;
5242 return 0;
5245 cm = parse_color_moved_ws(arg);
5246 if (cm & COLOR_MOVED_WS_ERROR)
5247 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5248 options->color_moved_ws_handling = cm;
5249 return 0;
5252 static int diff_opt_color_words(const struct option *opt,
5253 const char *arg, int unset)
5255 struct diff_options *options = opt->value;
5257 BUG_ON_OPT_NEG(unset);
5258 options->use_color = 1;
5259 options->word_diff = DIFF_WORDS_COLOR;
5260 options->word_regex = arg;
5261 return 0;
5264 static int diff_opt_compact_summary(const struct option *opt,
5265 const char *arg, int unset)
5267 struct diff_options *options = opt->value;
5269 BUG_ON_OPT_ARG(arg);
5270 if (unset) {
5271 options->flags.stat_with_summary = 0;
5272 } else {
5273 options->flags.stat_with_summary = 1;
5274 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
5275 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5277 return 0;
5280 static int diff_opt_diff_algorithm(const struct option *opt,
5281 const char *arg, int unset)
5283 struct diff_options *options = opt->value;
5285 BUG_ON_OPT_NEG(unset);
5287 if (set_diff_algorithm(options, arg))
5288 return error(_("option diff-algorithm accepts \"myers\", "
5289 "\"minimal\", \"patience\" and \"histogram\""));
5291 options->ignore_driver_algorithm = 1;
5293 return 0;
5296 static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5297 const char *arg, int unset)
5299 struct diff_options *options = opt->value;
5301 BUG_ON_OPT_NEG(unset);
5302 BUG_ON_OPT_ARG(arg);
5304 if (set_diff_algorithm(options, opt->long_name))
5305 BUG("available diff algorithms include \"myers\", "
5306 "\"minimal\", \"patience\" and \"histogram\"");
5308 options->ignore_driver_algorithm = 1;
5310 return 0;
5313 static int diff_opt_dirstat(const struct option *opt,
5314 const char *arg, int unset)
5316 struct diff_options *options = opt->value;
5318 BUG_ON_OPT_NEG(unset);
5319 if (!strcmp(opt->long_name, "cumulative")) {
5320 if (arg)
5321 BUG("how come --cumulative take a value?");
5322 arg = "cumulative";
5323 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5324 parse_dirstat_opt(options, "files");
5325 parse_dirstat_opt(options, arg ? arg : "");
5326 return 0;
5329 static int diff_opt_find_copies(const struct option *opt,
5330 const char *arg, int unset)
5332 struct diff_options *options = opt->value;
5334 BUG_ON_OPT_NEG(unset);
5335 if (!arg)
5336 arg = "";
5337 options->rename_score = parse_rename_score(&arg);
5338 if (*arg != 0)
5339 return error(_("invalid argument to %s"), opt->long_name);
5341 if (options->detect_rename == DIFF_DETECT_COPY)
5342 options->flags.find_copies_harder = 1;
5343 else
5344 options->detect_rename = DIFF_DETECT_COPY;
5346 return 0;
5349 static int diff_opt_find_renames(const struct option *opt,
5350 const char *arg, int unset)
5352 struct diff_options *options = opt->value;
5354 BUG_ON_OPT_NEG(unset);
5355 if (!arg)
5356 arg = "";
5357 options->rename_score = parse_rename_score(&arg);
5358 if (*arg != 0)
5359 return error(_("invalid argument to %s"), opt->long_name);
5361 options->detect_rename = DIFF_DETECT_RENAME;
5362 return 0;
5365 static int diff_opt_follow(const struct option *opt,
5366 const char *arg, int unset)
5368 struct diff_options *options = opt->value;
5370 BUG_ON_OPT_ARG(arg);
5371 if (unset) {
5372 options->flags.follow_renames = 0;
5373 options->flags.default_follow_renames = 0;
5374 } else {
5375 options->flags.follow_renames = 1;
5377 return 0;
5380 static int diff_opt_ignore_submodules(const struct option *opt,
5381 const char *arg, int unset)
5383 struct diff_options *options = opt->value;
5385 BUG_ON_OPT_NEG(unset);
5386 if (!arg)
5387 arg = "all";
5388 options->flags.override_submodule_config = 1;
5389 handle_ignore_submodules_arg(options, arg);
5390 return 0;
5393 static int diff_opt_line_prefix(const struct option *opt,
5394 const char *optarg, int unset)
5396 struct diff_options *options = opt->value;
5398 BUG_ON_OPT_NEG(unset);
5399 options->line_prefix = optarg;
5400 graph_setup_line_prefix(options);
5401 return 0;
5404 static int diff_opt_no_prefix(const struct option *opt,
5405 const char *optarg, int unset)
5407 struct diff_options *options = opt->value;
5409 BUG_ON_OPT_NEG(unset);
5410 BUG_ON_OPT_ARG(optarg);
5411 diff_set_noprefix(options);
5412 return 0;
5415 static int diff_opt_default_prefix(const struct option *opt,
5416 const char *optarg, int unset)
5418 struct diff_options *options = opt->value;
5420 BUG_ON_OPT_NEG(unset);
5421 BUG_ON_OPT_ARG(optarg);
5422 FREE_AND_NULL(diff_src_prefix);
5423 FREE_AND_NULL(diff_dst_prefix);
5424 diff_set_default_prefix(options);
5425 return 0;
5428 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5429 const struct option *opt,
5430 const char *arg, int unset)
5432 struct diff_options *options = opt->value;
5433 char *path;
5435 BUG_ON_OPT_NEG(unset);
5436 path = prefix_filename(ctx->prefix, arg);
5437 options->file = xfopen(path, "w");
5438 options->close_file = 1;
5439 if (options->use_color != GIT_COLOR_ALWAYS)
5440 options->use_color = GIT_COLOR_NEVER;
5441 free(path);
5442 return 0;
5445 static int diff_opt_patience(const struct option *opt,
5446 const char *arg, int unset)
5448 struct diff_options *options = opt->value;
5449 int i;
5451 BUG_ON_OPT_NEG(unset);
5452 BUG_ON_OPT_ARG(arg);
5454 * Both --patience and --anchored use PATIENCE_DIFF
5455 * internally, so remove any anchors previously
5456 * specified.
5458 for (i = 0; i < options->anchors_nr; i++)
5459 free(options->anchors[i]);
5460 options->anchors_nr = 0;
5461 options->ignore_driver_algorithm = 1;
5463 return set_diff_algorithm(options, "patience");
5466 static int diff_opt_ignore_regex(const struct option *opt,
5467 const char *arg, int unset)
5469 struct diff_options *options = opt->value;
5470 regex_t *regex;
5472 BUG_ON_OPT_NEG(unset);
5474 regex = xmalloc(sizeof(*regex));
5475 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE)) {
5476 free(regex);
5477 return error(_("invalid regex given to -I: '%s'"), arg);
5480 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5481 options->ignore_regex_alloc);
5482 options->ignore_regex[options->ignore_regex_nr++] = regex;
5483 return 0;
5486 static int diff_opt_pickaxe_regex(const struct option *opt,
5487 const char *arg, int unset)
5489 struct diff_options *options = opt->value;
5491 BUG_ON_OPT_NEG(unset);
5492 options->pickaxe = arg;
5493 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5494 return 0;
5497 static int diff_opt_pickaxe_string(const struct option *opt,
5498 const char *arg, int unset)
5500 struct diff_options *options = opt->value;
5502 BUG_ON_OPT_NEG(unset);
5503 options->pickaxe = arg;
5504 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5505 return 0;
5508 static int diff_opt_relative(const struct option *opt,
5509 const char *arg, int unset)
5511 struct diff_options *options = opt->value;
5513 options->flags.relative_name = !unset;
5514 if (arg)
5515 options->prefix = arg;
5516 return 0;
5519 static int diff_opt_submodule(const struct option *opt,
5520 const char *arg, int unset)
5522 struct diff_options *options = opt->value;
5524 BUG_ON_OPT_NEG(unset);
5525 if (!arg)
5526 arg = "log";
5527 if (parse_submodule_params(options, arg))
5528 return error(_("failed to parse --submodule option parameter: '%s'"),
5529 arg);
5530 return 0;
5533 static int diff_opt_textconv(const struct option *opt,
5534 const char *arg, int unset)
5536 struct diff_options *options = opt->value;
5538 BUG_ON_OPT_ARG(arg);
5539 if (unset) {
5540 options->flags.allow_textconv = 0;
5541 } else {
5542 options->flags.allow_textconv = 1;
5543 options->flags.textconv_set_via_cmdline = 1;
5545 return 0;
5548 static int diff_opt_unified(const struct option *opt,
5549 const char *arg, int unset)
5551 struct diff_options *options = opt->value;
5552 char *s;
5554 BUG_ON_OPT_NEG(unset);
5556 if (arg) {
5557 options->context = strtol(arg, &s, 10);
5558 if (*s)
5559 return error(_("%s expects a numerical value"), "--unified");
5561 enable_patch_output(&options->output_format);
5563 return 0;
5566 static int diff_opt_word_diff(const struct option *opt,
5567 const char *arg, int unset)
5569 struct diff_options *options = opt->value;
5571 BUG_ON_OPT_NEG(unset);
5572 if (arg) {
5573 if (!strcmp(arg, "plain"))
5574 options->word_diff = DIFF_WORDS_PLAIN;
5575 else if (!strcmp(arg, "color")) {
5576 options->use_color = 1;
5577 options->word_diff = DIFF_WORDS_COLOR;
5579 else if (!strcmp(arg, "porcelain"))
5580 options->word_diff = DIFF_WORDS_PORCELAIN;
5581 else if (!strcmp(arg, "none"))
5582 options->word_diff = DIFF_WORDS_NONE;
5583 else
5584 return error(_("bad --word-diff argument: %s"), arg);
5585 } else {
5586 if (options->word_diff == DIFF_WORDS_NONE)
5587 options->word_diff = DIFF_WORDS_PLAIN;
5589 return 0;
5592 static int diff_opt_word_diff_regex(const struct option *opt,
5593 const char *arg, int unset)
5595 struct diff_options *options = opt->value;
5597 BUG_ON_OPT_NEG(unset);
5598 if (options->word_diff == DIFF_WORDS_NONE)
5599 options->word_diff = DIFF_WORDS_PLAIN;
5600 options->word_regex = arg;
5601 return 0;
5604 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5606 struct diff_options *options = opt->value;
5608 BUG_ON_OPT_NEG(unset);
5609 if (!strcmp(opt->long_name, "skip-to"))
5610 options->skip_instead_of_rotate = 1;
5611 else
5612 options->skip_instead_of_rotate = 0;
5613 options->rotate_to = arg;
5614 return 0;
5618 * Consider adding new flags to __git_diff_common_options
5619 * in contrib/completion/git-completion.bash
5621 struct option *add_diff_options(const struct option *opts,
5622 struct diff_options *options)
5624 struct option parseopts[] = {
5625 OPT_GROUP(N_("Diff output format options")),
5626 OPT_BITOP('p', "patch", &options->output_format,
5627 N_("generate patch"),
5628 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5629 OPT_SET_INT('s', "no-patch", &options->output_format,
5630 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
5631 OPT_BITOP('u', NULL, &options->output_format,
5632 N_("generate patch"),
5633 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5634 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5635 N_("generate diffs with <n> lines context"),
5636 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5637 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5638 N_("generate diffs with <n> lines context")),
5639 OPT_BITOP(0, "raw", &options->output_format,
5640 N_("generate the diff in raw format"),
5641 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
5642 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5643 N_("synonym for '-p --raw'"),
5644 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5645 DIFF_FORMAT_NO_OUTPUT),
5646 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5647 N_("synonym for '-p --stat'"),
5648 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5649 DIFF_FORMAT_NO_OUTPUT),
5650 OPT_BITOP(0, "numstat", &options->output_format,
5651 N_("machine friendly --stat"),
5652 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5653 OPT_BITOP(0, "shortstat", &options->output_format,
5654 N_("output only the last line of --stat"),
5655 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
5656 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1>,<param2>..."),
5657 N_("output the distribution of relative amount of changes for each sub-directory"),
5658 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5659 diff_opt_dirstat),
5660 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5661 N_("synonym for --dirstat=cumulative"),
5662 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5663 diff_opt_dirstat),
5664 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1>,<param2>..."),
5665 N_("synonym for --dirstat=files,<param1>,<param2>..."),
5666 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5667 diff_opt_dirstat),
5668 OPT_BIT_F(0, "check", &options->output_format,
5669 N_("warn if changes introduce conflict markers or whitespace errors"),
5670 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5671 OPT_BITOP(0, "summary", &options->output_format,
5672 N_("condensed summary such as creations, renames and mode changes"),
5673 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
5674 OPT_BIT_F(0, "name-only", &options->output_format,
5675 N_("show only names of changed files"),
5676 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5677 OPT_BIT_F(0, "name-status", &options->output_format,
5678 N_("show only names and status of changed files"),
5679 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5680 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5681 N_("generate diffstat"),
5682 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5683 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5684 N_("generate diffstat with a given width"),
5685 PARSE_OPT_NONEG, diff_opt_stat),
5686 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5687 N_("generate diffstat with a given name width"),
5688 PARSE_OPT_NONEG, diff_opt_stat),
5689 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5690 N_("generate diffstat with a given graph width"),
5691 PARSE_OPT_NONEG, diff_opt_stat),
5692 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5693 N_("generate diffstat with limited lines"),
5694 PARSE_OPT_NONEG, diff_opt_stat),
5695 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5696 N_("generate compact summary in diffstat"),
5697 PARSE_OPT_NOARG, diff_opt_compact_summary),
5698 OPT_CALLBACK_F(0, "binary", options, NULL,
5699 N_("output a binary diff that can be applied"),
5700 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5701 OPT_BOOL(0, "full-index", &options->flags.full_index,
5702 N_("show full pre- and post-image object names on the \"index\" lines")),
5703 OPT_COLOR_FLAG(0, "color", &options->use_color,
5704 N_("show colored diff")),
5705 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5706 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5707 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5708 OPT_SET_INT('z', NULL, &options->line_termination,
5709 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5711 OPT__ABBREV(&options->abbrev),
5712 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5713 N_("show the given source prefix instead of \"a/\""),
5714 PARSE_OPT_NONEG),
5715 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5716 N_("show the given destination prefix instead of \"b/\""),
5717 PARSE_OPT_NONEG),
5718 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5719 N_("prepend an additional prefix to every line of output"),
5720 PARSE_OPT_NONEG, diff_opt_line_prefix),
5721 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5722 N_("do not show any source or destination prefix"),
5723 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5724 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5725 N_("use default prefixes a/ and b/"),
5726 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
5727 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5728 N_("show context between diff hunks up to the specified number of lines"),
5729 PARSE_OPT_NONEG),
5730 OPT_CALLBACK_F(0, "output-indicator-new",
5731 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5732 N_("<char>"),
5733 N_("specify the character to indicate a new line instead of '+'"),
5734 PARSE_OPT_NONEG, diff_opt_char),
5735 OPT_CALLBACK_F(0, "output-indicator-old",
5736 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5737 N_("<char>"),
5738 N_("specify the character to indicate an old line instead of '-'"),
5739 PARSE_OPT_NONEG, diff_opt_char),
5740 OPT_CALLBACK_F(0, "output-indicator-context",
5741 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5742 N_("<char>"),
5743 N_("specify the character to indicate a context instead of ' '"),
5744 PARSE_OPT_NONEG, diff_opt_char),
5746 OPT_GROUP(N_("Diff rename options")),
5747 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5748 N_("break complete rewrite changes into pairs of delete and create"),
5749 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5750 diff_opt_break_rewrites),
5751 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5752 N_("detect renames"),
5753 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5754 diff_opt_find_renames),
5755 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5756 N_("omit the preimage for deletes"),
5757 1, PARSE_OPT_NONEG),
5758 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5759 N_("detect copies"),
5760 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5761 diff_opt_find_copies),
5762 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5763 N_("use unmodified files as source to find copies")),
5764 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5765 N_("disable rename detection"),
5766 0, PARSE_OPT_NONEG),
5767 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5768 N_("use empty blobs as rename source")),
5769 OPT_CALLBACK_F(0, "follow", options, NULL,
5770 N_("continue listing the history of a file beyond renames"),
5771 PARSE_OPT_NOARG, diff_opt_follow),
5772 OPT_INTEGER('l', NULL, &options->rename_limit,
5773 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5775 OPT_GROUP(N_("Diff algorithm options")),
5776 OPT_CALLBACK_F(0, "minimal", options, NULL,
5777 N_("produce the smallest possible diff"),
5778 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5779 diff_opt_diff_algorithm_no_arg),
5780 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5781 N_("ignore whitespace when comparing lines"),
5782 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5783 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5784 N_("ignore changes in amount of whitespace"),
5785 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5786 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5787 N_("ignore changes in whitespace at EOL"),
5788 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5789 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5790 N_("ignore carrier-return at the end of line"),
5791 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5792 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5793 N_("ignore changes whose lines are all blank"),
5794 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5795 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5796 N_("ignore changes whose all lines match <regex>"),
5797 0, diff_opt_ignore_regex),
5798 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5799 N_("heuristic to shift diff hunk boundaries for easy reading"),
5800 XDF_INDENT_HEURISTIC),
5801 OPT_CALLBACK_F(0, "patience", options, NULL,
5802 N_("generate diff using the \"patience diff\" algorithm"),
5803 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5804 diff_opt_patience),
5805 OPT_CALLBACK_F(0, "histogram", options, NULL,
5806 N_("generate diff using the \"histogram diff\" algorithm"),
5807 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5808 diff_opt_diff_algorithm_no_arg),
5809 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5810 N_("choose a diff algorithm"),
5811 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5812 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5813 N_("generate diff using the \"anchored diff\" algorithm"),
5814 PARSE_OPT_NONEG, diff_opt_anchored),
5815 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5816 N_("show word diff, using <mode> to delimit changed words"),
5817 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5818 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5819 N_("use <regex> to decide what a word is"),
5820 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5821 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5822 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5823 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5824 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5825 N_("moved lines of code are colored differently"),
5826 PARSE_OPT_OPTARG, diff_opt_color_moved),
5827 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5828 N_("how white spaces are ignored in --color-moved"),
5829 0, diff_opt_color_moved_ws),
5831 OPT_GROUP(N_("Other diff options")),
5832 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5833 N_("when run from subdir, exclude changes outside and show relative paths"),
5834 PARSE_OPT_OPTARG,
5835 diff_opt_relative),
5836 OPT_BOOL('a', "text", &options->flags.text,
5837 N_("treat all files as text")),
5838 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5839 N_("swap two inputs, reverse the diff")),
5840 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5841 N_("exit with 1 if there were differences, 0 otherwise")),
5842 OPT_BOOL(0, "quiet", &options->flags.quick,
5843 N_("disable all output of the program")),
5844 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5845 N_("allow an external diff helper to be executed")),
5846 OPT_CALLBACK_F(0, "textconv", options, NULL,
5847 N_("run external text conversion filters when comparing binary files"),
5848 PARSE_OPT_NOARG, diff_opt_textconv),
5849 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5850 N_("ignore changes to submodules in the diff generation"),
5851 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5852 diff_opt_ignore_submodules),
5853 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5854 N_("specify how differences in submodules are shown"),
5855 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5856 diff_opt_submodule),
5857 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5858 N_("hide 'git add -N' entries from the index"),
5859 1, PARSE_OPT_NONEG),
5860 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5861 N_("treat 'git add -N' entries as real in the index"),
5862 0, PARSE_OPT_NONEG),
5863 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5864 N_("look for differences that change the number of occurrences of the specified string"),
5865 0, diff_opt_pickaxe_string),
5866 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5867 N_("look for differences that change the number of occurrences of the specified regex"),
5868 0, diff_opt_pickaxe_regex),
5869 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5870 N_("show all changes in the changeset with -S or -G"),
5871 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5872 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5873 N_("treat <string> in -S as extended POSIX regular expression"),
5874 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5875 OPT_FILENAME('O', NULL, &options->orderfile,
5876 N_("control the order in which files appear in the output")),
5877 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5878 N_("show the change in the specified path first"),
5879 PARSE_OPT_NONEG, diff_opt_rotate_to),
5880 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5881 N_("skip the output to the specified path"),
5882 PARSE_OPT_NONEG, diff_opt_rotate_to),
5883 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5884 N_("look for differences that change the number of occurrences of the specified object"),
5885 PARSE_OPT_NONEG, diff_opt_find_object),
5886 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5887 N_("select files by diff type"),
5888 PARSE_OPT_NONEG, diff_opt_diff_filter),
5889 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5890 N_("output to a specific file"),
5891 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5893 OPT_END()
5896 return parse_options_concat(opts, parseopts);
5899 int diff_opt_parse(struct diff_options *options,
5900 const char **av, int ac, const char *prefix)
5902 struct option no_options[] = { OPT_END() };
5903 struct option *parseopts = add_diff_options(no_options, options);
5905 if (!prefix)
5906 prefix = "";
5908 ac = parse_options(ac, av, prefix, parseopts, NULL,
5909 PARSE_OPT_KEEP_DASHDASH |
5910 PARSE_OPT_KEEP_UNKNOWN_OPT |
5911 PARSE_OPT_NO_INTERNAL_HELP |
5912 PARSE_OPT_ONE_SHOT |
5913 PARSE_OPT_STOP_AT_NON_OPTION);
5914 free(parseopts);
5916 return ac;
5919 int parse_rename_score(const char **cp_p)
5921 unsigned long num, scale;
5922 int ch, dot;
5923 const char *cp = *cp_p;
5925 num = 0;
5926 scale = 1;
5927 dot = 0;
5928 for (;;) {
5929 ch = *cp;
5930 if ( !dot && ch == '.' ) {
5931 scale = 1;
5932 dot = 1;
5933 } else if ( ch == '%' ) {
5934 scale = dot ? scale*100 : 100;
5935 cp++; /* % is always at the end */
5936 break;
5937 } else if ( ch >= '0' && ch <= '9' ) {
5938 if ( scale < 100000 ) {
5939 scale *= 10;
5940 num = (num*10) + (ch-'0');
5942 } else {
5943 break;
5945 cp++;
5947 *cp_p = cp;
5949 /* user says num divided by scale and we say internally that
5950 * is MAX_SCORE * num / scale.
5952 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5955 struct diff_queue_struct diff_queued_diff;
5957 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5959 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5960 queue->queue[queue->nr++] = dp;
5963 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5964 struct diff_filespec *one,
5965 struct diff_filespec *two)
5967 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5968 dp->one = one;
5969 dp->two = two;
5970 if (queue)
5971 diff_q(queue, dp);
5972 return dp;
5975 void diff_free_filepair(struct diff_filepair *p)
5977 free_filespec(p->one);
5978 free_filespec(p->two);
5979 free(p);
5982 void diff_queue_init(struct diff_queue_struct *q)
5984 struct diff_queue_struct blank = DIFF_QUEUE_INIT;
5985 memcpy(q, &blank, sizeof(*q));
5988 void diff_queue_clear(struct diff_queue_struct *q)
5990 for (int i = 0; i < q->nr; i++)
5991 diff_free_filepair(q->queue[i]);
5992 free(q->queue);
5993 diff_queue_init(q);
5996 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5998 int abblen;
5999 const char *abbrev;
6001 /* Do we want all 40 hex characters? */
6002 if (len == the_hash_algo->hexsz)
6003 return oid_to_hex(oid);
6005 /* An abbreviated value is fine, possibly followed by an ellipsis. */
6006 abbrev = diff_abbrev_oid(oid, len);
6008 if (!print_sha1_ellipsis())
6009 return abbrev;
6011 abblen = strlen(abbrev);
6014 * In well-behaved cases, where the abbreviated result is the
6015 * same as the requested length, append three dots after the
6016 * abbreviation (hence the whole logic is limited to the case
6017 * where abblen < 37); when the actual abbreviated result is a
6018 * bit longer than the requested length, we reduce the number
6019 * of dots so that they match the well-behaved ones. However,
6020 * if the actual abbreviation is longer than the requested
6021 * length by more than three, we give up on aligning, and add
6022 * three dots anyway, to indicate that the output is not the
6023 * full object name. Yes, this may be suboptimal, but this
6024 * appears only in "diff --raw --abbrev" output and it is not
6025 * worth the effort to change it now. Note that this would
6026 * likely to work fine when the automatic sizing of default
6027 * abbreviation length is used--we would be fed -1 in "len" in
6028 * that case, and will end up always appending three-dots, but
6029 * the automatic sizing is supposed to give abblen that ensures
6030 * uniqueness across all objects (statistically speaking).
6032 if (abblen < the_hash_algo->hexsz - 3) {
6033 static char hex[GIT_MAX_HEXSZ + 1];
6034 if (len < abblen && abblen <= len + 2)
6035 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6036 else
6037 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6038 return hex;
6041 return oid_to_hex(oid);
6044 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6046 int line_termination = opt->line_termination;
6047 int inter_name_termination = line_termination ? '\t' : '\0';
6049 fprintf(opt->file, "%s", diff_line_prefix(opt));
6050 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
6051 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
6052 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
6053 fprintf(opt->file, "%s ",
6054 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6056 if (p->score) {
6057 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
6058 inter_name_termination);
6059 } else {
6060 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6063 if (p->status == DIFF_STATUS_COPIED ||
6064 p->status == DIFF_STATUS_RENAMED) {
6065 const char *name_a, *name_b;
6066 name_a = p->one->path;
6067 name_b = p->two->path;
6068 strip_prefix(opt->prefix_length, &name_a, &name_b);
6069 write_name_quoted(name_a, opt->file, inter_name_termination);
6070 write_name_quoted(name_b, opt->file, line_termination);
6071 } else {
6072 const char *name_a, *name_b;
6073 name_a = p->one->mode ? p->one->path : p->two->path;
6074 name_b = NULL;
6075 strip_prefix(opt->prefix_length, &name_a, &name_b);
6076 write_name_quoted(name_a, opt->file, line_termination);
6080 int diff_unmodified_pair(struct diff_filepair *p)
6082 /* This function is written stricter than necessary to support
6083 * the currently implemented transformers, but the idea is to
6084 * let transformers to produce diff_filepairs any way they want,
6085 * and filter and clean them up here before producing the output.
6087 struct diff_filespec *one = p->one, *two = p->two;
6089 if (DIFF_PAIR_UNMERGED(p))
6090 return 0; /* unmerged is interesting */
6092 /* deletion, addition, mode or type change
6093 * and rename are all interesting.
6095 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
6096 DIFF_PAIR_MODE_CHANGED(p) ||
6097 strcmp(one->path, two->path))
6098 return 0;
6100 /* both are valid and point at the same path. that is, we are
6101 * dealing with a change.
6103 if (one->oid_valid && two->oid_valid &&
6104 oideq(&one->oid, &two->oid) &&
6105 !one->dirty_submodule && !two->dirty_submodule)
6106 return 1; /* no change */
6107 if (!one->oid_valid && !two->oid_valid)
6108 return 1; /* both look at the same file on the filesystem. */
6109 return 0;
6112 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6114 int include_conflict_headers =
6115 (additional_headers(o, p->one->path) &&
6116 !o->pickaxe_opts &&
6117 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6120 * Check if we can return early without showing a diff. Note that
6121 * diff_filepair only stores {oid, path, mode, is_valid}
6122 * information for each path, and thus diff_unmodified_pair() only
6123 * considers those bits of info. However, we do not want pairs
6124 * created by create_filepairs_for_header_only_notifications()
6125 * (which always look like unmodified pairs) to be ignored, so
6126 * return early if both p is unmodified AND we don't want to
6127 * include_conflict_headers.
6129 if (diff_unmodified_pair(p) && !include_conflict_headers)
6130 return;
6132 /* Actually, we can also return early to avoid showing tree diffs */
6133 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6134 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6135 return;
6137 run_diff(p, o);
6140 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6141 struct diffstat_t *diffstat)
6143 if (diff_unmodified_pair(p))
6144 return;
6146 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6147 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6148 return; /* no useful stat for tree diffs */
6150 run_diffstat(p, o, diffstat);
6153 static void diff_flush_checkdiff(struct diff_filepair *p,
6154 struct diff_options *o)
6156 if (diff_unmodified_pair(p))
6157 return;
6159 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6160 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6161 return; /* nothing to check in tree diffs */
6163 run_checkdiff(p, o);
6166 int diff_queue_is_empty(struct diff_options *o)
6168 struct diff_queue_struct *q = &diff_queued_diff;
6169 int i;
6170 int include_conflict_headers =
6171 (o->additional_path_headers &&
6172 strmap_get_size(o->additional_path_headers) &&
6173 !o->pickaxe_opts &&
6174 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6176 if (include_conflict_headers)
6177 return 0;
6179 for (i = 0; i < q->nr; i++)
6180 if (!diff_unmodified_pair(q->queue[i]))
6181 return 0;
6182 return 1;
6185 #if DIFF_DEBUG
6186 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6188 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6189 x, one ? one : "",
6190 s->path,
6191 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6192 s->mode,
6193 s->oid_valid ? oid_to_hex(&s->oid) : "");
6194 fprintf(stderr, "queue[%d] %s size %lu\n",
6195 x, one ? one : "",
6196 s->size);
6199 void diff_debug_filepair(const struct diff_filepair *p, int i)
6201 diff_debug_filespec(p->one, i, "one");
6202 diff_debug_filespec(p->two, i, "two");
6203 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6204 p->score, p->status ? p->status : '?',
6205 p->one->rename_used, p->broken_pair);
6208 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6210 int i;
6211 if (msg)
6212 fprintf(stderr, "%s\n", msg);
6213 fprintf(stderr, "q->nr = %d\n", q->nr);
6214 for (i = 0; i < q->nr; i++) {
6215 struct diff_filepair *p = q->queue[i];
6216 diff_debug_filepair(p, i);
6219 #endif
6221 static void diff_resolve_rename_copy(void)
6223 int i;
6224 struct diff_filepair *p;
6225 struct diff_queue_struct *q = &diff_queued_diff;
6227 diff_debug_queue("resolve-rename-copy", q);
6229 for (i = 0; i < q->nr; i++) {
6230 p = q->queue[i];
6231 p->status = 0; /* undecided */
6232 if (DIFF_PAIR_UNMERGED(p))
6233 p->status = DIFF_STATUS_UNMERGED;
6234 else if (!DIFF_FILE_VALID(p->one))
6235 p->status = DIFF_STATUS_ADDED;
6236 else if (!DIFF_FILE_VALID(p->two))
6237 p->status = DIFF_STATUS_DELETED;
6238 else if (DIFF_PAIR_TYPE_CHANGED(p))
6239 p->status = DIFF_STATUS_TYPE_CHANGED;
6241 /* from this point on, we are dealing with a pair
6242 * whose both sides are valid and of the same type, i.e.
6243 * either in-place edit or rename/copy edit.
6245 else if (DIFF_PAIR_RENAME(p)) {
6247 * A rename might have re-connected a broken
6248 * pair up, causing the pathnames to be the
6249 * same again. If so, that's not a rename at
6250 * all, just a modification..
6252 * Otherwise, see if this source was used for
6253 * multiple renames, in which case we decrement
6254 * the count, and call it a copy.
6256 if (!strcmp(p->one->path, p->two->path))
6257 p->status = DIFF_STATUS_MODIFIED;
6258 else if (--p->one->rename_used > 0)
6259 p->status = DIFF_STATUS_COPIED;
6260 else
6261 p->status = DIFF_STATUS_RENAMED;
6263 else if (!oideq(&p->one->oid, &p->two->oid) ||
6264 p->one->mode != p->two->mode ||
6265 p->one->dirty_submodule ||
6266 p->two->dirty_submodule ||
6267 is_null_oid(&p->one->oid))
6268 p->status = DIFF_STATUS_MODIFIED;
6269 else {
6270 /* This is a "no-change" entry and should not
6271 * happen anymore, but prepare for broken callers.
6273 error("feeding unmodified %s to diffcore",
6274 p->one->path);
6275 p->status = DIFF_STATUS_UNKNOWN;
6278 diff_debug_queue("resolve-rename-copy done", q);
6281 static int check_pair_status(struct diff_filepair *p)
6283 switch (p->status) {
6284 case DIFF_STATUS_UNKNOWN:
6285 return 0;
6286 case 0:
6287 die("internal error in diff-resolve-rename-copy");
6288 default:
6289 return 1;
6293 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6295 int fmt = opt->output_format;
6297 if (fmt & DIFF_FORMAT_CHECKDIFF)
6298 diff_flush_checkdiff(p, opt);
6299 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6300 diff_flush_raw(p, opt);
6301 else if (fmt & DIFF_FORMAT_NAME) {
6302 const char *name_a, *name_b;
6303 name_a = p->two->path;
6304 name_b = NULL;
6305 strip_prefix(opt->prefix_length, &name_a, &name_b);
6306 fprintf(opt->file, "%s", diff_line_prefix(opt));
6307 write_name_quoted(name_a, opt->file, opt->line_termination);
6310 opt->found_changes = 1;
6313 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6315 struct strbuf sb = STRBUF_INIT;
6316 if (fs->mode)
6317 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6318 else
6319 strbuf_addf(&sb, " %s ", newdelete);
6321 quote_c_style(fs->path, &sb, NULL, 0);
6322 strbuf_addch(&sb, '\n');
6323 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6324 sb.buf, sb.len, 0);
6325 strbuf_release(&sb);
6328 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6329 int show_name)
6331 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6332 struct strbuf sb = STRBUF_INIT;
6333 strbuf_addf(&sb, " mode change %06o => %06o",
6334 p->one->mode, p->two->mode);
6335 if (show_name) {
6336 strbuf_addch(&sb, ' ');
6337 quote_c_style(p->two->path, &sb, NULL, 0);
6339 strbuf_addch(&sb, '\n');
6340 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6341 sb.buf, sb.len, 0);
6342 strbuf_release(&sb);
6346 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6347 struct diff_filepair *p)
6349 struct strbuf sb = STRBUF_INIT;
6350 struct strbuf names = STRBUF_INIT;
6352 pprint_rename(&names, p->one->path, p->two->path);
6353 strbuf_addf(&sb, " %s %s (%d%%)\n",
6354 renamecopy, names.buf, similarity_index(p));
6355 strbuf_release(&names);
6356 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6357 sb.buf, sb.len, 0);
6358 show_mode_change(opt, p, 0);
6359 strbuf_release(&sb);
6362 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6364 switch(p->status) {
6365 case DIFF_STATUS_DELETED:
6366 show_file_mode_name(opt, "delete", p->one);
6367 break;
6368 case DIFF_STATUS_ADDED:
6369 show_file_mode_name(opt, "create", p->two);
6370 break;
6371 case DIFF_STATUS_COPIED:
6372 show_rename_copy(opt, "copy", p);
6373 break;
6374 case DIFF_STATUS_RENAMED:
6375 show_rename_copy(opt, "rename", p);
6376 break;
6377 default:
6378 if (p->score) {
6379 struct strbuf sb = STRBUF_INIT;
6380 strbuf_addstr(&sb, " rewrite ");
6381 quote_c_style(p->two->path, &sb, NULL, 0);
6382 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6383 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6384 sb.buf, sb.len, 0);
6385 strbuf_release(&sb);
6387 show_mode_change(opt, p, !p->score);
6388 break;
6392 struct patch_id_t {
6393 git_hash_ctx *ctx;
6394 int patchlen;
6397 static int remove_space(char *line, int len)
6399 int i;
6400 char *dst = line;
6401 unsigned char c;
6403 for (i = 0; i < len; i++)
6404 if (!isspace((c = line[i])))
6405 *dst++ = c;
6407 return dst - line;
6410 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6412 unsigned char hash[GIT_MAX_RAWSZ];
6413 unsigned short carry = 0;
6414 int i;
6416 the_hash_algo->final_fn(hash, ctx);
6417 the_hash_algo->init_fn(ctx);
6418 /* 20-byte sum, with carry */
6419 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6420 carry += result->hash[i] + hash[i];
6421 result->hash[i] = carry;
6422 carry >>= 8;
6426 static int patch_id_consume(void *priv, char *line, unsigned long len)
6428 struct patch_id_t *data = priv;
6429 int new_len;
6431 if (len > 12 && starts_with(line, "\\ "))
6432 return 0;
6433 new_len = remove_space(line, len);
6435 the_hash_algo->update_fn(data->ctx, line, new_len);
6436 data->patchlen += new_len;
6437 return 0;
6440 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6442 the_hash_algo->update_fn(ctx, str, strlen(str));
6445 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6447 /* large enough for 2^32 in octal */
6448 char buf[12];
6449 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6450 the_hash_algo->update_fn(ctx, buf, len);
6453 /* returns 0 upon success, and writes result into oid */
6454 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6456 struct diff_queue_struct *q = &diff_queued_diff;
6457 int i;
6458 git_hash_ctx ctx;
6459 struct patch_id_t data;
6461 the_hash_algo->init_fn(&ctx);
6462 memset(&data, 0, sizeof(struct patch_id_t));
6463 data.ctx = &ctx;
6464 oidclr(oid, the_repository->hash_algo);
6466 for (i = 0; i < q->nr; i++) {
6467 xpparam_t xpp;
6468 xdemitconf_t xecfg;
6469 mmfile_t mf1, mf2;
6470 struct diff_filepair *p = q->queue[i];
6471 int len1, len2;
6473 memset(&xpp, 0, sizeof(xpp));
6474 memset(&xecfg, 0, sizeof(xecfg));
6475 if (p->status == 0)
6476 return error("internal diff status error");
6477 if (p->status == DIFF_STATUS_UNKNOWN)
6478 continue;
6479 if (diff_unmodified_pair(p))
6480 continue;
6481 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6482 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6483 continue;
6484 if (DIFF_PAIR_UNMERGED(p))
6485 continue;
6487 diff_fill_oid_info(p->one, options->repo->index);
6488 diff_fill_oid_info(p->two, options->repo->index);
6490 len1 = remove_space(p->one->path, strlen(p->one->path));
6491 len2 = remove_space(p->two->path, strlen(p->two->path));
6492 patch_id_add_string(&ctx, "diff--git");
6493 patch_id_add_string(&ctx, "a/");
6494 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6495 patch_id_add_string(&ctx, "b/");
6496 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6498 if (p->one->mode == 0) {
6499 patch_id_add_string(&ctx, "newfilemode");
6500 patch_id_add_mode(&ctx, p->two->mode);
6501 } else if (p->two->mode == 0) {
6502 patch_id_add_string(&ctx, "deletedfilemode");
6503 patch_id_add_mode(&ctx, p->one->mode);
6504 } else if (p->one->mode != p->two->mode) {
6505 patch_id_add_string(&ctx, "oldmode");
6506 patch_id_add_mode(&ctx, p->one->mode);
6507 patch_id_add_string(&ctx, "newmode");
6508 patch_id_add_mode(&ctx, p->two->mode);
6511 if (diff_header_only) {
6512 /* don't do anything since we're only populating header info */
6513 } else if (diff_filespec_is_binary(options->repo, p->one) ||
6514 diff_filespec_is_binary(options->repo, p->two)) {
6515 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6516 the_hash_algo->hexsz);
6517 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6518 the_hash_algo->hexsz);
6519 } else {
6520 if (p->one->mode == 0) {
6521 patch_id_add_string(&ctx, "---/dev/null");
6522 patch_id_add_string(&ctx, "+++b/");
6523 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6524 } else if (p->two->mode == 0) {
6525 patch_id_add_string(&ctx, "---a/");
6526 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6527 patch_id_add_string(&ctx, "+++/dev/null");
6528 } else {
6529 patch_id_add_string(&ctx, "---a/");
6530 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6531 patch_id_add_string(&ctx, "+++b/");
6532 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6535 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6536 fill_mmfile(options->repo, &mf2, p->two) < 0)
6537 return error("unable to read files to diff");
6538 xpp.flags = 0;
6539 xecfg.ctxlen = 3;
6540 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6541 if (xdi_diff_outf(&mf1, &mf2, NULL,
6542 patch_id_consume, &data, &xpp, &xecfg))
6543 return error("unable to generate patch-id diff for %s",
6544 p->one->path);
6546 flush_one_hunk(oid, &ctx);
6549 return 0;
6552 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6554 struct diff_queue_struct *q = &diff_queued_diff;
6555 int result = diff_get_patch_id(options, oid, diff_header_only);
6557 diff_queue_clear(q);
6559 return result;
6562 static int is_summary_empty(const struct diff_queue_struct *q)
6564 int i;
6566 for (i = 0; i < q->nr; i++) {
6567 const struct diff_filepair *p = q->queue[i];
6569 switch (p->status) {
6570 case DIFF_STATUS_DELETED:
6571 case DIFF_STATUS_ADDED:
6572 case DIFF_STATUS_COPIED:
6573 case DIFF_STATUS_RENAMED:
6574 return 0;
6575 default:
6576 if (p->score)
6577 return 0;
6578 if (p->one->mode && p->two->mode &&
6579 p->one->mode != p->two->mode)
6580 return 0;
6581 break;
6584 return 1;
6587 static const char rename_limit_warning[] =
6588 N_("exhaustive rename detection was skipped due to too many files.");
6590 static const char degrade_cc_to_c_warning[] =
6591 N_("only found copies from modified paths due to too many files.");
6593 static const char rename_limit_advice[] =
6594 N_("you may want to set your %s variable to at least "
6595 "%d and retry the command.");
6597 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6599 fflush(stdout);
6600 if (degraded_cc)
6601 warning(_(degrade_cc_to_c_warning));
6602 else if (needed)
6603 warning(_(rename_limit_warning));
6604 else
6605 return;
6606 if (0 < needed)
6607 warning(_(rename_limit_advice), varname, needed);
6610 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6612 struct strset present;
6613 struct diff_queue_struct *q = &diff_queued_diff;
6614 struct hashmap_iter iter;
6615 struct strmap_entry *e;
6616 int i;
6618 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6621 * Find out which paths exist in diff_queued_diff, preferring
6622 * one->path for any pair that has multiple paths.
6624 for (i = 0; i < q->nr; i++) {
6625 struct diff_filepair *p = q->queue[i];
6626 char *path = p->one->path ? p->one->path : p->two->path;
6628 if (strmap_contains(o->additional_path_headers, path))
6629 strset_add(&present, path);
6633 * Loop over paths in additional_path_headers; for each NOT already
6634 * in diff_queued_diff, create a synthetic filepair and insert that
6635 * into diff_queued_diff.
6637 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6638 if (!strset_contains(&present, e->key)) {
6639 struct diff_filespec *one, *two;
6640 struct diff_filepair *p;
6642 one = alloc_filespec(e->key);
6643 two = alloc_filespec(e->key);
6644 fill_filespec(one, null_oid(), 0, 0);
6645 fill_filespec(two, null_oid(), 0, 0);
6646 p = diff_queue(q, one, two);
6647 p->status = DIFF_STATUS_MODIFIED;
6651 /* Re-sort the filepairs */
6652 diffcore_fix_diff_index();
6654 /* Cleanup */
6655 strset_clear(&present);
6658 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6660 int i;
6661 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6662 struct diff_queue_struct *q = &diff_queued_diff;
6664 if (WSEH_NEW & WS_RULE_MASK)
6665 BUG("WS rules bit mask overlaps with diff symbol flags");
6667 if (o->color_moved)
6668 o->emitted_symbols = &esm;
6670 if (o->additional_path_headers)
6671 create_filepairs_for_header_only_notifications(o);
6673 for (i = 0; i < q->nr; i++) {
6674 struct diff_filepair *p = q->queue[i];
6675 if (check_pair_status(p))
6676 diff_flush_patch(p, o);
6679 if (o->emitted_symbols) {
6680 if (o->color_moved) {
6681 struct mem_pool entry_pool;
6682 struct moved_entry_list *entry_list;
6684 mem_pool_init(&entry_pool, 1024 * 1024);
6685 entry_list = add_lines_to_move_detection(o,
6686 &entry_pool);
6687 mark_color_as_moved(o, entry_list);
6688 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6689 dim_moved_lines(o);
6691 mem_pool_discard(&entry_pool, 0);
6692 free(entry_list);
6695 for (i = 0; i < esm.nr; i++)
6696 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6698 for (i = 0; i < esm.nr; i++)
6699 free((void *)esm.buf[i].line);
6700 esm.nr = 0;
6702 o->emitted_symbols = NULL;
6706 static void diff_free_file(struct diff_options *options)
6708 if (options->close_file && options->file) {
6709 fclose(options->file);
6710 options->file = NULL;
6714 static void diff_free_ignore_regex(struct diff_options *options)
6716 int i;
6718 for (i = 0; i < options->ignore_regex_nr; i++) {
6719 regfree(options->ignore_regex[i]);
6720 free(options->ignore_regex[i]);
6723 FREE_AND_NULL(options->ignore_regex);
6724 options->ignore_regex_nr = 0;
6727 void diff_free(struct diff_options *options)
6729 if (options->no_free)
6730 return;
6732 if (options->objfind) {
6733 oidset_clear(options->objfind);
6734 FREE_AND_NULL(options->objfind);
6737 FREE_AND_NULL(options->orderfile);
6738 for (size_t i = 0; i < options->anchors_nr; i++)
6739 free(options->anchors[i]);
6740 FREE_AND_NULL(options->anchors);
6741 options->anchors_nr = options->anchors_alloc = 0;
6743 diff_free_file(options);
6744 diff_free_ignore_regex(options);
6745 clear_pathspec(&options->pathspec);
6748 void diff_flush(struct diff_options *options)
6750 struct diff_queue_struct *q = &diff_queued_diff;
6751 int i, output_format = options->output_format;
6752 int separator = 0;
6753 int dirstat_by_line = 0;
6756 * Order: raw, stat, summary, patch
6757 * or: name/name-status/checkdiff (other bits clear)
6759 if (!q->nr && !options->additional_path_headers)
6760 goto free_queue;
6762 if (output_format & (DIFF_FORMAT_RAW |
6763 DIFF_FORMAT_NAME |
6764 DIFF_FORMAT_NAME_STATUS |
6765 DIFF_FORMAT_CHECKDIFF)) {
6766 for (i = 0; i < q->nr; i++) {
6767 struct diff_filepair *p = q->queue[i];
6768 if (check_pair_status(p))
6769 flush_one_pair(p, options);
6771 separator++;
6774 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6775 dirstat_by_line = 1;
6777 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6778 dirstat_by_line) {
6779 struct diffstat_t diffstat;
6781 compute_diffstat(options, &diffstat, q);
6782 if (output_format & DIFF_FORMAT_NUMSTAT)
6783 show_numstat(&diffstat, options);
6784 if (output_format & DIFF_FORMAT_DIFFSTAT)
6785 show_stats(&diffstat, options);
6786 if (output_format & DIFF_FORMAT_SHORTSTAT)
6787 show_shortstats(&diffstat, options);
6788 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6789 show_dirstat_by_line(&diffstat, options);
6790 free_diffstat_info(&diffstat);
6791 separator++;
6793 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6794 show_dirstat(options);
6796 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6797 for (i = 0; i < q->nr; i++) {
6798 diff_summary(options, q->queue[i]);
6800 separator++;
6803 if (output_format & DIFF_FORMAT_PATCH) {
6804 if (separator) {
6805 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6806 if (options->stat_sep)
6807 /* attach patch instead of inline */
6808 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6809 NULL, 0, 0);
6812 diff_flush_patch_all_file_pairs(options);
6815 if (output_format & DIFF_FORMAT_CALLBACK)
6816 options->format_callback(q, options, options->format_callback_data);
6818 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6819 options->flags.exit_with_status &&
6820 options->flags.diff_from_contents) {
6822 * run diff_flush_patch for the exit status. setting
6823 * options->file to /dev/null should be safe, because we
6824 * aren't supposed to produce any output anyway.
6826 diff_free_file(options);
6827 options->file = xfopen("/dev/null", "w");
6828 options->close_file = 1;
6829 options->color_moved = 0;
6830 for (i = 0; i < q->nr; i++) {
6831 struct diff_filepair *p = q->queue[i];
6832 if (check_pair_status(p))
6833 diff_flush_patch(p, options);
6834 if (options->found_changes)
6835 break;
6839 free_queue:
6840 diff_queue_clear(q);
6841 diff_free(options);
6844 * Report the content-level differences with HAS_CHANGES;
6845 * diff_addremove/diff_change does not set the bit when
6846 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6848 if (options->flags.diff_from_contents) {
6849 if (options->found_changes)
6850 options->flags.has_changes = 1;
6851 else
6852 options->flags.has_changes = 0;
6856 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6858 return (((p->status == DIFF_STATUS_MODIFIED) &&
6859 ((p->score &&
6860 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6861 (!p->score &&
6862 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6863 ((p->status != DIFF_STATUS_MODIFIED) &&
6864 filter_bit_tst(p->status, options)));
6867 static void diffcore_apply_filter(struct diff_options *options)
6869 int i;
6870 struct diff_queue_struct *q = &diff_queued_diff;
6871 struct diff_queue_struct outq = DIFF_QUEUE_INIT;
6873 if (!options->filter)
6874 return;
6876 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6877 int found;
6878 for (i = found = 0; !found && i < q->nr; i++) {
6879 if (match_filter(options, q->queue[i]))
6880 found++;
6882 if (found)
6883 return;
6885 /* otherwise we will clear the whole queue
6886 * by copying the empty outq at the end of this
6887 * function, but first clear the current entries
6888 * in the queue.
6890 for (i = 0; i < q->nr; i++)
6891 diff_free_filepair(q->queue[i]);
6893 else {
6894 /* Only the matching ones */
6895 for (i = 0; i < q->nr; i++) {
6896 struct diff_filepair *p = q->queue[i];
6897 if (match_filter(options, p))
6898 diff_q(&outq, p);
6899 else
6900 diff_free_filepair(p);
6903 free(q->queue);
6904 *q = outq;
6907 /* Check whether two filespecs with the same mode and size are identical */
6908 static int diff_filespec_is_identical(struct repository *r,
6909 struct diff_filespec *one,
6910 struct diff_filespec *two)
6912 if (S_ISGITLINK(one->mode))
6913 return 0;
6914 if (diff_populate_filespec(r, one, NULL))
6915 return 0;
6916 if (diff_populate_filespec(r, two, NULL))
6917 return 0;
6918 return !memcmp(one->data, two->data, one->size);
6921 static int diff_filespec_check_stat_unmatch(struct repository *r,
6922 struct diff_filepair *p)
6924 struct diff_populate_filespec_options dpf_options = {
6925 .check_size_only = 1,
6926 .missing_object_cb = diff_queued_diff_prefetch,
6927 .missing_object_data = r,
6930 if (p->done_skip_stat_unmatch)
6931 return p->skip_stat_unmatch_result;
6933 p->done_skip_stat_unmatch = 1;
6934 p->skip_stat_unmatch_result = 0;
6936 * 1. Entries that come from stat info dirtiness
6937 * always have both sides (iow, not create/delete),
6938 * one side of the object name is unknown, with
6939 * the same mode and size. Keep the ones that
6940 * do not match these criteria. They have real
6941 * differences.
6943 * 2. At this point, the file is known to be modified,
6944 * with the same mode and size, and the object
6945 * name of one side is unknown. Need to inspect
6946 * the identical contents.
6948 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6949 !DIFF_FILE_VALID(p->two) ||
6950 (p->one->oid_valid && p->two->oid_valid) ||
6951 (p->one->mode != p->two->mode) ||
6952 diff_populate_filespec(r, p->one, &dpf_options) ||
6953 diff_populate_filespec(r, p->two, &dpf_options) ||
6954 (p->one->size != p->two->size) ||
6955 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6956 p->skip_stat_unmatch_result = 1;
6957 return p->skip_stat_unmatch_result;
6960 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6962 int i;
6963 struct diff_queue_struct *q = &diff_queued_diff;
6964 struct diff_queue_struct outq = DIFF_QUEUE_INIT;
6966 for (i = 0; i < q->nr; i++) {
6967 struct diff_filepair *p = q->queue[i];
6969 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6970 diff_q(&outq, p);
6971 else {
6973 * The caller can subtract 1 from skip_stat_unmatch
6974 * to determine how many paths were dirty only
6975 * due to stat info mismatch.
6977 if (!diffopt->flags.no_index)
6978 diffopt->skip_stat_unmatch++;
6979 diff_free_filepair(p);
6982 free(q->queue);
6983 *q = outq;
6986 static int diffnamecmp(const void *a_, const void *b_)
6988 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6989 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6990 const char *name_a, *name_b;
6992 name_a = a->one ? a->one->path : a->two->path;
6993 name_b = b->one ? b->one->path : b->two->path;
6994 return strcmp(name_a, name_b);
6997 void diffcore_fix_diff_index(void)
6999 struct diff_queue_struct *q = &diff_queued_diff;
7000 QSORT(q->queue, q->nr, diffnamecmp);
7003 void diff_add_if_missing(struct repository *r,
7004 struct oid_array *to_fetch,
7005 const struct diff_filespec *filespec)
7007 if (filespec && filespec->oid_valid &&
7008 !S_ISGITLINK(filespec->mode) &&
7009 oid_object_info_extended(r, &filespec->oid, NULL,
7010 OBJECT_INFO_FOR_PREFETCH))
7011 oid_array_append(to_fetch, &filespec->oid);
7014 void diff_queued_diff_prefetch(void *repository)
7016 struct repository *repo = repository;
7017 int i;
7018 struct diff_queue_struct *q = &diff_queued_diff;
7019 struct oid_array to_fetch = OID_ARRAY_INIT;
7021 for (i = 0; i < q->nr; i++) {
7022 struct diff_filepair *p = q->queue[i];
7023 diff_add_if_missing(repo, &to_fetch, p->one);
7024 diff_add_if_missing(repo, &to_fetch, p->two);
7028 * NEEDSWORK: Consider deduplicating the OIDs sent.
7030 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
7032 oid_array_clear(&to_fetch);
7035 void init_diffstat_widths(struct diff_options *options)
7037 options->stat_width = -1; /* use full terminal width */
7038 options->stat_name_width = -1; /* respect diff.statNameWidth config */
7039 options->stat_graph_width = -1; /* respect diff.statGraphWidth config */
7042 void diffcore_std(struct diff_options *options)
7044 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
7045 DIFF_FORMAT_NUMSTAT |
7046 DIFF_FORMAT_PATCH |
7047 DIFF_FORMAT_SHORTSTAT |
7048 DIFF_FORMAT_DIRSTAT;
7051 * Check if the user requested a blob-data-requiring diff output and/or
7052 * break-rewrite detection (which requires blob data). If yes, prefetch
7053 * the diff pairs.
7055 * If no prefetching occurs, diffcore_rename() will prefetch if it
7056 * decides that it needs inexact rename detection.
7058 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
7059 (options->output_format & output_formats_to_prefetch ||
7060 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
7061 diff_queued_diff_prefetch(options->repo);
7063 /* NOTE please keep the following in sync with diff_tree_combined() */
7064 if (options->skip_stat_unmatch)
7065 diffcore_skip_stat_unmatch(options);
7066 if (!options->found_follow) {
7067 /* See try_to_follow_renames() in tree-diff.c */
7068 if (options->break_opt != -1)
7069 diffcore_break(options->repo,
7070 options->break_opt);
7071 if (options->detect_rename)
7072 diffcore_rename(options);
7073 if (options->break_opt != -1)
7074 diffcore_merge_broken();
7076 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
7077 diffcore_pickaxe(options);
7078 if (options->orderfile)
7079 diffcore_order(options->orderfile);
7080 if (options->rotate_to)
7081 diffcore_rotate(options);
7082 if (!options->found_follow)
7083 /* See try_to_follow_renames() in tree-diff.c */
7084 diff_resolve_rename_copy();
7085 diffcore_apply_filter(options);
7087 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
7088 options->flags.has_changes = 1;
7089 else
7090 options->flags.has_changes = 0;
7092 options->found_follow = 0;
7095 int diff_result_code(struct rev_info *revs)
7097 struct diff_options *opt = &revs->diffopt;
7098 int result = 0;
7100 if (revs->remerge_diff) {
7101 tmp_objdir_destroy(revs->remerge_objdir);
7102 revs->remerge_objdir = NULL;
7105 diff_warn_rename_limit("diff.renameLimit",
7106 opt->needed_rename_limit,
7107 opt->degraded_cc_to_c);
7109 if (opt->flags.exit_with_status &&
7110 opt->flags.has_changes)
7111 result |= 01;
7112 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
7113 opt->flags.check_failed)
7114 result |= 02;
7115 return result;
7118 int diff_can_quit_early(struct diff_options *opt)
7120 return (opt->flags.quick &&
7121 !opt->filter &&
7122 opt->flags.has_changes);
7126 * Shall changes to this submodule be ignored?
7128 * Submodule changes can be configured to be ignored separately for each path,
7129 * but that configuration can be overridden from the command line.
7131 static int is_submodule_ignored(const char *path, struct diff_options *options)
7133 int ignored = 0;
7134 struct diff_flags orig_flags = options->flags;
7135 if (!options->flags.override_submodule_config)
7136 set_diffopt_flags_from_submodule_config(options, path);
7137 if (options->flags.ignore_submodules)
7138 ignored = 1;
7139 options->flags = orig_flags;
7140 return ignored;
7143 void compute_diffstat(struct diff_options *options,
7144 struct diffstat_t *diffstat,
7145 struct diff_queue_struct *q)
7147 int i;
7149 memset(diffstat, 0, sizeof(struct diffstat_t));
7150 for (i = 0; i < q->nr; i++) {
7151 struct diff_filepair *p = q->queue[i];
7152 if (check_pair_status(p))
7153 diff_flush_stat(p, options, diffstat);
7155 options->found_changes = !!diffstat->nr;
7158 void diff_addremove(struct diff_options *options,
7159 int addremove, unsigned mode,
7160 const struct object_id *oid,
7161 int oid_valid,
7162 const char *concatpath, unsigned dirty_submodule)
7164 struct diff_filespec *one, *two;
7166 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
7167 return;
7169 /* This may look odd, but it is a preparation for
7170 * feeding "there are unchanged files which should
7171 * not produce diffs, but when you are doing copy
7172 * detection you would need them, so here they are"
7173 * entries to the diff-core. They will be prefixed
7174 * with something like '=' or '*' (I haven't decided
7175 * which but should not make any difference).
7176 * Feeding the same new and old to diff_change()
7177 * also has the same effect.
7178 * Before the final output happens, they are pruned after
7179 * merged into rename/copy pairs as appropriate.
7181 if (options->flags.reverse_diff)
7182 addremove = (addremove == '+' ? '-' :
7183 addremove == '-' ? '+' : addremove);
7185 if (options->prefix &&
7186 strncmp(concatpath, options->prefix, options->prefix_length))
7187 return;
7189 one = alloc_filespec(concatpath);
7190 two = alloc_filespec(concatpath);
7192 if (addremove != '+')
7193 fill_filespec(one, oid, oid_valid, mode);
7194 if (addremove != '-') {
7195 fill_filespec(two, oid, oid_valid, mode);
7196 two->dirty_submodule = dirty_submodule;
7199 diff_queue(&diff_queued_diff, one, two);
7200 if (!options->flags.diff_from_contents)
7201 options->flags.has_changes = 1;
7204 void diff_change(struct diff_options *options,
7205 unsigned old_mode, unsigned new_mode,
7206 const struct object_id *old_oid,
7207 const struct object_id *new_oid,
7208 int old_oid_valid, int new_oid_valid,
7209 const char *concatpath,
7210 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
7212 struct diff_filespec *one, *two;
7213 struct diff_filepair *p;
7215 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7216 is_submodule_ignored(concatpath, options))
7217 return;
7219 if (options->flags.reverse_diff) {
7220 SWAP(old_mode, new_mode);
7221 SWAP(old_oid, new_oid);
7222 SWAP(old_oid_valid, new_oid_valid);
7223 SWAP(old_dirty_submodule, new_dirty_submodule);
7226 if (options->prefix &&
7227 strncmp(concatpath, options->prefix, options->prefix_length))
7228 return;
7230 one = alloc_filespec(concatpath);
7231 two = alloc_filespec(concatpath);
7232 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7233 fill_filespec(two, new_oid, new_oid_valid, new_mode);
7234 one->dirty_submodule = old_dirty_submodule;
7235 two->dirty_submodule = new_dirty_submodule;
7236 p = diff_queue(&diff_queued_diff, one, two);
7238 if (options->flags.diff_from_contents)
7239 return;
7241 if (options->flags.quick && options->skip_stat_unmatch &&
7242 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7243 diff_free_filespec_data(p->one);
7244 diff_free_filespec_data(p->two);
7245 return;
7248 options->flags.has_changes = 1;
7251 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
7253 struct diff_filepair *pair;
7254 struct diff_filespec *one, *two;
7256 if (options->prefix &&
7257 strncmp(path, options->prefix, options->prefix_length))
7258 return NULL;
7260 one = alloc_filespec(path);
7261 two = alloc_filespec(path);
7262 pair = diff_queue(&diff_queued_diff, one, two);
7263 pair->is_unmerged = 1;
7264 return pair;
7267 static char *run_textconv(struct repository *r,
7268 const char *pgm,
7269 struct diff_filespec *spec,
7270 size_t *outsize)
7272 struct diff_tempfile *temp;
7273 struct child_process child = CHILD_PROCESS_INIT;
7274 struct strbuf buf = STRBUF_INIT;
7275 int err = 0;
7277 temp = prepare_temp_file(r, spec);
7278 strvec_push(&child.args, pgm);
7279 strvec_push(&child.args, temp->name);
7281 child.use_shell = 1;
7282 child.out = -1;
7283 if (start_command(&child)) {
7284 remove_tempfile();
7285 return NULL;
7288 if (strbuf_read(&buf, child.out, 0) < 0)
7289 err = error("error reading from textconv command '%s'", pgm);
7290 close(child.out);
7292 if (finish_command(&child) || err) {
7293 strbuf_release(&buf);
7294 remove_tempfile();
7295 return NULL;
7297 remove_tempfile();
7299 return strbuf_detach(&buf, outsize);
7302 size_t fill_textconv(struct repository *r,
7303 struct userdiff_driver *driver,
7304 struct diff_filespec *df,
7305 char **outbuf)
7307 size_t size;
7309 if (!driver) {
7310 if (!DIFF_FILE_VALID(df)) {
7311 *outbuf = (char *) "";
7312 return 0;
7314 if (diff_populate_filespec(r, df, NULL))
7315 die("unable to read files to diff");
7316 *outbuf = df->data;
7317 return df->size;
7320 if (!driver->textconv)
7321 BUG("fill_textconv called with non-textconv driver");
7323 if (driver->textconv_cache && df->oid_valid) {
7324 *outbuf = notes_cache_get(driver->textconv_cache,
7325 &df->oid,
7326 &size);
7327 if (*outbuf)
7328 return size;
7331 *outbuf = run_textconv(r, driver->textconv, df, &size);
7332 if (!*outbuf)
7333 die("unable to read files to diff");
7335 if (driver->textconv_cache && df->oid_valid) {
7336 /* ignore errors, as we might be in a readonly repository */
7337 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7338 size);
7340 * we could save up changes and flush them all at the end,
7341 * but we would need an extra call after all diffing is done.
7342 * Since generating a cache entry is the slow path anyway,
7343 * this extra overhead probably isn't a big deal.
7345 notes_cache_write(driver->textconv_cache);
7348 return size;
7351 int textconv_object(struct repository *r,
7352 const char *path,
7353 unsigned mode,
7354 const struct object_id *oid,
7355 int oid_valid,
7356 char **buf,
7357 unsigned long *buf_size)
7359 struct diff_filespec *df;
7360 struct userdiff_driver *textconv;
7362 df = alloc_filespec(path);
7363 fill_filespec(df, oid, oid_valid, mode);
7364 textconv = get_textconv(r, df);
7365 if (!textconv) {
7366 free_filespec(df);
7367 return 0;
7370 *buf_size = fill_textconv(r, textconv, df, buf);
7371 free_filespec(df);
7372 return 1;
7375 void setup_diff_pager(struct diff_options *opt)
7378 * If the user asked for our exit code, then either they want --quiet
7379 * or --exit-code. We should definitely not bother with a pager in the
7380 * former case, as we will generate no output. Since we still properly
7381 * report our exit code even when a pager is run, we _could_ run a
7382 * pager with --exit-code. But since we have not done so historically,
7383 * and because it is easy to find people oneline advising "git diff
7384 * --exit-code" in hooks and other scripts, we do not do so.
7386 if (!opt->flags.exit_with_status &&
7387 check_pager_config("diff") != 0)
7388 setup_pager();