diff.c: free "buf" in diff_words_flush()
[git.git] / diff.c
blobc5bc9bc5128365d5168881a55c79b39d88ca242b
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "tempfile.h"
7 #include "quote.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "delta.h"
11 #include "xdiff-interface.h"
12 #include "color.h"
13 #include "attr.h"
14 #include "run-command.h"
15 #include "utf8.h"
16 #include "object-store.h"
17 #include "userdiff.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
20 #include "hashmap.h"
21 #include "mem-pool.h"
22 #include "ll-merge.h"
23 #include "string-list.h"
24 #include "strvec.h"
25 #include "graph.h"
26 #include "packfile.h"
27 #include "parse-options.h"
28 #include "help.h"
29 #include "promisor-remote.h"
30 #include "dir.h"
31 #include "strmap.h"
33 #ifdef NO_FAST_WORKING_DIRECTORY
34 #define FAST_WORKING_DIRECTORY 0
35 #else
36 #define FAST_WORKING_DIRECTORY 1
37 #endif
39 static int diff_detect_rename_default;
40 static int diff_indent_heuristic = 1;
41 static int diff_rename_limit_default = 1000;
42 static int diff_suppress_blank_empty;
43 static int diff_use_color_default = -1;
44 static int diff_color_moved_default;
45 static int diff_color_moved_ws_default;
46 static int diff_context_default = 3;
47 static int diff_interhunk_context_default;
48 static const char *diff_word_regex_cfg;
49 static const char *external_diff_cmd_cfg;
50 static const char *diff_order_file_cfg;
51 int diff_auto_refresh_index = 1;
52 static int diff_mnemonic_prefix;
53 static int diff_no_prefix;
54 static int diff_relative;
55 static int diff_stat_graph_width;
56 static int diff_dirstat_permille_default = 30;
57 static struct diff_options default_diff_options;
58 static long diff_algorithm;
59 static unsigned ws_error_highlight_default = WSEH_NEW;
61 static char diff_colors[][COLOR_MAXLEN] = {
62 GIT_COLOR_RESET,
63 GIT_COLOR_NORMAL, /* CONTEXT */
64 GIT_COLOR_BOLD, /* METAINFO */
65 GIT_COLOR_CYAN, /* FRAGINFO */
66 GIT_COLOR_RED, /* OLD */
67 GIT_COLOR_GREEN, /* NEW */
68 GIT_COLOR_YELLOW, /* COMMIT */
69 GIT_COLOR_BG_RED, /* WHITESPACE */
70 GIT_COLOR_NORMAL, /* FUNCINFO */
71 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
72 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
73 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
74 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
75 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
76 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
77 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
78 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
79 GIT_COLOR_FAINT, /* CONTEXT_DIM */
80 GIT_COLOR_FAINT_RED, /* OLD_DIM */
81 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
82 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
83 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
84 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
87 static const char *color_diff_slots[] = {
88 [DIFF_CONTEXT] = "context",
89 [DIFF_METAINFO] = "meta",
90 [DIFF_FRAGINFO] = "frag",
91 [DIFF_FILE_OLD] = "old",
92 [DIFF_FILE_NEW] = "new",
93 [DIFF_COMMIT] = "commit",
94 [DIFF_WHITESPACE] = "whitespace",
95 [DIFF_FUNCINFO] = "func",
96 [DIFF_FILE_OLD_MOVED] = "oldMoved",
97 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
98 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
99 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
100 [DIFF_FILE_NEW_MOVED] = "newMoved",
101 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
102 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
103 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
104 [DIFF_CONTEXT_DIM] = "contextDimmed",
105 [DIFF_FILE_OLD_DIM] = "oldDimmed",
106 [DIFF_FILE_NEW_DIM] = "newDimmed",
107 [DIFF_CONTEXT_BOLD] = "contextBold",
108 [DIFF_FILE_OLD_BOLD] = "oldBold",
109 [DIFF_FILE_NEW_BOLD] = "newBold",
112 define_list_config_array_extra(color_diff_slots, {"plain"});
114 static int parse_diff_color_slot(const char *var)
116 if (!strcasecmp(var, "plain"))
117 return DIFF_CONTEXT;
118 return LOOKUP_CONFIG(color_diff_slots, var);
121 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
122 struct strbuf *errmsg)
124 char *params_copy = xstrdup(params_string);
125 struct string_list params = STRING_LIST_INIT_NODUP;
126 int ret = 0;
127 int i;
129 if (*params_copy)
130 string_list_split_in_place(&params, params_copy, ',', -1);
131 for (i = 0; i < params.nr; i++) {
132 const char *p = params.items[i].string;
133 if (!strcmp(p, "changes")) {
134 options->flags.dirstat_by_line = 0;
135 options->flags.dirstat_by_file = 0;
136 } else if (!strcmp(p, "lines")) {
137 options->flags.dirstat_by_line = 1;
138 options->flags.dirstat_by_file = 0;
139 } else if (!strcmp(p, "files")) {
140 options->flags.dirstat_by_line = 0;
141 options->flags.dirstat_by_file = 1;
142 } else if (!strcmp(p, "noncumulative")) {
143 options->flags.dirstat_cumulative = 0;
144 } else if (!strcmp(p, "cumulative")) {
145 options->flags.dirstat_cumulative = 1;
146 } else if (isdigit(*p)) {
147 char *end;
148 int permille = strtoul(p, &end, 10) * 10;
149 if (*end == '.' && isdigit(*++end)) {
150 /* only use first digit */
151 permille += *end - '0';
152 /* .. and ignore any further digits */
153 while (isdigit(*++end))
154 ; /* nothing */
156 if (!*end)
157 options->dirstat_permille = permille;
158 else {
159 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
161 ret++;
163 } else {
164 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
165 ret++;
169 string_list_clear(&params, 0);
170 free(params_copy);
171 return ret;
174 static int parse_submodule_params(struct diff_options *options, const char *value)
176 if (!strcmp(value, "log"))
177 options->submodule_format = DIFF_SUBMODULE_LOG;
178 else if (!strcmp(value, "short"))
179 options->submodule_format = DIFF_SUBMODULE_SHORT;
180 else if (!strcmp(value, "diff"))
181 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
183 * Please update $__git_diff_submodule_formats in
184 * git-completion.bash when you add new formats.
186 else
187 return -1;
188 return 0;
191 int git_config_rename(const char *var, const char *value)
193 if (!value)
194 return DIFF_DETECT_RENAME;
195 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
196 return DIFF_DETECT_COPY;
197 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
200 long parse_algorithm_value(const char *value)
202 if (!value)
203 return -1;
204 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
205 return 0;
206 else if (!strcasecmp(value, "minimal"))
207 return XDF_NEED_MINIMAL;
208 else if (!strcasecmp(value, "patience"))
209 return XDF_PATIENCE_DIFF;
210 else if (!strcasecmp(value, "histogram"))
211 return XDF_HISTOGRAM_DIFF;
213 * Please update $__git_diff_algorithms in git-completion.bash
214 * when you add new algorithms.
216 return -1;
219 static int parse_one_token(const char **arg, const char *token)
221 const char *rest;
222 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
223 *arg = rest;
224 return 1;
226 return 0;
229 static int parse_ws_error_highlight(const char *arg)
231 const char *orig_arg = arg;
232 unsigned val = 0;
234 while (*arg) {
235 if (parse_one_token(&arg, "none"))
236 val = 0;
237 else if (parse_one_token(&arg, "default"))
238 val = WSEH_NEW;
239 else if (parse_one_token(&arg, "all"))
240 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
241 else if (parse_one_token(&arg, "new"))
242 val |= WSEH_NEW;
243 else if (parse_one_token(&arg, "old"))
244 val |= WSEH_OLD;
245 else if (parse_one_token(&arg, "context"))
246 val |= WSEH_CONTEXT;
247 else {
248 return -1 - (int)(arg - orig_arg);
250 if (*arg)
251 arg++;
253 return val;
257 * These are to give UI layer defaults.
258 * The core-level commands such as git-diff-files should
259 * never be affected by the setting of diff.renames
260 * the user happens to have in the configuration file.
262 void init_diff_ui_defaults(void)
264 diff_detect_rename_default = DIFF_DETECT_RENAME;
267 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
269 if (!strcmp(var, "diff.indentheuristic"))
270 diff_indent_heuristic = git_config_bool(var, value);
271 return 0;
274 static int parse_color_moved(const char *arg)
276 switch (git_parse_maybe_bool(arg)) {
277 case 0:
278 return COLOR_MOVED_NO;
279 case 1:
280 return COLOR_MOVED_DEFAULT;
281 default:
282 break;
285 if (!strcmp(arg, "no"))
286 return COLOR_MOVED_NO;
287 else if (!strcmp(arg, "plain"))
288 return COLOR_MOVED_PLAIN;
289 else if (!strcmp(arg, "blocks"))
290 return COLOR_MOVED_BLOCKS;
291 else if (!strcmp(arg, "zebra"))
292 return COLOR_MOVED_ZEBRA;
293 else if (!strcmp(arg, "default"))
294 return COLOR_MOVED_DEFAULT;
295 else if (!strcmp(arg, "dimmed-zebra"))
296 return COLOR_MOVED_ZEBRA_DIM;
297 else if (!strcmp(arg, "dimmed_zebra"))
298 return COLOR_MOVED_ZEBRA_DIM;
299 else
300 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
303 static unsigned parse_color_moved_ws(const char *arg)
305 int ret = 0;
306 struct string_list l = STRING_LIST_INIT_DUP;
307 struct string_list_item *i;
309 string_list_split(&l, arg, ',', -1);
311 for_each_string_list_item(i, &l) {
312 struct strbuf sb = STRBUF_INIT;
313 strbuf_addstr(&sb, i->string);
314 strbuf_trim(&sb);
316 if (!strcmp(sb.buf, "no"))
317 ret = 0;
318 else if (!strcmp(sb.buf, "ignore-space-change"))
319 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
320 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
321 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
322 else if (!strcmp(sb.buf, "ignore-all-space"))
323 ret |= XDF_IGNORE_WHITESPACE;
324 else if (!strcmp(sb.buf, "allow-indentation-change"))
325 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
326 else {
327 ret |= COLOR_MOVED_WS_ERROR;
328 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);
331 strbuf_release(&sb);
334 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
335 (ret & XDF_WHITESPACE_FLAGS)) {
336 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
337 ret |= COLOR_MOVED_WS_ERROR;
340 string_list_clear(&l, 0);
342 return ret;
345 int git_diff_ui_config(const char *var, const char *value, void *cb)
347 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
348 diff_use_color_default = git_config_colorbool(var, value);
349 return 0;
351 if (!strcmp(var, "diff.colormoved")) {
352 int cm = parse_color_moved(value);
353 if (cm < 0)
354 return -1;
355 diff_color_moved_default = cm;
356 return 0;
358 if (!strcmp(var, "diff.colormovedws")) {
359 unsigned cm = parse_color_moved_ws(value);
360 if (cm & COLOR_MOVED_WS_ERROR)
361 return -1;
362 diff_color_moved_ws_default = cm;
363 return 0;
365 if (!strcmp(var, "diff.context")) {
366 diff_context_default = git_config_int(var, value);
367 if (diff_context_default < 0)
368 return -1;
369 return 0;
371 if (!strcmp(var, "diff.interhunkcontext")) {
372 diff_interhunk_context_default = git_config_int(var, value);
373 if (diff_interhunk_context_default < 0)
374 return -1;
375 return 0;
377 if (!strcmp(var, "diff.renames")) {
378 diff_detect_rename_default = git_config_rename(var, value);
379 return 0;
381 if (!strcmp(var, "diff.autorefreshindex")) {
382 diff_auto_refresh_index = git_config_bool(var, value);
383 return 0;
385 if (!strcmp(var, "diff.mnemonicprefix")) {
386 diff_mnemonic_prefix = git_config_bool(var, value);
387 return 0;
389 if (!strcmp(var, "diff.noprefix")) {
390 diff_no_prefix = git_config_bool(var, value);
391 return 0;
393 if (!strcmp(var, "diff.relative")) {
394 diff_relative = git_config_bool(var, value);
395 return 0;
397 if (!strcmp(var, "diff.statgraphwidth")) {
398 diff_stat_graph_width = git_config_int(var, value);
399 return 0;
401 if (!strcmp(var, "diff.external"))
402 return git_config_string(&external_diff_cmd_cfg, var, value);
403 if (!strcmp(var, "diff.wordregex"))
404 return git_config_string(&diff_word_regex_cfg, var, value);
405 if (!strcmp(var, "diff.orderfile"))
406 return git_config_pathname(&diff_order_file_cfg, var, value);
408 if (!strcmp(var, "diff.ignoresubmodules"))
409 handle_ignore_submodules_arg(&default_diff_options, value);
411 if (!strcmp(var, "diff.submodule")) {
412 if (parse_submodule_params(&default_diff_options, value))
413 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
414 value);
415 return 0;
418 if (!strcmp(var, "diff.algorithm")) {
419 diff_algorithm = parse_algorithm_value(value);
420 if (diff_algorithm < 0)
421 return -1;
422 return 0;
425 if (git_color_config(var, value, cb) < 0)
426 return -1;
428 return git_diff_basic_config(var, value, cb);
431 int git_diff_basic_config(const char *var, const char *value, void *cb)
433 const char *name;
435 if (!strcmp(var, "diff.renamelimit")) {
436 diff_rename_limit_default = git_config_int(var, value);
437 return 0;
440 if (userdiff_config(var, value) < 0)
441 return -1;
443 if (skip_prefix(var, "diff.color.", &name) ||
444 skip_prefix(var, "color.diff.", &name)) {
445 int slot = parse_diff_color_slot(name);
446 if (slot < 0)
447 return 0;
448 if (!value)
449 return config_error_nonbool(var);
450 return color_parse(value, diff_colors[slot]);
453 if (!strcmp(var, "diff.wserrorhighlight")) {
454 int val = parse_ws_error_highlight(value);
455 if (val < 0)
456 return -1;
457 ws_error_highlight_default = val;
458 return 0;
461 /* like GNU diff's --suppress-blank-empty option */
462 if (!strcmp(var, "diff.suppressblankempty") ||
463 /* for backwards compatibility */
464 !strcmp(var, "diff.suppress-blank-empty")) {
465 diff_suppress_blank_empty = git_config_bool(var, value);
466 return 0;
469 if (!strcmp(var, "diff.dirstat")) {
470 struct strbuf errmsg = STRBUF_INIT;
471 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
472 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
473 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
474 errmsg.buf);
475 strbuf_release(&errmsg);
476 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
477 return 0;
480 if (git_diff_heuristic_config(var, value, cb) < 0)
481 return -1;
483 return git_default_config(var, value, cb);
486 static char *quote_two(const char *one, const char *two)
488 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
489 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
490 struct strbuf res = STRBUF_INIT;
492 if (need_one + need_two) {
493 strbuf_addch(&res, '"');
494 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
495 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
496 strbuf_addch(&res, '"');
497 } else {
498 strbuf_addstr(&res, one);
499 strbuf_addstr(&res, two);
501 return strbuf_detach(&res, NULL);
504 static const char *external_diff(void)
506 static const char *external_diff_cmd = NULL;
507 static int done_preparing = 0;
509 if (done_preparing)
510 return external_diff_cmd;
511 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
512 if (!external_diff_cmd)
513 external_diff_cmd = external_diff_cmd_cfg;
514 done_preparing = 1;
515 return external_diff_cmd;
519 * Keep track of files used for diffing. Sometimes such an entry
520 * refers to a temporary file, sometimes to an existing file, and
521 * sometimes to "/dev/null".
523 static struct diff_tempfile {
525 * filename external diff should read from, or NULL if this
526 * entry is currently not in use:
528 const char *name;
530 char hex[GIT_MAX_HEXSZ + 1];
531 char mode[10];
534 * If this diff_tempfile instance refers to a temporary file,
535 * this tempfile object is used to manage its lifetime.
537 struct tempfile *tempfile;
538 } diff_temp[2];
540 struct emit_callback {
541 int color_diff;
542 unsigned ws_rule;
543 int blank_at_eof_in_preimage;
544 int blank_at_eof_in_postimage;
545 int lno_in_preimage;
546 int lno_in_postimage;
547 const char **label_path;
548 struct diff_words_data *diff_words;
549 struct diff_options *opt;
550 struct strbuf *header;
553 static int count_lines(const char *data, int size)
555 int count, ch, completely_empty = 1, nl_just_seen = 0;
556 count = 0;
557 while (0 < size--) {
558 ch = *data++;
559 if (ch == '\n') {
560 count++;
561 nl_just_seen = 1;
562 completely_empty = 0;
564 else {
565 nl_just_seen = 0;
566 completely_empty = 0;
569 if (completely_empty)
570 return 0;
571 if (!nl_just_seen)
572 count++; /* no trailing newline */
573 return count;
576 static int fill_mmfile(struct repository *r, mmfile_t *mf,
577 struct diff_filespec *one)
579 if (!DIFF_FILE_VALID(one)) {
580 mf->ptr = (char *)""; /* does not matter */
581 mf->size = 0;
582 return 0;
584 else if (diff_populate_filespec(r, one, NULL))
585 return -1;
587 mf->ptr = one->data;
588 mf->size = one->size;
589 return 0;
592 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
593 static unsigned long diff_filespec_size(struct repository *r,
594 struct diff_filespec *one)
596 struct diff_populate_filespec_options dpf_options = {
597 .check_size_only = 1,
600 if (!DIFF_FILE_VALID(one))
601 return 0;
602 diff_populate_filespec(r, one, &dpf_options);
603 return one->size;
606 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
608 char *ptr = mf->ptr;
609 long size = mf->size;
610 int cnt = 0;
612 if (!size)
613 return cnt;
614 ptr += size - 1; /* pointing at the very end */
615 if (*ptr != '\n')
616 ; /* incomplete line */
617 else
618 ptr--; /* skip the last LF */
619 while (mf->ptr < ptr) {
620 char *prev_eol;
621 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
622 if (*prev_eol == '\n')
623 break;
624 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
625 break;
626 cnt++;
627 ptr = prev_eol - 1;
629 return cnt;
632 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
633 struct emit_callback *ecbdata)
635 int l1, l2, at;
636 unsigned ws_rule = ecbdata->ws_rule;
637 l1 = count_trailing_blank(mf1, ws_rule);
638 l2 = count_trailing_blank(mf2, ws_rule);
639 if (l2 <= l1) {
640 ecbdata->blank_at_eof_in_preimage = 0;
641 ecbdata->blank_at_eof_in_postimage = 0;
642 return;
644 at = count_lines(mf1->ptr, mf1->size);
645 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
647 at = count_lines(mf2->ptr, mf2->size);
648 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
651 static void emit_line_0(struct diff_options *o,
652 const char *set_sign, const char *set, unsigned reverse, const char *reset,
653 int first, const char *line, int len)
655 int has_trailing_newline, has_trailing_carriage_return;
656 int needs_reset = 0; /* at the end of the line */
657 FILE *file = o->file;
659 fputs(diff_line_prefix(o), file);
661 has_trailing_newline = (len > 0 && line[len-1] == '\n');
662 if (has_trailing_newline)
663 len--;
665 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
666 if (has_trailing_carriage_return)
667 len--;
669 if (!len && !first)
670 goto end_of_line;
672 if (reverse && want_color(o->use_color)) {
673 fputs(GIT_COLOR_REVERSE, file);
674 needs_reset = 1;
677 if (set_sign) {
678 fputs(set_sign, file);
679 needs_reset = 1;
682 if (first)
683 fputc(first, file);
685 if (!len)
686 goto end_of_line;
688 if (set) {
689 if (set_sign && set != set_sign)
690 fputs(reset, file);
691 fputs(set, file);
692 needs_reset = 1;
694 fwrite(line, len, 1, file);
695 needs_reset = 1; /* 'line' may contain color codes. */
697 end_of_line:
698 if (needs_reset)
699 fputs(reset, file);
700 if (has_trailing_carriage_return)
701 fputc('\r', file);
702 if (has_trailing_newline)
703 fputc('\n', file);
706 static void emit_line(struct diff_options *o, const char *set, const char *reset,
707 const char *line, int len)
709 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
712 enum diff_symbol {
713 DIFF_SYMBOL_BINARY_DIFF_HEADER,
714 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
715 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
716 DIFF_SYMBOL_BINARY_DIFF_BODY,
717 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
718 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
719 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
720 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
721 DIFF_SYMBOL_STATS_LINE,
722 DIFF_SYMBOL_WORD_DIFF,
723 DIFF_SYMBOL_STAT_SEP,
724 DIFF_SYMBOL_SUMMARY,
725 DIFF_SYMBOL_SUBMODULE_ADD,
726 DIFF_SYMBOL_SUBMODULE_DEL,
727 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
728 DIFF_SYMBOL_SUBMODULE_MODIFIED,
729 DIFF_SYMBOL_SUBMODULE_HEADER,
730 DIFF_SYMBOL_SUBMODULE_ERROR,
731 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
732 DIFF_SYMBOL_REWRITE_DIFF,
733 DIFF_SYMBOL_BINARY_FILES,
734 DIFF_SYMBOL_HEADER,
735 DIFF_SYMBOL_FILEPAIR_PLUS,
736 DIFF_SYMBOL_FILEPAIR_MINUS,
737 DIFF_SYMBOL_WORDS_PORCELAIN,
738 DIFF_SYMBOL_WORDS,
739 DIFF_SYMBOL_CONTEXT,
740 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
741 DIFF_SYMBOL_PLUS,
742 DIFF_SYMBOL_MINUS,
743 DIFF_SYMBOL_NO_LF_EOF,
744 DIFF_SYMBOL_CONTEXT_FRAGINFO,
745 DIFF_SYMBOL_CONTEXT_MARKER,
746 DIFF_SYMBOL_SEPARATOR
749 * Flags for content lines:
750 * 0..12 are whitespace rules
751 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
752 * 16 is marking if the line is blank at EOF
754 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
755 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
756 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
757 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
758 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
761 * This struct is used when we need to buffer the output of the diff output.
763 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
764 * into the pre/post image file. This pointer could be a union with the
765 * line pointer. By storing an offset into the file instead of the literal line,
766 * we can decrease the memory footprint for the buffered output. At first we
767 * may want to only have indirection for the content lines, but we could also
768 * enhance the state for emitting prefabricated lines, e.g. the similarity
769 * score line or hunk/file headers would only need to store a number or path
770 * and then the output can be constructed later on depending on state.
772 struct emitted_diff_symbol {
773 const char *line;
774 int len;
775 int flags;
776 int indent_off; /* Offset to first non-whitespace character */
777 int indent_width; /* The visual width of the indentation */
778 unsigned id;
779 enum diff_symbol s;
781 #define EMITTED_DIFF_SYMBOL_INIT { 0 }
783 struct emitted_diff_symbols {
784 struct emitted_diff_symbol *buf;
785 int nr, alloc;
787 #define EMITTED_DIFF_SYMBOLS_INIT { 0 }
789 static void append_emitted_diff_symbol(struct diff_options *o,
790 struct emitted_diff_symbol *e)
792 struct emitted_diff_symbol *f;
794 ALLOC_GROW(o->emitted_symbols->buf,
795 o->emitted_symbols->nr + 1,
796 o->emitted_symbols->alloc);
797 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
799 memcpy(f, e, sizeof(struct emitted_diff_symbol));
800 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
803 struct moved_entry {
804 const struct emitted_diff_symbol *es;
805 struct moved_entry *next_line;
806 struct moved_entry *next_match;
809 struct moved_block {
810 struct moved_entry *match;
811 int wsd; /* The whitespace delta of this block */
814 #define INDENT_BLANKLINE INT_MIN
816 static void fill_es_indent_data(struct emitted_diff_symbol *es)
818 unsigned int off = 0, i;
819 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
820 const char *s = es->line;
821 const int len = es->len;
823 /* skip any \v \f \r at start of indentation */
824 while (s[off] == '\f' || s[off] == '\v' ||
825 (s[off] == '\r' && off < len - 1))
826 off++;
828 /* calculate the visual width of indentation */
829 while(1) {
830 if (s[off] == ' ') {
831 width++;
832 off++;
833 } else if (s[off] == '\t') {
834 width += tab_width - (width % tab_width);
835 while (s[++off] == '\t')
836 width += tab_width;
837 } else {
838 break;
842 /* check if this line is blank */
843 for (i = off; i < len; i++)
844 if (!isspace(s[i]))
845 break;
847 if (i == len) {
848 es->indent_width = INDENT_BLANKLINE;
849 es->indent_off = len;
850 } else {
851 es->indent_off = off;
852 es->indent_width = width;
856 static int compute_ws_delta(const struct emitted_diff_symbol *a,
857 const struct emitted_diff_symbol *b)
859 int a_width = a->indent_width,
860 b_width = b->indent_width;
862 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE)
863 return INDENT_BLANKLINE;
865 return a_width - b_width;
868 static int cmp_in_block_with_wsd(const struct moved_entry *cur,
869 const struct emitted_diff_symbol *l,
870 struct moved_block *pmb)
872 int a_width = cur->es->indent_width, b_width = l->indent_width;
873 int delta;
875 /* The text of each line must match */
876 if (cur->es->id != l->id)
877 return 1;
880 * If 'l' and 'cur' are both blank then we don't need to check the
881 * indent. We only need to check cur as we know the strings match.
882 * */
883 if (a_width == INDENT_BLANKLINE)
884 return 0;
887 * The indent changes of the block are known and stored in pmb->wsd;
888 * however we need to check if the indent changes of the current line
889 * match those of the current block.
891 delta = b_width - a_width;
894 * If the previous lines of this block were all blank then set its
895 * whitespace delta.
897 if (pmb->wsd == INDENT_BLANKLINE)
898 pmb->wsd = delta;
900 return delta != pmb->wsd;
903 struct interned_diff_symbol {
904 struct hashmap_entry ent;
905 struct emitted_diff_symbol *es;
908 static int interned_diff_symbol_cmp(const void *hashmap_cmp_fn_data,
909 const struct hashmap_entry *eptr,
910 const struct hashmap_entry *entry_or_key,
911 const void *keydata)
913 const struct diff_options *diffopt = hashmap_cmp_fn_data;
914 const struct emitted_diff_symbol *a, *b;
915 unsigned flags = diffopt->color_moved_ws_handling
916 & XDF_WHITESPACE_FLAGS;
918 a = container_of(eptr, const struct interned_diff_symbol, ent)->es;
919 b = container_of(entry_or_key, const struct interned_diff_symbol, ent)->es;
921 return !xdiff_compare_lines(a->line + a->indent_off,
922 a->len - a->indent_off,
923 b->line + b->indent_off,
924 b->len - b->indent_off, flags);
927 static void prepare_entry(struct diff_options *o, struct emitted_diff_symbol *l,
928 struct interned_diff_symbol *s)
930 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
931 unsigned int hash = xdiff_hash_string(l->line + l->indent_off,
932 l->len - l->indent_off, flags);
934 hashmap_entry_init(&s->ent, hash);
935 s->es = l;
938 struct moved_entry_list {
939 struct moved_entry *add, *del;
942 static struct moved_entry_list *add_lines_to_move_detection(struct diff_options *o,
943 struct mem_pool *entry_mem_pool)
945 struct moved_entry *prev_line = NULL;
946 struct mem_pool interned_pool;
947 struct hashmap interned_map;
948 struct moved_entry_list *entry_list = NULL;
949 size_t entry_list_alloc = 0;
950 unsigned id = 0;
951 int n;
953 hashmap_init(&interned_map, interned_diff_symbol_cmp, o, 8096);
954 mem_pool_init(&interned_pool, 1024 * 1024);
956 for (n = 0; n < o->emitted_symbols->nr; n++) {
957 struct interned_diff_symbol key;
958 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
959 struct interned_diff_symbol *s;
960 struct moved_entry *entry;
962 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS) {
963 prev_line = NULL;
964 continue;
967 if (o->color_moved_ws_handling &
968 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
969 fill_es_indent_data(l);
971 prepare_entry(o, l, &key);
972 s = hashmap_get_entry(&interned_map, &key, ent, &key.ent);
973 if (s) {
974 l->id = s->es->id;
975 } else {
976 l->id = id;
977 ALLOC_GROW_BY(entry_list, id, 1, entry_list_alloc);
978 hashmap_add(&interned_map,
979 memcpy(mem_pool_alloc(&interned_pool,
980 sizeof(key)),
981 &key, sizeof(key)));
983 entry = mem_pool_alloc(entry_mem_pool, sizeof(*entry));
984 entry->es = l;
985 entry->next_line = NULL;
986 if (prev_line && prev_line->es->s == l->s)
987 prev_line->next_line = entry;
988 prev_line = entry;
989 if (l->s == DIFF_SYMBOL_PLUS) {
990 entry->next_match = entry_list[l->id].add;
991 entry_list[l->id].add = entry;
992 } else {
993 entry->next_match = entry_list[l->id].del;
994 entry_list[l->id].del = entry;
998 hashmap_clear(&interned_map);
999 mem_pool_discard(&interned_pool, 0);
1001 return entry_list;
1004 static void pmb_advance_or_null(struct diff_options *o,
1005 struct emitted_diff_symbol *l,
1006 struct moved_block *pmb,
1007 int *pmb_nr)
1009 int i, j;
1011 for (i = 0, j = 0; i < *pmb_nr; i++) {
1012 int match;
1013 struct moved_entry *prev = pmb[i].match;
1014 struct moved_entry *cur = (prev && prev->next_line) ?
1015 prev->next_line : NULL;
1017 if (o->color_moved_ws_handling &
1018 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1019 match = cur &&
1020 !cmp_in_block_with_wsd(cur, l, &pmb[i]);
1021 else
1022 match = cur && cur->es->id == l->id;
1024 if (match) {
1025 pmb[j] = pmb[i];
1026 pmb[j++].match = cur;
1029 *pmb_nr = j;
1032 static void fill_potential_moved_blocks(struct diff_options *o,
1033 struct moved_entry *match,
1034 struct emitted_diff_symbol *l,
1035 struct moved_block **pmb_p,
1036 int *pmb_alloc_p, int *pmb_nr_p)
1039 struct moved_block *pmb = *pmb_p;
1040 int pmb_alloc = *pmb_alloc_p, pmb_nr = *pmb_nr_p;
1043 * The current line is the start of a new block.
1044 * Setup the set of potential blocks.
1046 for (; match; match = match->next_match) {
1047 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1048 if (o->color_moved_ws_handling &
1049 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1050 pmb[pmb_nr].wsd = compute_ws_delta(l, match->es);
1051 else
1052 pmb[pmb_nr].wsd = 0;
1053 pmb[pmb_nr++].match = match;
1056 *pmb_p = pmb;
1057 *pmb_alloc_p = pmb_alloc;
1058 *pmb_nr_p = pmb_nr;
1062 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1064 * Otherwise, if the last block has fewer alphanumeric characters than
1065 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1066 * that block.
1068 * The last block consists of the (n - block_length)'th line up to but not
1069 * including the nth line.
1071 * Returns 0 if the last block is empty or is unset by this function, non zero
1072 * otherwise.
1074 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1075 * Think of a way to unify them.
1077 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1078 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1079 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1081 int i, alnum_count = 0;
1082 if (o->color_moved == COLOR_MOVED_PLAIN)
1083 return block_length;
1084 for (i = 1; i < block_length + 1; i++) {
1085 const char *c = o->emitted_symbols->buf[n - i].line;
1086 for (; *c; c++) {
1087 if (!isalnum(*c))
1088 continue;
1089 alnum_count++;
1090 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1091 return 1;
1094 for (i = 1; i < block_length + 1; i++)
1095 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK;
1096 return 0;
1099 /* Find blocks of moved code, delegate actual coloring decision to helper */
1100 static void mark_color_as_moved(struct diff_options *o,
1101 struct moved_entry_list *entry_list)
1103 struct moved_block *pmb = NULL; /* potentially moved blocks */
1104 int pmb_nr = 0, pmb_alloc = 0;
1105 int n, flipped_block = 0, block_length = 0;
1106 enum diff_symbol moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1109 for (n = 0; n < o->emitted_symbols->nr; n++) {
1110 struct moved_entry *match = NULL;
1111 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1113 switch (l->s) {
1114 case DIFF_SYMBOL_PLUS:
1115 match = entry_list[l->id].del;
1116 break;
1117 case DIFF_SYMBOL_MINUS:
1118 match = entry_list[l->id].add;
1119 break;
1120 default:
1121 flipped_block = 0;
1124 if (pmb_nr && (!match || l->s != moved_symbol)) {
1125 if (!adjust_last_block(o, n, block_length) &&
1126 block_length > 1) {
1128 * Rewind in case there is another match
1129 * starting at the second line of the block
1131 match = NULL;
1132 n -= block_length;
1134 pmb_nr = 0;
1135 block_length = 0;
1136 flipped_block = 0;
1138 if (!match) {
1139 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1140 continue;
1143 if (o->color_moved == COLOR_MOVED_PLAIN) {
1144 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1145 continue;
1148 pmb_advance_or_null(o, l, pmb, &pmb_nr);
1150 if (pmb_nr == 0) {
1151 int contiguous = adjust_last_block(o, n, block_length);
1153 if (!contiguous && block_length > 1)
1155 * Rewind in case there is another match
1156 * starting at the second line of the block
1158 n -= block_length;
1159 else
1160 fill_potential_moved_blocks(o, match, l,
1161 &pmb, &pmb_alloc,
1162 &pmb_nr);
1164 if (contiguous && pmb_nr && moved_symbol == l->s)
1165 flipped_block = (flipped_block + 1) % 2;
1166 else
1167 flipped_block = 0;
1169 if (pmb_nr)
1170 moved_symbol = l->s;
1171 else
1172 moved_symbol = DIFF_SYMBOL_BINARY_DIFF_HEADER;
1174 block_length = 0;
1177 if (pmb_nr) {
1178 block_length++;
1179 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1180 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1181 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1184 adjust_last_block(o, n, block_length);
1186 free(pmb);
1189 static void dim_moved_lines(struct diff_options *o)
1191 int n;
1192 for (n = 0; n < o->emitted_symbols->nr; n++) {
1193 struct emitted_diff_symbol *prev = (n != 0) ?
1194 &o->emitted_symbols->buf[n - 1] : NULL;
1195 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1196 struct emitted_diff_symbol *next =
1197 (n < o->emitted_symbols->nr - 1) ?
1198 &o->emitted_symbols->buf[n + 1] : NULL;
1200 /* Not a plus or minus line? */
1201 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1202 continue;
1204 /* Not a moved line? */
1205 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1206 continue;
1209 * If prev or next are not a plus or minus line,
1210 * pretend they don't exist
1212 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1213 prev->s != DIFF_SYMBOL_MINUS)
1214 prev = NULL;
1215 if (next && next->s != DIFF_SYMBOL_PLUS &&
1216 next->s != DIFF_SYMBOL_MINUS)
1217 next = NULL;
1219 /* Inside a block? */
1220 if ((prev &&
1221 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1222 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1223 (next &&
1224 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1225 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1226 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1227 continue;
1230 /* Check if we are at an interesting bound: */
1231 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1232 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1233 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1234 continue;
1235 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1236 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1237 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1238 continue;
1241 * The boundary to prev and next are not interesting,
1242 * so this line is not interesting as a whole
1244 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1248 static void emit_line_ws_markup(struct diff_options *o,
1249 const char *set_sign, const char *set,
1250 const char *reset,
1251 int sign_index, const char *line, int len,
1252 unsigned ws_rule, int blank_at_eof)
1254 const char *ws = NULL;
1255 int sign = o->output_indicators[sign_index];
1257 if (o->ws_error_highlight & ws_rule) {
1258 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1259 if (!*ws)
1260 ws = NULL;
1263 if (!ws && !set_sign)
1264 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1265 else if (!ws) {
1266 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1267 } else if (blank_at_eof)
1268 /* Blank line at EOF - paint '+' as well */
1269 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1270 else {
1271 /* Emit just the prefix, then the rest. */
1272 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1273 sign, "", 0);
1274 ws_check_emit(line, len, ws_rule,
1275 o->file, set, reset, ws);
1279 static void emit_diff_symbol_from_struct(struct diff_options *o,
1280 struct emitted_diff_symbol *eds)
1282 static const char *nneof = " No newline at end of file\n";
1283 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1284 struct strbuf sb = STRBUF_INIT;
1286 enum diff_symbol s = eds->s;
1287 const char *line = eds->line;
1288 int len = eds->len;
1289 unsigned flags = eds->flags;
1291 switch (s) {
1292 case DIFF_SYMBOL_NO_LF_EOF:
1293 context = diff_get_color_opt(o, DIFF_CONTEXT);
1294 reset = diff_get_color_opt(o, DIFF_RESET);
1295 putc('\n', o->file);
1296 emit_line_0(o, context, NULL, 0, reset, '\\',
1297 nneof, strlen(nneof));
1298 break;
1299 case DIFF_SYMBOL_SUBMODULE_HEADER:
1300 case DIFF_SYMBOL_SUBMODULE_ERROR:
1301 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1302 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1303 case DIFF_SYMBOL_SUMMARY:
1304 case DIFF_SYMBOL_STATS_LINE:
1305 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1306 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1307 emit_line(o, "", "", line, len);
1308 break;
1309 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1310 case DIFF_SYMBOL_CONTEXT_MARKER:
1311 context = diff_get_color_opt(o, DIFF_CONTEXT);
1312 reset = diff_get_color_opt(o, DIFF_RESET);
1313 emit_line(o, context, reset, line, len);
1314 break;
1315 case DIFF_SYMBOL_SEPARATOR:
1316 fprintf(o->file, "%s%c",
1317 diff_line_prefix(o),
1318 o->line_termination);
1319 break;
1320 case DIFF_SYMBOL_CONTEXT:
1321 set = diff_get_color_opt(o, DIFF_CONTEXT);
1322 reset = diff_get_color_opt(o, DIFF_RESET);
1323 set_sign = NULL;
1324 if (o->flags.dual_color_diffed_diffs) {
1325 char c = !len ? 0 : line[0];
1327 if (c == '+')
1328 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1329 else if (c == '@')
1330 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1331 else if (c == '-')
1332 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1334 emit_line_ws_markup(o, set_sign, set, reset,
1335 OUTPUT_INDICATOR_CONTEXT, line, len,
1336 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1337 break;
1338 case DIFF_SYMBOL_PLUS:
1339 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1340 DIFF_SYMBOL_MOVED_LINE_ALT |
1341 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1342 case DIFF_SYMBOL_MOVED_LINE |
1343 DIFF_SYMBOL_MOVED_LINE_ALT |
1344 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1345 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1346 break;
1347 case DIFF_SYMBOL_MOVED_LINE |
1348 DIFF_SYMBOL_MOVED_LINE_ALT:
1349 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1350 break;
1351 case DIFF_SYMBOL_MOVED_LINE |
1352 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1353 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1354 break;
1355 case DIFF_SYMBOL_MOVED_LINE:
1356 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1357 break;
1358 default:
1359 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1361 reset = diff_get_color_opt(o, DIFF_RESET);
1362 if (!o->flags.dual_color_diffed_diffs)
1363 set_sign = NULL;
1364 else {
1365 char c = !len ? 0 : line[0];
1367 set_sign = set;
1368 if (c == '-')
1369 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1370 else if (c == '@')
1371 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1372 else if (c == '+')
1373 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1374 else
1375 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1376 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1378 emit_line_ws_markup(o, set_sign, set, reset,
1379 OUTPUT_INDICATOR_NEW, line, len,
1380 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1381 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1382 break;
1383 case DIFF_SYMBOL_MINUS:
1384 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1385 DIFF_SYMBOL_MOVED_LINE_ALT |
1386 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1387 case DIFF_SYMBOL_MOVED_LINE |
1388 DIFF_SYMBOL_MOVED_LINE_ALT |
1389 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1390 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1391 break;
1392 case DIFF_SYMBOL_MOVED_LINE |
1393 DIFF_SYMBOL_MOVED_LINE_ALT:
1394 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1395 break;
1396 case DIFF_SYMBOL_MOVED_LINE |
1397 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1398 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1399 break;
1400 case DIFF_SYMBOL_MOVED_LINE:
1401 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1402 break;
1403 default:
1404 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1406 reset = diff_get_color_opt(o, DIFF_RESET);
1407 if (!o->flags.dual_color_diffed_diffs)
1408 set_sign = NULL;
1409 else {
1410 char c = !len ? 0 : line[0];
1412 set_sign = set;
1413 if (c == '+')
1414 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1415 else if (c == '@')
1416 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1417 else if (c == '-')
1418 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1419 else
1420 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1422 emit_line_ws_markup(o, set_sign, set, reset,
1423 OUTPUT_INDICATOR_OLD, line, len,
1424 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1425 break;
1426 case DIFF_SYMBOL_WORDS_PORCELAIN:
1427 context = diff_get_color_opt(o, DIFF_CONTEXT);
1428 reset = diff_get_color_opt(o, DIFF_RESET);
1429 emit_line(o, context, reset, line, len);
1430 fputs("~\n", o->file);
1431 break;
1432 case DIFF_SYMBOL_WORDS:
1433 context = diff_get_color_opt(o, DIFF_CONTEXT);
1434 reset = diff_get_color_opt(o, DIFF_RESET);
1436 * Skip the prefix character, if any. With
1437 * diff_suppress_blank_empty, there may be
1438 * none.
1440 if (line[0] != '\n') {
1441 line++;
1442 len--;
1444 emit_line(o, context, reset, line, len);
1445 break;
1446 case DIFF_SYMBOL_FILEPAIR_PLUS:
1447 meta = diff_get_color_opt(o, DIFF_METAINFO);
1448 reset = diff_get_color_opt(o, DIFF_RESET);
1449 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1450 line, reset,
1451 strchr(line, ' ') ? "\t" : "");
1452 break;
1453 case DIFF_SYMBOL_FILEPAIR_MINUS:
1454 meta = diff_get_color_opt(o, DIFF_METAINFO);
1455 reset = diff_get_color_opt(o, DIFF_RESET);
1456 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1457 line, reset,
1458 strchr(line, ' ') ? "\t" : "");
1459 break;
1460 case DIFF_SYMBOL_BINARY_FILES:
1461 case DIFF_SYMBOL_HEADER:
1462 fprintf(o->file, "%s", line);
1463 break;
1464 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1465 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1466 break;
1467 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1468 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1469 break;
1470 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1471 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1472 break;
1473 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1474 fputs(diff_line_prefix(o), o->file);
1475 fputc('\n', o->file);
1476 break;
1477 case DIFF_SYMBOL_REWRITE_DIFF:
1478 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1479 reset = diff_get_color_opt(o, DIFF_RESET);
1480 emit_line(o, fraginfo, reset, line, len);
1481 break;
1482 case DIFF_SYMBOL_SUBMODULE_ADD:
1483 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1484 reset = diff_get_color_opt(o, DIFF_RESET);
1485 emit_line(o, set, reset, line, len);
1486 break;
1487 case DIFF_SYMBOL_SUBMODULE_DEL:
1488 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1489 reset = diff_get_color_opt(o, DIFF_RESET);
1490 emit_line(o, set, reset, line, len);
1491 break;
1492 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1493 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1494 diff_line_prefix(o), line);
1495 break;
1496 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1497 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1498 diff_line_prefix(o), line);
1499 break;
1500 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1501 emit_line(o, "", "", " 0 files changed\n",
1502 strlen(" 0 files changed\n"));
1503 break;
1504 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1505 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1506 break;
1507 case DIFF_SYMBOL_WORD_DIFF:
1508 fprintf(o->file, "%.*s", len, line);
1509 break;
1510 case DIFF_SYMBOL_STAT_SEP:
1511 fputs(o->stat_sep, o->file);
1512 break;
1513 default:
1514 BUG("unknown diff symbol");
1516 strbuf_release(&sb);
1519 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1520 const char *line, int len, unsigned flags)
1522 struct emitted_diff_symbol e = {
1523 .line = line, .len = len, .flags = flags, .s = s
1526 if (o->emitted_symbols)
1527 append_emitted_diff_symbol(o, &e);
1528 else
1529 emit_diff_symbol_from_struct(o, &e);
1532 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1534 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1537 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1539 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1542 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1544 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1545 path, strlen(path), 0);
1548 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1550 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1551 path, strlen(path), 0);
1554 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1556 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1557 header, strlen(header), 0);
1560 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1562 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1565 void diff_emit_submodule_pipethrough(struct diff_options *o,
1566 const char *line, int len)
1568 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1571 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1573 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1574 ecbdata->blank_at_eof_in_preimage &&
1575 ecbdata->blank_at_eof_in_postimage &&
1576 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1577 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1578 return 0;
1579 return ws_blank_line(line, len, ecbdata->ws_rule);
1582 static void emit_add_line(struct emit_callback *ecbdata,
1583 const char *line, int len)
1585 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1586 if (new_blank_line_at_eof(ecbdata, line, len))
1587 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1589 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1592 static void emit_del_line(struct emit_callback *ecbdata,
1593 const char *line, int len)
1595 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1596 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1599 static void emit_context_line(struct emit_callback *ecbdata,
1600 const char *line, int len)
1602 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1603 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1606 static void emit_hunk_header(struct emit_callback *ecbdata,
1607 const char *line, int len)
1609 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1610 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1611 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1612 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1613 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1614 static const char atat[2] = { '@', '@' };
1615 const char *cp, *ep;
1616 struct strbuf msgbuf = STRBUF_INIT;
1617 int org_len = len;
1618 int i = 1;
1621 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1622 * it always is at least 10 bytes long.
1624 if (len < 10 ||
1625 memcmp(line, atat, 2) ||
1626 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1627 emit_diff_symbol(ecbdata->opt,
1628 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1629 return;
1631 ep += 2; /* skip over @@ */
1633 /* The hunk header in fraginfo color */
1634 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1635 strbuf_addstr(&msgbuf, reverse);
1636 strbuf_addstr(&msgbuf, frag);
1637 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1638 strbuf_add(&msgbuf, atat, sizeof(atat));
1639 else
1640 strbuf_add(&msgbuf, line, ep - line);
1641 strbuf_addstr(&msgbuf, reset);
1644 * trailing "\r\n"
1646 for ( ; i < 3; i++)
1647 if (line[len - i] == '\r' || line[len - i] == '\n')
1648 len--;
1650 /* blank before the func header */
1651 for (cp = ep; ep - line < len; ep++)
1652 if (*ep != ' ' && *ep != '\t')
1653 break;
1654 if (ep != cp) {
1655 strbuf_addstr(&msgbuf, context);
1656 strbuf_add(&msgbuf, cp, ep - cp);
1657 strbuf_addstr(&msgbuf, reset);
1660 if (ep < line + len) {
1661 strbuf_addstr(&msgbuf, func);
1662 strbuf_add(&msgbuf, ep, line + len - ep);
1663 strbuf_addstr(&msgbuf, reset);
1666 strbuf_add(&msgbuf, line + len, org_len - len);
1667 strbuf_complete_line(&msgbuf);
1668 emit_diff_symbol(ecbdata->opt,
1669 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1670 strbuf_release(&msgbuf);
1673 static struct diff_tempfile *claim_diff_tempfile(void)
1675 int i;
1676 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1677 if (!diff_temp[i].name)
1678 return diff_temp + i;
1679 BUG("diff is failing to clean up its tempfiles");
1682 static void remove_tempfile(void)
1684 int i;
1685 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1686 if (is_tempfile_active(diff_temp[i].tempfile))
1687 delete_tempfile(&diff_temp[i].tempfile);
1688 diff_temp[i].name = NULL;
1692 static void add_line_count(struct strbuf *out, int count)
1694 switch (count) {
1695 case 0:
1696 strbuf_addstr(out, "0,0");
1697 break;
1698 case 1:
1699 strbuf_addstr(out, "1");
1700 break;
1701 default:
1702 strbuf_addf(out, "1,%d", count);
1703 break;
1707 static void emit_rewrite_lines(struct emit_callback *ecb,
1708 int prefix, const char *data, int size)
1710 const char *endp = NULL;
1712 while (0 < size) {
1713 int len;
1715 endp = memchr(data, '\n', size);
1716 len = endp ? (endp - data + 1) : size;
1717 if (prefix != '+') {
1718 ecb->lno_in_preimage++;
1719 emit_del_line(ecb, data, len);
1720 } else {
1721 ecb->lno_in_postimage++;
1722 emit_add_line(ecb, data, len);
1724 size -= len;
1725 data += len;
1727 if (!endp)
1728 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1731 static void emit_rewrite_diff(const char *name_a,
1732 const char *name_b,
1733 struct diff_filespec *one,
1734 struct diff_filespec *two,
1735 struct userdiff_driver *textconv_one,
1736 struct userdiff_driver *textconv_two,
1737 struct diff_options *o)
1739 int lc_a, lc_b;
1740 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1741 const char *a_prefix, *b_prefix;
1742 char *data_one, *data_two;
1743 size_t size_one, size_two;
1744 struct emit_callback ecbdata;
1745 struct strbuf out = STRBUF_INIT;
1747 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1748 a_prefix = o->b_prefix;
1749 b_prefix = o->a_prefix;
1750 } else {
1751 a_prefix = o->a_prefix;
1752 b_prefix = o->b_prefix;
1755 name_a += (*name_a == '/');
1756 name_b += (*name_b == '/');
1758 strbuf_reset(&a_name);
1759 strbuf_reset(&b_name);
1760 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1761 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1763 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1764 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1766 memset(&ecbdata, 0, sizeof(ecbdata));
1767 ecbdata.color_diff = want_color(o->use_color);
1768 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1769 ecbdata.opt = o;
1770 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1771 mmfile_t mf1, mf2;
1772 mf1.ptr = (char *)data_one;
1773 mf2.ptr = (char *)data_two;
1774 mf1.size = size_one;
1775 mf2.size = size_two;
1776 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1778 ecbdata.lno_in_preimage = 1;
1779 ecbdata.lno_in_postimage = 1;
1781 lc_a = count_lines(data_one, size_one);
1782 lc_b = count_lines(data_two, size_two);
1784 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1785 a_name.buf, a_name.len, 0);
1786 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1787 b_name.buf, b_name.len, 0);
1789 strbuf_addstr(&out, "@@ -");
1790 if (!o->irreversible_delete)
1791 add_line_count(&out, lc_a);
1792 else
1793 strbuf_addstr(&out, "?,?");
1794 strbuf_addstr(&out, " +");
1795 add_line_count(&out, lc_b);
1796 strbuf_addstr(&out, " @@\n");
1797 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1798 strbuf_release(&out);
1800 if (lc_a && !o->irreversible_delete)
1801 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1802 if (lc_b)
1803 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1804 if (textconv_one)
1805 free((char *)data_one);
1806 if (textconv_two)
1807 free((char *)data_two);
1810 struct diff_words_buffer {
1811 mmfile_t text;
1812 unsigned long alloc;
1813 struct diff_words_orig {
1814 const char *begin, *end;
1815 } *orig;
1816 int orig_nr, orig_alloc;
1819 static void diff_words_append(char *line, unsigned long len,
1820 struct diff_words_buffer *buffer)
1822 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1823 line++;
1824 len--;
1825 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1826 buffer->text.size += len;
1827 buffer->text.ptr[buffer->text.size] = '\0';
1830 struct diff_words_style_elem {
1831 const char *prefix;
1832 const char *suffix;
1833 const char *color; /* NULL; filled in by the setup code if
1834 * color is enabled */
1837 struct diff_words_style {
1838 enum diff_words_type type;
1839 struct diff_words_style_elem new_word, old_word, ctx;
1840 const char *newline;
1843 static struct diff_words_style diff_words_styles[] = {
1844 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1845 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1846 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1849 struct diff_words_data {
1850 struct diff_words_buffer minus, plus;
1851 const char *current_plus;
1852 int last_minus;
1853 struct diff_options *opt;
1854 regex_t *word_regex;
1855 enum diff_words_type type;
1856 struct diff_words_style *style;
1859 static int fn_out_diff_words_write_helper(struct diff_options *o,
1860 struct diff_words_style_elem *st_el,
1861 const char *newline,
1862 size_t count, const char *buf)
1864 int print = 0;
1865 struct strbuf sb = STRBUF_INIT;
1867 while (count) {
1868 char *p = memchr(buf, '\n', count);
1869 if (print)
1870 strbuf_addstr(&sb, diff_line_prefix(o));
1872 if (p != buf) {
1873 const char *reset = st_el->color && *st_el->color ?
1874 GIT_COLOR_RESET : NULL;
1875 if (st_el->color && *st_el->color)
1876 strbuf_addstr(&sb, st_el->color);
1877 strbuf_addstr(&sb, st_el->prefix);
1878 strbuf_add(&sb, buf, p ? p - buf : count);
1879 strbuf_addstr(&sb, st_el->suffix);
1880 if (reset)
1881 strbuf_addstr(&sb, reset);
1883 if (!p)
1884 goto out;
1886 strbuf_addstr(&sb, newline);
1887 count -= p + 1 - buf;
1888 buf = p + 1;
1889 print = 1;
1890 if (count) {
1891 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1892 sb.buf, sb.len, 0);
1893 strbuf_reset(&sb);
1897 out:
1898 if (sb.len)
1899 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1900 sb.buf, sb.len, 0);
1901 strbuf_release(&sb);
1902 return 0;
1906 * '--color-words' algorithm can be described as:
1908 * 1. collect the minus/plus lines of a diff hunk, divided into
1909 * minus-lines and plus-lines;
1911 * 2. break both minus-lines and plus-lines into words and
1912 * place them into two mmfile_t with one word for each line;
1914 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1916 * And for the common parts of the both file, we output the plus side text.
1917 * diff_words->current_plus is used to trace the current position of the plus file
1918 * which printed. diff_words->last_minus is used to trace the last minus word
1919 * printed.
1921 * For '--graph' to work with '--color-words', we need to output the graph prefix
1922 * on each line of color words output. Generally, there are two conditions on
1923 * which we should output the prefix.
1925 * 1. diff_words->last_minus == 0 &&
1926 * diff_words->current_plus == diff_words->plus.text.ptr
1928 * that is: the plus text must start as a new line, and if there is no minus
1929 * word printed, a graph prefix must be printed.
1931 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1932 * *(diff_words->current_plus - 1) == '\n'
1934 * that is: a graph prefix must be printed following a '\n'
1936 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1938 if ((diff_words->last_minus == 0 &&
1939 diff_words->current_plus == diff_words->plus.text.ptr) ||
1940 (diff_words->current_plus > diff_words->plus.text.ptr &&
1941 *(diff_words->current_plus - 1) == '\n')) {
1942 return 1;
1943 } else {
1944 return 0;
1948 static void fn_out_diff_words_aux(void *priv,
1949 long minus_first, long minus_len,
1950 long plus_first, long plus_len,
1951 const char *func, long funclen)
1953 struct diff_words_data *diff_words = priv;
1954 struct diff_words_style *style = diff_words->style;
1955 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1956 struct diff_options *opt = diff_words->opt;
1957 const char *line_prefix;
1959 assert(opt);
1960 line_prefix = diff_line_prefix(opt);
1962 /* POSIX requires that first be decremented by one if len == 0... */
1963 if (minus_len) {
1964 minus_begin = diff_words->minus.orig[minus_first].begin;
1965 minus_end =
1966 diff_words->minus.orig[minus_first + minus_len - 1].end;
1967 } else
1968 minus_begin = minus_end =
1969 diff_words->minus.orig[minus_first].end;
1971 if (plus_len) {
1972 plus_begin = diff_words->plus.orig[plus_first].begin;
1973 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1974 } else
1975 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1977 if (color_words_output_graph_prefix(diff_words)) {
1978 fputs(line_prefix, diff_words->opt->file);
1980 if (diff_words->current_plus != plus_begin) {
1981 fn_out_diff_words_write_helper(diff_words->opt,
1982 &style->ctx, style->newline,
1983 plus_begin - diff_words->current_plus,
1984 diff_words->current_plus);
1986 if (minus_begin != minus_end) {
1987 fn_out_diff_words_write_helper(diff_words->opt,
1988 &style->old_word, style->newline,
1989 minus_end - minus_begin, minus_begin);
1991 if (plus_begin != plus_end) {
1992 fn_out_diff_words_write_helper(diff_words->opt,
1993 &style->new_word, style->newline,
1994 plus_end - plus_begin, plus_begin);
1997 diff_words->current_plus = plus_end;
1998 diff_words->last_minus = minus_first;
2001 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2002 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2003 int *begin, int *end)
2005 while (word_regex && *begin < buffer->size) {
2006 regmatch_t match[1];
2007 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2008 buffer->size - *begin, 1, match, 0)) {
2009 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2010 '\n', match[0].rm_eo - match[0].rm_so);
2011 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2012 *begin += match[0].rm_so;
2013 if (*begin == *end)
2014 (*begin)++;
2015 else
2016 return *begin > *end;
2017 } else {
2018 return -1;
2022 /* find the next word */
2023 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2024 (*begin)++;
2025 if (*begin >= buffer->size)
2026 return -1;
2028 /* find the end of the word */
2029 *end = *begin + 1;
2030 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2031 (*end)++;
2033 return 0;
2037 * This function splits the words in buffer->text, stores the list with
2038 * newline separator into out, and saves the offsets of the original words
2039 * in buffer->orig.
2041 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2042 regex_t *word_regex)
2044 int i, j;
2045 long alloc = 0;
2047 out->size = 0;
2048 out->ptr = NULL;
2050 /* fake an empty "0th" word */
2051 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2052 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2053 buffer->orig_nr = 1;
2055 for (i = 0; i < buffer->text.size; i++) {
2056 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2057 return;
2059 /* store original boundaries */
2060 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2061 buffer->orig_alloc);
2062 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2063 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2064 buffer->orig_nr++;
2066 /* store one word */
2067 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2068 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2069 out->ptr[out->size + j - i] = '\n';
2070 out->size += j - i + 1;
2072 i = j - 1;
2076 /* this executes the word diff on the accumulated buffers */
2077 static void diff_words_show(struct diff_words_data *diff_words)
2079 xpparam_t xpp;
2080 xdemitconf_t xecfg;
2081 mmfile_t minus, plus;
2082 struct diff_words_style *style = diff_words->style;
2084 struct diff_options *opt = diff_words->opt;
2085 const char *line_prefix;
2087 assert(opt);
2088 line_prefix = diff_line_prefix(opt);
2090 /* special case: only removal */
2091 if (!diff_words->plus.text.size) {
2092 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2093 line_prefix, strlen(line_prefix), 0);
2094 fn_out_diff_words_write_helper(diff_words->opt,
2095 &style->old_word, style->newline,
2096 diff_words->minus.text.size,
2097 diff_words->minus.text.ptr);
2098 diff_words->minus.text.size = 0;
2099 return;
2102 diff_words->current_plus = diff_words->plus.text.ptr;
2103 diff_words->last_minus = 0;
2105 memset(&xpp, 0, sizeof(xpp));
2106 memset(&xecfg, 0, sizeof(xecfg));
2107 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2108 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2109 xpp.flags = 0;
2110 /* as only the hunk header will be parsed, we need a 0-context */
2111 xecfg.ctxlen = 0;
2112 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2113 diff_words, &xpp, &xecfg))
2114 die("unable to generate word diff");
2115 free(minus.ptr);
2116 free(plus.ptr);
2117 if (diff_words->current_plus != diff_words->plus.text.ptr +
2118 diff_words->plus.text.size) {
2119 if (color_words_output_graph_prefix(diff_words))
2120 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2121 line_prefix, strlen(line_prefix), 0);
2122 fn_out_diff_words_write_helper(diff_words->opt,
2123 &style->ctx, style->newline,
2124 diff_words->plus.text.ptr + diff_words->plus.text.size
2125 - diff_words->current_plus, diff_words->current_plus);
2127 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2130 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2131 static void diff_words_flush(struct emit_callback *ecbdata)
2133 struct diff_options *wo = ecbdata->diff_words->opt;
2135 if (ecbdata->diff_words->minus.text.size ||
2136 ecbdata->diff_words->plus.text.size)
2137 diff_words_show(ecbdata->diff_words);
2139 if (wo->emitted_symbols) {
2140 struct diff_options *o = ecbdata->opt;
2141 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2142 int i;
2145 * NEEDSWORK:
2146 * Instead of appending each, concat all words to a line?
2148 for (i = 0; i < wol->nr; i++)
2149 append_emitted_diff_symbol(o, &wol->buf[i]);
2151 for (i = 0; i < wol->nr; i++)
2152 free((void *)wol->buf[i].line);
2153 free(wol->buf);
2155 wol->nr = 0;
2159 static void diff_filespec_load_driver(struct diff_filespec *one,
2160 struct index_state *istate)
2162 /* Use already-loaded driver */
2163 if (one->driver)
2164 return;
2166 if (S_ISREG(one->mode))
2167 one->driver = userdiff_find_by_path(istate, one->path);
2169 /* Fallback to default settings */
2170 if (!one->driver)
2171 one->driver = userdiff_find_by_name("default");
2174 static const char *userdiff_word_regex(struct diff_filespec *one,
2175 struct index_state *istate)
2177 diff_filespec_load_driver(one, istate);
2178 return one->driver->word_regex;
2181 static void init_diff_words_data(struct emit_callback *ecbdata,
2182 struct diff_options *orig_opts,
2183 struct diff_filespec *one,
2184 struct diff_filespec *two)
2186 int i;
2187 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2188 memcpy(o, orig_opts, sizeof(struct diff_options));
2190 CALLOC_ARRAY(ecbdata->diff_words, 1);
2191 ecbdata->diff_words->type = o->word_diff;
2192 ecbdata->diff_words->opt = o;
2194 if (orig_opts->emitted_symbols)
2195 CALLOC_ARRAY(o->emitted_symbols, 1);
2197 if (!o->word_regex)
2198 o->word_regex = userdiff_word_regex(one, o->repo->index);
2199 if (!o->word_regex)
2200 o->word_regex = userdiff_word_regex(two, o->repo->index);
2201 if (!o->word_regex)
2202 o->word_regex = diff_word_regex_cfg;
2203 if (o->word_regex) {
2204 ecbdata->diff_words->word_regex = (regex_t *)
2205 xmalloc(sizeof(regex_t));
2206 if (regcomp(ecbdata->diff_words->word_regex,
2207 o->word_regex,
2208 REG_EXTENDED | REG_NEWLINE))
2209 die("invalid regular expression: %s",
2210 o->word_regex);
2212 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2213 if (o->word_diff == diff_words_styles[i].type) {
2214 ecbdata->diff_words->style =
2215 &diff_words_styles[i];
2216 break;
2219 if (want_color(o->use_color)) {
2220 struct diff_words_style *st = ecbdata->diff_words->style;
2221 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2222 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2223 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2227 static void free_diff_words_data(struct emit_callback *ecbdata)
2229 if (ecbdata->diff_words) {
2230 diff_words_flush(ecbdata);
2231 free (ecbdata->diff_words->opt->emitted_symbols);
2232 free (ecbdata->diff_words->opt);
2233 free (ecbdata->diff_words->minus.text.ptr);
2234 free (ecbdata->diff_words->minus.orig);
2235 free (ecbdata->diff_words->plus.text.ptr);
2236 free (ecbdata->diff_words->plus.orig);
2237 if (ecbdata->diff_words->word_regex) {
2238 regfree(ecbdata->diff_words->word_regex);
2239 free(ecbdata->diff_words->word_regex);
2241 FREE_AND_NULL(ecbdata->diff_words);
2245 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2247 if (want_color(diff_use_color))
2248 return diff_colors[ix];
2249 return "";
2252 const char *diff_line_prefix(struct diff_options *opt)
2254 struct strbuf *msgbuf;
2255 if (!opt->output_prefix)
2256 return "";
2258 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2259 return msgbuf->buf;
2262 static unsigned long sane_truncate_line(char *line, unsigned long len)
2264 const char *cp;
2265 unsigned long allot;
2266 size_t l = len;
2268 cp = line;
2269 allot = l;
2270 while (0 < l) {
2271 (void) utf8_width(&cp, &l);
2272 if (!cp)
2273 break; /* truncated in the middle? */
2275 return allot - l;
2278 static void find_lno(const char *line, struct emit_callback *ecbdata)
2280 const char *p;
2281 ecbdata->lno_in_preimage = 0;
2282 ecbdata->lno_in_postimage = 0;
2283 p = strchr(line, '-');
2284 if (!p)
2285 return; /* cannot happen */
2286 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2287 p = strchr(p, '+');
2288 if (!p)
2289 return; /* cannot happen */
2290 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2293 static int fn_out_consume(void *priv, char *line, unsigned long len)
2295 struct emit_callback *ecbdata = priv;
2296 struct diff_options *o = ecbdata->opt;
2298 o->found_changes = 1;
2300 if (ecbdata->header) {
2301 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2302 ecbdata->header->buf, ecbdata->header->len, 0);
2303 strbuf_reset(ecbdata->header);
2304 ecbdata->header = NULL;
2307 if (ecbdata->label_path[0]) {
2308 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2309 ecbdata->label_path[0],
2310 strlen(ecbdata->label_path[0]), 0);
2311 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2312 ecbdata->label_path[1],
2313 strlen(ecbdata->label_path[1]), 0);
2314 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2317 if (diff_suppress_blank_empty
2318 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2319 line[0] = '\n';
2320 len = 1;
2323 if (line[0] == '@') {
2324 if (ecbdata->diff_words)
2325 diff_words_flush(ecbdata);
2326 len = sane_truncate_line(line, len);
2327 find_lno(line, ecbdata);
2328 emit_hunk_header(ecbdata, line, len);
2329 return 0;
2332 if (ecbdata->diff_words) {
2333 enum diff_symbol s =
2334 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2335 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2336 if (line[0] == '-') {
2337 diff_words_append(line, len,
2338 &ecbdata->diff_words->minus);
2339 return 0;
2340 } else if (line[0] == '+') {
2341 diff_words_append(line, len,
2342 &ecbdata->diff_words->plus);
2343 return 0;
2344 } else if (starts_with(line, "\\ ")) {
2346 * Eat the "no newline at eof" marker as if we
2347 * saw a "+" or "-" line with nothing on it,
2348 * and return without diff_words_flush() to
2349 * defer processing. If this is the end of
2350 * preimage, more "+" lines may come after it.
2352 return 0;
2354 diff_words_flush(ecbdata);
2355 emit_diff_symbol(o, s, line, len, 0);
2356 return 0;
2359 switch (line[0]) {
2360 case '+':
2361 ecbdata->lno_in_postimage++;
2362 emit_add_line(ecbdata, line + 1, len - 1);
2363 break;
2364 case '-':
2365 ecbdata->lno_in_preimage++;
2366 emit_del_line(ecbdata, line + 1, len - 1);
2367 break;
2368 case ' ':
2369 ecbdata->lno_in_postimage++;
2370 ecbdata->lno_in_preimage++;
2371 emit_context_line(ecbdata, line + 1, len - 1);
2372 break;
2373 default:
2374 /* incomplete line at the end */
2375 ecbdata->lno_in_preimage++;
2376 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2377 line, len, 0);
2378 break;
2380 return 0;
2383 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2385 const char *old_name = a;
2386 const char *new_name = b;
2387 int pfx_length, sfx_length;
2388 int pfx_adjust_for_slash;
2389 int len_a = strlen(a);
2390 int len_b = strlen(b);
2391 int a_midlen, b_midlen;
2392 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2393 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2395 if (qlen_a || qlen_b) {
2396 quote_c_style(a, name, NULL, 0);
2397 strbuf_addstr(name, " => ");
2398 quote_c_style(b, name, NULL, 0);
2399 return;
2402 /* Find common prefix */
2403 pfx_length = 0;
2404 while (*old_name && *new_name && *old_name == *new_name) {
2405 if (*old_name == '/')
2406 pfx_length = old_name - a + 1;
2407 old_name++;
2408 new_name++;
2411 /* Find common suffix */
2412 old_name = a + len_a;
2413 new_name = b + len_b;
2414 sfx_length = 0;
2416 * If there is a common prefix, it must end in a slash. In
2417 * that case we let this loop run 1 into the prefix to see the
2418 * same slash.
2420 * If there is no common prefix, we cannot do this as it would
2421 * underrun the input strings.
2423 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2424 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2425 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2426 *old_name == *new_name) {
2427 if (*old_name == '/')
2428 sfx_length = len_a - (old_name - a);
2429 old_name--;
2430 new_name--;
2434 * pfx{mid-a => mid-b}sfx
2435 * {pfx-a => pfx-b}sfx
2436 * pfx{sfx-a => sfx-b}
2437 * name-a => name-b
2439 a_midlen = len_a - pfx_length - sfx_length;
2440 b_midlen = len_b - pfx_length - sfx_length;
2441 if (a_midlen < 0)
2442 a_midlen = 0;
2443 if (b_midlen < 0)
2444 b_midlen = 0;
2446 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2447 if (pfx_length + sfx_length) {
2448 strbuf_add(name, a, pfx_length);
2449 strbuf_addch(name, '{');
2451 strbuf_add(name, a + pfx_length, a_midlen);
2452 strbuf_addstr(name, " => ");
2453 strbuf_add(name, b + pfx_length, b_midlen);
2454 if (pfx_length + sfx_length) {
2455 strbuf_addch(name, '}');
2456 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2460 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2461 const char *name_a,
2462 const char *name_b)
2464 struct diffstat_file *x;
2465 CALLOC_ARRAY(x, 1);
2466 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2467 diffstat->files[diffstat->nr++] = x;
2468 if (name_b) {
2469 x->from_name = xstrdup(name_a);
2470 x->name = xstrdup(name_b);
2471 x->is_renamed = 1;
2473 else {
2474 x->from_name = NULL;
2475 x->name = xstrdup(name_a);
2477 return x;
2480 static int diffstat_consume(void *priv, char *line, unsigned long len)
2482 struct diffstat_t *diffstat = priv;
2483 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2485 if (line[0] == '+')
2486 x->added++;
2487 else if (line[0] == '-')
2488 x->deleted++;
2489 return 0;
2492 const char mime_boundary_leader[] = "------------";
2494 static int scale_linear(int it, int width, int max_change)
2496 if (!it)
2497 return 0;
2499 * make sure that at least one '-' or '+' is printed if
2500 * there is any change to this path. The easiest way is to
2501 * scale linearly as if the allotted width is one column shorter
2502 * than it is, and then add 1 to the result.
2504 return 1 + (it * (width - 1) / max_change);
2507 static void show_graph(struct strbuf *out, char ch, int cnt,
2508 const char *set, const char *reset)
2510 if (cnt <= 0)
2511 return;
2512 strbuf_addstr(out, set);
2513 strbuf_addchars(out, ch, cnt);
2514 strbuf_addstr(out, reset);
2517 static void fill_print_name(struct diffstat_file *file)
2519 struct strbuf pname = STRBUF_INIT;
2521 if (file->print_name)
2522 return;
2524 if (file->is_renamed)
2525 pprint_rename(&pname, file->from_name, file->name);
2526 else
2527 quote_c_style(file->name, &pname, NULL, 0);
2529 if (file->comments)
2530 strbuf_addf(&pname, " (%s)", file->comments);
2532 file->print_name = strbuf_detach(&pname, NULL);
2535 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2536 int files, int insertions, int deletions)
2538 struct strbuf sb = STRBUF_INIT;
2540 if (!files) {
2541 assert(insertions == 0 && deletions == 0);
2542 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2543 NULL, 0, 0);
2544 return;
2547 strbuf_addf(&sb,
2548 (files == 1) ? " %d file changed" : " %d files changed",
2549 files);
2552 * For binary diff, the caller may want to print "x files
2553 * changed" with insertions == 0 && deletions == 0.
2555 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2556 * is probably less confusing (i.e skip over "2 files changed
2557 * but nothing about added/removed lines? Is this a bug in Git?").
2559 if (insertions || deletions == 0) {
2560 strbuf_addf(&sb,
2561 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2562 insertions);
2565 if (deletions || insertions == 0) {
2566 strbuf_addf(&sb,
2567 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2568 deletions);
2570 strbuf_addch(&sb, '\n');
2571 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2572 sb.buf, sb.len, 0);
2573 strbuf_release(&sb);
2576 void print_stat_summary(FILE *fp, int files,
2577 int insertions, int deletions)
2579 struct diff_options o;
2580 memset(&o, 0, sizeof(o));
2581 o.file = fp;
2583 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2586 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2588 int i, len, add, del, adds = 0, dels = 0;
2589 uintmax_t max_change = 0, max_len = 0;
2590 int total_files = data->nr, count;
2591 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2592 const char *reset, *add_c, *del_c;
2593 int extra_shown = 0;
2594 const char *line_prefix = diff_line_prefix(options);
2595 struct strbuf out = STRBUF_INIT;
2597 if (data->nr == 0)
2598 return;
2600 count = options->stat_count ? options->stat_count : data->nr;
2602 reset = diff_get_color_opt(options, DIFF_RESET);
2603 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2604 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2607 * Find the longest filename and max number of changes
2609 for (i = 0; (i < count) && (i < data->nr); i++) {
2610 struct diffstat_file *file = data->files[i];
2611 uintmax_t change = file->added + file->deleted;
2613 if (!file->is_interesting && (change == 0)) {
2614 count++; /* not shown == room for one more */
2615 continue;
2617 fill_print_name(file);
2618 len = strlen(file->print_name);
2619 if (max_len < len)
2620 max_len = len;
2622 if (file->is_unmerged) {
2623 /* "Unmerged" is 8 characters */
2624 bin_width = bin_width < 8 ? 8 : bin_width;
2625 continue;
2627 if (file->is_binary) {
2628 /* "Bin XXX -> YYY bytes" */
2629 int w = 14 + decimal_width(file->added)
2630 + decimal_width(file->deleted);
2631 bin_width = bin_width < w ? w : bin_width;
2632 /* Display change counts aligned with "Bin" */
2633 number_width = 3;
2634 continue;
2637 if (max_change < change)
2638 max_change = change;
2640 count = i; /* where we can stop scanning in data->files[] */
2643 * We have width = stat_width or term_columns() columns total.
2644 * We want a maximum of min(max_len, stat_name_width) for the name part.
2645 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2646 * We also need 1 for " " and 4 + decimal_width(max_change)
2647 * for " | NNNN " and one the empty column at the end, altogether
2648 * 6 + decimal_width(max_change).
2650 * If there's not enough space, we will use the smaller of
2651 * stat_name_width (if set) and 5/8*width for the filename,
2652 * and the rest for constant elements + graph part, but no more
2653 * than stat_graph_width for the graph part.
2654 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2655 * for the standard terminal size).
2657 * In other words: stat_width limits the maximum width, and
2658 * stat_name_width fixes the maximum width of the filename,
2659 * and is also used to divide available columns if there
2660 * aren't enough.
2662 * Binary files are displayed with "Bin XXX -> YYY bytes"
2663 * instead of the change count and graph. This part is treated
2664 * similarly to the graph part, except that it is not
2665 * "scaled". If total width is too small to accommodate the
2666 * guaranteed minimum width of the filename part and the
2667 * separators and this message, this message will "overflow"
2668 * making the line longer than the maximum width.
2671 if (options->stat_width == -1)
2672 width = term_columns() - strlen(line_prefix);
2673 else
2674 width = options->stat_width ? options->stat_width : 80;
2675 number_width = decimal_width(max_change) > number_width ?
2676 decimal_width(max_change) : number_width;
2678 if (options->stat_graph_width == -1)
2679 options->stat_graph_width = diff_stat_graph_width;
2682 * Guarantee 3/8*16==6 for the graph part
2683 * and 5/8*16==10 for the filename part
2685 if (width < 16 + 6 + number_width)
2686 width = 16 + 6 + number_width;
2689 * First assign sizes that are wanted, ignoring available width.
2690 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2691 * starting from "XXX" should fit in graph_width.
2693 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2694 if (options->stat_graph_width &&
2695 options->stat_graph_width < graph_width)
2696 graph_width = options->stat_graph_width;
2698 name_width = (options->stat_name_width > 0 &&
2699 options->stat_name_width < max_len) ?
2700 options->stat_name_width : max_len;
2703 * Adjust adjustable widths not to exceed maximum width
2705 if (name_width + number_width + 6 + graph_width > width) {
2706 if (graph_width > width * 3/8 - number_width - 6) {
2707 graph_width = width * 3/8 - number_width - 6;
2708 if (graph_width < 6)
2709 graph_width = 6;
2712 if (options->stat_graph_width &&
2713 graph_width > options->stat_graph_width)
2714 graph_width = options->stat_graph_width;
2715 if (name_width > width - number_width - 6 - graph_width)
2716 name_width = width - number_width - 6 - graph_width;
2717 else
2718 graph_width = width - number_width - 6 - name_width;
2722 * From here name_width is the width of the name area,
2723 * and graph_width is the width of the graph area.
2724 * max_change is used to scale graph properly.
2726 for (i = 0; i < count; i++) {
2727 const char *prefix = "";
2728 struct diffstat_file *file = data->files[i];
2729 char *name = file->print_name;
2730 uintmax_t added = file->added;
2731 uintmax_t deleted = file->deleted;
2732 int name_len;
2734 if (!file->is_interesting && (added + deleted == 0))
2735 continue;
2738 * "scale" the filename
2740 len = name_width;
2741 name_len = strlen(name);
2742 if (name_width < name_len) {
2743 char *slash;
2744 prefix = "...";
2745 len -= 3;
2746 name += name_len - len;
2747 slash = strchr(name, '/');
2748 if (slash)
2749 name = slash;
2752 if (file->is_binary) {
2753 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2754 strbuf_addf(&out, " %*s", number_width, "Bin");
2755 if (!added && !deleted) {
2756 strbuf_addch(&out, '\n');
2757 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2758 out.buf, out.len, 0);
2759 strbuf_reset(&out);
2760 continue;
2762 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2763 del_c, deleted, reset);
2764 strbuf_addstr(&out, " -> ");
2765 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2766 add_c, added, reset);
2767 strbuf_addstr(&out, " bytes\n");
2768 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2769 out.buf, out.len, 0);
2770 strbuf_reset(&out);
2771 continue;
2773 else if (file->is_unmerged) {
2774 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2775 strbuf_addstr(&out, " Unmerged\n");
2776 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2777 out.buf, out.len, 0);
2778 strbuf_reset(&out);
2779 continue;
2783 * scale the add/delete
2785 add = added;
2786 del = deleted;
2788 if (graph_width <= max_change) {
2789 int total = scale_linear(add + del, graph_width, max_change);
2790 if (total < 2 && add && del)
2791 /* width >= 2 due to the sanity check */
2792 total = 2;
2793 if (add < del) {
2794 add = scale_linear(add, graph_width, max_change);
2795 del = total - add;
2796 } else {
2797 del = scale_linear(del, graph_width, max_change);
2798 add = total - del;
2801 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2802 strbuf_addf(&out, " %*"PRIuMAX"%s",
2803 number_width, added + deleted,
2804 added + deleted ? " " : "");
2805 show_graph(&out, '+', add, add_c, reset);
2806 show_graph(&out, '-', del, del_c, reset);
2807 strbuf_addch(&out, '\n');
2808 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2809 out.buf, out.len, 0);
2810 strbuf_reset(&out);
2813 for (i = 0; i < data->nr; i++) {
2814 struct diffstat_file *file = data->files[i];
2815 uintmax_t added = file->added;
2816 uintmax_t deleted = file->deleted;
2818 if (file->is_unmerged ||
2819 (!file->is_interesting && (added + deleted == 0))) {
2820 total_files--;
2821 continue;
2824 if (!file->is_binary) {
2825 adds += added;
2826 dels += deleted;
2828 if (i < count)
2829 continue;
2830 if (!extra_shown)
2831 emit_diff_symbol(options,
2832 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2833 NULL, 0, 0);
2834 extra_shown = 1;
2837 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2838 strbuf_release(&out);
2841 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2843 int i, adds = 0, dels = 0, total_files = data->nr;
2845 if (data->nr == 0)
2846 return;
2848 for (i = 0; i < data->nr; i++) {
2849 int added = data->files[i]->added;
2850 int deleted = data->files[i]->deleted;
2852 if (data->files[i]->is_unmerged ||
2853 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2854 total_files--;
2855 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2856 adds += added;
2857 dels += deleted;
2860 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2863 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2865 int i;
2867 if (data->nr == 0)
2868 return;
2870 for (i = 0; i < data->nr; i++) {
2871 struct diffstat_file *file = data->files[i];
2873 fprintf(options->file, "%s", diff_line_prefix(options));
2875 if (file->is_binary)
2876 fprintf(options->file, "-\t-\t");
2877 else
2878 fprintf(options->file,
2879 "%"PRIuMAX"\t%"PRIuMAX"\t",
2880 file->added, file->deleted);
2881 if (options->line_termination) {
2882 fill_print_name(file);
2883 if (!file->is_renamed)
2884 write_name_quoted(file->name, options->file,
2885 options->line_termination);
2886 else {
2887 fputs(file->print_name, options->file);
2888 putc(options->line_termination, options->file);
2890 } else {
2891 if (file->is_renamed) {
2892 putc('\0', options->file);
2893 write_name_quoted(file->from_name, options->file, '\0');
2895 write_name_quoted(file->name, options->file, '\0');
2900 struct dirstat_file {
2901 const char *name;
2902 unsigned long changed;
2905 struct dirstat_dir {
2906 struct dirstat_file *files;
2907 int alloc, nr, permille, cumulative;
2910 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2911 unsigned long changed, const char *base, int baselen)
2913 unsigned long sum_changes = 0;
2914 unsigned int sources = 0;
2915 const char *line_prefix = diff_line_prefix(opt);
2917 while (dir->nr) {
2918 struct dirstat_file *f = dir->files;
2919 int namelen = strlen(f->name);
2920 unsigned long changes;
2921 char *slash;
2923 if (namelen < baselen)
2924 break;
2925 if (memcmp(f->name, base, baselen))
2926 break;
2927 slash = strchr(f->name + baselen, '/');
2928 if (slash) {
2929 int newbaselen = slash + 1 - f->name;
2930 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2931 sources++;
2932 } else {
2933 changes = f->changed;
2934 dir->files++;
2935 dir->nr--;
2936 sources += 2;
2938 sum_changes += changes;
2942 * We don't report dirstat's for
2943 * - the top level
2944 * - or cases where everything came from a single directory
2945 * under this directory (sources == 1).
2947 if (baselen && sources != 1) {
2948 if (sum_changes) {
2949 int permille = sum_changes * 1000 / changed;
2950 if (permille >= dir->permille) {
2951 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2952 permille / 10, permille % 10, baselen, base);
2953 if (!dir->cumulative)
2954 return 0;
2958 return sum_changes;
2961 static int dirstat_compare(const void *_a, const void *_b)
2963 const struct dirstat_file *a = _a;
2964 const struct dirstat_file *b = _b;
2965 return strcmp(a->name, b->name);
2968 static void show_dirstat(struct diff_options *options)
2970 int i;
2971 unsigned long changed;
2972 struct dirstat_dir dir;
2973 struct diff_queue_struct *q = &diff_queued_diff;
2975 dir.files = NULL;
2976 dir.alloc = 0;
2977 dir.nr = 0;
2978 dir.permille = options->dirstat_permille;
2979 dir.cumulative = options->flags.dirstat_cumulative;
2981 changed = 0;
2982 for (i = 0; i < q->nr; i++) {
2983 struct diff_filepair *p = q->queue[i];
2984 const char *name;
2985 unsigned long copied, added, damage;
2986 struct diff_populate_filespec_options dpf_options = {
2987 .check_size_only = 1,
2990 name = p->two->path ? p->two->path : p->one->path;
2992 if (p->one->oid_valid && p->two->oid_valid &&
2993 oideq(&p->one->oid, &p->two->oid)) {
2995 * The SHA1 has not changed, so pre-/post-content is
2996 * identical. We can therefore skip looking at the
2997 * file contents altogether.
2999 damage = 0;
3000 goto found_damage;
3003 if (options->flags.dirstat_by_file) {
3005 * In --dirstat-by-file mode, we don't really need to
3006 * look at the actual file contents at all.
3007 * The fact that the SHA1 changed is enough for us to
3008 * add this file to the list of results
3009 * (with each file contributing equal damage).
3011 damage = 1;
3012 goto found_damage;
3015 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3016 diff_populate_filespec(options->repo, p->one, NULL);
3017 diff_populate_filespec(options->repo, p->two, NULL);
3018 diffcore_count_changes(options->repo,
3019 p->one, p->two, NULL, NULL,
3020 &copied, &added);
3021 diff_free_filespec_data(p->one);
3022 diff_free_filespec_data(p->two);
3023 } else if (DIFF_FILE_VALID(p->one)) {
3024 diff_populate_filespec(options->repo, p->one, &dpf_options);
3025 copied = added = 0;
3026 diff_free_filespec_data(p->one);
3027 } else if (DIFF_FILE_VALID(p->two)) {
3028 diff_populate_filespec(options->repo, p->two, &dpf_options);
3029 copied = 0;
3030 added = p->two->size;
3031 diff_free_filespec_data(p->two);
3032 } else
3033 continue;
3036 * Original minus copied is the removed material,
3037 * added is the new material. They are both damages
3038 * made to the preimage.
3039 * If the resulting damage is zero, we know that
3040 * diffcore_count_changes() considers the two entries to
3041 * be identical, but since the oid changed, we
3042 * know that there must have been _some_ kind of change,
3043 * so we force all entries to have damage > 0.
3045 damage = (p->one->size - copied) + added;
3046 if (!damage)
3047 damage = 1;
3049 found_damage:
3050 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3051 dir.files[dir.nr].name = name;
3052 dir.files[dir.nr].changed = damage;
3053 changed += damage;
3054 dir.nr++;
3057 /* This can happen even with many files, if everything was renames */
3058 if (!changed)
3059 return;
3061 /* Show all directories with more than x% of the changes */
3062 QSORT(dir.files, dir.nr, dirstat_compare);
3063 gather_dirstat(options, &dir, changed, "", 0);
3066 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3068 int i;
3069 unsigned long changed;
3070 struct dirstat_dir dir;
3072 if (data->nr == 0)
3073 return;
3075 dir.files = NULL;
3076 dir.alloc = 0;
3077 dir.nr = 0;
3078 dir.permille = options->dirstat_permille;
3079 dir.cumulative = options->flags.dirstat_cumulative;
3081 changed = 0;
3082 for (i = 0; i < data->nr; i++) {
3083 struct diffstat_file *file = data->files[i];
3084 unsigned long damage = file->added + file->deleted;
3085 if (file->is_binary)
3087 * binary files counts bytes, not lines. Must find some
3088 * way to normalize binary bytes vs. textual lines.
3089 * The following heuristic assumes that there are 64
3090 * bytes per "line".
3091 * This is stupid and ugly, but very cheap...
3093 damage = DIV_ROUND_UP(damage, 64);
3094 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3095 dir.files[dir.nr].name = file->name;
3096 dir.files[dir.nr].changed = damage;
3097 changed += damage;
3098 dir.nr++;
3101 /* This can happen even with many files, if everything was renames */
3102 if (!changed)
3103 return;
3105 /* Show all directories with more than x% of the changes */
3106 QSORT(dir.files, dir.nr, dirstat_compare);
3107 gather_dirstat(options, &dir, changed, "", 0);
3110 static void free_diffstat_file(struct diffstat_file *f)
3112 free(f->print_name);
3113 free(f->name);
3114 free(f->from_name);
3115 free(f);
3118 void free_diffstat_info(struct diffstat_t *diffstat)
3120 int i;
3121 for (i = 0; i < diffstat->nr; i++)
3122 free_diffstat_file(diffstat->files[i]);
3123 free(diffstat->files);
3126 struct checkdiff_t {
3127 const char *filename;
3128 int lineno;
3129 int conflict_marker_size;
3130 struct diff_options *o;
3131 unsigned ws_rule;
3132 unsigned status;
3135 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3137 char firstchar;
3138 int cnt;
3140 if (len < marker_size + 1)
3141 return 0;
3142 firstchar = line[0];
3143 switch (firstchar) {
3144 case '=': case '>': case '<': case '|':
3145 break;
3146 default:
3147 return 0;
3149 for (cnt = 1; cnt < marker_size; cnt++)
3150 if (line[cnt] != firstchar)
3151 return 0;
3152 /* line[1] through line[marker_size-1] are same as firstchar */
3153 if (len < marker_size + 1 || !isspace(line[marker_size]))
3154 return 0;
3155 return 1;
3158 static void checkdiff_consume_hunk(void *priv,
3159 long ob, long on, long nb, long nn,
3160 const char *func, long funclen)
3163 struct checkdiff_t *data = priv;
3164 data->lineno = nb - 1;
3167 static int checkdiff_consume(void *priv, char *line, unsigned long len)
3169 struct checkdiff_t *data = priv;
3170 int marker_size = data->conflict_marker_size;
3171 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3172 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3173 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3174 char *err;
3175 const char *line_prefix;
3177 assert(data->o);
3178 line_prefix = diff_line_prefix(data->o);
3180 if (line[0] == '+') {
3181 unsigned bad;
3182 data->lineno++;
3183 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3184 data->status |= 1;
3185 fprintf(data->o->file,
3186 "%s%s:%d: leftover conflict marker\n",
3187 line_prefix, data->filename, data->lineno);
3189 bad = ws_check(line + 1, len - 1, data->ws_rule);
3190 if (!bad)
3191 return 0;
3192 data->status |= bad;
3193 err = whitespace_error_string(bad);
3194 fprintf(data->o->file, "%s%s:%d: %s.\n",
3195 line_prefix, data->filename, data->lineno, err);
3196 free(err);
3197 emit_line(data->o, set, reset, line, 1);
3198 ws_check_emit(line + 1, len - 1, data->ws_rule,
3199 data->o->file, set, reset, ws);
3200 } else if (line[0] == ' ') {
3201 data->lineno++;
3203 return 0;
3206 static unsigned char *deflate_it(char *data,
3207 unsigned long size,
3208 unsigned long *result_size)
3210 int bound;
3211 unsigned char *deflated;
3212 git_zstream stream;
3214 git_deflate_init(&stream, zlib_compression_level);
3215 bound = git_deflate_bound(&stream, size);
3216 deflated = xmalloc(bound);
3217 stream.next_out = deflated;
3218 stream.avail_out = bound;
3220 stream.next_in = (unsigned char *)data;
3221 stream.avail_in = size;
3222 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3223 ; /* nothing */
3224 git_deflate_end(&stream);
3225 *result_size = stream.total_out;
3226 return deflated;
3229 static void emit_binary_diff_body(struct diff_options *o,
3230 mmfile_t *one, mmfile_t *two)
3232 void *cp;
3233 void *delta;
3234 void *deflated;
3235 void *data;
3236 unsigned long orig_size;
3237 unsigned long delta_size;
3238 unsigned long deflate_size;
3239 unsigned long data_size;
3241 /* We could do deflated delta, or we could do just deflated two,
3242 * whichever is smaller.
3244 delta = NULL;
3245 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3246 if (one->size && two->size) {
3247 delta = diff_delta(one->ptr, one->size,
3248 two->ptr, two->size,
3249 &delta_size, deflate_size);
3250 if (delta) {
3251 void *to_free = delta;
3252 orig_size = delta_size;
3253 delta = deflate_it(delta, delta_size, &delta_size);
3254 free(to_free);
3258 if (delta && delta_size < deflate_size) {
3259 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3260 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3261 s, strlen(s), 0);
3262 free(s);
3263 free(deflated);
3264 data = delta;
3265 data_size = delta_size;
3266 } else {
3267 char *s = xstrfmt("%lu", two->size);
3268 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3269 s, strlen(s), 0);
3270 free(s);
3271 free(delta);
3272 data = deflated;
3273 data_size = deflate_size;
3276 /* emit data encoded in base85 */
3277 cp = data;
3278 while (data_size) {
3279 int len;
3280 int bytes = (52 < data_size) ? 52 : data_size;
3281 char line[71];
3282 data_size -= bytes;
3283 if (bytes <= 26)
3284 line[0] = bytes + 'A' - 1;
3285 else
3286 line[0] = bytes - 26 + 'a' - 1;
3287 encode_85(line + 1, cp, bytes);
3288 cp = (char *) cp + bytes;
3290 len = strlen(line);
3291 line[len++] = '\n';
3292 line[len] = '\0';
3294 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3295 line, len, 0);
3297 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3298 free(data);
3301 static void emit_binary_diff(struct diff_options *o,
3302 mmfile_t *one, mmfile_t *two)
3304 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3305 emit_binary_diff_body(o, one, two);
3306 emit_binary_diff_body(o, two, one);
3309 int diff_filespec_is_binary(struct repository *r,
3310 struct diff_filespec *one)
3312 struct diff_populate_filespec_options dpf_options = {
3313 .check_binary = 1,
3316 if (one->is_binary == -1) {
3317 diff_filespec_load_driver(one, r->index);
3318 if (one->driver->binary != -1)
3319 one->is_binary = one->driver->binary;
3320 else {
3321 if (!one->data && DIFF_FILE_VALID(one))
3322 diff_populate_filespec(r, one, &dpf_options);
3323 if (one->is_binary == -1 && one->data)
3324 one->is_binary = buffer_is_binary(one->data,
3325 one->size);
3326 if (one->is_binary == -1)
3327 one->is_binary = 0;
3330 return one->is_binary;
3333 static const struct userdiff_funcname *
3334 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3336 diff_filespec_load_driver(one, o->repo->index);
3337 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3340 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3342 if (!options->a_prefix)
3343 options->a_prefix = a;
3344 if (!options->b_prefix)
3345 options->b_prefix = b;
3348 struct userdiff_driver *get_textconv(struct repository *r,
3349 struct diff_filespec *one)
3351 if (!DIFF_FILE_VALID(one))
3352 return NULL;
3354 diff_filespec_load_driver(one, r->index);
3355 return userdiff_get_textconv(r, one->driver);
3358 static struct strbuf *additional_headers(struct diff_options *o,
3359 const char *path)
3361 if (!o->additional_path_headers)
3362 return NULL;
3363 return strmap_get(o->additional_path_headers, path);
3366 static void add_formatted_headers(struct strbuf *msg,
3367 struct strbuf *more_headers,
3368 const char *line_prefix,
3369 const char *meta,
3370 const char *reset)
3372 char *next, *newline;
3374 for (next = more_headers->buf; *next; next = newline) {
3375 newline = strchrnul(next, '\n');
3376 strbuf_addf(msg, "%s%s%.*s%s\n", line_prefix, meta,
3377 (int)(newline - next), next, reset);
3378 if (*newline)
3379 newline++;
3383 static void builtin_diff(const char *name_a,
3384 const char *name_b,
3385 struct diff_filespec *one,
3386 struct diff_filespec *two,
3387 const char *xfrm_msg,
3388 int must_show_header,
3389 struct diff_options *o,
3390 int complete_rewrite)
3392 mmfile_t mf1, mf2;
3393 const char *lbl[2];
3394 char *a_one, *b_two;
3395 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3396 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3397 const char *a_prefix, *b_prefix;
3398 struct userdiff_driver *textconv_one = NULL;
3399 struct userdiff_driver *textconv_two = NULL;
3400 struct strbuf header = STRBUF_INIT;
3401 const char *line_prefix = diff_line_prefix(o);
3403 diff_set_mnemonic_prefix(o, "a/", "b/");
3404 if (o->flags.reverse_diff) {
3405 a_prefix = o->b_prefix;
3406 b_prefix = o->a_prefix;
3407 } else {
3408 a_prefix = o->a_prefix;
3409 b_prefix = o->b_prefix;
3412 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3413 (!one->mode || S_ISGITLINK(one->mode)) &&
3414 (!two->mode || S_ISGITLINK(two->mode))) {
3415 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3416 &one->oid, &two->oid,
3417 two->dirty_submodule);
3418 return;
3419 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3420 (!one->mode || S_ISGITLINK(one->mode)) &&
3421 (!two->mode || S_ISGITLINK(two->mode))) {
3422 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3423 &one->oid, &two->oid,
3424 two->dirty_submodule);
3425 return;
3428 if (o->flags.allow_textconv) {
3429 textconv_one = get_textconv(o->repo, one);
3430 textconv_two = get_textconv(o->repo, two);
3433 /* Never use a non-valid filename anywhere if at all possible */
3434 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3435 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3437 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3438 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3439 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3440 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3441 if (!DIFF_FILE_VALID(one) && !DIFF_FILE_VALID(two)) {
3443 * We should only reach this point for pairs from
3444 * create_filepairs_for_header_only_notifications(). For
3445 * these, we should avoid the "/dev/null" special casing
3446 * above, meaning we avoid showing such pairs as either
3447 * "new file" or "deleted file" below.
3449 lbl[0] = a_one;
3450 lbl[1] = b_two;
3452 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3453 if (lbl[0][0] == '/') {
3454 /* /dev/null */
3455 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3456 if (xfrm_msg)
3457 strbuf_addstr(&header, xfrm_msg);
3458 must_show_header = 1;
3460 else if (lbl[1][0] == '/') {
3461 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3462 if (xfrm_msg)
3463 strbuf_addstr(&header, xfrm_msg);
3464 must_show_header = 1;
3466 else {
3467 if (one->mode != two->mode) {
3468 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3469 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3470 must_show_header = 1;
3472 if (xfrm_msg)
3473 strbuf_addstr(&header, xfrm_msg);
3476 * we do not run diff between different kind
3477 * of objects.
3479 if ((one->mode ^ two->mode) & S_IFMT)
3480 goto free_ab_and_return;
3481 if (complete_rewrite &&
3482 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3483 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3484 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3485 header.buf, header.len, 0);
3486 strbuf_reset(&header);
3487 emit_rewrite_diff(name_a, name_b, one, two,
3488 textconv_one, textconv_two, o);
3489 o->found_changes = 1;
3490 goto free_ab_and_return;
3494 if (o->irreversible_delete && lbl[1][0] == '/') {
3495 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3496 header.len, 0);
3497 strbuf_reset(&header);
3498 goto free_ab_and_return;
3499 } else if (!o->flags.text &&
3500 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3501 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3502 struct strbuf sb = STRBUF_INIT;
3503 if (!one->data && !two->data &&
3504 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3505 !o->flags.binary) {
3506 if (oideq(&one->oid, &two->oid)) {
3507 if (must_show_header)
3508 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3509 header.buf, header.len,
3511 goto free_ab_and_return;
3513 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3514 header.buf, header.len, 0);
3515 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3516 diff_line_prefix(o), lbl[0], lbl[1]);
3517 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3518 sb.buf, sb.len, 0);
3519 strbuf_release(&sb);
3520 goto free_ab_and_return;
3522 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3523 fill_mmfile(o->repo, &mf2, two) < 0)
3524 die("unable to read files to diff");
3525 /* Quite common confusing case */
3526 if (mf1.size == mf2.size &&
3527 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3528 if (must_show_header)
3529 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3530 header.buf, header.len, 0);
3531 goto free_ab_and_return;
3533 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3534 strbuf_reset(&header);
3535 if (o->flags.binary)
3536 emit_binary_diff(o, &mf1, &mf2);
3537 else {
3538 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3539 diff_line_prefix(o), lbl[0], lbl[1]);
3540 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3541 sb.buf, sb.len, 0);
3542 strbuf_release(&sb);
3544 o->found_changes = 1;
3545 } else {
3546 /* Crazy xdl interfaces.. */
3547 const char *diffopts;
3548 const char *v;
3549 xpparam_t xpp;
3550 xdemitconf_t xecfg;
3551 struct emit_callback ecbdata;
3552 const struct userdiff_funcname *pe;
3554 if (must_show_header) {
3555 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3556 header.buf, header.len, 0);
3557 strbuf_reset(&header);
3560 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3561 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3563 pe = diff_funcname_pattern(o, one);
3564 if (!pe)
3565 pe = diff_funcname_pattern(o, two);
3567 memset(&xpp, 0, sizeof(xpp));
3568 memset(&xecfg, 0, sizeof(xecfg));
3569 memset(&ecbdata, 0, sizeof(ecbdata));
3570 if (o->flags.suppress_diff_headers)
3571 lbl[0] = NULL;
3572 ecbdata.label_path = lbl;
3573 ecbdata.color_diff = want_color(o->use_color);
3574 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3575 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3576 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3577 ecbdata.opt = o;
3578 if (header.len && !o->flags.suppress_diff_headers)
3579 ecbdata.header = &header;
3580 xpp.flags = o->xdl_opts;
3581 xpp.ignore_regex = o->ignore_regex;
3582 xpp.ignore_regex_nr = o->ignore_regex_nr;
3583 xpp.anchors = o->anchors;
3584 xpp.anchors_nr = o->anchors_nr;
3585 xecfg.ctxlen = o->context;
3586 xecfg.interhunkctxlen = o->interhunkcontext;
3587 xecfg.flags = XDL_EMIT_FUNCNAMES;
3588 if (o->flags.funccontext)
3589 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3590 if (pe)
3591 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3593 diffopts = getenv("GIT_DIFF_OPTS");
3594 if (!diffopts)
3596 else if (skip_prefix(diffopts, "--unified=", &v))
3597 xecfg.ctxlen = strtoul(v, NULL, 10);
3598 else if (skip_prefix(diffopts, "-u", &v))
3599 xecfg.ctxlen = strtoul(v, NULL, 10);
3601 if (o->word_diff)
3602 init_diff_words_data(&ecbdata, o, one, two);
3603 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3604 &ecbdata, &xpp, &xecfg))
3605 die("unable to generate diff for %s", one->path);
3606 if (o->word_diff)
3607 free_diff_words_data(&ecbdata);
3608 if (textconv_one)
3609 free(mf1.ptr);
3610 if (textconv_two)
3611 free(mf2.ptr);
3612 xdiff_clear_find_func(&xecfg);
3615 free_ab_and_return:
3616 strbuf_release(&header);
3617 diff_free_filespec_data(one);
3618 diff_free_filespec_data(two);
3619 free(a_one);
3620 free(b_two);
3621 return;
3624 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3626 if (!is_renamed) {
3627 if (p->status == DIFF_STATUS_ADDED) {
3628 if (S_ISLNK(p->two->mode))
3629 return "new +l";
3630 else if ((p->two->mode & 0777) == 0755)
3631 return "new +x";
3632 else
3633 return "new";
3634 } else if (p->status == DIFF_STATUS_DELETED)
3635 return "gone";
3637 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3638 return "mode -l";
3639 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3640 return "mode +l";
3641 else if ((p->one->mode & 0777) == 0644 &&
3642 (p->two->mode & 0777) == 0755)
3643 return "mode +x";
3644 else if ((p->one->mode & 0777) == 0755 &&
3645 (p->two->mode & 0777) == 0644)
3646 return "mode -x";
3647 return NULL;
3650 static void builtin_diffstat(const char *name_a, const char *name_b,
3651 struct diff_filespec *one,
3652 struct diff_filespec *two,
3653 struct diffstat_t *diffstat,
3654 struct diff_options *o,
3655 struct diff_filepair *p)
3657 mmfile_t mf1, mf2;
3658 struct diffstat_file *data;
3659 int may_differ;
3660 int complete_rewrite = 0;
3662 if (!DIFF_PAIR_UNMERGED(p)) {
3663 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3664 complete_rewrite = 1;
3667 data = diffstat_add(diffstat, name_a, name_b);
3668 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3669 if (o->flags.stat_with_summary)
3670 data->comments = get_compact_summary(p, data->is_renamed);
3672 if (!one || !two) {
3673 data->is_unmerged = 1;
3674 return;
3677 /* saves some reads if true, not a guarantee of diff outcome */
3678 may_differ = !(one->oid_valid && two->oid_valid &&
3679 oideq(&one->oid, &two->oid));
3681 if (diff_filespec_is_binary(o->repo, one) ||
3682 diff_filespec_is_binary(o->repo, two)) {
3683 data->is_binary = 1;
3684 if (!may_differ) {
3685 data->added = 0;
3686 data->deleted = 0;
3687 } else {
3688 data->added = diff_filespec_size(o->repo, two);
3689 data->deleted = diff_filespec_size(o->repo, one);
3693 else if (complete_rewrite) {
3694 diff_populate_filespec(o->repo, one, NULL);
3695 diff_populate_filespec(o->repo, two, NULL);
3696 data->deleted = count_lines(one->data, one->size);
3697 data->added = count_lines(two->data, two->size);
3700 else if (may_differ) {
3701 /* Crazy xdl interfaces.. */
3702 xpparam_t xpp;
3703 xdemitconf_t xecfg;
3705 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3706 fill_mmfile(o->repo, &mf2, two) < 0)
3707 die("unable to read files to diff");
3709 memset(&xpp, 0, sizeof(xpp));
3710 memset(&xecfg, 0, sizeof(xecfg));
3711 xpp.flags = o->xdl_opts;
3712 xpp.ignore_regex = o->ignore_regex;
3713 xpp.ignore_regex_nr = o->ignore_regex_nr;
3714 xpp.anchors = o->anchors;
3715 xpp.anchors_nr = o->anchors_nr;
3716 xecfg.ctxlen = o->context;
3717 xecfg.interhunkctxlen = o->interhunkcontext;
3718 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3719 if (xdi_diff_outf(&mf1, &mf2, NULL,
3720 diffstat_consume, diffstat, &xpp, &xecfg))
3721 die("unable to generate diffstat for %s", one->path);
3723 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3724 struct diffstat_file *file =
3725 diffstat->files[diffstat->nr - 1];
3727 * Omit diffstats of modified files where nothing changed.
3728 * Even if may_differ, this might be the case due to
3729 * ignoring whitespace changes, etc.
3731 * But note that we special-case additions, deletions,
3732 * renames, and mode changes as adding an empty file,
3733 * for example is still of interest.
3735 if ((p->status == DIFF_STATUS_MODIFIED)
3736 && !file->added
3737 && !file->deleted
3738 && one->mode == two->mode) {
3739 free_diffstat_file(file);
3740 diffstat->nr--;
3745 diff_free_filespec_data(one);
3746 diff_free_filespec_data(two);
3749 static void builtin_checkdiff(const char *name_a, const char *name_b,
3750 const char *attr_path,
3751 struct diff_filespec *one,
3752 struct diff_filespec *two,
3753 struct diff_options *o)
3755 mmfile_t mf1, mf2;
3756 struct checkdiff_t data;
3758 if (!two)
3759 return;
3761 memset(&data, 0, sizeof(data));
3762 data.filename = name_b ? name_b : name_a;
3763 data.lineno = 0;
3764 data.o = o;
3765 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3766 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3768 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3769 fill_mmfile(o->repo, &mf2, two) < 0)
3770 die("unable to read files to diff");
3773 * All the other codepaths check both sides, but not checking
3774 * the "old" side here is deliberate. We are checking the newly
3775 * introduced changes, and as long as the "new" side is text, we
3776 * can and should check what it introduces.
3778 if (diff_filespec_is_binary(o->repo, two))
3779 goto free_and_return;
3780 else {
3781 /* Crazy xdl interfaces.. */
3782 xpparam_t xpp;
3783 xdemitconf_t xecfg;
3785 memset(&xpp, 0, sizeof(xpp));
3786 memset(&xecfg, 0, sizeof(xecfg));
3787 xecfg.ctxlen = 1; /* at least one context line */
3788 xpp.flags = 0;
3789 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3790 checkdiff_consume, &data,
3791 &xpp, &xecfg))
3792 die("unable to generate checkdiff for %s", one->path);
3794 if (data.ws_rule & WS_BLANK_AT_EOF) {
3795 struct emit_callback ecbdata;
3796 int blank_at_eof;
3798 ecbdata.ws_rule = data.ws_rule;
3799 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3800 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3802 if (blank_at_eof) {
3803 static char *err;
3804 if (!err)
3805 err = whitespace_error_string(WS_BLANK_AT_EOF);
3806 fprintf(o->file, "%s:%d: %s.\n",
3807 data.filename, blank_at_eof, err);
3808 data.status = 1; /* report errors */
3812 free_and_return:
3813 diff_free_filespec_data(one);
3814 diff_free_filespec_data(two);
3815 if (data.status)
3816 o->flags.check_failed = 1;
3819 struct diff_filespec *alloc_filespec(const char *path)
3821 struct diff_filespec *spec;
3823 FLEXPTR_ALLOC_STR(spec, path, path);
3824 spec->count = 1;
3825 spec->is_binary = -1;
3826 return spec;
3829 void free_filespec(struct diff_filespec *spec)
3831 if (!--spec->count) {
3832 diff_free_filespec_data(spec);
3833 free(spec);
3837 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3838 int oid_valid, unsigned short mode)
3840 if (mode) {
3841 spec->mode = canon_mode(mode);
3842 oidcpy(&spec->oid, oid);
3843 spec->oid_valid = oid_valid;
3848 * Given a name and sha1 pair, if the index tells us the file in
3849 * the work tree has that object contents, return true, so that
3850 * prepare_temp_file() does not have to inflate and extract.
3852 static int reuse_worktree_file(struct index_state *istate,
3853 const char *name,
3854 const struct object_id *oid,
3855 int want_file)
3857 const struct cache_entry *ce;
3858 struct stat st;
3859 int pos, len;
3862 * We do not read the cache ourselves here, because the
3863 * benchmark with my previous version that always reads cache
3864 * shows that it makes things worse for diff-tree comparing
3865 * two linux-2.6 kernel trees in an already checked out work
3866 * tree. This is because most diff-tree comparisons deal with
3867 * only a small number of files, while reading the cache is
3868 * expensive for a large project, and its cost outweighs the
3869 * savings we get by not inflating the object to a temporary
3870 * file. Practically, this code only helps when we are used
3871 * by diff-cache --cached, which does read the cache before
3872 * calling us.
3874 if (!istate->cache)
3875 return 0;
3877 /* We want to avoid the working directory if our caller
3878 * doesn't need the data in a normal file, this system
3879 * is rather slow with its stat/open/mmap/close syscalls,
3880 * and the object is contained in a pack file. The pack
3881 * is probably already open and will be faster to obtain
3882 * the data through than the working directory. Loose
3883 * objects however would tend to be slower as they need
3884 * to be individually opened and inflated.
3886 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3887 return 0;
3890 * Similarly, if we'd have to convert the file contents anyway, that
3891 * makes the optimization not worthwhile.
3893 if (!want_file && would_convert_to_git(istate, name))
3894 return 0;
3897 * If this path does not match our sparse-checkout definition,
3898 * then the file will not be in the working directory.
3900 if (!path_in_sparse_checkout(name, istate))
3901 return 0;
3903 len = strlen(name);
3904 pos = index_name_pos(istate, name, len);
3905 if (pos < 0)
3906 return 0;
3907 ce = istate->cache[pos];
3910 * This is not the sha1 we are looking for, or
3911 * unreusable because it is not a regular file.
3913 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3914 return 0;
3917 * If ce is marked as "assume unchanged", there is no
3918 * guarantee that work tree matches what we are looking for.
3920 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3921 return 0;
3924 * If ce matches the file in the work tree, we can reuse it.
3926 if (ce_uptodate(ce) ||
3927 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3928 return 1;
3930 return 0;
3933 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3935 struct strbuf buf = STRBUF_INIT;
3936 char *dirty = "";
3938 /* Are we looking at the work tree? */
3939 if (s->dirty_submodule)
3940 dirty = "-dirty";
3942 strbuf_addf(&buf, "Subproject commit %s%s\n",
3943 oid_to_hex(&s->oid), dirty);
3944 s->size = buf.len;
3945 if (size_only) {
3946 s->data = NULL;
3947 strbuf_release(&buf);
3948 } else {
3949 s->data = strbuf_detach(&buf, NULL);
3950 s->should_free = 1;
3952 return 0;
3956 * While doing rename detection and pickaxe operation, we may need to
3957 * grab the data for the blob (or file) for our own in-core comparison.
3958 * diff_filespec has data and size fields for this purpose.
3960 int diff_populate_filespec(struct repository *r,
3961 struct diff_filespec *s,
3962 const struct diff_populate_filespec_options *options)
3964 int size_only = options ? options->check_size_only : 0;
3965 int check_binary = options ? options->check_binary : 0;
3966 int err = 0;
3967 int conv_flags = global_conv_flags_eol;
3969 * demote FAIL to WARN to allow inspecting the situation
3970 * instead of refusing.
3972 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3973 conv_flags = CONV_EOL_RNDTRP_WARN;
3975 if (!DIFF_FILE_VALID(s))
3976 die("internal error: asking to populate invalid file.");
3977 if (S_ISDIR(s->mode))
3978 return -1;
3980 if (s->data)
3981 return 0;
3983 if (size_only && 0 < s->size)
3984 return 0;
3986 if (S_ISGITLINK(s->mode))
3987 return diff_populate_gitlink(s, size_only);
3989 if (!s->oid_valid ||
3990 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3991 struct strbuf buf = STRBUF_INIT;
3992 struct stat st;
3993 int fd;
3995 if (lstat(s->path, &st) < 0) {
3996 err_empty:
3997 err = -1;
3998 empty:
3999 s->data = (char *)"";
4000 s->size = 0;
4001 return err;
4003 s->size = xsize_t(st.st_size);
4004 if (!s->size)
4005 goto empty;
4006 if (S_ISLNK(st.st_mode)) {
4007 struct strbuf sb = STRBUF_INIT;
4009 if (strbuf_readlink(&sb, s->path, s->size))
4010 goto err_empty;
4011 s->size = sb.len;
4012 s->data = strbuf_detach(&sb, NULL);
4013 s->should_free = 1;
4014 return 0;
4018 * Even if the caller would be happy with getting
4019 * only the size, we cannot return early at this
4020 * point if the path requires us to run the content
4021 * conversion.
4023 if (size_only && !would_convert_to_git(r->index, s->path))
4024 return 0;
4027 * Note: this check uses xsize_t(st.st_size) that may
4028 * not be the true size of the blob after it goes
4029 * through convert_to_git(). This may not strictly be
4030 * correct, but the whole point of big_file_threshold
4031 * and is_binary check being that we want to avoid
4032 * opening the file and inspecting the contents, this
4033 * is probably fine.
4035 if (check_binary &&
4036 s->size > big_file_threshold && s->is_binary == -1) {
4037 s->is_binary = 1;
4038 return 0;
4040 fd = open(s->path, O_RDONLY);
4041 if (fd < 0)
4042 goto err_empty;
4043 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4044 close(fd);
4045 s->should_munmap = 1;
4048 * Convert from working tree format to canonical git format
4050 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4051 size_t size = 0;
4052 munmap(s->data, s->size);
4053 s->should_munmap = 0;
4054 s->data = strbuf_detach(&buf, &size);
4055 s->size = size;
4056 s->should_free = 1;
4059 else {
4060 struct object_info info = {
4061 .sizep = &s->size
4064 if (!(size_only || check_binary))
4066 * Set contentp, since there is no chance that merely
4067 * the size is sufficient.
4069 info.contentp = &s->data;
4071 if (options && options->missing_object_cb) {
4072 if (!oid_object_info_extended(r, &s->oid, &info,
4073 OBJECT_INFO_LOOKUP_REPLACE |
4074 OBJECT_INFO_SKIP_FETCH_OBJECT))
4075 goto object_read;
4076 options->missing_object_cb(options->missing_object_data);
4078 if (oid_object_info_extended(r, &s->oid, &info,
4079 OBJECT_INFO_LOOKUP_REPLACE))
4080 die("unable to read %s", oid_to_hex(&s->oid));
4082 object_read:
4083 if (size_only || check_binary) {
4084 if (size_only)
4085 return 0;
4086 if (s->size > big_file_threshold && s->is_binary == -1) {
4087 s->is_binary = 1;
4088 return 0;
4091 if (!info.contentp) {
4092 info.contentp = &s->data;
4093 if (oid_object_info_extended(r, &s->oid, &info,
4094 OBJECT_INFO_LOOKUP_REPLACE))
4095 die("unable to read %s", oid_to_hex(&s->oid));
4097 s->should_free = 1;
4099 return 0;
4102 void diff_free_filespec_blob(struct diff_filespec *s)
4104 if (s->should_free)
4105 free(s->data);
4106 else if (s->should_munmap)
4107 munmap(s->data, s->size);
4109 if (s->should_free || s->should_munmap) {
4110 s->should_free = s->should_munmap = 0;
4111 s->data = NULL;
4115 void diff_free_filespec_data(struct diff_filespec *s)
4117 if (!s)
4118 return;
4120 diff_free_filespec_blob(s);
4121 FREE_AND_NULL(s->cnt_data);
4124 static void prep_temp_blob(struct index_state *istate,
4125 const char *path, struct diff_tempfile *temp,
4126 void *blob,
4127 unsigned long size,
4128 const struct object_id *oid,
4129 int mode)
4131 struct strbuf buf = STRBUF_INIT;
4132 struct strbuf tempfile = STRBUF_INIT;
4133 char *path_dup = xstrdup(path);
4134 const char *base = basename(path_dup);
4135 struct checkout_metadata meta;
4137 init_checkout_metadata(&meta, NULL, NULL, oid);
4139 /* Generate "XXXXXX_basename.ext" */
4140 strbuf_addstr(&tempfile, "XXXXXX_");
4141 strbuf_addstr(&tempfile, base);
4143 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4144 if (!temp->tempfile)
4145 die_errno("unable to create temp-file");
4146 if (convert_to_working_tree(istate, path,
4147 (const char *)blob, (size_t)size, &buf, &meta)) {
4148 blob = buf.buf;
4149 size = buf.len;
4151 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4152 close_tempfile_gently(temp->tempfile))
4153 die_errno("unable to write temp-file");
4154 temp->name = get_tempfile_path(temp->tempfile);
4155 oid_to_hex_r(temp->hex, oid);
4156 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4157 strbuf_release(&buf);
4158 strbuf_release(&tempfile);
4159 free(path_dup);
4162 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4163 const char *name,
4164 struct diff_filespec *one)
4166 struct diff_tempfile *temp = claim_diff_tempfile();
4168 if (!DIFF_FILE_VALID(one)) {
4169 not_a_valid_file:
4170 /* A '-' entry produces this for file-2, and
4171 * a '+' entry produces this for file-1.
4173 temp->name = "/dev/null";
4174 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4175 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4176 return temp;
4179 if (!S_ISGITLINK(one->mode) &&
4180 (!one->oid_valid ||
4181 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4182 struct stat st;
4183 if (lstat(name, &st) < 0) {
4184 if (errno == ENOENT)
4185 goto not_a_valid_file;
4186 die_errno("stat(%s)", name);
4188 if (S_ISLNK(st.st_mode)) {
4189 struct strbuf sb = STRBUF_INIT;
4190 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4191 die_errno("readlink(%s)", name);
4192 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4193 (one->oid_valid ?
4194 &one->oid : null_oid()),
4195 (one->oid_valid ?
4196 one->mode : S_IFLNK));
4197 strbuf_release(&sb);
4199 else {
4200 /* we can borrow from the file in the work tree */
4201 temp->name = name;
4202 if (!one->oid_valid)
4203 oid_to_hex_r(temp->hex, null_oid());
4204 else
4205 oid_to_hex_r(temp->hex, &one->oid);
4206 /* Even though we may sometimes borrow the
4207 * contents from the work tree, we always want
4208 * one->mode. mode is trustworthy even when
4209 * !(one->oid_valid), as long as
4210 * DIFF_FILE_VALID(one).
4212 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4214 return temp;
4216 else {
4217 if (diff_populate_filespec(r, one, NULL))
4218 die("cannot read data blob for %s", one->path);
4219 prep_temp_blob(r->index, name, temp,
4220 one->data, one->size,
4221 &one->oid, one->mode);
4223 return temp;
4226 static void add_external_diff_name(struct repository *r,
4227 struct strvec *argv,
4228 const char *name,
4229 struct diff_filespec *df)
4231 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4232 strvec_push(argv, temp->name);
4233 strvec_push(argv, temp->hex);
4234 strvec_push(argv, temp->mode);
4237 /* An external diff command takes:
4239 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4240 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4243 static void run_external_diff(const char *pgm,
4244 const char *name,
4245 const char *other,
4246 struct diff_filespec *one,
4247 struct diff_filespec *two,
4248 const char *xfrm_msg,
4249 struct diff_options *o)
4251 struct strvec argv = STRVEC_INIT;
4252 struct strvec env = STRVEC_INIT;
4253 struct diff_queue_struct *q = &diff_queued_diff;
4255 strvec_push(&argv, pgm);
4256 strvec_push(&argv, name);
4258 if (one && two) {
4259 add_external_diff_name(o->repo, &argv, name, one);
4260 if (!other)
4261 add_external_diff_name(o->repo, &argv, name, two);
4262 else {
4263 add_external_diff_name(o->repo, &argv, other, two);
4264 strvec_push(&argv, other);
4265 strvec_push(&argv, xfrm_msg);
4269 strvec_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4270 strvec_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4272 diff_free_filespec_data(one);
4273 diff_free_filespec_data(two);
4274 if (run_command_v_opt_cd_env(argv.v, RUN_USING_SHELL, NULL, env.v))
4275 die(_("external diff died, stopping at %s"), name);
4277 remove_tempfile();
4278 strvec_clear(&argv);
4279 strvec_clear(&env);
4282 static int similarity_index(struct diff_filepair *p)
4284 return p->score * 100 / MAX_SCORE;
4287 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4289 if (startup_info->have_repository)
4290 return find_unique_abbrev(oid, abbrev);
4291 else {
4292 char *hex = oid_to_hex(oid);
4293 if (abbrev < 0)
4294 abbrev = FALLBACK_DEFAULT_ABBREV;
4295 if (abbrev > the_hash_algo->hexsz)
4296 BUG("oid abbreviation out of range: %d", abbrev);
4297 if (abbrev)
4298 hex[abbrev] = '\0';
4299 return hex;
4303 static void fill_metainfo(struct strbuf *msg,
4304 const char *name,
4305 const char *other,
4306 struct diff_filespec *one,
4307 struct diff_filespec *two,
4308 struct diff_options *o,
4309 struct diff_filepair *p,
4310 int *must_show_header,
4311 int use_color)
4313 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4314 const char *reset = diff_get_color(use_color, DIFF_RESET);
4315 const char *line_prefix = diff_line_prefix(o);
4316 struct strbuf *more_headers = NULL;
4318 *must_show_header = 1;
4319 strbuf_init(msg, PATH_MAX * 2 + 300);
4320 switch (p->status) {
4321 case DIFF_STATUS_COPIED:
4322 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4323 line_prefix, set, similarity_index(p));
4324 strbuf_addf(msg, "%s\n%s%scopy from ",
4325 reset, line_prefix, set);
4326 quote_c_style(name, msg, NULL, 0);
4327 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4328 quote_c_style(other, msg, NULL, 0);
4329 strbuf_addf(msg, "%s\n", reset);
4330 break;
4331 case DIFF_STATUS_RENAMED:
4332 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4333 line_prefix, set, similarity_index(p));
4334 strbuf_addf(msg, "%s\n%s%srename from ",
4335 reset, line_prefix, set);
4336 quote_c_style(name, msg, NULL, 0);
4337 strbuf_addf(msg, "%s\n%s%srename to ",
4338 reset, line_prefix, set);
4339 quote_c_style(other, msg, NULL, 0);
4340 strbuf_addf(msg, "%s\n", reset);
4341 break;
4342 case DIFF_STATUS_MODIFIED:
4343 if (p->score) {
4344 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4345 line_prefix,
4346 set, similarity_index(p), reset);
4347 break;
4349 /* fallthru */
4350 default:
4351 *must_show_header = 0;
4353 if ((more_headers = additional_headers(o, name))) {
4354 add_formatted_headers(msg, more_headers,
4355 line_prefix, set, reset);
4356 *must_show_header = 1;
4358 if (one && two && !oideq(&one->oid, &two->oid)) {
4359 const unsigned hexsz = the_hash_algo->hexsz;
4360 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4362 if (o->flags.full_index)
4363 abbrev = hexsz;
4365 if (o->flags.binary) {
4366 mmfile_t mf;
4367 if ((!fill_mmfile(o->repo, &mf, one) &&
4368 diff_filespec_is_binary(o->repo, one)) ||
4369 (!fill_mmfile(o->repo, &mf, two) &&
4370 diff_filespec_is_binary(o->repo, two)))
4371 abbrev = hexsz;
4373 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4374 diff_abbrev_oid(&one->oid, abbrev),
4375 diff_abbrev_oid(&two->oid, abbrev));
4376 if (one->mode == two->mode)
4377 strbuf_addf(msg, " %06o", one->mode);
4378 strbuf_addf(msg, "%s\n", reset);
4382 static void run_diff_cmd(const char *pgm,
4383 const char *name,
4384 const char *other,
4385 const char *attr_path,
4386 struct diff_filespec *one,
4387 struct diff_filespec *two,
4388 struct strbuf *msg,
4389 struct diff_options *o,
4390 struct diff_filepair *p)
4392 const char *xfrm_msg = NULL;
4393 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4394 int must_show_header = 0;
4397 if (o->flags.allow_external) {
4398 struct userdiff_driver *drv;
4400 drv = userdiff_find_by_path(o->repo->index, attr_path);
4401 if (drv && drv->external)
4402 pgm = drv->external;
4405 if (msg) {
4407 * don't use colors when the header is intended for an
4408 * external diff driver
4410 fill_metainfo(msg, name, other, one, two, o, p,
4411 &must_show_header,
4412 want_color(o->use_color) && !pgm);
4413 xfrm_msg = msg->len ? msg->buf : NULL;
4416 if (pgm) {
4417 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4418 return;
4420 if (one && two)
4421 builtin_diff(name, other ? other : name,
4422 one, two, xfrm_msg, must_show_header,
4423 o, complete_rewrite);
4424 else
4425 fprintf(o->file, "* Unmerged path %s\n", name);
4428 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4430 if (DIFF_FILE_VALID(one)) {
4431 if (!one->oid_valid) {
4432 struct stat st;
4433 if (one->is_stdin) {
4434 oidclr(&one->oid);
4435 return;
4437 if (lstat(one->path, &st) < 0)
4438 die_errno("stat '%s'", one->path);
4439 if (index_path(istate, &one->oid, one->path, &st, 0))
4440 die("cannot hash %s", one->path);
4443 else
4444 oidclr(&one->oid);
4447 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4449 /* Strip the prefix but do not molest /dev/null and absolute paths */
4450 if (*namep && !is_absolute_path(*namep)) {
4451 *namep += prefix_length;
4452 if (**namep == '/')
4453 ++*namep;
4455 if (*otherp && !is_absolute_path(*otherp)) {
4456 *otherp += prefix_length;
4457 if (**otherp == '/')
4458 ++*otherp;
4462 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4464 const char *pgm = external_diff();
4465 struct strbuf msg;
4466 struct diff_filespec *one = p->one;
4467 struct diff_filespec *two = p->two;
4468 const char *name;
4469 const char *other;
4470 const char *attr_path;
4472 name = one->path;
4473 other = (strcmp(name, two->path) ? two->path : NULL);
4474 attr_path = name;
4475 if (o->prefix_length)
4476 strip_prefix(o->prefix_length, &name, &other);
4478 if (!o->flags.allow_external)
4479 pgm = NULL;
4481 if (DIFF_PAIR_UNMERGED(p)) {
4482 run_diff_cmd(pgm, name, NULL, attr_path,
4483 NULL, NULL, NULL, o, p);
4484 return;
4487 diff_fill_oid_info(one, o->repo->index);
4488 diff_fill_oid_info(two, o->repo->index);
4490 if (!pgm &&
4491 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4492 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4494 * a filepair that changes between file and symlink
4495 * needs to be split into deletion and creation.
4497 struct diff_filespec *null = alloc_filespec(two->path);
4498 run_diff_cmd(NULL, name, other, attr_path,
4499 one, null, &msg,
4500 o, p);
4501 free(null);
4502 strbuf_release(&msg);
4504 null = alloc_filespec(one->path);
4505 run_diff_cmd(NULL, name, other, attr_path,
4506 null, two, &msg, o, p);
4507 free(null);
4509 else
4510 run_diff_cmd(pgm, name, other, attr_path,
4511 one, two, &msg, o, p);
4513 strbuf_release(&msg);
4516 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4517 struct diffstat_t *diffstat)
4519 const char *name;
4520 const char *other;
4522 if (DIFF_PAIR_UNMERGED(p)) {
4523 /* unmerged */
4524 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4525 diffstat, o, p);
4526 return;
4529 name = p->one->path;
4530 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4532 if (o->prefix_length)
4533 strip_prefix(o->prefix_length, &name, &other);
4535 diff_fill_oid_info(p->one, o->repo->index);
4536 diff_fill_oid_info(p->two, o->repo->index);
4538 builtin_diffstat(name, other, p->one, p->two,
4539 diffstat, o, p);
4542 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4544 const char *name;
4545 const char *other;
4546 const char *attr_path;
4548 if (DIFF_PAIR_UNMERGED(p)) {
4549 /* unmerged */
4550 return;
4553 name = p->one->path;
4554 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4555 attr_path = other ? other : name;
4557 if (o->prefix_length)
4558 strip_prefix(o->prefix_length, &name, &other);
4560 diff_fill_oid_info(p->one, o->repo->index);
4561 diff_fill_oid_info(p->two, o->repo->index);
4563 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4566 static void prep_parse_options(struct diff_options *options);
4568 void repo_diff_setup(struct repository *r, struct diff_options *options)
4570 memcpy(options, &default_diff_options, sizeof(*options));
4572 options->file = stdout;
4573 options->repo = r;
4575 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4576 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4577 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4578 options->abbrev = DEFAULT_ABBREV;
4579 options->line_termination = '\n';
4580 options->break_opt = -1;
4581 options->rename_limit = -1;
4582 options->dirstat_permille = diff_dirstat_permille_default;
4583 options->context = diff_context_default;
4584 options->interhunkcontext = diff_interhunk_context_default;
4585 options->ws_error_highlight = ws_error_highlight_default;
4586 options->flags.rename_empty = 1;
4587 options->flags.relative_name = diff_relative;
4588 options->objfind = NULL;
4590 /* pathchange left =NULL by default */
4591 options->change = diff_change;
4592 options->add_remove = diff_addremove;
4593 options->use_color = diff_use_color_default;
4594 options->detect_rename = diff_detect_rename_default;
4595 options->xdl_opts |= diff_algorithm;
4596 if (diff_indent_heuristic)
4597 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4599 options->orderfile = diff_order_file_cfg;
4601 if (!options->flags.ignore_submodule_set)
4602 options->flags.ignore_untracked_in_submodules = 1;
4604 if (diff_no_prefix) {
4605 options->a_prefix = options->b_prefix = "";
4606 } else if (!diff_mnemonic_prefix) {
4607 options->a_prefix = "a/";
4608 options->b_prefix = "b/";
4611 options->color_moved = diff_color_moved_default;
4612 options->color_moved_ws_handling = diff_color_moved_ws_default;
4614 prep_parse_options(options);
4617 static const char diff_status_letters[] = {
4618 DIFF_STATUS_ADDED,
4619 DIFF_STATUS_COPIED,
4620 DIFF_STATUS_DELETED,
4621 DIFF_STATUS_MODIFIED,
4622 DIFF_STATUS_RENAMED,
4623 DIFF_STATUS_TYPE_CHANGED,
4624 DIFF_STATUS_UNKNOWN,
4625 DIFF_STATUS_UNMERGED,
4626 DIFF_STATUS_FILTER_AON,
4627 DIFF_STATUS_FILTER_BROKEN,
4628 '\0',
4631 static unsigned int filter_bit['Z' + 1];
4633 static void prepare_filter_bits(void)
4635 int i;
4637 if (!filter_bit[DIFF_STATUS_ADDED]) {
4638 for (i = 0; diff_status_letters[i]; i++)
4639 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4643 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4645 return opt->filter & filter_bit[(int) status];
4648 unsigned diff_filter_bit(char status)
4650 prepare_filter_bits();
4651 return filter_bit[(int) status];
4654 void diff_setup_done(struct diff_options *options)
4656 unsigned check_mask = DIFF_FORMAT_NAME |
4657 DIFF_FORMAT_NAME_STATUS |
4658 DIFF_FORMAT_CHECKDIFF |
4659 DIFF_FORMAT_NO_OUTPUT;
4661 * This must be signed because we're comparing against a potentially
4662 * negative value.
4664 const int hexsz = the_hash_algo->hexsz;
4666 if (options->set_default)
4667 options->set_default(options);
4669 if (HAS_MULTI_BITS(options->output_format & check_mask))
4670 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4671 "--name-only", "--name-status", "--check", "-s");
4673 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4674 die(_("options '%s', '%s', and '%s' cannot be used together"),
4675 "-G", "-S", "--find-object");
4677 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
4678 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4679 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
4681 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
4682 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4683 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
4686 * Most of the time we can say "there are changes"
4687 * only by checking if there are changed paths, but
4688 * --ignore-whitespace* options force us to look
4689 * inside contents.
4692 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4693 options->ignore_regex_nr)
4694 options->flags.diff_from_contents = 1;
4695 else
4696 options->flags.diff_from_contents = 0;
4698 if (options->flags.find_copies_harder)
4699 options->detect_rename = DIFF_DETECT_COPY;
4701 if (!options->flags.relative_name)
4702 options->prefix = NULL;
4703 if (options->prefix)
4704 options->prefix_length = strlen(options->prefix);
4705 else
4706 options->prefix_length = 0;
4708 if (options->output_format & (DIFF_FORMAT_NAME |
4709 DIFF_FORMAT_NAME_STATUS |
4710 DIFF_FORMAT_CHECKDIFF |
4711 DIFF_FORMAT_NO_OUTPUT))
4712 options->output_format &= ~(DIFF_FORMAT_RAW |
4713 DIFF_FORMAT_NUMSTAT |
4714 DIFF_FORMAT_DIFFSTAT |
4715 DIFF_FORMAT_SHORTSTAT |
4716 DIFF_FORMAT_DIRSTAT |
4717 DIFF_FORMAT_SUMMARY |
4718 DIFF_FORMAT_PATCH);
4721 * These cases always need recursive; we do not drop caller-supplied
4722 * recursive bits for other formats here.
4724 if (options->output_format & (DIFF_FORMAT_PATCH |
4725 DIFF_FORMAT_NUMSTAT |
4726 DIFF_FORMAT_DIFFSTAT |
4727 DIFF_FORMAT_SHORTSTAT |
4728 DIFF_FORMAT_DIRSTAT |
4729 DIFF_FORMAT_SUMMARY |
4730 DIFF_FORMAT_CHECKDIFF))
4731 options->flags.recursive = 1;
4733 * Also pickaxe would not work very well if you do not say recursive
4735 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4736 options->flags.recursive = 1;
4738 * When patches are generated, submodules diffed against the work tree
4739 * must be checked for dirtiness too so it can be shown in the output
4741 if (options->output_format & DIFF_FORMAT_PATCH)
4742 options->flags.dirty_submodules = 1;
4744 if (options->detect_rename && options->rename_limit < 0)
4745 options->rename_limit = diff_rename_limit_default;
4746 if (hexsz < options->abbrev)
4747 options->abbrev = hexsz; /* full */
4750 * It does not make sense to show the first hit we happened
4751 * to have found. It does not make sense not to return with
4752 * exit code in such a case either.
4754 if (options->flags.quick) {
4755 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4756 options->flags.exit_with_status = 1;
4759 options->diff_path_counter = 0;
4761 if (options->flags.follow_renames && options->pathspec.nr != 1)
4762 die(_("--follow requires exactly one pathspec"));
4764 if (!options->use_color || external_diff())
4765 options->color_moved = 0;
4767 if (options->filter_not) {
4768 if (!options->filter)
4769 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4770 options->filter &= ~options->filter_not;
4773 FREE_AND_NULL(options->parseopts);
4776 int parse_long_opt(const char *opt, const char **argv,
4777 const char **optarg)
4779 const char *arg = argv[0];
4780 if (!skip_prefix(arg, "--", &arg))
4781 return 0;
4782 if (!skip_prefix(arg, opt, &arg))
4783 return 0;
4784 if (*arg == '=') { /* stuck form: --option=value */
4785 *optarg = arg + 1;
4786 return 1;
4788 if (*arg != '\0')
4789 return 0;
4790 /* separate form: --option value */
4791 if (!argv[1])
4792 die("Option '--%s' requires a value", opt);
4793 *optarg = argv[1];
4794 return 2;
4797 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4799 struct diff_options *options = opt->value;
4800 int width = options->stat_width;
4801 int name_width = options->stat_name_width;
4802 int graph_width = options->stat_graph_width;
4803 int count = options->stat_count;
4804 char *end;
4806 BUG_ON_OPT_NEG(unset);
4808 if (!strcmp(opt->long_name, "stat")) {
4809 if (value) {
4810 width = strtoul(value, &end, 10);
4811 if (*end == ',')
4812 name_width = strtoul(end+1, &end, 10);
4813 if (*end == ',')
4814 count = strtoul(end+1, &end, 10);
4815 if (*end)
4816 return error(_("invalid --stat value: %s"), value);
4818 } else if (!strcmp(opt->long_name, "stat-width")) {
4819 width = strtoul(value, &end, 10);
4820 if (*end)
4821 return error(_("%s expects a numerical value"),
4822 opt->long_name);
4823 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4824 name_width = strtoul(value, &end, 10);
4825 if (*end)
4826 return error(_("%s expects a numerical value"),
4827 opt->long_name);
4828 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4829 graph_width = strtoul(value, &end, 10);
4830 if (*end)
4831 return error(_("%s expects a numerical value"),
4832 opt->long_name);
4833 } else if (!strcmp(opt->long_name, "stat-count")) {
4834 count = strtoul(value, &end, 10);
4835 if (*end)
4836 return error(_("%s expects a numerical value"),
4837 opt->long_name);
4838 } else
4839 BUG("%s should not get here", opt->long_name);
4841 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4842 options->stat_name_width = name_width;
4843 options->stat_graph_width = graph_width;
4844 options->stat_width = width;
4845 options->stat_count = count;
4846 return 0;
4849 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4851 struct strbuf errmsg = STRBUF_INIT;
4852 if (parse_dirstat_params(options, params, &errmsg))
4853 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4854 errmsg.buf);
4855 strbuf_release(&errmsg);
4857 * The caller knows a dirstat-related option is given from the command
4858 * line; allow it to say "return this_function();"
4860 options->output_format |= DIFF_FORMAT_DIRSTAT;
4861 return 1;
4864 static int diff_opt_diff_filter(const struct option *option,
4865 const char *optarg, int unset)
4867 struct diff_options *opt = option->value;
4868 int i, optch;
4870 BUG_ON_OPT_NEG(unset);
4871 prepare_filter_bits();
4873 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4874 unsigned int bit;
4875 int negate;
4877 if ('a' <= optch && optch <= 'z') {
4878 negate = 1;
4879 optch = toupper(optch);
4880 } else {
4881 negate = 0;
4884 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4885 if (!bit)
4886 return error(_("unknown change class '%c' in --diff-filter=%s"),
4887 optarg[i], optarg);
4888 if (negate)
4889 opt->filter_not |= bit;
4890 else
4891 opt->filter |= bit;
4893 return 0;
4896 static void enable_patch_output(int *fmt)
4898 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4899 *fmt |= DIFF_FORMAT_PATCH;
4902 static int diff_opt_ws_error_highlight(const struct option *option,
4903 const char *arg, int unset)
4905 struct diff_options *opt = option->value;
4906 int val = parse_ws_error_highlight(arg);
4908 BUG_ON_OPT_NEG(unset);
4909 if (val < 0)
4910 return error(_("unknown value after ws-error-highlight=%.*s"),
4911 -1 - val, arg);
4912 opt->ws_error_highlight = val;
4913 return 0;
4916 static int diff_opt_find_object(const struct option *option,
4917 const char *arg, int unset)
4919 struct diff_options *opt = option->value;
4920 struct object_id oid;
4922 BUG_ON_OPT_NEG(unset);
4923 if (get_oid(arg, &oid))
4924 return error(_("unable to resolve '%s'"), arg);
4926 if (!opt->objfind)
4927 CALLOC_ARRAY(opt->objfind, 1);
4929 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4930 opt->flags.recursive = 1;
4931 opt->flags.tree_in_recursive = 1;
4932 oidset_insert(opt->objfind, &oid);
4933 return 0;
4936 static int diff_opt_anchored(const struct option *opt,
4937 const char *arg, int unset)
4939 struct diff_options *options = opt->value;
4941 BUG_ON_OPT_NEG(unset);
4942 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4943 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4944 options->anchors_alloc);
4945 options->anchors[options->anchors_nr++] = xstrdup(arg);
4946 return 0;
4949 static int diff_opt_binary(const struct option *opt,
4950 const char *arg, int unset)
4952 struct diff_options *options = opt->value;
4954 BUG_ON_OPT_NEG(unset);
4955 BUG_ON_OPT_ARG(arg);
4956 enable_patch_output(&options->output_format);
4957 options->flags.binary = 1;
4958 return 0;
4961 static int diff_opt_break_rewrites(const struct option *opt,
4962 const char *arg, int unset)
4964 int *break_opt = opt->value;
4965 int opt1, opt2;
4967 BUG_ON_OPT_NEG(unset);
4968 if (!arg)
4969 arg = "";
4970 opt1 = parse_rename_score(&arg);
4971 if (*arg == 0)
4972 opt2 = 0;
4973 else if (*arg != '/')
4974 return error(_("%s expects <n>/<m> form"), opt->long_name);
4975 else {
4976 arg++;
4977 opt2 = parse_rename_score(&arg);
4979 if (*arg != 0)
4980 return error(_("%s expects <n>/<m> form"), opt->long_name);
4981 *break_opt = opt1 | (opt2 << 16);
4982 return 0;
4985 static int diff_opt_char(const struct option *opt,
4986 const char *arg, int unset)
4988 char *value = opt->value;
4990 BUG_ON_OPT_NEG(unset);
4991 if (arg[1])
4992 return error(_("%s expects a character, got '%s'"),
4993 opt->long_name, arg);
4994 *value = arg[0];
4995 return 0;
4998 static int diff_opt_color_moved(const struct option *opt,
4999 const char *arg, int unset)
5001 struct diff_options *options = opt->value;
5003 if (unset) {
5004 options->color_moved = COLOR_MOVED_NO;
5005 } else if (!arg) {
5006 if (diff_color_moved_default)
5007 options->color_moved = diff_color_moved_default;
5008 if (options->color_moved == COLOR_MOVED_NO)
5009 options->color_moved = COLOR_MOVED_DEFAULT;
5010 } else {
5011 int cm = parse_color_moved(arg);
5012 if (cm < 0)
5013 return error(_("bad --color-moved argument: %s"), arg);
5014 options->color_moved = cm;
5016 return 0;
5019 static int diff_opt_color_moved_ws(const struct option *opt,
5020 const char *arg, int unset)
5022 struct diff_options *options = opt->value;
5023 unsigned cm;
5025 if (unset) {
5026 options->color_moved_ws_handling = 0;
5027 return 0;
5030 cm = parse_color_moved_ws(arg);
5031 if (cm & COLOR_MOVED_WS_ERROR)
5032 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5033 options->color_moved_ws_handling = cm;
5034 return 0;
5037 static int diff_opt_color_words(const struct option *opt,
5038 const char *arg, int unset)
5040 struct diff_options *options = opt->value;
5042 BUG_ON_OPT_NEG(unset);
5043 options->use_color = 1;
5044 options->word_diff = DIFF_WORDS_COLOR;
5045 options->word_regex = arg;
5046 return 0;
5049 static int diff_opt_compact_summary(const struct option *opt,
5050 const char *arg, int unset)
5052 struct diff_options *options = opt->value;
5054 BUG_ON_OPT_ARG(arg);
5055 if (unset) {
5056 options->flags.stat_with_summary = 0;
5057 } else {
5058 options->flags.stat_with_summary = 1;
5059 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5061 return 0;
5064 static int diff_opt_diff_algorithm(const struct option *opt,
5065 const char *arg, int unset)
5067 struct diff_options *options = opt->value;
5068 long value = parse_algorithm_value(arg);
5070 BUG_ON_OPT_NEG(unset);
5071 if (value < 0)
5072 return error(_("option diff-algorithm accepts \"myers\", "
5073 "\"minimal\", \"patience\" and \"histogram\""));
5075 /* clear out previous settings */
5076 DIFF_XDL_CLR(options, NEED_MINIMAL);
5077 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5078 options->xdl_opts |= value;
5079 return 0;
5082 static int diff_opt_dirstat(const struct option *opt,
5083 const char *arg, int unset)
5085 struct diff_options *options = opt->value;
5087 BUG_ON_OPT_NEG(unset);
5088 if (!strcmp(opt->long_name, "cumulative")) {
5089 if (arg)
5090 BUG("how come --cumulative take a value?");
5091 arg = "cumulative";
5092 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5093 parse_dirstat_opt(options, "files");
5094 parse_dirstat_opt(options, arg ? arg : "");
5095 return 0;
5098 static int diff_opt_find_copies(const struct option *opt,
5099 const char *arg, int unset)
5101 struct diff_options *options = opt->value;
5103 BUG_ON_OPT_NEG(unset);
5104 if (!arg)
5105 arg = "";
5106 options->rename_score = parse_rename_score(&arg);
5107 if (*arg != 0)
5108 return error(_("invalid argument to %s"), opt->long_name);
5110 if (options->detect_rename == DIFF_DETECT_COPY)
5111 options->flags.find_copies_harder = 1;
5112 else
5113 options->detect_rename = DIFF_DETECT_COPY;
5115 return 0;
5118 static int diff_opt_find_renames(const struct option *opt,
5119 const char *arg, int unset)
5121 struct diff_options *options = opt->value;
5123 BUG_ON_OPT_NEG(unset);
5124 if (!arg)
5125 arg = "";
5126 options->rename_score = parse_rename_score(&arg);
5127 if (*arg != 0)
5128 return error(_("invalid argument to %s"), opt->long_name);
5130 options->detect_rename = DIFF_DETECT_RENAME;
5131 return 0;
5134 static int diff_opt_follow(const struct option *opt,
5135 const char *arg, int unset)
5137 struct diff_options *options = opt->value;
5139 BUG_ON_OPT_ARG(arg);
5140 if (unset) {
5141 options->flags.follow_renames = 0;
5142 options->flags.default_follow_renames = 0;
5143 } else {
5144 options->flags.follow_renames = 1;
5146 return 0;
5149 static int diff_opt_ignore_submodules(const struct option *opt,
5150 const char *arg, int unset)
5152 struct diff_options *options = opt->value;
5154 BUG_ON_OPT_NEG(unset);
5155 if (!arg)
5156 arg = "all";
5157 options->flags.override_submodule_config = 1;
5158 handle_ignore_submodules_arg(options, arg);
5159 return 0;
5162 static int diff_opt_line_prefix(const struct option *opt,
5163 const char *optarg, int unset)
5165 struct diff_options *options = opt->value;
5167 BUG_ON_OPT_NEG(unset);
5168 options->line_prefix = optarg;
5169 options->line_prefix_length = strlen(options->line_prefix);
5170 graph_setup_line_prefix(options);
5171 return 0;
5174 static int diff_opt_no_prefix(const struct option *opt,
5175 const char *optarg, int unset)
5177 struct diff_options *options = opt->value;
5179 BUG_ON_OPT_NEG(unset);
5180 BUG_ON_OPT_ARG(optarg);
5181 options->a_prefix = "";
5182 options->b_prefix = "";
5183 return 0;
5186 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5187 const struct option *opt,
5188 const char *arg, int unset)
5190 struct diff_options *options = opt->value;
5191 char *path;
5193 BUG_ON_OPT_NEG(unset);
5194 path = prefix_filename(ctx->prefix, arg);
5195 options->file = xfopen(path, "w");
5196 options->close_file = 1;
5197 if (options->use_color != GIT_COLOR_ALWAYS)
5198 options->use_color = GIT_COLOR_NEVER;
5199 free(path);
5200 return 0;
5203 static int diff_opt_patience(const struct option *opt,
5204 const char *arg, int unset)
5206 struct diff_options *options = opt->value;
5207 int i;
5209 BUG_ON_OPT_NEG(unset);
5210 BUG_ON_OPT_ARG(arg);
5211 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5213 * Both --patience and --anchored use PATIENCE_DIFF
5214 * internally, so remove any anchors previously
5215 * specified.
5217 for (i = 0; i < options->anchors_nr; i++)
5218 free(options->anchors[i]);
5219 options->anchors_nr = 0;
5220 return 0;
5223 static int diff_opt_ignore_regex(const struct option *opt,
5224 const char *arg, int unset)
5226 struct diff_options *options = opt->value;
5227 regex_t *regex;
5229 BUG_ON_OPT_NEG(unset);
5230 regex = xmalloc(sizeof(*regex));
5231 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5232 return error(_("invalid regex given to -I: '%s'"), arg);
5233 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5234 options->ignore_regex_alloc);
5235 options->ignore_regex[options->ignore_regex_nr++] = regex;
5236 return 0;
5239 static int diff_opt_pickaxe_regex(const struct option *opt,
5240 const char *arg, int unset)
5242 struct diff_options *options = opt->value;
5244 BUG_ON_OPT_NEG(unset);
5245 options->pickaxe = arg;
5246 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5247 return 0;
5250 static int diff_opt_pickaxe_string(const struct option *opt,
5251 const char *arg, int unset)
5253 struct diff_options *options = opt->value;
5255 BUG_ON_OPT_NEG(unset);
5256 options->pickaxe = arg;
5257 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5258 return 0;
5261 static int diff_opt_relative(const struct option *opt,
5262 const char *arg, int unset)
5264 struct diff_options *options = opt->value;
5266 options->flags.relative_name = !unset;
5267 if (arg)
5268 options->prefix = arg;
5269 return 0;
5272 static int diff_opt_submodule(const struct option *opt,
5273 const char *arg, int unset)
5275 struct diff_options *options = opt->value;
5277 BUG_ON_OPT_NEG(unset);
5278 if (!arg)
5279 arg = "log";
5280 if (parse_submodule_params(options, arg))
5281 return error(_("failed to parse --submodule option parameter: '%s'"),
5282 arg);
5283 return 0;
5286 static int diff_opt_textconv(const struct option *opt,
5287 const char *arg, int unset)
5289 struct diff_options *options = opt->value;
5291 BUG_ON_OPT_ARG(arg);
5292 if (unset) {
5293 options->flags.allow_textconv = 0;
5294 } else {
5295 options->flags.allow_textconv = 1;
5296 options->flags.textconv_set_via_cmdline = 1;
5298 return 0;
5301 static int diff_opt_unified(const struct option *opt,
5302 const char *arg, int unset)
5304 struct diff_options *options = opt->value;
5305 char *s;
5307 BUG_ON_OPT_NEG(unset);
5309 if (arg) {
5310 options->context = strtol(arg, &s, 10);
5311 if (*s)
5312 return error(_("%s expects a numerical value"), "--unified");
5314 enable_patch_output(&options->output_format);
5316 return 0;
5319 static int diff_opt_word_diff(const struct option *opt,
5320 const char *arg, int unset)
5322 struct diff_options *options = opt->value;
5324 BUG_ON_OPT_NEG(unset);
5325 if (arg) {
5326 if (!strcmp(arg, "plain"))
5327 options->word_diff = DIFF_WORDS_PLAIN;
5328 else if (!strcmp(arg, "color")) {
5329 options->use_color = 1;
5330 options->word_diff = DIFF_WORDS_COLOR;
5332 else if (!strcmp(arg, "porcelain"))
5333 options->word_diff = DIFF_WORDS_PORCELAIN;
5334 else if (!strcmp(arg, "none"))
5335 options->word_diff = DIFF_WORDS_NONE;
5336 else
5337 return error(_("bad --word-diff argument: %s"), arg);
5338 } else {
5339 if (options->word_diff == DIFF_WORDS_NONE)
5340 options->word_diff = DIFF_WORDS_PLAIN;
5342 return 0;
5345 static int diff_opt_word_diff_regex(const struct option *opt,
5346 const char *arg, int unset)
5348 struct diff_options *options = opt->value;
5350 BUG_ON_OPT_NEG(unset);
5351 if (options->word_diff == DIFF_WORDS_NONE)
5352 options->word_diff = DIFF_WORDS_PLAIN;
5353 options->word_regex = arg;
5354 return 0;
5357 static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5359 struct diff_options *options = opt->value;
5361 BUG_ON_OPT_NEG(unset);
5362 if (!strcmp(opt->long_name, "skip-to"))
5363 options->skip_instead_of_rotate = 1;
5364 else
5365 options->skip_instead_of_rotate = 0;
5366 options->rotate_to = arg;
5367 return 0;
5370 static void prep_parse_options(struct diff_options *options)
5372 struct option parseopts[] = {
5373 OPT_GROUP(N_("Diff output format options")),
5374 OPT_BITOP('p', "patch", &options->output_format,
5375 N_("generate patch"),
5376 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5377 OPT_BIT_F('s', "no-patch", &options->output_format,
5378 N_("suppress diff output"),
5379 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5380 OPT_BITOP('u', NULL, &options->output_format,
5381 N_("generate patch"),
5382 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5383 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5384 N_("generate diffs with <n> lines context"),
5385 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5386 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5387 N_("generate diffs with <n> lines context")),
5388 OPT_BIT_F(0, "raw", &options->output_format,
5389 N_("generate the diff in raw format"),
5390 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5391 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5392 N_("synonym for '-p --raw'"),
5393 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5394 DIFF_FORMAT_NO_OUTPUT),
5395 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5396 N_("synonym for '-p --stat'"),
5397 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5398 DIFF_FORMAT_NO_OUTPUT),
5399 OPT_BIT_F(0, "numstat", &options->output_format,
5400 N_("machine friendly --stat"),
5401 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5402 OPT_BIT_F(0, "shortstat", &options->output_format,
5403 N_("output only the last line of --stat"),
5404 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5405 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5406 N_("output the distribution of relative amount of changes for each sub-directory"),
5407 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5408 diff_opt_dirstat),
5409 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5410 N_("synonym for --dirstat=cumulative"),
5411 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5412 diff_opt_dirstat),
5413 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5414 N_("synonym for --dirstat=files,param1,param2..."),
5415 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5416 diff_opt_dirstat),
5417 OPT_BIT_F(0, "check", &options->output_format,
5418 N_("warn if changes introduce conflict markers or whitespace errors"),
5419 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5420 OPT_BIT_F(0, "summary", &options->output_format,
5421 N_("condensed summary such as creations, renames and mode changes"),
5422 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5423 OPT_BIT_F(0, "name-only", &options->output_format,
5424 N_("show only names of changed files"),
5425 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5426 OPT_BIT_F(0, "name-status", &options->output_format,
5427 N_("show only names and status of changed files"),
5428 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5429 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5430 N_("generate diffstat"),
5431 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5432 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5433 N_("generate diffstat with a given width"),
5434 PARSE_OPT_NONEG, diff_opt_stat),
5435 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5436 N_("generate diffstat with a given name width"),
5437 PARSE_OPT_NONEG, diff_opt_stat),
5438 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5439 N_("generate diffstat with a given graph width"),
5440 PARSE_OPT_NONEG, diff_opt_stat),
5441 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5442 N_("generate diffstat with limited lines"),
5443 PARSE_OPT_NONEG, diff_opt_stat),
5444 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5445 N_("generate compact summary in diffstat"),
5446 PARSE_OPT_NOARG, diff_opt_compact_summary),
5447 OPT_CALLBACK_F(0, "binary", options, NULL,
5448 N_("output a binary diff that can be applied"),
5449 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5450 OPT_BOOL(0, "full-index", &options->flags.full_index,
5451 N_("show full pre- and post-image object names on the \"index\" lines")),
5452 OPT_COLOR_FLAG(0, "color", &options->use_color,
5453 N_("show colored diff")),
5454 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5455 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5456 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5457 OPT_SET_INT('z', NULL, &options->line_termination,
5458 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5460 OPT__ABBREV(&options->abbrev),
5461 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5462 N_("show the given source prefix instead of \"a/\""),
5463 PARSE_OPT_NONEG),
5464 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5465 N_("show the given destination prefix instead of \"b/\""),
5466 PARSE_OPT_NONEG),
5467 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5468 N_("prepend an additional prefix to every line of output"),
5469 PARSE_OPT_NONEG, diff_opt_line_prefix),
5470 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5471 N_("do not show any source or destination prefix"),
5472 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5473 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5474 N_("show context between diff hunks up to the specified number of lines"),
5475 PARSE_OPT_NONEG),
5476 OPT_CALLBACK_F(0, "output-indicator-new",
5477 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5478 N_("<char>"),
5479 N_("specify the character to indicate a new line instead of '+'"),
5480 PARSE_OPT_NONEG, diff_opt_char),
5481 OPT_CALLBACK_F(0, "output-indicator-old",
5482 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5483 N_("<char>"),
5484 N_("specify the character to indicate an old line instead of '-'"),
5485 PARSE_OPT_NONEG, diff_opt_char),
5486 OPT_CALLBACK_F(0, "output-indicator-context",
5487 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5488 N_("<char>"),
5489 N_("specify the character to indicate a context instead of ' '"),
5490 PARSE_OPT_NONEG, diff_opt_char),
5492 OPT_GROUP(N_("Diff rename options")),
5493 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5494 N_("break complete rewrite changes into pairs of delete and create"),
5495 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5496 diff_opt_break_rewrites),
5497 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5498 N_("detect renames"),
5499 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5500 diff_opt_find_renames),
5501 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5502 N_("omit the preimage for deletes"),
5503 1, PARSE_OPT_NONEG),
5504 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5505 N_("detect copies"),
5506 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5507 diff_opt_find_copies),
5508 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5509 N_("use unmodified files as source to find copies")),
5510 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5511 N_("disable rename detection"),
5512 0, PARSE_OPT_NONEG),
5513 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5514 N_("use empty blobs as rename source")),
5515 OPT_CALLBACK_F(0, "follow", options, NULL,
5516 N_("continue listing the history of a file beyond renames"),
5517 PARSE_OPT_NOARG, diff_opt_follow),
5518 OPT_INTEGER('l', NULL, &options->rename_limit,
5519 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5521 OPT_GROUP(N_("Diff algorithm options")),
5522 OPT_BIT(0, "minimal", &options->xdl_opts,
5523 N_("produce the smallest possible diff"),
5524 XDF_NEED_MINIMAL),
5525 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5526 N_("ignore whitespace when comparing lines"),
5527 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5528 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5529 N_("ignore changes in amount of whitespace"),
5530 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5531 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5532 N_("ignore changes in whitespace at EOL"),
5533 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5534 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5535 N_("ignore carrier-return at the end of line"),
5536 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5537 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5538 N_("ignore changes whose lines are all blank"),
5539 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5540 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5541 N_("ignore changes whose all lines match <regex>"),
5542 0, diff_opt_ignore_regex),
5543 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5544 N_("heuristic to shift diff hunk boundaries for easy reading"),
5545 XDF_INDENT_HEURISTIC),
5546 OPT_CALLBACK_F(0, "patience", options, NULL,
5547 N_("generate diff using the \"patience diff\" algorithm"),
5548 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5549 diff_opt_patience),
5550 OPT_BITOP(0, "histogram", &options->xdl_opts,
5551 N_("generate diff using the \"histogram diff\" algorithm"),
5552 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5553 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5554 N_("choose a diff algorithm"),
5555 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5556 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5557 N_("generate diff using the \"anchored diff\" algorithm"),
5558 PARSE_OPT_NONEG, diff_opt_anchored),
5559 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5560 N_("show word diff, using <mode> to delimit changed words"),
5561 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5562 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5563 N_("use <regex> to decide what a word is"),
5564 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5565 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5566 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5567 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5568 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5569 N_("moved lines of code are colored differently"),
5570 PARSE_OPT_OPTARG, diff_opt_color_moved),
5571 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5572 N_("how white spaces are ignored in --color-moved"),
5573 0, diff_opt_color_moved_ws),
5575 OPT_GROUP(N_("Other diff options")),
5576 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5577 N_("when run from subdir, exclude changes outside and show relative paths"),
5578 PARSE_OPT_OPTARG,
5579 diff_opt_relative),
5580 OPT_BOOL('a', "text", &options->flags.text,
5581 N_("treat all files as text")),
5582 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5583 N_("swap two inputs, reverse the diff")),
5584 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5585 N_("exit with 1 if there were differences, 0 otherwise")),
5586 OPT_BOOL(0, "quiet", &options->flags.quick,
5587 N_("disable all output of the program")),
5588 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5589 N_("allow an external diff helper to be executed")),
5590 OPT_CALLBACK_F(0, "textconv", options, NULL,
5591 N_("run external text conversion filters when comparing binary files"),
5592 PARSE_OPT_NOARG, diff_opt_textconv),
5593 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5594 N_("ignore changes to submodules in the diff generation"),
5595 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5596 diff_opt_ignore_submodules),
5597 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5598 N_("specify how differences in submodules are shown"),
5599 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5600 diff_opt_submodule),
5601 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5602 N_("hide 'git add -N' entries from the index"),
5603 1, PARSE_OPT_NONEG),
5604 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5605 N_("treat 'git add -N' entries as real in the index"),
5606 0, PARSE_OPT_NONEG),
5607 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5608 N_("look for differences that change the number of occurrences of the specified string"),
5609 0, diff_opt_pickaxe_string),
5610 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5611 N_("look for differences that change the number of occurrences of the specified regex"),
5612 0, diff_opt_pickaxe_regex),
5613 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5614 N_("show all changes in the changeset with -S or -G"),
5615 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5616 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5617 N_("treat <string> in -S as extended POSIX regular expression"),
5618 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5619 OPT_FILENAME('O', NULL, &options->orderfile,
5620 N_("control the order in which files appear in the output")),
5621 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5622 N_("show the change in the specified path first"),
5623 PARSE_OPT_NONEG, diff_opt_rotate_to),
5624 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5625 N_("skip the output to the specified path"),
5626 PARSE_OPT_NONEG, diff_opt_rotate_to),
5627 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5628 N_("look for differences that change the number of occurrences of the specified object"),
5629 PARSE_OPT_NONEG, diff_opt_find_object),
5630 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5631 N_("select files by diff type"),
5632 PARSE_OPT_NONEG, diff_opt_diff_filter),
5633 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5634 N_("Output to a specific file"),
5635 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5637 OPT_END()
5640 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5641 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5644 int diff_opt_parse(struct diff_options *options,
5645 const char **av, int ac, const char *prefix)
5647 if (!prefix)
5648 prefix = "";
5650 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5651 PARSE_OPT_KEEP_DASHDASH |
5652 PARSE_OPT_KEEP_UNKNOWN |
5653 PARSE_OPT_NO_INTERNAL_HELP |
5654 PARSE_OPT_ONE_SHOT |
5655 PARSE_OPT_STOP_AT_NON_OPTION);
5657 return ac;
5660 int parse_rename_score(const char **cp_p)
5662 unsigned long num, scale;
5663 int ch, dot;
5664 const char *cp = *cp_p;
5666 num = 0;
5667 scale = 1;
5668 dot = 0;
5669 for (;;) {
5670 ch = *cp;
5671 if ( !dot && ch == '.' ) {
5672 scale = 1;
5673 dot = 1;
5674 } else if ( ch == '%' ) {
5675 scale = dot ? scale*100 : 100;
5676 cp++; /* % is always at the end */
5677 break;
5678 } else if ( ch >= '0' && ch <= '9' ) {
5679 if ( scale < 100000 ) {
5680 scale *= 10;
5681 num = (num*10) + (ch-'0');
5683 } else {
5684 break;
5686 cp++;
5688 *cp_p = cp;
5690 /* user says num divided by scale and we say internally that
5691 * is MAX_SCORE * num / scale.
5693 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5696 struct diff_queue_struct diff_queued_diff;
5698 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5700 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5701 queue->queue[queue->nr++] = dp;
5704 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5705 struct diff_filespec *one,
5706 struct diff_filespec *two)
5708 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5709 dp->one = one;
5710 dp->two = two;
5711 if (queue)
5712 diff_q(queue, dp);
5713 return dp;
5716 void diff_free_filepair(struct diff_filepair *p)
5718 free_filespec(p->one);
5719 free_filespec(p->two);
5720 free(p);
5723 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5725 int abblen;
5726 const char *abbrev;
5728 /* Do we want all 40 hex characters? */
5729 if (len == the_hash_algo->hexsz)
5730 return oid_to_hex(oid);
5732 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5733 abbrev = diff_abbrev_oid(oid, len);
5735 if (!print_sha1_ellipsis())
5736 return abbrev;
5738 abblen = strlen(abbrev);
5741 * In well-behaved cases, where the abbreviated result is the
5742 * same as the requested length, append three dots after the
5743 * abbreviation (hence the whole logic is limited to the case
5744 * where abblen < 37); when the actual abbreviated result is a
5745 * bit longer than the requested length, we reduce the number
5746 * of dots so that they match the well-behaved ones. However,
5747 * if the actual abbreviation is longer than the requested
5748 * length by more than three, we give up on aligning, and add
5749 * three dots anyway, to indicate that the output is not the
5750 * full object name. Yes, this may be suboptimal, but this
5751 * appears only in "diff --raw --abbrev" output and it is not
5752 * worth the effort to change it now. Note that this would
5753 * likely to work fine when the automatic sizing of default
5754 * abbreviation length is used--we would be fed -1 in "len" in
5755 * that case, and will end up always appending three-dots, but
5756 * the automatic sizing is supposed to give abblen that ensures
5757 * uniqueness across all objects (statistically speaking).
5759 if (abblen < the_hash_algo->hexsz - 3) {
5760 static char hex[GIT_MAX_HEXSZ + 1];
5761 if (len < abblen && abblen <= len + 2)
5762 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5763 else
5764 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5765 return hex;
5768 return oid_to_hex(oid);
5771 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5773 int line_termination = opt->line_termination;
5774 int inter_name_termination = line_termination ? '\t' : '\0';
5776 fprintf(opt->file, "%s", diff_line_prefix(opt));
5777 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5778 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5779 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5780 fprintf(opt->file, "%s ",
5781 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5783 if (p->score) {
5784 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5785 inter_name_termination);
5786 } else {
5787 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5790 if (p->status == DIFF_STATUS_COPIED ||
5791 p->status == DIFF_STATUS_RENAMED) {
5792 const char *name_a, *name_b;
5793 name_a = p->one->path;
5794 name_b = p->two->path;
5795 strip_prefix(opt->prefix_length, &name_a, &name_b);
5796 write_name_quoted(name_a, opt->file, inter_name_termination);
5797 write_name_quoted(name_b, opt->file, line_termination);
5798 } else {
5799 const char *name_a, *name_b;
5800 name_a = p->one->mode ? p->one->path : p->two->path;
5801 name_b = NULL;
5802 strip_prefix(opt->prefix_length, &name_a, &name_b);
5803 write_name_quoted(name_a, opt->file, line_termination);
5807 int diff_unmodified_pair(struct diff_filepair *p)
5809 /* This function is written stricter than necessary to support
5810 * the currently implemented transformers, but the idea is to
5811 * let transformers to produce diff_filepairs any way they want,
5812 * and filter and clean them up here before producing the output.
5814 struct diff_filespec *one = p->one, *two = p->two;
5816 if (DIFF_PAIR_UNMERGED(p))
5817 return 0; /* unmerged is interesting */
5819 /* deletion, addition, mode or type change
5820 * and rename are all interesting.
5822 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5823 DIFF_PAIR_MODE_CHANGED(p) ||
5824 strcmp(one->path, two->path))
5825 return 0;
5827 /* both are valid and point at the same path. that is, we are
5828 * dealing with a change.
5830 if (one->oid_valid && two->oid_valid &&
5831 oideq(&one->oid, &two->oid) &&
5832 !one->dirty_submodule && !two->dirty_submodule)
5833 return 1; /* no change */
5834 if (!one->oid_valid && !two->oid_valid)
5835 return 1; /* both look at the same file on the filesystem. */
5836 return 0;
5839 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5841 int include_conflict_headers =
5842 (additional_headers(o, p->one->path) &&
5843 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5846 * Check if we can return early without showing a diff. Note that
5847 * diff_filepair only stores {oid, path, mode, is_valid}
5848 * information for each path, and thus diff_unmodified_pair() only
5849 * considers those bits of info. However, we do not want pairs
5850 * created by create_filepairs_for_header_only_notifications()
5851 * (which always look like unmodified pairs) to be ignored, so
5852 * return early if both p is unmodified AND we don't want to
5853 * include_conflict_headers.
5855 if (diff_unmodified_pair(p) && !include_conflict_headers)
5856 return;
5858 /* Actually, we can also return early to avoid showing tree diffs */
5859 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5860 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5861 return;
5863 run_diff(p, o);
5866 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5867 struct diffstat_t *diffstat)
5869 if (diff_unmodified_pair(p))
5870 return;
5872 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5873 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5874 return; /* no useful stat for tree diffs */
5876 run_diffstat(p, o, diffstat);
5879 static void diff_flush_checkdiff(struct diff_filepair *p,
5880 struct diff_options *o)
5882 if (diff_unmodified_pair(p))
5883 return;
5885 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5886 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5887 return; /* nothing to check in tree diffs */
5889 run_checkdiff(p, o);
5892 int diff_queue_is_empty(struct diff_options *o)
5894 struct diff_queue_struct *q = &diff_queued_diff;
5895 int i;
5896 int include_conflict_headers =
5897 (o->additional_path_headers &&
5898 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
5900 if (include_conflict_headers)
5901 return 0;
5903 for (i = 0; i < q->nr; i++)
5904 if (!diff_unmodified_pair(q->queue[i]))
5905 return 0;
5906 return 1;
5909 #if DIFF_DEBUG
5910 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5912 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5913 x, one ? one : "",
5914 s->path,
5915 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5916 s->mode,
5917 s->oid_valid ? oid_to_hex(&s->oid) : "");
5918 fprintf(stderr, "queue[%d] %s size %lu\n",
5919 x, one ? one : "",
5920 s->size);
5923 void diff_debug_filepair(const struct diff_filepair *p, int i)
5925 diff_debug_filespec(p->one, i, "one");
5926 diff_debug_filespec(p->two, i, "two");
5927 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5928 p->score, p->status ? p->status : '?',
5929 p->one->rename_used, p->broken_pair);
5932 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5934 int i;
5935 if (msg)
5936 fprintf(stderr, "%s\n", msg);
5937 fprintf(stderr, "q->nr = %d\n", q->nr);
5938 for (i = 0; i < q->nr; i++) {
5939 struct diff_filepair *p = q->queue[i];
5940 diff_debug_filepair(p, i);
5943 #endif
5945 static void diff_resolve_rename_copy(void)
5947 int i;
5948 struct diff_filepair *p;
5949 struct diff_queue_struct *q = &diff_queued_diff;
5951 diff_debug_queue("resolve-rename-copy", q);
5953 for (i = 0; i < q->nr; i++) {
5954 p = q->queue[i];
5955 p->status = 0; /* undecided */
5956 if (DIFF_PAIR_UNMERGED(p))
5957 p->status = DIFF_STATUS_UNMERGED;
5958 else if (!DIFF_FILE_VALID(p->one))
5959 p->status = DIFF_STATUS_ADDED;
5960 else if (!DIFF_FILE_VALID(p->two))
5961 p->status = DIFF_STATUS_DELETED;
5962 else if (DIFF_PAIR_TYPE_CHANGED(p))
5963 p->status = DIFF_STATUS_TYPE_CHANGED;
5965 /* from this point on, we are dealing with a pair
5966 * whose both sides are valid and of the same type, i.e.
5967 * either in-place edit or rename/copy edit.
5969 else if (DIFF_PAIR_RENAME(p)) {
5971 * A rename might have re-connected a broken
5972 * pair up, causing the pathnames to be the
5973 * same again. If so, that's not a rename at
5974 * all, just a modification..
5976 * Otherwise, see if this source was used for
5977 * multiple renames, in which case we decrement
5978 * the count, and call it a copy.
5980 if (!strcmp(p->one->path, p->two->path))
5981 p->status = DIFF_STATUS_MODIFIED;
5982 else if (--p->one->rename_used > 0)
5983 p->status = DIFF_STATUS_COPIED;
5984 else
5985 p->status = DIFF_STATUS_RENAMED;
5987 else if (!oideq(&p->one->oid, &p->two->oid) ||
5988 p->one->mode != p->two->mode ||
5989 p->one->dirty_submodule ||
5990 p->two->dirty_submodule ||
5991 is_null_oid(&p->one->oid))
5992 p->status = DIFF_STATUS_MODIFIED;
5993 else {
5994 /* This is a "no-change" entry and should not
5995 * happen anymore, but prepare for broken callers.
5997 error("feeding unmodified %s to diffcore",
5998 p->one->path);
5999 p->status = DIFF_STATUS_UNKNOWN;
6002 diff_debug_queue("resolve-rename-copy done", q);
6005 static int check_pair_status(struct diff_filepair *p)
6007 switch (p->status) {
6008 case DIFF_STATUS_UNKNOWN:
6009 return 0;
6010 case 0:
6011 die("internal error in diff-resolve-rename-copy");
6012 default:
6013 return 1;
6017 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6019 int fmt = opt->output_format;
6021 if (fmt & DIFF_FORMAT_CHECKDIFF)
6022 diff_flush_checkdiff(p, opt);
6023 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6024 diff_flush_raw(p, opt);
6025 else if (fmt & DIFF_FORMAT_NAME) {
6026 const char *name_a, *name_b;
6027 name_a = p->two->path;
6028 name_b = NULL;
6029 strip_prefix(opt->prefix_length, &name_a, &name_b);
6030 fprintf(opt->file, "%s", diff_line_prefix(opt));
6031 write_name_quoted(name_a, opt->file, opt->line_termination);
6035 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
6037 struct strbuf sb = STRBUF_INIT;
6038 if (fs->mode)
6039 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
6040 else
6041 strbuf_addf(&sb, " %s ", newdelete);
6043 quote_c_style(fs->path, &sb, NULL, 0);
6044 strbuf_addch(&sb, '\n');
6045 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6046 sb.buf, sb.len, 0);
6047 strbuf_release(&sb);
6050 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6051 int show_name)
6053 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
6054 struct strbuf sb = STRBUF_INIT;
6055 strbuf_addf(&sb, " mode change %06o => %06o",
6056 p->one->mode, p->two->mode);
6057 if (show_name) {
6058 strbuf_addch(&sb, ' ');
6059 quote_c_style(p->two->path, &sb, NULL, 0);
6061 strbuf_addch(&sb, '\n');
6062 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6063 sb.buf, sb.len, 0);
6064 strbuf_release(&sb);
6068 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6069 struct diff_filepair *p)
6071 struct strbuf sb = STRBUF_INIT;
6072 struct strbuf names = STRBUF_INIT;
6074 pprint_rename(&names, p->one->path, p->two->path);
6075 strbuf_addf(&sb, " %s %s (%d%%)\n",
6076 renamecopy, names.buf, similarity_index(p));
6077 strbuf_release(&names);
6078 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6079 sb.buf, sb.len, 0);
6080 show_mode_change(opt, p, 0);
6081 strbuf_release(&sb);
6084 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6086 switch(p->status) {
6087 case DIFF_STATUS_DELETED:
6088 show_file_mode_name(opt, "delete", p->one);
6089 break;
6090 case DIFF_STATUS_ADDED:
6091 show_file_mode_name(opt, "create", p->two);
6092 break;
6093 case DIFF_STATUS_COPIED:
6094 show_rename_copy(opt, "copy", p);
6095 break;
6096 case DIFF_STATUS_RENAMED:
6097 show_rename_copy(opt, "rename", p);
6098 break;
6099 default:
6100 if (p->score) {
6101 struct strbuf sb = STRBUF_INIT;
6102 strbuf_addstr(&sb, " rewrite ");
6103 quote_c_style(p->two->path, &sb, NULL, 0);
6104 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6105 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6106 sb.buf, sb.len, 0);
6107 strbuf_release(&sb);
6109 show_mode_change(opt, p, !p->score);
6110 break;
6114 struct patch_id_t {
6115 git_hash_ctx *ctx;
6116 int patchlen;
6119 static int remove_space(char *line, int len)
6121 int i;
6122 char *dst = line;
6123 unsigned char c;
6125 for (i = 0; i < len; i++)
6126 if (!isspace((c = line[i])))
6127 *dst++ = c;
6129 return dst - line;
6132 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6134 unsigned char hash[GIT_MAX_RAWSZ];
6135 unsigned short carry = 0;
6136 int i;
6138 the_hash_algo->final_fn(hash, ctx);
6139 the_hash_algo->init_fn(ctx);
6140 /* 20-byte sum, with carry */
6141 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6142 carry += result->hash[i] + hash[i];
6143 result->hash[i] = carry;
6144 carry >>= 8;
6148 static int patch_id_consume(void *priv, char *line, unsigned long len)
6150 struct patch_id_t *data = priv;
6151 int new_len;
6153 if (len > 12 && starts_with(line, "\\ "))
6154 return 0;
6155 new_len = remove_space(line, len);
6157 the_hash_algo->update_fn(data->ctx, line, new_len);
6158 data->patchlen += new_len;
6159 return 0;
6162 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6164 the_hash_algo->update_fn(ctx, str, strlen(str));
6167 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6169 /* large enough for 2^32 in octal */
6170 char buf[12];
6171 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6172 the_hash_algo->update_fn(ctx, buf, len);
6175 /* returns 0 upon success, and writes result into oid */
6176 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6178 struct diff_queue_struct *q = &diff_queued_diff;
6179 int i;
6180 git_hash_ctx ctx;
6181 struct patch_id_t data;
6183 the_hash_algo->init_fn(&ctx);
6184 memset(&data, 0, sizeof(struct patch_id_t));
6185 data.ctx = &ctx;
6186 oidclr(oid);
6188 for (i = 0; i < q->nr; i++) {
6189 xpparam_t xpp;
6190 xdemitconf_t xecfg;
6191 mmfile_t mf1, mf2;
6192 struct diff_filepair *p = q->queue[i];
6193 int len1, len2;
6195 memset(&xpp, 0, sizeof(xpp));
6196 memset(&xecfg, 0, sizeof(xecfg));
6197 if (p->status == 0)
6198 return error("internal diff status error");
6199 if (p->status == DIFF_STATUS_UNKNOWN)
6200 continue;
6201 if (diff_unmodified_pair(p))
6202 continue;
6203 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6204 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6205 continue;
6206 if (DIFF_PAIR_UNMERGED(p))
6207 continue;
6209 diff_fill_oid_info(p->one, options->repo->index);
6210 diff_fill_oid_info(p->two, options->repo->index);
6212 len1 = remove_space(p->one->path, strlen(p->one->path));
6213 len2 = remove_space(p->two->path, strlen(p->two->path));
6214 patch_id_add_string(&ctx, "diff--git");
6215 patch_id_add_string(&ctx, "a/");
6216 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6217 patch_id_add_string(&ctx, "b/");
6218 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6220 if (p->one->mode == 0) {
6221 patch_id_add_string(&ctx, "newfilemode");
6222 patch_id_add_mode(&ctx, p->two->mode);
6223 patch_id_add_string(&ctx, "---/dev/null");
6224 patch_id_add_string(&ctx, "+++b/");
6225 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6226 } else if (p->two->mode == 0) {
6227 patch_id_add_string(&ctx, "deletedfilemode");
6228 patch_id_add_mode(&ctx, p->one->mode);
6229 patch_id_add_string(&ctx, "---a/");
6230 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6231 patch_id_add_string(&ctx, "+++/dev/null");
6232 } else {
6233 patch_id_add_string(&ctx, "---a/");
6234 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6235 patch_id_add_string(&ctx, "+++b/");
6236 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6239 if (diff_header_only)
6240 continue;
6242 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6243 fill_mmfile(options->repo, &mf2, p->two) < 0)
6244 return error("unable to read files to diff");
6246 if (diff_filespec_is_binary(options->repo, p->one) ||
6247 diff_filespec_is_binary(options->repo, p->two)) {
6248 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6249 the_hash_algo->hexsz);
6250 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6251 the_hash_algo->hexsz);
6252 continue;
6255 xpp.flags = 0;
6256 xecfg.ctxlen = 3;
6257 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6258 if (xdi_diff_outf(&mf1, &mf2, NULL,
6259 patch_id_consume, &data, &xpp, &xecfg))
6260 return error("unable to generate patch-id diff for %s",
6261 p->one->path);
6263 if (stable)
6264 flush_one_hunk(oid, &ctx);
6267 if (!stable)
6268 the_hash_algo->final_oid_fn(oid, &ctx);
6270 return 0;
6273 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6275 struct diff_queue_struct *q = &diff_queued_diff;
6276 int i;
6277 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
6279 for (i = 0; i < q->nr; i++)
6280 diff_free_filepair(q->queue[i]);
6282 free(q->queue);
6283 DIFF_QUEUE_CLEAR(q);
6285 return result;
6288 static int is_summary_empty(const struct diff_queue_struct *q)
6290 int i;
6292 for (i = 0; i < q->nr; i++) {
6293 const struct diff_filepair *p = q->queue[i];
6295 switch (p->status) {
6296 case DIFF_STATUS_DELETED:
6297 case DIFF_STATUS_ADDED:
6298 case DIFF_STATUS_COPIED:
6299 case DIFF_STATUS_RENAMED:
6300 return 0;
6301 default:
6302 if (p->score)
6303 return 0;
6304 if (p->one->mode && p->two->mode &&
6305 p->one->mode != p->two->mode)
6306 return 0;
6307 break;
6310 return 1;
6313 static const char rename_limit_warning[] =
6314 N_("exhaustive rename detection was skipped due to too many files.");
6316 static const char degrade_cc_to_c_warning[] =
6317 N_("only found copies from modified paths due to too many files.");
6319 static const char rename_limit_advice[] =
6320 N_("you may want to set your %s variable to at least "
6321 "%d and retry the command.");
6323 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6325 fflush(stdout);
6326 if (degraded_cc)
6327 warning(_(degrade_cc_to_c_warning));
6328 else if (needed)
6329 warning(_(rename_limit_warning));
6330 else
6331 return;
6332 if (0 < needed)
6333 warning(_(rename_limit_advice), varname, needed);
6336 static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6338 struct strset present;
6339 struct diff_queue_struct *q = &diff_queued_diff;
6340 struct hashmap_iter iter;
6341 struct strmap_entry *e;
6342 int i;
6344 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6347 * Find out which paths exist in diff_queued_diff, preferring
6348 * one->path for any pair that has multiple paths.
6350 for (i = 0; i < q->nr; i++) {
6351 struct diff_filepair *p = q->queue[i];
6352 char *path = p->one->path ? p->one->path : p->two->path;
6354 if (strmap_contains(o->additional_path_headers, path))
6355 strset_add(&present, path);
6359 * Loop over paths in additional_path_headers; for each NOT already
6360 * in diff_queued_diff, create a synthetic filepair and insert that
6361 * into diff_queued_diff.
6363 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6364 if (!strset_contains(&present, e->key)) {
6365 struct diff_filespec *one, *two;
6366 struct diff_filepair *p;
6368 one = alloc_filespec(e->key);
6369 two = alloc_filespec(e->key);
6370 fill_filespec(one, null_oid(), 0, 0);
6371 fill_filespec(two, null_oid(), 0, 0);
6372 p = diff_queue(q, one, two);
6373 p->status = DIFF_STATUS_MODIFIED;
6377 /* Re-sort the filepairs */
6378 diffcore_fix_diff_index();
6380 /* Cleanup */
6381 strset_clear(&present);
6384 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6386 int i;
6387 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6388 struct diff_queue_struct *q = &diff_queued_diff;
6390 if (WSEH_NEW & WS_RULE_MASK)
6391 BUG("WS rules bit mask overlaps with diff symbol flags");
6393 if (o->color_moved)
6394 o->emitted_symbols = &esm;
6396 if (o->additional_path_headers)
6397 create_filepairs_for_header_only_notifications(o);
6399 for (i = 0; i < q->nr; i++) {
6400 struct diff_filepair *p = q->queue[i];
6401 if (check_pair_status(p))
6402 diff_flush_patch(p, o);
6405 if (o->emitted_symbols) {
6406 if (o->color_moved) {
6407 struct mem_pool entry_pool;
6408 struct moved_entry_list *entry_list;
6410 mem_pool_init(&entry_pool, 1024 * 1024);
6411 entry_list = add_lines_to_move_detection(o,
6412 &entry_pool);
6413 mark_color_as_moved(o, entry_list);
6414 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6415 dim_moved_lines(o);
6417 mem_pool_discard(&entry_pool, 0);
6418 free(entry_list);
6421 for (i = 0; i < esm.nr; i++)
6422 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6424 for (i = 0; i < esm.nr; i++)
6425 free((void *)esm.buf[i].line);
6426 esm.nr = 0;
6428 o->emitted_symbols = NULL;
6432 static void diff_free_file(struct diff_options *options)
6434 if (options->close_file)
6435 fclose(options->file);
6438 static void diff_free_ignore_regex(struct diff_options *options)
6440 int i;
6442 for (i = 0; i < options->ignore_regex_nr; i++) {
6443 regfree(options->ignore_regex[i]);
6444 free(options->ignore_regex[i]);
6446 free(options->ignore_regex);
6449 void diff_free(struct diff_options *options)
6451 if (options->no_free)
6452 return;
6454 diff_free_file(options);
6455 diff_free_ignore_regex(options);
6456 clear_pathspec(&options->pathspec);
6457 FREE_AND_NULL(options->parseopts);
6460 void diff_flush(struct diff_options *options)
6462 struct diff_queue_struct *q = &diff_queued_diff;
6463 int i, output_format = options->output_format;
6464 int separator = 0;
6465 int dirstat_by_line = 0;
6468 * Order: raw, stat, summary, patch
6469 * or: name/name-status/checkdiff (other bits clear)
6471 if (!q->nr && !options->additional_path_headers)
6472 goto free_queue;
6474 if (output_format & (DIFF_FORMAT_RAW |
6475 DIFF_FORMAT_NAME |
6476 DIFF_FORMAT_NAME_STATUS |
6477 DIFF_FORMAT_CHECKDIFF)) {
6478 for (i = 0; i < q->nr; i++) {
6479 struct diff_filepair *p = q->queue[i];
6480 if (check_pair_status(p))
6481 flush_one_pair(p, options);
6483 separator++;
6486 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6487 dirstat_by_line = 1;
6489 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6490 dirstat_by_line) {
6491 struct diffstat_t diffstat;
6493 compute_diffstat(options, &diffstat, q);
6494 if (output_format & DIFF_FORMAT_NUMSTAT)
6495 show_numstat(&diffstat, options);
6496 if (output_format & DIFF_FORMAT_DIFFSTAT)
6497 show_stats(&diffstat, options);
6498 if (output_format & DIFF_FORMAT_SHORTSTAT)
6499 show_shortstats(&diffstat, options);
6500 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6501 show_dirstat_by_line(&diffstat, options);
6502 free_diffstat_info(&diffstat);
6503 separator++;
6505 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6506 show_dirstat(options);
6508 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6509 for (i = 0; i < q->nr; i++) {
6510 diff_summary(options, q->queue[i]);
6512 separator++;
6515 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6516 options->flags.exit_with_status &&
6517 options->flags.diff_from_contents) {
6519 * run diff_flush_patch for the exit status. setting
6520 * options->file to /dev/null should be safe, because we
6521 * aren't supposed to produce any output anyway.
6523 diff_free_file(options);
6524 options->file = xfopen("/dev/null", "w");
6525 options->close_file = 1;
6526 options->color_moved = 0;
6527 for (i = 0; i < q->nr; i++) {
6528 struct diff_filepair *p = q->queue[i];
6529 if (check_pair_status(p))
6530 diff_flush_patch(p, options);
6531 if (options->found_changes)
6532 break;
6536 if (output_format & DIFF_FORMAT_PATCH) {
6537 if (separator) {
6538 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6539 if (options->stat_sep)
6540 /* attach patch instead of inline */
6541 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6542 NULL, 0, 0);
6545 diff_flush_patch_all_file_pairs(options);
6548 if (output_format & DIFF_FORMAT_CALLBACK)
6549 options->format_callback(q, options, options->format_callback_data);
6551 for (i = 0; i < q->nr; i++)
6552 diff_free_filepair(q->queue[i]);
6553 free_queue:
6554 free(q->queue);
6555 DIFF_QUEUE_CLEAR(q);
6556 diff_free(options);
6559 * Report the content-level differences with HAS_CHANGES;
6560 * diff_addremove/diff_change does not set the bit when
6561 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6563 if (options->flags.diff_from_contents) {
6564 if (options->found_changes)
6565 options->flags.has_changes = 1;
6566 else
6567 options->flags.has_changes = 0;
6571 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6573 return (((p->status == DIFF_STATUS_MODIFIED) &&
6574 ((p->score &&
6575 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6576 (!p->score &&
6577 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6578 ((p->status != DIFF_STATUS_MODIFIED) &&
6579 filter_bit_tst(p->status, options)));
6582 static void diffcore_apply_filter(struct diff_options *options)
6584 int i;
6585 struct diff_queue_struct *q = &diff_queued_diff;
6586 struct diff_queue_struct outq;
6588 DIFF_QUEUE_CLEAR(&outq);
6590 if (!options->filter)
6591 return;
6593 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6594 int found;
6595 for (i = found = 0; !found && i < q->nr; i++) {
6596 if (match_filter(options, q->queue[i]))
6597 found++;
6599 if (found)
6600 return;
6602 /* otherwise we will clear the whole queue
6603 * by copying the empty outq at the end of this
6604 * function, but first clear the current entries
6605 * in the queue.
6607 for (i = 0; i < q->nr; i++)
6608 diff_free_filepair(q->queue[i]);
6610 else {
6611 /* Only the matching ones */
6612 for (i = 0; i < q->nr; i++) {
6613 struct diff_filepair *p = q->queue[i];
6614 if (match_filter(options, p))
6615 diff_q(&outq, p);
6616 else
6617 diff_free_filepair(p);
6620 free(q->queue);
6621 *q = outq;
6624 /* Check whether two filespecs with the same mode and size are identical */
6625 static int diff_filespec_is_identical(struct repository *r,
6626 struct diff_filespec *one,
6627 struct diff_filespec *two)
6629 if (S_ISGITLINK(one->mode))
6630 return 0;
6631 if (diff_populate_filespec(r, one, NULL))
6632 return 0;
6633 if (diff_populate_filespec(r, two, NULL))
6634 return 0;
6635 return !memcmp(one->data, two->data, one->size);
6638 static int diff_filespec_check_stat_unmatch(struct repository *r,
6639 struct diff_filepair *p)
6641 struct diff_populate_filespec_options dpf_options = {
6642 .check_size_only = 1,
6643 .missing_object_cb = diff_queued_diff_prefetch,
6644 .missing_object_data = r,
6647 if (p->done_skip_stat_unmatch)
6648 return p->skip_stat_unmatch_result;
6650 p->done_skip_stat_unmatch = 1;
6651 p->skip_stat_unmatch_result = 0;
6653 * 1. Entries that come from stat info dirtiness
6654 * always have both sides (iow, not create/delete),
6655 * one side of the object name is unknown, with
6656 * the same mode and size. Keep the ones that
6657 * do not match these criteria. They have real
6658 * differences.
6660 * 2. At this point, the file is known to be modified,
6661 * with the same mode and size, and the object
6662 * name of one side is unknown. Need to inspect
6663 * the identical contents.
6665 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6666 !DIFF_FILE_VALID(p->two) ||
6667 (p->one->oid_valid && p->two->oid_valid) ||
6668 (p->one->mode != p->two->mode) ||
6669 diff_populate_filespec(r, p->one, &dpf_options) ||
6670 diff_populate_filespec(r, p->two, &dpf_options) ||
6671 (p->one->size != p->two->size) ||
6672 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6673 p->skip_stat_unmatch_result = 1;
6674 return p->skip_stat_unmatch_result;
6677 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6679 int i;
6680 struct diff_queue_struct *q = &diff_queued_diff;
6681 struct diff_queue_struct outq;
6682 DIFF_QUEUE_CLEAR(&outq);
6684 for (i = 0; i < q->nr; i++) {
6685 struct diff_filepair *p = q->queue[i];
6687 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6688 diff_q(&outq, p);
6689 else {
6691 * The caller can subtract 1 from skip_stat_unmatch
6692 * to determine how many paths were dirty only
6693 * due to stat info mismatch.
6695 if (!diffopt->flags.no_index)
6696 diffopt->skip_stat_unmatch++;
6697 diff_free_filepair(p);
6700 free(q->queue);
6701 *q = outq;
6704 static int diffnamecmp(const void *a_, const void *b_)
6706 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6707 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6708 const char *name_a, *name_b;
6710 name_a = a->one ? a->one->path : a->two->path;
6711 name_b = b->one ? b->one->path : b->two->path;
6712 return strcmp(name_a, name_b);
6715 void diffcore_fix_diff_index(void)
6717 struct diff_queue_struct *q = &diff_queued_diff;
6718 QSORT(q->queue, q->nr, diffnamecmp);
6721 void diff_add_if_missing(struct repository *r,
6722 struct oid_array *to_fetch,
6723 const struct diff_filespec *filespec)
6725 if (filespec && filespec->oid_valid &&
6726 !S_ISGITLINK(filespec->mode) &&
6727 oid_object_info_extended(r, &filespec->oid, NULL,
6728 OBJECT_INFO_FOR_PREFETCH))
6729 oid_array_append(to_fetch, &filespec->oid);
6732 void diff_queued_diff_prefetch(void *repository)
6734 struct repository *repo = repository;
6735 int i;
6736 struct diff_queue_struct *q = &diff_queued_diff;
6737 struct oid_array to_fetch = OID_ARRAY_INIT;
6739 for (i = 0; i < q->nr; i++) {
6740 struct diff_filepair *p = q->queue[i];
6741 diff_add_if_missing(repo, &to_fetch, p->one);
6742 diff_add_if_missing(repo, &to_fetch, p->two);
6746 * NEEDSWORK: Consider deduplicating the OIDs sent.
6748 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6750 oid_array_clear(&to_fetch);
6753 void diffcore_std(struct diff_options *options)
6755 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6756 DIFF_FORMAT_NUMSTAT |
6757 DIFF_FORMAT_PATCH |
6758 DIFF_FORMAT_SHORTSTAT |
6759 DIFF_FORMAT_DIRSTAT;
6762 * Check if the user requested a blob-data-requiring diff output and/or
6763 * break-rewrite detection (which requires blob data). If yes, prefetch
6764 * the diff pairs.
6766 * If no prefetching occurs, diffcore_rename() will prefetch if it
6767 * decides that it needs inexact rename detection.
6769 if (options->repo == the_repository && has_promisor_remote() &&
6770 (options->output_format & output_formats_to_prefetch ||
6771 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6772 diff_queued_diff_prefetch(options->repo);
6774 /* NOTE please keep the following in sync with diff_tree_combined() */
6775 if (options->skip_stat_unmatch)
6776 diffcore_skip_stat_unmatch(options);
6777 if (!options->found_follow) {
6778 /* See try_to_follow_renames() in tree-diff.c */
6779 if (options->break_opt != -1)
6780 diffcore_break(options->repo,
6781 options->break_opt);
6782 if (options->detect_rename)
6783 diffcore_rename(options);
6784 if (options->break_opt != -1)
6785 diffcore_merge_broken();
6787 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6788 diffcore_pickaxe(options);
6789 if (options->orderfile)
6790 diffcore_order(options->orderfile);
6791 if (options->rotate_to)
6792 diffcore_rotate(options);
6793 if (!options->found_follow)
6794 /* See try_to_follow_renames() in tree-diff.c */
6795 diff_resolve_rename_copy();
6796 diffcore_apply_filter(options);
6798 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6799 options->flags.has_changes = 1;
6800 else
6801 options->flags.has_changes = 0;
6803 options->found_follow = 0;
6806 int diff_result_code(struct diff_options *opt, int status)
6808 int result = 0;
6810 diff_warn_rename_limit("diff.renameLimit",
6811 opt->needed_rename_limit,
6812 opt->degraded_cc_to_c);
6813 if (!opt->flags.exit_with_status &&
6814 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6815 return status;
6816 if (opt->flags.exit_with_status &&
6817 opt->flags.has_changes)
6818 result |= 01;
6819 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6820 opt->flags.check_failed)
6821 result |= 02;
6822 return result;
6825 int diff_can_quit_early(struct diff_options *opt)
6827 return (opt->flags.quick &&
6828 !opt->filter &&
6829 opt->flags.has_changes);
6833 * Shall changes to this submodule be ignored?
6835 * Submodule changes can be configured to be ignored separately for each path,
6836 * but that configuration can be overridden from the command line.
6838 static int is_submodule_ignored(const char *path, struct diff_options *options)
6840 int ignored = 0;
6841 struct diff_flags orig_flags = options->flags;
6842 if (!options->flags.override_submodule_config)
6843 set_diffopt_flags_from_submodule_config(options, path);
6844 if (options->flags.ignore_submodules)
6845 ignored = 1;
6846 options->flags = orig_flags;
6847 return ignored;
6850 void compute_diffstat(struct diff_options *options,
6851 struct diffstat_t *diffstat,
6852 struct diff_queue_struct *q)
6854 int i;
6856 memset(diffstat, 0, sizeof(struct diffstat_t));
6857 for (i = 0; i < q->nr; i++) {
6858 struct diff_filepair *p = q->queue[i];
6859 if (check_pair_status(p))
6860 diff_flush_stat(p, options, diffstat);
6864 void diff_addremove(struct diff_options *options,
6865 int addremove, unsigned mode,
6866 const struct object_id *oid,
6867 int oid_valid,
6868 const char *concatpath, unsigned dirty_submodule)
6870 struct diff_filespec *one, *two;
6872 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6873 return;
6875 /* This may look odd, but it is a preparation for
6876 * feeding "there are unchanged files which should
6877 * not produce diffs, but when you are doing copy
6878 * detection you would need them, so here they are"
6879 * entries to the diff-core. They will be prefixed
6880 * with something like '=' or '*' (I haven't decided
6881 * which but should not make any difference).
6882 * Feeding the same new and old to diff_change()
6883 * also has the same effect.
6884 * Before the final output happens, they are pruned after
6885 * merged into rename/copy pairs as appropriate.
6887 if (options->flags.reverse_diff)
6888 addremove = (addremove == '+' ? '-' :
6889 addremove == '-' ? '+' : addremove);
6891 if (options->prefix &&
6892 strncmp(concatpath, options->prefix, options->prefix_length))
6893 return;
6895 one = alloc_filespec(concatpath);
6896 two = alloc_filespec(concatpath);
6898 if (addremove != '+')
6899 fill_filespec(one, oid, oid_valid, mode);
6900 if (addremove != '-') {
6901 fill_filespec(two, oid, oid_valid, mode);
6902 two->dirty_submodule = dirty_submodule;
6905 diff_queue(&diff_queued_diff, one, two);
6906 if (!options->flags.diff_from_contents)
6907 options->flags.has_changes = 1;
6910 void diff_change(struct diff_options *options,
6911 unsigned old_mode, unsigned new_mode,
6912 const struct object_id *old_oid,
6913 const struct object_id *new_oid,
6914 int old_oid_valid, int new_oid_valid,
6915 const char *concatpath,
6916 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6918 struct diff_filespec *one, *two;
6919 struct diff_filepair *p;
6921 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6922 is_submodule_ignored(concatpath, options))
6923 return;
6925 if (options->flags.reverse_diff) {
6926 SWAP(old_mode, new_mode);
6927 SWAP(old_oid, new_oid);
6928 SWAP(old_oid_valid, new_oid_valid);
6929 SWAP(old_dirty_submodule, new_dirty_submodule);
6932 if (options->prefix &&
6933 strncmp(concatpath, options->prefix, options->prefix_length))
6934 return;
6936 one = alloc_filespec(concatpath);
6937 two = alloc_filespec(concatpath);
6938 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6939 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6940 one->dirty_submodule = old_dirty_submodule;
6941 two->dirty_submodule = new_dirty_submodule;
6942 p = diff_queue(&diff_queued_diff, one, two);
6944 if (options->flags.diff_from_contents)
6945 return;
6947 if (options->flags.quick && options->skip_stat_unmatch &&
6948 !diff_filespec_check_stat_unmatch(options->repo, p)) {
6949 diff_free_filespec_data(p->one);
6950 diff_free_filespec_data(p->two);
6951 return;
6954 options->flags.has_changes = 1;
6957 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6959 struct diff_filepair *pair;
6960 struct diff_filespec *one, *two;
6962 if (options->prefix &&
6963 strncmp(path, options->prefix, options->prefix_length))
6964 return NULL;
6966 one = alloc_filespec(path);
6967 two = alloc_filespec(path);
6968 pair = diff_queue(&diff_queued_diff, one, two);
6969 pair->is_unmerged = 1;
6970 return pair;
6973 static char *run_textconv(struct repository *r,
6974 const char *pgm,
6975 struct diff_filespec *spec,
6976 size_t *outsize)
6978 struct diff_tempfile *temp;
6979 struct child_process child = CHILD_PROCESS_INIT;
6980 struct strbuf buf = STRBUF_INIT;
6981 int err = 0;
6983 temp = prepare_temp_file(r, spec->path, spec);
6984 strvec_push(&child.args, pgm);
6985 strvec_push(&child.args, temp->name);
6987 child.use_shell = 1;
6988 child.out = -1;
6989 if (start_command(&child)) {
6990 remove_tempfile();
6991 return NULL;
6994 if (strbuf_read(&buf, child.out, 0) < 0)
6995 err = error("error reading from textconv command '%s'", pgm);
6996 close(child.out);
6998 if (finish_command(&child) || err) {
6999 strbuf_release(&buf);
7000 remove_tempfile();
7001 return NULL;
7003 remove_tempfile();
7005 return strbuf_detach(&buf, outsize);
7008 size_t fill_textconv(struct repository *r,
7009 struct userdiff_driver *driver,
7010 struct diff_filespec *df,
7011 char **outbuf)
7013 size_t size;
7015 if (!driver) {
7016 if (!DIFF_FILE_VALID(df)) {
7017 *outbuf = "";
7018 return 0;
7020 if (diff_populate_filespec(r, df, NULL))
7021 die("unable to read files to diff");
7022 *outbuf = df->data;
7023 return df->size;
7026 if (!driver->textconv)
7027 BUG("fill_textconv called with non-textconv driver");
7029 if (driver->textconv_cache && df->oid_valid) {
7030 *outbuf = notes_cache_get(driver->textconv_cache,
7031 &df->oid,
7032 &size);
7033 if (*outbuf)
7034 return size;
7037 *outbuf = run_textconv(r, driver->textconv, df, &size);
7038 if (!*outbuf)
7039 die("unable to read files to diff");
7041 if (driver->textconv_cache && df->oid_valid) {
7042 /* ignore errors, as we might be in a readonly repository */
7043 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
7044 size);
7046 * we could save up changes and flush them all at the end,
7047 * but we would need an extra call after all diffing is done.
7048 * Since generating a cache entry is the slow path anyway,
7049 * this extra overhead probably isn't a big deal.
7051 notes_cache_write(driver->textconv_cache);
7054 return size;
7057 int textconv_object(struct repository *r,
7058 const char *path,
7059 unsigned mode,
7060 const struct object_id *oid,
7061 int oid_valid,
7062 char **buf,
7063 unsigned long *buf_size)
7065 struct diff_filespec *df;
7066 struct userdiff_driver *textconv;
7068 df = alloc_filespec(path);
7069 fill_filespec(df, oid, oid_valid, mode);
7070 textconv = get_textconv(r, df);
7071 if (!textconv) {
7072 free_filespec(df);
7073 return 0;
7076 *buf_size = fill_textconv(r, textconv, df, buf);
7077 free_filespec(df);
7078 return 1;
7081 void setup_diff_pager(struct diff_options *opt)
7084 * If the user asked for our exit code, then either they want --quiet
7085 * or --exit-code. We should definitely not bother with a pager in the
7086 * former case, as we will generate no output. Since we still properly
7087 * report our exit code even when a pager is run, we _could_ run a
7088 * pager with --exit-code. But since we have not done so historically,
7089 * and because it is easy to find people oneline advising "git diff
7090 * --exit-code" in hooks and other scripts, we do not do so.
7092 if (!opt->flags.exit_with_status &&
7093 check_pager_config("diff") != 0)
7094 setup_pager();