Merge branch 'jk/unused'
[git/debian.git] / diff.c
blob2bb2f8f57e8b7ce5a6d861b7a1d598a7fbaf68e9
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 "ll-merge.h"
22 #include "string-list.h"
23 #include "strvec.h"
24 #include "graph.h"
25 #include "packfile.h"
26 #include "parse-options.h"
27 #include "help.h"
28 #include "promisor-remote.h"
30 #ifdef NO_FAST_WORKING_DIRECTORY
31 #define FAST_WORKING_DIRECTORY 0
32 #else
33 #define FAST_WORKING_DIRECTORY 1
34 #endif
36 static int diff_detect_rename_default;
37 static int diff_indent_heuristic = 1;
38 static int diff_rename_limit_default = 400;
39 static int diff_suppress_blank_empty;
40 static int diff_use_color_default = -1;
41 static int diff_color_moved_default;
42 static int diff_color_moved_ws_default;
43 static int diff_context_default = 3;
44 static int diff_interhunk_context_default;
45 static const char *diff_word_regex_cfg;
46 static const char *external_diff_cmd_cfg;
47 static const char *diff_order_file_cfg;
48 int diff_auto_refresh_index = 1;
49 static int diff_mnemonic_prefix;
50 static int diff_no_prefix;
51 static int diff_relative;
52 static int diff_stat_graph_width;
53 static int diff_dirstat_permille_default = 30;
54 static struct diff_options default_diff_options;
55 static long diff_algorithm;
56 static unsigned ws_error_highlight_default = WSEH_NEW;
58 static char diff_colors[][COLOR_MAXLEN] = {
59 GIT_COLOR_RESET,
60 GIT_COLOR_NORMAL, /* CONTEXT */
61 GIT_COLOR_BOLD, /* METAINFO */
62 GIT_COLOR_CYAN, /* FRAGINFO */
63 GIT_COLOR_RED, /* OLD */
64 GIT_COLOR_GREEN, /* NEW */
65 GIT_COLOR_YELLOW, /* COMMIT */
66 GIT_COLOR_BG_RED, /* WHITESPACE */
67 GIT_COLOR_NORMAL, /* FUNCINFO */
68 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
69 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
70 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
71 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
72 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
73 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
74 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
75 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
76 GIT_COLOR_FAINT, /* CONTEXT_DIM */
77 GIT_COLOR_FAINT_RED, /* OLD_DIM */
78 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
79 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
80 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
81 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
84 static const char *color_diff_slots[] = {
85 [DIFF_CONTEXT] = "context",
86 [DIFF_METAINFO] = "meta",
87 [DIFF_FRAGINFO] = "frag",
88 [DIFF_FILE_OLD] = "old",
89 [DIFF_FILE_NEW] = "new",
90 [DIFF_COMMIT] = "commit",
91 [DIFF_WHITESPACE] = "whitespace",
92 [DIFF_FUNCINFO] = "func",
93 [DIFF_FILE_OLD_MOVED] = "oldMoved",
94 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
95 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
96 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
97 [DIFF_FILE_NEW_MOVED] = "newMoved",
98 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
99 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
100 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
101 [DIFF_CONTEXT_DIM] = "contextDimmed",
102 [DIFF_FILE_OLD_DIM] = "oldDimmed",
103 [DIFF_FILE_NEW_DIM] = "newDimmed",
104 [DIFF_CONTEXT_BOLD] = "contextBold",
105 [DIFF_FILE_OLD_BOLD] = "oldBold",
106 [DIFF_FILE_NEW_BOLD] = "newBold",
109 define_list_config_array_extra(color_diff_slots, {"plain"});
111 static int parse_diff_color_slot(const char *var)
113 if (!strcasecmp(var, "plain"))
114 return DIFF_CONTEXT;
115 return LOOKUP_CONFIG(color_diff_slots, var);
118 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
119 struct strbuf *errmsg)
121 char *params_copy = xstrdup(params_string);
122 struct string_list params = STRING_LIST_INIT_NODUP;
123 int ret = 0;
124 int i;
126 if (*params_copy)
127 string_list_split_in_place(&params, params_copy, ',', -1);
128 for (i = 0; i < params.nr; i++) {
129 const char *p = params.items[i].string;
130 if (!strcmp(p, "changes")) {
131 options->flags.dirstat_by_line = 0;
132 options->flags.dirstat_by_file = 0;
133 } else if (!strcmp(p, "lines")) {
134 options->flags.dirstat_by_line = 1;
135 options->flags.dirstat_by_file = 0;
136 } else if (!strcmp(p, "files")) {
137 options->flags.dirstat_by_line = 0;
138 options->flags.dirstat_by_file = 1;
139 } else if (!strcmp(p, "noncumulative")) {
140 options->flags.dirstat_cumulative = 0;
141 } else if (!strcmp(p, "cumulative")) {
142 options->flags.dirstat_cumulative = 1;
143 } else if (isdigit(*p)) {
144 char *end;
145 int permille = strtoul(p, &end, 10) * 10;
146 if (*end == '.' && isdigit(*++end)) {
147 /* only use first digit */
148 permille += *end - '0';
149 /* .. and ignore any further digits */
150 while (isdigit(*++end))
151 ; /* nothing */
153 if (!*end)
154 options->dirstat_permille = permille;
155 else {
156 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
158 ret++;
160 } else {
161 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
162 ret++;
166 string_list_clear(&params, 0);
167 free(params_copy);
168 return ret;
171 static int parse_submodule_params(struct diff_options *options, const char *value)
173 if (!strcmp(value, "log"))
174 options->submodule_format = DIFF_SUBMODULE_LOG;
175 else if (!strcmp(value, "short"))
176 options->submodule_format = DIFF_SUBMODULE_SHORT;
177 else if (!strcmp(value, "diff"))
178 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
180 * Please update $__git_diff_submodule_formats in
181 * git-completion.bash when you add new formats.
183 else
184 return -1;
185 return 0;
188 int git_config_rename(const char *var, const char *value)
190 if (!value)
191 return DIFF_DETECT_RENAME;
192 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
193 return DIFF_DETECT_COPY;
194 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
197 long parse_algorithm_value(const char *value)
199 if (!value)
200 return -1;
201 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
202 return 0;
203 else if (!strcasecmp(value, "minimal"))
204 return XDF_NEED_MINIMAL;
205 else if (!strcasecmp(value, "patience"))
206 return XDF_PATIENCE_DIFF;
207 else if (!strcasecmp(value, "histogram"))
208 return XDF_HISTOGRAM_DIFF;
210 * Please update $__git_diff_algorithms in git-completion.bash
211 * when you add new algorithms.
213 return -1;
216 static int parse_one_token(const char **arg, const char *token)
218 const char *rest;
219 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
220 *arg = rest;
221 return 1;
223 return 0;
226 static int parse_ws_error_highlight(const char *arg)
228 const char *orig_arg = arg;
229 unsigned val = 0;
231 while (*arg) {
232 if (parse_one_token(&arg, "none"))
233 val = 0;
234 else if (parse_one_token(&arg, "default"))
235 val = WSEH_NEW;
236 else if (parse_one_token(&arg, "all"))
237 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
238 else if (parse_one_token(&arg, "new"))
239 val |= WSEH_NEW;
240 else if (parse_one_token(&arg, "old"))
241 val |= WSEH_OLD;
242 else if (parse_one_token(&arg, "context"))
243 val |= WSEH_CONTEXT;
244 else {
245 return -1 - (int)(arg - orig_arg);
247 if (*arg)
248 arg++;
250 return val;
254 * These are to give UI layer defaults.
255 * The core-level commands such as git-diff-files should
256 * never be affected by the setting of diff.renames
257 * the user happens to have in the configuration file.
259 void init_diff_ui_defaults(void)
261 diff_detect_rename_default = DIFF_DETECT_RENAME;
264 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
266 if (!strcmp(var, "diff.indentheuristic"))
267 diff_indent_heuristic = git_config_bool(var, value);
268 return 0;
271 static int parse_color_moved(const char *arg)
273 switch (git_parse_maybe_bool(arg)) {
274 case 0:
275 return COLOR_MOVED_NO;
276 case 1:
277 return COLOR_MOVED_DEFAULT;
278 default:
279 break;
282 if (!strcmp(arg, "no"))
283 return COLOR_MOVED_NO;
284 else if (!strcmp(arg, "plain"))
285 return COLOR_MOVED_PLAIN;
286 else if (!strcmp(arg, "blocks"))
287 return COLOR_MOVED_BLOCKS;
288 else if (!strcmp(arg, "zebra"))
289 return COLOR_MOVED_ZEBRA;
290 else if (!strcmp(arg, "default"))
291 return COLOR_MOVED_DEFAULT;
292 else if (!strcmp(arg, "dimmed-zebra"))
293 return COLOR_MOVED_ZEBRA_DIM;
294 else if (!strcmp(arg, "dimmed_zebra"))
295 return COLOR_MOVED_ZEBRA_DIM;
296 else
297 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
300 static unsigned parse_color_moved_ws(const char *arg)
302 int ret = 0;
303 struct string_list l = STRING_LIST_INIT_DUP;
304 struct string_list_item *i;
306 string_list_split(&l, arg, ',', -1);
308 for_each_string_list_item(i, &l) {
309 struct strbuf sb = STRBUF_INIT;
310 strbuf_addstr(&sb, i->string);
311 strbuf_trim(&sb);
313 if (!strcmp(sb.buf, "no"))
314 ret = 0;
315 else if (!strcmp(sb.buf, "ignore-space-change"))
316 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
317 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
318 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
319 else if (!strcmp(sb.buf, "ignore-all-space"))
320 ret |= XDF_IGNORE_WHITESPACE;
321 else if (!strcmp(sb.buf, "allow-indentation-change"))
322 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
323 else {
324 ret |= COLOR_MOVED_WS_ERROR;
325 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);
328 strbuf_release(&sb);
331 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
332 (ret & XDF_WHITESPACE_FLAGS)) {
333 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
334 ret |= COLOR_MOVED_WS_ERROR;
337 string_list_clear(&l, 0);
339 return ret;
342 int git_diff_ui_config(const char *var, const char *value, void *cb)
344 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
345 diff_use_color_default = git_config_colorbool(var, value);
346 return 0;
348 if (!strcmp(var, "diff.colormoved")) {
349 int cm = parse_color_moved(value);
350 if (cm < 0)
351 return -1;
352 diff_color_moved_default = cm;
353 return 0;
355 if (!strcmp(var, "diff.colormovedws")) {
356 unsigned cm = parse_color_moved_ws(value);
357 if (cm & COLOR_MOVED_WS_ERROR)
358 return -1;
359 diff_color_moved_ws_default = cm;
360 return 0;
362 if (!strcmp(var, "diff.context")) {
363 diff_context_default = git_config_int(var, value);
364 if (diff_context_default < 0)
365 return -1;
366 return 0;
368 if (!strcmp(var, "diff.interhunkcontext")) {
369 diff_interhunk_context_default = git_config_int(var, value);
370 if (diff_interhunk_context_default < 0)
371 return -1;
372 return 0;
374 if (!strcmp(var, "diff.renames")) {
375 diff_detect_rename_default = git_config_rename(var, value);
376 return 0;
378 if (!strcmp(var, "diff.autorefreshindex")) {
379 diff_auto_refresh_index = git_config_bool(var, value);
380 return 0;
382 if (!strcmp(var, "diff.mnemonicprefix")) {
383 diff_mnemonic_prefix = git_config_bool(var, value);
384 return 0;
386 if (!strcmp(var, "diff.noprefix")) {
387 diff_no_prefix = git_config_bool(var, value);
388 return 0;
390 if (!strcmp(var, "diff.relative")) {
391 diff_relative = git_config_bool(var, value);
392 return 0;
394 if (!strcmp(var, "diff.statgraphwidth")) {
395 diff_stat_graph_width = git_config_int(var, value);
396 return 0;
398 if (!strcmp(var, "diff.external"))
399 return git_config_string(&external_diff_cmd_cfg, var, value);
400 if (!strcmp(var, "diff.wordregex"))
401 return git_config_string(&diff_word_regex_cfg, var, value);
402 if (!strcmp(var, "diff.orderfile"))
403 return git_config_pathname(&diff_order_file_cfg, var, value);
405 if (!strcmp(var, "diff.ignoresubmodules"))
406 handle_ignore_submodules_arg(&default_diff_options, value);
408 if (!strcmp(var, "diff.submodule")) {
409 if (parse_submodule_params(&default_diff_options, value))
410 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
411 value);
412 return 0;
415 if (!strcmp(var, "diff.algorithm")) {
416 diff_algorithm = parse_algorithm_value(value);
417 if (diff_algorithm < 0)
418 return -1;
419 return 0;
422 if (git_color_config(var, value, cb) < 0)
423 return -1;
425 return git_diff_basic_config(var, value, cb);
428 int git_diff_basic_config(const char *var, const char *value, void *cb)
430 const char *name;
432 if (!strcmp(var, "diff.renamelimit")) {
433 diff_rename_limit_default = git_config_int(var, value);
434 return 0;
437 if (userdiff_config(var, value) < 0)
438 return -1;
440 if (skip_prefix(var, "diff.color.", &name) ||
441 skip_prefix(var, "color.diff.", &name)) {
442 int slot = parse_diff_color_slot(name);
443 if (slot < 0)
444 return 0;
445 if (!value)
446 return config_error_nonbool(var);
447 return color_parse(value, diff_colors[slot]);
450 if (!strcmp(var, "diff.wserrorhighlight")) {
451 int val = parse_ws_error_highlight(value);
452 if (val < 0)
453 return -1;
454 ws_error_highlight_default = val;
455 return 0;
458 /* like GNU diff's --suppress-blank-empty option */
459 if (!strcmp(var, "diff.suppressblankempty") ||
460 /* for backwards compatibility */
461 !strcmp(var, "diff.suppress-blank-empty")) {
462 diff_suppress_blank_empty = git_config_bool(var, value);
463 return 0;
466 if (!strcmp(var, "diff.dirstat")) {
467 struct strbuf errmsg = STRBUF_INIT;
468 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
469 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
470 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
471 errmsg.buf);
472 strbuf_release(&errmsg);
473 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
474 return 0;
477 if (git_diff_heuristic_config(var, value, cb) < 0)
478 return -1;
480 return git_default_config(var, value, cb);
483 static char *quote_two(const char *one, const char *two)
485 int need_one = quote_c_style(one, NULL, NULL, CQUOTE_NODQ);
486 int need_two = quote_c_style(two, NULL, NULL, CQUOTE_NODQ);
487 struct strbuf res = STRBUF_INIT;
489 if (need_one + need_two) {
490 strbuf_addch(&res, '"');
491 quote_c_style(one, &res, NULL, CQUOTE_NODQ);
492 quote_c_style(two, &res, NULL, CQUOTE_NODQ);
493 strbuf_addch(&res, '"');
494 } else {
495 strbuf_addstr(&res, one);
496 strbuf_addstr(&res, two);
498 return strbuf_detach(&res, NULL);
501 static const char *external_diff(void)
503 static const char *external_diff_cmd = NULL;
504 static int done_preparing = 0;
506 if (done_preparing)
507 return external_diff_cmd;
508 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
509 if (!external_diff_cmd)
510 external_diff_cmd = external_diff_cmd_cfg;
511 done_preparing = 1;
512 return external_diff_cmd;
516 * Keep track of files used for diffing. Sometimes such an entry
517 * refers to a temporary file, sometimes to an existing file, and
518 * sometimes to "/dev/null".
520 static struct diff_tempfile {
522 * filename external diff should read from, or NULL if this
523 * entry is currently not in use:
525 const char *name;
527 char hex[GIT_MAX_HEXSZ + 1];
528 char mode[10];
531 * If this diff_tempfile instance refers to a temporary file,
532 * this tempfile object is used to manage its lifetime.
534 struct tempfile *tempfile;
535 } diff_temp[2];
537 struct emit_callback {
538 int color_diff;
539 unsigned ws_rule;
540 int blank_at_eof_in_preimage;
541 int blank_at_eof_in_postimage;
542 int lno_in_preimage;
543 int lno_in_postimage;
544 const char **label_path;
545 struct diff_words_data *diff_words;
546 struct diff_options *opt;
547 struct strbuf *header;
550 static int count_lines(const char *data, int size)
552 int count, ch, completely_empty = 1, nl_just_seen = 0;
553 count = 0;
554 while (0 < size--) {
555 ch = *data++;
556 if (ch == '\n') {
557 count++;
558 nl_just_seen = 1;
559 completely_empty = 0;
561 else {
562 nl_just_seen = 0;
563 completely_empty = 0;
566 if (completely_empty)
567 return 0;
568 if (!nl_just_seen)
569 count++; /* no trailing newline */
570 return count;
573 static int fill_mmfile(struct repository *r, mmfile_t *mf,
574 struct diff_filespec *one)
576 if (!DIFF_FILE_VALID(one)) {
577 mf->ptr = (char *)""; /* does not matter */
578 mf->size = 0;
579 return 0;
581 else if (diff_populate_filespec(r, one, NULL))
582 return -1;
584 mf->ptr = one->data;
585 mf->size = one->size;
586 return 0;
589 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
590 static unsigned long diff_filespec_size(struct repository *r,
591 struct diff_filespec *one)
593 struct diff_populate_filespec_options dpf_options = {
594 .check_size_only = 1,
597 if (!DIFF_FILE_VALID(one))
598 return 0;
599 diff_populate_filespec(r, one, &dpf_options);
600 return one->size;
603 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
605 char *ptr = mf->ptr;
606 long size = mf->size;
607 int cnt = 0;
609 if (!size)
610 return cnt;
611 ptr += size - 1; /* pointing at the very end */
612 if (*ptr != '\n')
613 ; /* incomplete line */
614 else
615 ptr--; /* skip the last LF */
616 while (mf->ptr < ptr) {
617 char *prev_eol;
618 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
619 if (*prev_eol == '\n')
620 break;
621 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
622 break;
623 cnt++;
624 ptr = prev_eol - 1;
626 return cnt;
629 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
630 struct emit_callback *ecbdata)
632 int l1, l2, at;
633 unsigned ws_rule = ecbdata->ws_rule;
634 l1 = count_trailing_blank(mf1, ws_rule);
635 l2 = count_trailing_blank(mf2, ws_rule);
636 if (l2 <= l1) {
637 ecbdata->blank_at_eof_in_preimage = 0;
638 ecbdata->blank_at_eof_in_postimage = 0;
639 return;
641 at = count_lines(mf1->ptr, mf1->size);
642 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
644 at = count_lines(mf2->ptr, mf2->size);
645 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
648 static void emit_line_0(struct diff_options *o,
649 const char *set_sign, const char *set, unsigned reverse, const char *reset,
650 int first, const char *line, int len)
652 int has_trailing_newline, has_trailing_carriage_return;
653 int needs_reset = 0; /* at the end of the line */
654 FILE *file = o->file;
656 fputs(diff_line_prefix(o), file);
658 has_trailing_newline = (len > 0 && line[len-1] == '\n');
659 if (has_trailing_newline)
660 len--;
662 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
663 if (has_trailing_carriage_return)
664 len--;
666 if (!len && !first)
667 goto end_of_line;
669 if (reverse && want_color(o->use_color)) {
670 fputs(GIT_COLOR_REVERSE, file);
671 needs_reset = 1;
674 if (set_sign) {
675 fputs(set_sign, file);
676 needs_reset = 1;
679 if (first)
680 fputc(first, file);
682 if (!len)
683 goto end_of_line;
685 if (set) {
686 if (set_sign && set != set_sign)
687 fputs(reset, file);
688 fputs(set, file);
689 needs_reset = 1;
691 fwrite(line, len, 1, file);
692 needs_reset = 1; /* 'line' may contain color codes. */
694 end_of_line:
695 if (needs_reset)
696 fputs(reset, file);
697 if (has_trailing_carriage_return)
698 fputc('\r', file);
699 if (has_trailing_newline)
700 fputc('\n', file);
703 static void emit_line(struct diff_options *o, const char *set, const char *reset,
704 const char *line, int len)
706 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
709 enum diff_symbol {
710 DIFF_SYMBOL_BINARY_DIFF_HEADER,
711 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
712 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
713 DIFF_SYMBOL_BINARY_DIFF_BODY,
714 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
715 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
716 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
717 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
718 DIFF_SYMBOL_STATS_LINE,
719 DIFF_SYMBOL_WORD_DIFF,
720 DIFF_SYMBOL_STAT_SEP,
721 DIFF_SYMBOL_SUMMARY,
722 DIFF_SYMBOL_SUBMODULE_ADD,
723 DIFF_SYMBOL_SUBMODULE_DEL,
724 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
725 DIFF_SYMBOL_SUBMODULE_MODIFIED,
726 DIFF_SYMBOL_SUBMODULE_HEADER,
727 DIFF_SYMBOL_SUBMODULE_ERROR,
728 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
729 DIFF_SYMBOL_REWRITE_DIFF,
730 DIFF_SYMBOL_BINARY_FILES,
731 DIFF_SYMBOL_HEADER,
732 DIFF_SYMBOL_FILEPAIR_PLUS,
733 DIFF_SYMBOL_FILEPAIR_MINUS,
734 DIFF_SYMBOL_WORDS_PORCELAIN,
735 DIFF_SYMBOL_WORDS,
736 DIFF_SYMBOL_CONTEXT,
737 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
738 DIFF_SYMBOL_PLUS,
739 DIFF_SYMBOL_MINUS,
740 DIFF_SYMBOL_NO_LF_EOF,
741 DIFF_SYMBOL_CONTEXT_FRAGINFO,
742 DIFF_SYMBOL_CONTEXT_MARKER,
743 DIFF_SYMBOL_SEPARATOR
746 * Flags for content lines:
747 * 0..12 are whitespace rules
748 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
749 * 16 is marking if the line is blank at EOF
751 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
752 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
753 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
754 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
755 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
758 * This struct is used when we need to buffer the output of the diff output.
760 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
761 * into the pre/post image file. This pointer could be a union with the
762 * line pointer. By storing an offset into the file instead of the literal line,
763 * we can decrease the memory footprint for the buffered output. At first we
764 * may want to only have indirection for the content lines, but we could also
765 * enhance the state for emitting prefabricated lines, e.g. the similarity
766 * score line or hunk/file headers would only need to store a number or path
767 * and then the output can be constructed later on depending on state.
769 struct emitted_diff_symbol {
770 const char *line;
771 int len;
772 int flags;
773 int indent_off; /* Offset to first non-whitespace character */
774 int indent_width; /* The visual width of the indentation */
775 enum diff_symbol s;
777 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
779 struct emitted_diff_symbols {
780 struct emitted_diff_symbol *buf;
781 int nr, alloc;
783 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
785 static void append_emitted_diff_symbol(struct diff_options *o,
786 struct emitted_diff_symbol *e)
788 struct emitted_diff_symbol *f;
790 ALLOC_GROW(o->emitted_symbols->buf,
791 o->emitted_symbols->nr + 1,
792 o->emitted_symbols->alloc);
793 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
795 memcpy(f, e, sizeof(struct emitted_diff_symbol));
796 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
799 struct moved_entry {
800 struct hashmap_entry ent;
801 const struct emitted_diff_symbol *es;
802 struct moved_entry *next_line;
805 struct moved_block {
806 struct moved_entry *match;
807 int wsd; /* The whitespace delta of this block */
810 static void moved_block_clear(struct moved_block *b)
812 memset(b, 0, sizeof(*b));
815 #define INDENT_BLANKLINE INT_MIN
817 static void fill_es_indent_data(struct emitted_diff_symbol *es)
819 unsigned int off = 0, i;
820 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
821 const char *s = es->line;
822 const int len = es->len;
824 /* skip any \v \f \r at start of indentation */
825 while (s[off] == '\f' || s[off] == '\v' ||
826 (s[off] == '\r' && off < len - 1))
827 off++;
829 /* calculate the visual width of indentation */
830 while(1) {
831 if (s[off] == ' ') {
832 width++;
833 off++;
834 } else if (s[off] == '\t') {
835 width += tab_width - (width % tab_width);
836 while (s[++off] == '\t')
837 width += tab_width;
838 } else {
839 break;
843 /* check if this line is blank */
844 for (i = off; i < len; i++)
845 if (!isspace(s[i]))
846 break;
848 if (i == len) {
849 es->indent_width = INDENT_BLANKLINE;
850 es->indent_off = len;
851 } else {
852 es->indent_off = off;
853 es->indent_width = width;
857 static int compute_ws_delta(const struct emitted_diff_symbol *a,
858 const struct emitted_diff_symbol *b,
859 int *out)
861 int a_len = a->len,
862 b_len = b->len,
863 a_off = a->indent_off,
864 a_width = a->indent_width,
865 b_off = b->indent_off,
866 b_width = b->indent_width;
867 int delta;
869 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE) {
870 *out = INDENT_BLANKLINE;
871 return 1;
874 if (a->s == DIFF_SYMBOL_PLUS)
875 delta = a_width - b_width;
876 else
877 delta = b_width - a_width;
879 if (a_len - a_off != b_len - b_off ||
880 memcmp(a->line + a_off, b->line + b_off, a_len - a_off))
881 return 0;
883 *out = delta;
885 return 1;
888 static int cmp_in_block_with_wsd(const struct diff_options *o,
889 const struct moved_entry *cur,
890 const struct moved_entry *match,
891 struct moved_block *pmb,
892 int n)
894 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
895 int al = cur->es->len, bl = match->es->len, cl = l->len;
896 const char *a = cur->es->line,
897 *b = match->es->line,
898 *c = l->line;
899 int a_off = cur->es->indent_off,
900 a_width = cur->es->indent_width,
901 c_off = l->indent_off,
902 c_width = l->indent_width;
903 int delta;
906 * We need to check if 'cur' is equal to 'match'. As those
907 * are from the same (+/-) side, we do not need to adjust for
908 * indent changes. However these were found using fuzzy
909 * matching so we do have to check if they are equal. Here we
910 * just check the lengths. We delay calling memcmp() to check
911 * the contents until later as if the length comparison for a
912 * and c fails we can avoid the call all together.
914 if (al != bl)
915 return 1;
917 /* If 'l' and 'cur' are both blank then they match. */
918 if (a_width == INDENT_BLANKLINE && c_width == INDENT_BLANKLINE)
919 return 0;
922 * The indent changes of the block are known and stored in pmb->wsd;
923 * however we need to check if the indent changes of the current line
924 * match those of the current block and that the text of 'l' and 'cur'
925 * after the indentation match.
927 if (cur->es->s == DIFF_SYMBOL_PLUS)
928 delta = a_width - c_width;
929 else
930 delta = c_width - a_width;
933 * If the previous lines of this block were all blank then set its
934 * whitespace delta.
936 if (pmb->wsd == INDENT_BLANKLINE)
937 pmb->wsd = delta;
939 return !(delta == pmb->wsd && al - a_off == cl - c_off &&
940 !memcmp(a, b, al) && !
941 memcmp(a + a_off, c + c_off, al - a_off));
944 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
945 const struct hashmap_entry *eptr,
946 const struct hashmap_entry *entry_or_key,
947 const void *keydata)
949 const struct diff_options *diffopt = hashmap_cmp_fn_data;
950 const struct moved_entry *a, *b;
951 unsigned flags = diffopt->color_moved_ws_handling
952 & XDF_WHITESPACE_FLAGS;
954 a = container_of(eptr, const struct moved_entry, ent);
955 b = container_of(entry_or_key, const struct moved_entry, ent);
957 if (diffopt->color_moved_ws_handling &
958 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
960 * As there is not specific white space config given,
961 * we'd need to check for a new block, so ignore all
962 * white space. The setup of the white space
963 * configuration for the next block is done else where
965 flags |= XDF_IGNORE_WHITESPACE;
967 return !xdiff_compare_lines(a->es->line, a->es->len,
968 b->es->line, b->es->len,
969 flags);
972 static struct moved_entry *prepare_entry(struct diff_options *o,
973 int line_no)
975 struct moved_entry *ret = xmalloc(sizeof(*ret));
976 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
977 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
978 unsigned int hash = xdiff_hash_string(l->line, l->len, flags);
980 hashmap_entry_init(&ret->ent, hash);
981 ret->es = l;
982 ret->next_line = NULL;
984 return ret;
987 static void add_lines_to_move_detection(struct diff_options *o,
988 struct hashmap *add_lines,
989 struct hashmap *del_lines)
991 struct moved_entry *prev_line = NULL;
993 int n;
994 for (n = 0; n < o->emitted_symbols->nr; n++) {
995 struct hashmap *hm;
996 struct moved_entry *key;
998 switch (o->emitted_symbols->buf[n].s) {
999 case DIFF_SYMBOL_PLUS:
1000 hm = add_lines;
1001 break;
1002 case DIFF_SYMBOL_MINUS:
1003 hm = del_lines;
1004 break;
1005 default:
1006 prev_line = NULL;
1007 continue;
1010 if (o->color_moved_ws_handling &
1011 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1012 fill_es_indent_data(&o->emitted_symbols->buf[n]);
1013 key = prepare_entry(o, n);
1014 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
1015 prev_line->next_line = key;
1017 hashmap_add(hm, &key->ent);
1018 prev_line = key;
1022 static void pmb_advance_or_null(struct diff_options *o,
1023 struct moved_entry *match,
1024 struct hashmap *hm,
1025 struct moved_block *pmb,
1026 int pmb_nr)
1028 int i;
1029 for (i = 0; i < pmb_nr; i++) {
1030 struct moved_entry *prev = pmb[i].match;
1031 struct moved_entry *cur = (prev && prev->next_line) ?
1032 prev->next_line : NULL;
1033 if (cur && !hm->cmpfn(o, &cur->ent, &match->ent, NULL)) {
1034 pmb[i].match = cur;
1035 } else {
1036 pmb[i].match = NULL;
1041 static void pmb_advance_or_null_multi_match(struct diff_options *o,
1042 struct moved_entry *match,
1043 struct hashmap *hm,
1044 struct moved_block *pmb,
1045 int pmb_nr, int n)
1047 int i;
1048 char *got_match = xcalloc(1, pmb_nr);
1050 hashmap_for_each_entry_from(hm, match, ent) {
1051 for (i = 0; i < pmb_nr; i++) {
1052 struct moved_entry *prev = pmb[i].match;
1053 struct moved_entry *cur = (prev && prev->next_line) ?
1054 prev->next_line : NULL;
1055 if (!cur)
1056 continue;
1057 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
1058 got_match[i] |= 1;
1062 for (i = 0; i < pmb_nr; i++) {
1063 if (got_match[i]) {
1064 /* Advance to the next line */
1065 pmb[i].match = pmb[i].match->next_line;
1066 } else {
1067 moved_block_clear(&pmb[i]);
1071 free(got_match);
1074 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1075 int pmb_nr)
1077 int lp, rp;
1079 /* Shrink the set of potential block to the remaining running */
1080 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1081 while (lp < pmb_nr && pmb[lp].match)
1082 lp++;
1083 /* lp points at the first NULL now */
1085 while (rp > -1 && !pmb[rp].match)
1086 rp--;
1087 /* rp points at the last non-NULL */
1089 if (lp < pmb_nr && rp > -1 && lp < rp) {
1090 pmb[lp] = pmb[rp];
1091 memset(&pmb[rp], 0, sizeof(pmb[rp]));
1092 rp--;
1093 lp++;
1097 /* Remember the number of running sets */
1098 return rp + 1;
1102 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1104 * Otherwise, if the last block has fewer alphanumeric characters than
1105 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1106 * that block.
1108 * The last block consists of the (n - block_length)'th line up to but not
1109 * including the nth line.
1111 * Returns 0 if the last block is empty or is unset by this function, non zero
1112 * otherwise.
1114 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1115 * Think of a way to unify them.
1117 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1119 int i, alnum_count = 0;
1120 if (o->color_moved == COLOR_MOVED_PLAIN)
1121 return block_length;
1122 for (i = 1; i < block_length + 1; i++) {
1123 const char *c = o->emitted_symbols->buf[n - i].line;
1124 for (; *c; c++) {
1125 if (!isalnum(*c))
1126 continue;
1127 alnum_count++;
1128 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1129 return 1;
1132 for (i = 1; i < block_length + 1; i++)
1133 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1134 return 0;
1137 /* Find blocks of moved code, delegate actual coloring decision to helper */
1138 static void mark_color_as_moved(struct diff_options *o,
1139 struct hashmap *add_lines,
1140 struct hashmap *del_lines)
1142 struct moved_block *pmb = NULL; /* potentially moved blocks */
1143 int pmb_nr = 0, pmb_alloc = 0;
1144 int n, flipped_block = 0, block_length = 0;
1147 for (n = 0; n < o->emitted_symbols->nr; n++) {
1148 struct hashmap *hm = NULL;
1149 struct moved_entry *key;
1150 struct moved_entry *match = NULL;
1151 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1152 enum diff_symbol last_symbol = 0;
1154 switch (l->s) {
1155 case DIFF_SYMBOL_PLUS:
1156 hm = del_lines;
1157 key = prepare_entry(o, n);
1158 match = hashmap_get_entry(hm, key, ent, NULL);
1159 free(key);
1160 break;
1161 case DIFF_SYMBOL_MINUS:
1162 hm = add_lines;
1163 key = prepare_entry(o, n);
1164 match = hashmap_get_entry(hm, key, ent, NULL);
1165 free(key);
1166 break;
1167 default:
1168 flipped_block = 0;
1171 if (!match) {
1172 int i;
1174 adjust_last_block(o, n, block_length);
1175 for(i = 0; i < pmb_nr; i++)
1176 moved_block_clear(&pmb[i]);
1177 pmb_nr = 0;
1178 block_length = 0;
1179 flipped_block = 0;
1180 last_symbol = l->s;
1181 continue;
1184 if (o->color_moved == COLOR_MOVED_PLAIN) {
1185 last_symbol = l->s;
1186 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1187 continue;
1190 if (o->color_moved_ws_handling &
1191 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1192 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1193 else
1194 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1196 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1198 if (pmb_nr == 0) {
1200 * The current line is the start of a new block.
1201 * Setup the set of potential blocks.
1203 hashmap_for_each_entry_from(hm, match, ent) {
1204 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1205 if (o->color_moved_ws_handling &
1206 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1207 if (compute_ws_delta(l, match->es,
1208 &pmb[pmb_nr].wsd))
1209 pmb[pmb_nr++].match = match;
1210 } else {
1211 pmb[pmb_nr].wsd = 0;
1212 pmb[pmb_nr++].match = match;
1216 if (adjust_last_block(o, n, block_length) &&
1217 pmb_nr && last_symbol != l->s)
1218 flipped_block = (flipped_block + 1) % 2;
1219 else
1220 flipped_block = 0;
1222 block_length = 0;
1225 if (pmb_nr) {
1226 block_length++;
1227 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1228 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1229 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1231 last_symbol = l->s;
1233 adjust_last_block(o, n, block_length);
1235 for(n = 0; n < pmb_nr; n++)
1236 moved_block_clear(&pmb[n]);
1237 free(pmb);
1240 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1241 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1242 static void dim_moved_lines(struct diff_options *o)
1244 int n;
1245 for (n = 0; n < o->emitted_symbols->nr; n++) {
1246 struct emitted_diff_symbol *prev = (n != 0) ?
1247 &o->emitted_symbols->buf[n - 1] : NULL;
1248 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1249 struct emitted_diff_symbol *next =
1250 (n < o->emitted_symbols->nr - 1) ?
1251 &o->emitted_symbols->buf[n + 1] : NULL;
1253 /* Not a plus or minus line? */
1254 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1255 continue;
1257 /* Not a moved line? */
1258 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1259 continue;
1262 * If prev or next are not a plus or minus line,
1263 * pretend they don't exist
1265 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1266 prev->s != DIFF_SYMBOL_MINUS)
1267 prev = NULL;
1268 if (next && next->s != DIFF_SYMBOL_PLUS &&
1269 next->s != DIFF_SYMBOL_MINUS)
1270 next = NULL;
1272 /* Inside a block? */
1273 if ((prev &&
1274 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1275 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1276 (next &&
1277 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1278 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1279 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1280 continue;
1283 /* Check if we are at an interesting bound: */
1284 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1285 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1286 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1287 continue;
1288 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1289 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1290 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1291 continue;
1294 * The boundary to prev and next are not interesting,
1295 * so this line is not interesting as a whole
1297 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1301 static void emit_line_ws_markup(struct diff_options *o,
1302 const char *set_sign, const char *set,
1303 const char *reset,
1304 int sign_index, const char *line, int len,
1305 unsigned ws_rule, int blank_at_eof)
1307 const char *ws = NULL;
1308 int sign = o->output_indicators[sign_index];
1310 if (o->ws_error_highlight & ws_rule) {
1311 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1312 if (!*ws)
1313 ws = NULL;
1316 if (!ws && !set_sign)
1317 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1318 else if (!ws) {
1319 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1320 } else if (blank_at_eof)
1321 /* Blank line at EOF - paint '+' as well */
1322 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1323 else {
1324 /* Emit just the prefix, then the rest. */
1325 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1326 sign, "", 0);
1327 ws_check_emit(line, len, ws_rule,
1328 o->file, set, reset, ws);
1332 static void emit_diff_symbol_from_struct(struct diff_options *o,
1333 struct emitted_diff_symbol *eds)
1335 static const char *nneof = " No newline at end of file\n";
1336 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1337 struct strbuf sb = STRBUF_INIT;
1339 enum diff_symbol s = eds->s;
1340 const char *line = eds->line;
1341 int len = eds->len;
1342 unsigned flags = eds->flags;
1344 switch (s) {
1345 case DIFF_SYMBOL_NO_LF_EOF:
1346 context = diff_get_color_opt(o, DIFF_CONTEXT);
1347 reset = diff_get_color_opt(o, DIFF_RESET);
1348 putc('\n', o->file);
1349 emit_line_0(o, context, NULL, 0, reset, '\\',
1350 nneof, strlen(nneof));
1351 break;
1352 case DIFF_SYMBOL_SUBMODULE_HEADER:
1353 case DIFF_SYMBOL_SUBMODULE_ERROR:
1354 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1355 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1356 case DIFF_SYMBOL_SUMMARY:
1357 case DIFF_SYMBOL_STATS_LINE:
1358 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1359 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1360 emit_line(o, "", "", line, len);
1361 break;
1362 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1363 case DIFF_SYMBOL_CONTEXT_MARKER:
1364 context = diff_get_color_opt(o, DIFF_CONTEXT);
1365 reset = diff_get_color_opt(o, DIFF_RESET);
1366 emit_line(o, context, reset, line, len);
1367 break;
1368 case DIFF_SYMBOL_SEPARATOR:
1369 fprintf(o->file, "%s%c",
1370 diff_line_prefix(o),
1371 o->line_termination);
1372 break;
1373 case DIFF_SYMBOL_CONTEXT:
1374 set = diff_get_color_opt(o, DIFF_CONTEXT);
1375 reset = diff_get_color_opt(o, DIFF_RESET);
1376 set_sign = NULL;
1377 if (o->flags.dual_color_diffed_diffs) {
1378 char c = !len ? 0 : line[0];
1380 if (c == '+')
1381 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1382 else if (c == '@')
1383 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1384 else if (c == '-')
1385 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1387 emit_line_ws_markup(o, set_sign, set, reset,
1388 OUTPUT_INDICATOR_CONTEXT, line, len,
1389 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1390 break;
1391 case DIFF_SYMBOL_PLUS:
1392 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1393 DIFF_SYMBOL_MOVED_LINE_ALT |
1394 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1395 case DIFF_SYMBOL_MOVED_LINE |
1396 DIFF_SYMBOL_MOVED_LINE_ALT |
1397 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1398 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1399 break;
1400 case DIFF_SYMBOL_MOVED_LINE |
1401 DIFF_SYMBOL_MOVED_LINE_ALT:
1402 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1403 break;
1404 case DIFF_SYMBOL_MOVED_LINE |
1405 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1406 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1407 break;
1408 case DIFF_SYMBOL_MOVED_LINE:
1409 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1410 break;
1411 default:
1412 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1414 reset = diff_get_color_opt(o, DIFF_RESET);
1415 if (!o->flags.dual_color_diffed_diffs)
1416 set_sign = NULL;
1417 else {
1418 char c = !len ? 0 : line[0];
1420 set_sign = set;
1421 if (c == '-')
1422 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1423 else if (c == '@')
1424 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1425 else if (c == '+')
1426 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1427 else
1428 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1429 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1431 emit_line_ws_markup(o, set_sign, set, reset,
1432 OUTPUT_INDICATOR_NEW, line, len,
1433 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1434 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1435 break;
1436 case DIFF_SYMBOL_MINUS:
1437 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1438 DIFF_SYMBOL_MOVED_LINE_ALT |
1439 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1440 case DIFF_SYMBOL_MOVED_LINE |
1441 DIFF_SYMBOL_MOVED_LINE_ALT |
1442 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1443 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1444 break;
1445 case DIFF_SYMBOL_MOVED_LINE |
1446 DIFF_SYMBOL_MOVED_LINE_ALT:
1447 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1448 break;
1449 case DIFF_SYMBOL_MOVED_LINE |
1450 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1451 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1452 break;
1453 case DIFF_SYMBOL_MOVED_LINE:
1454 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1455 break;
1456 default:
1457 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1459 reset = diff_get_color_opt(o, DIFF_RESET);
1460 if (!o->flags.dual_color_diffed_diffs)
1461 set_sign = NULL;
1462 else {
1463 char c = !len ? 0 : line[0];
1465 set_sign = set;
1466 if (c == '+')
1467 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1468 else if (c == '@')
1469 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1470 else if (c == '-')
1471 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1472 else
1473 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1475 emit_line_ws_markup(o, set_sign, set, reset,
1476 OUTPUT_INDICATOR_OLD, line, len,
1477 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1478 break;
1479 case DIFF_SYMBOL_WORDS_PORCELAIN:
1480 context = diff_get_color_opt(o, DIFF_CONTEXT);
1481 reset = diff_get_color_opt(o, DIFF_RESET);
1482 emit_line(o, context, reset, line, len);
1483 fputs("~\n", o->file);
1484 break;
1485 case DIFF_SYMBOL_WORDS:
1486 context = diff_get_color_opt(o, DIFF_CONTEXT);
1487 reset = diff_get_color_opt(o, DIFF_RESET);
1489 * Skip the prefix character, if any. With
1490 * diff_suppress_blank_empty, there may be
1491 * none.
1493 if (line[0] != '\n') {
1494 line++;
1495 len--;
1497 emit_line(o, context, reset, line, len);
1498 break;
1499 case DIFF_SYMBOL_FILEPAIR_PLUS:
1500 meta = diff_get_color_opt(o, DIFF_METAINFO);
1501 reset = diff_get_color_opt(o, DIFF_RESET);
1502 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1503 line, reset,
1504 strchr(line, ' ') ? "\t" : "");
1505 break;
1506 case DIFF_SYMBOL_FILEPAIR_MINUS:
1507 meta = diff_get_color_opt(o, DIFF_METAINFO);
1508 reset = diff_get_color_opt(o, DIFF_RESET);
1509 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1510 line, reset,
1511 strchr(line, ' ') ? "\t" : "");
1512 break;
1513 case DIFF_SYMBOL_BINARY_FILES:
1514 case DIFF_SYMBOL_HEADER:
1515 fprintf(o->file, "%s", line);
1516 break;
1517 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1518 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1519 break;
1520 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1521 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1522 break;
1523 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1524 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1525 break;
1526 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1527 fputs(diff_line_prefix(o), o->file);
1528 fputc('\n', o->file);
1529 break;
1530 case DIFF_SYMBOL_REWRITE_DIFF:
1531 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1532 reset = diff_get_color_opt(o, DIFF_RESET);
1533 emit_line(o, fraginfo, reset, line, len);
1534 break;
1535 case DIFF_SYMBOL_SUBMODULE_ADD:
1536 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1537 reset = diff_get_color_opt(o, DIFF_RESET);
1538 emit_line(o, set, reset, line, len);
1539 break;
1540 case DIFF_SYMBOL_SUBMODULE_DEL:
1541 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1542 reset = diff_get_color_opt(o, DIFF_RESET);
1543 emit_line(o, set, reset, line, len);
1544 break;
1545 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1546 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1547 diff_line_prefix(o), line);
1548 break;
1549 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1550 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1551 diff_line_prefix(o), line);
1552 break;
1553 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1554 emit_line(o, "", "", " 0 files changed\n",
1555 strlen(" 0 files changed\n"));
1556 break;
1557 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1558 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1559 break;
1560 case DIFF_SYMBOL_WORD_DIFF:
1561 fprintf(o->file, "%.*s", len, line);
1562 break;
1563 case DIFF_SYMBOL_STAT_SEP:
1564 fputs(o->stat_sep, o->file);
1565 break;
1566 default:
1567 BUG("unknown diff symbol");
1569 strbuf_release(&sb);
1572 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1573 const char *line, int len, unsigned flags)
1575 struct emitted_diff_symbol e = {line, len, flags, 0, 0, s};
1577 if (o->emitted_symbols)
1578 append_emitted_diff_symbol(o, &e);
1579 else
1580 emit_diff_symbol_from_struct(o, &e);
1583 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1585 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1588 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1590 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1593 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1595 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1596 path, strlen(path), 0);
1599 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1601 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1602 path, strlen(path), 0);
1605 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1607 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1608 header, strlen(header), 0);
1611 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1613 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1616 void diff_emit_submodule_pipethrough(struct diff_options *o,
1617 const char *line, int len)
1619 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1622 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1624 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1625 ecbdata->blank_at_eof_in_preimage &&
1626 ecbdata->blank_at_eof_in_postimage &&
1627 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1628 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1629 return 0;
1630 return ws_blank_line(line, len, ecbdata->ws_rule);
1633 static void emit_add_line(struct emit_callback *ecbdata,
1634 const char *line, int len)
1636 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1637 if (new_blank_line_at_eof(ecbdata, line, len))
1638 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1640 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1643 static void emit_del_line(struct emit_callback *ecbdata,
1644 const char *line, int len)
1646 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1647 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1650 static void emit_context_line(struct emit_callback *ecbdata,
1651 const char *line, int len)
1653 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1654 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1657 static void emit_hunk_header(struct emit_callback *ecbdata,
1658 const char *line, int len)
1660 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1661 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1662 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1663 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1664 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1665 static const char atat[2] = { '@', '@' };
1666 const char *cp, *ep;
1667 struct strbuf msgbuf = STRBUF_INIT;
1668 int org_len = len;
1669 int i = 1;
1672 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1673 * it always is at least 10 bytes long.
1675 if (len < 10 ||
1676 memcmp(line, atat, 2) ||
1677 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1678 emit_diff_symbol(ecbdata->opt,
1679 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1680 return;
1682 ep += 2; /* skip over @@ */
1684 /* The hunk header in fraginfo color */
1685 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1686 strbuf_addstr(&msgbuf, reverse);
1687 strbuf_addstr(&msgbuf, frag);
1688 if (ecbdata->opt->flags.suppress_hunk_header_line_count)
1689 strbuf_add(&msgbuf, atat, sizeof(atat));
1690 else
1691 strbuf_add(&msgbuf, line, ep - line);
1692 strbuf_addstr(&msgbuf, reset);
1695 * trailing "\r\n"
1697 for ( ; i < 3; i++)
1698 if (line[len - i] == '\r' || line[len - i] == '\n')
1699 len--;
1701 /* blank before the func header */
1702 for (cp = ep; ep - line < len; ep++)
1703 if (*ep != ' ' && *ep != '\t')
1704 break;
1705 if (ep != cp) {
1706 strbuf_addstr(&msgbuf, context);
1707 strbuf_add(&msgbuf, cp, ep - cp);
1708 strbuf_addstr(&msgbuf, reset);
1711 if (ep < line + len) {
1712 strbuf_addstr(&msgbuf, func);
1713 strbuf_add(&msgbuf, ep, line + len - ep);
1714 strbuf_addstr(&msgbuf, reset);
1717 strbuf_add(&msgbuf, line + len, org_len - len);
1718 strbuf_complete_line(&msgbuf);
1719 emit_diff_symbol(ecbdata->opt,
1720 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1721 strbuf_release(&msgbuf);
1724 static struct diff_tempfile *claim_diff_tempfile(void)
1726 int i;
1727 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1728 if (!diff_temp[i].name)
1729 return diff_temp + i;
1730 BUG("diff is failing to clean up its tempfiles");
1733 static void remove_tempfile(void)
1735 int i;
1736 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1737 if (is_tempfile_active(diff_temp[i].tempfile))
1738 delete_tempfile(&diff_temp[i].tempfile);
1739 diff_temp[i].name = NULL;
1743 static void add_line_count(struct strbuf *out, int count)
1745 switch (count) {
1746 case 0:
1747 strbuf_addstr(out, "0,0");
1748 break;
1749 case 1:
1750 strbuf_addstr(out, "1");
1751 break;
1752 default:
1753 strbuf_addf(out, "1,%d", count);
1754 break;
1758 static void emit_rewrite_lines(struct emit_callback *ecb,
1759 int prefix, const char *data, int size)
1761 const char *endp = NULL;
1763 while (0 < size) {
1764 int len;
1766 endp = memchr(data, '\n', size);
1767 len = endp ? (endp - data + 1) : size;
1768 if (prefix != '+') {
1769 ecb->lno_in_preimage++;
1770 emit_del_line(ecb, data, len);
1771 } else {
1772 ecb->lno_in_postimage++;
1773 emit_add_line(ecb, data, len);
1775 size -= len;
1776 data += len;
1778 if (!endp)
1779 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1782 static void emit_rewrite_diff(const char *name_a,
1783 const char *name_b,
1784 struct diff_filespec *one,
1785 struct diff_filespec *two,
1786 struct userdiff_driver *textconv_one,
1787 struct userdiff_driver *textconv_two,
1788 struct diff_options *o)
1790 int lc_a, lc_b;
1791 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1792 const char *a_prefix, *b_prefix;
1793 char *data_one, *data_two;
1794 size_t size_one, size_two;
1795 struct emit_callback ecbdata;
1796 struct strbuf out = STRBUF_INIT;
1798 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1799 a_prefix = o->b_prefix;
1800 b_prefix = o->a_prefix;
1801 } else {
1802 a_prefix = o->a_prefix;
1803 b_prefix = o->b_prefix;
1806 name_a += (*name_a == '/');
1807 name_b += (*name_b == '/');
1809 strbuf_reset(&a_name);
1810 strbuf_reset(&b_name);
1811 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1812 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1814 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1815 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1817 memset(&ecbdata, 0, sizeof(ecbdata));
1818 ecbdata.color_diff = want_color(o->use_color);
1819 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1820 ecbdata.opt = o;
1821 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1822 mmfile_t mf1, mf2;
1823 mf1.ptr = (char *)data_one;
1824 mf2.ptr = (char *)data_two;
1825 mf1.size = size_one;
1826 mf2.size = size_two;
1827 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1829 ecbdata.lno_in_preimage = 1;
1830 ecbdata.lno_in_postimage = 1;
1832 lc_a = count_lines(data_one, size_one);
1833 lc_b = count_lines(data_two, size_two);
1835 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1836 a_name.buf, a_name.len, 0);
1837 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1838 b_name.buf, b_name.len, 0);
1840 strbuf_addstr(&out, "@@ -");
1841 if (!o->irreversible_delete)
1842 add_line_count(&out, lc_a);
1843 else
1844 strbuf_addstr(&out, "?,?");
1845 strbuf_addstr(&out, " +");
1846 add_line_count(&out, lc_b);
1847 strbuf_addstr(&out, " @@\n");
1848 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1849 strbuf_release(&out);
1851 if (lc_a && !o->irreversible_delete)
1852 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1853 if (lc_b)
1854 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1855 if (textconv_one)
1856 free((char *)data_one);
1857 if (textconv_two)
1858 free((char *)data_two);
1861 struct diff_words_buffer {
1862 mmfile_t text;
1863 unsigned long alloc;
1864 struct diff_words_orig {
1865 const char *begin, *end;
1866 } *orig;
1867 int orig_nr, orig_alloc;
1870 static void diff_words_append(char *line, unsigned long len,
1871 struct diff_words_buffer *buffer)
1873 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1874 line++;
1875 len--;
1876 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1877 buffer->text.size += len;
1878 buffer->text.ptr[buffer->text.size] = '\0';
1881 struct diff_words_style_elem {
1882 const char *prefix;
1883 const char *suffix;
1884 const char *color; /* NULL; filled in by the setup code if
1885 * color is enabled */
1888 struct diff_words_style {
1889 enum diff_words_type type;
1890 struct diff_words_style_elem new_word, old_word, ctx;
1891 const char *newline;
1894 static struct diff_words_style diff_words_styles[] = {
1895 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1896 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1897 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1900 struct diff_words_data {
1901 struct diff_words_buffer minus, plus;
1902 const char *current_plus;
1903 int last_minus;
1904 struct diff_options *opt;
1905 regex_t *word_regex;
1906 enum diff_words_type type;
1907 struct diff_words_style *style;
1910 static int fn_out_diff_words_write_helper(struct diff_options *o,
1911 struct diff_words_style_elem *st_el,
1912 const char *newline,
1913 size_t count, const char *buf)
1915 int print = 0;
1916 struct strbuf sb = STRBUF_INIT;
1918 while (count) {
1919 char *p = memchr(buf, '\n', count);
1920 if (print)
1921 strbuf_addstr(&sb, diff_line_prefix(o));
1923 if (p != buf) {
1924 const char *reset = st_el->color && *st_el->color ?
1925 GIT_COLOR_RESET : NULL;
1926 if (st_el->color && *st_el->color)
1927 strbuf_addstr(&sb, st_el->color);
1928 strbuf_addstr(&sb, st_el->prefix);
1929 strbuf_add(&sb, buf, p ? p - buf : count);
1930 strbuf_addstr(&sb, st_el->suffix);
1931 if (reset)
1932 strbuf_addstr(&sb, reset);
1934 if (!p)
1935 goto out;
1937 strbuf_addstr(&sb, newline);
1938 count -= p + 1 - buf;
1939 buf = p + 1;
1940 print = 1;
1941 if (count) {
1942 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1943 sb.buf, sb.len, 0);
1944 strbuf_reset(&sb);
1948 out:
1949 if (sb.len)
1950 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1951 sb.buf, sb.len, 0);
1952 strbuf_release(&sb);
1953 return 0;
1957 * '--color-words' algorithm can be described as:
1959 * 1. collect the minus/plus lines of a diff hunk, divided into
1960 * minus-lines and plus-lines;
1962 * 2. break both minus-lines and plus-lines into words and
1963 * place them into two mmfile_t with one word for each line;
1965 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1967 * And for the common parts of the both file, we output the plus side text.
1968 * diff_words->current_plus is used to trace the current position of the plus file
1969 * which printed. diff_words->last_minus is used to trace the last minus word
1970 * printed.
1972 * For '--graph' to work with '--color-words', we need to output the graph prefix
1973 * on each line of color words output. Generally, there are two conditions on
1974 * which we should output the prefix.
1976 * 1. diff_words->last_minus == 0 &&
1977 * diff_words->current_plus == diff_words->plus.text.ptr
1979 * that is: the plus text must start as a new line, and if there is no minus
1980 * word printed, a graph prefix must be printed.
1982 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1983 * *(diff_words->current_plus - 1) == '\n'
1985 * that is: a graph prefix must be printed following a '\n'
1987 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1989 if ((diff_words->last_minus == 0 &&
1990 diff_words->current_plus == diff_words->plus.text.ptr) ||
1991 (diff_words->current_plus > diff_words->plus.text.ptr &&
1992 *(diff_words->current_plus - 1) == '\n')) {
1993 return 1;
1994 } else {
1995 return 0;
1999 static void fn_out_diff_words_aux(void *priv,
2000 long minus_first, long minus_len,
2001 long plus_first, long plus_len,
2002 const char *func, long funclen)
2004 struct diff_words_data *diff_words = priv;
2005 struct diff_words_style *style = diff_words->style;
2006 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
2007 struct diff_options *opt = diff_words->opt;
2008 const char *line_prefix;
2010 assert(opt);
2011 line_prefix = diff_line_prefix(opt);
2013 /* POSIX requires that first be decremented by one if len == 0... */
2014 if (minus_len) {
2015 minus_begin = diff_words->minus.orig[minus_first].begin;
2016 minus_end =
2017 diff_words->minus.orig[minus_first + minus_len - 1].end;
2018 } else
2019 minus_begin = minus_end =
2020 diff_words->minus.orig[minus_first].end;
2022 if (plus_len) {
2023 plus_begin = diff_words->plus.orig[plus_first].begin;
2024 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2025 } else
2026 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2028 if (color_words_output_graph_prefix(diff_words)) {
2029 fputs(line_prefix, diff_words->opt->file);
2031 if (diff_words->current_plus != plus_begin) {
2032 fn_out_diff_words_write_helper(diff_words->opt,
2033 &style->ctx, style->newline,
2034 plus_begin - diff_words->current_plus,
2035 diff_words->current_plus);
2037 if (minus_begin != minus_end) {
2038 fn_out_diff_words_write_helper(diff_words->opt,
2039 &style->old_word, style->newline,
2040 minus_end - minus_begin, minus_begin);
2042 if (plus_begin != plus_end) {
2043 fn_out_diff_words_write_helper(diff_words->opt,
2044 &style->new_word, style->newline,
2045 plus_end - plus_begin, plus_begin);
2048 diff_words->current_plus = plus_end;
2049 diff_words->last_minus = minus_first;
2052 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2053 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2054 int *begin, int *end)
2056 if (word_regex && *begin < buffer->size) {
2057 regmatch_t match[1];
2058 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2059 buffer->size - *begin, 1, match, 0)) {
2060 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2061 '\n', match[0].rm_eo - match[0].rm_so);
2062 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2063 *begin += match[0].rm_so;
2064 return *begin >= *end;
2066 return -1;
2069 /* find the next word */
2070 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2071 (*begin)++;
2072 if (*begin >= buffer->size)
2073 return -1;
2075 /* find the end of the word */
2076 *end = *begin + 1;
2077 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2078 (*end)++;
2080 return 0;
2084 * This function splits the words in buffer->text, stores the list with
2085 * newline separator into out, and saves the offsets of the original words
2086 * in buffer->orig.
2088 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2089 regex_t *word_regex)
2091 int i, j;
2092 long alloc = 0;
2094 out->size = 0;
2095 out->ptr = NULL;
2097 /* fake an empty "0th" word */
2098 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2099 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2100 buffer->orig_nr = 1;
2102 for (i = 0; i < buffer->text.size; i++) {
2103 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2104 return;
2106 /* store original boundaries */
2107 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2108 buffer->orig_alloc);
2109 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2110 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2111 buffer->orig_nr++;
2113 /* store one word */
2114 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2115 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2116 out->ptr[out->size + j - i] = '\n';
2117 out->size += j - i + 1;
2119 i = j - 1;
2123 /* this executes the word diff on the accumulated buffers */
2124 static void diff_words_show(struct diff_words_data *diff_words)
2126 xpparam_t xpp;
2127 xdemitconf_t xecfg;
2128 mmfile_t minus, plus;
2129 struct diff_words_style *style = diff_words->style;
2131 struct diff_options *opt = diff_words->opt;
2132 const char *line_prefix;
2134 assert(opt);
2135 line_prefix = diff_line_prefix(opt);
2137 /* special case: only removal */
2138 if (!diff_words->plus.text.size) {
2139 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2140 line_prefix, strlen(line_prefix), 0);
2141 fn_out_diff_words_write_helper(diff_words->opt,
2142 &style->old_word, style->newline,
2143 diff_words->minus.text.size,
2144 diff_words->minus.text.ptr);
2145 diff_words->minus.text.size = 0;
2146 return;
2149 diff_words->current_plus = diff_words->plus.text.ptr;
2150 diff_words->last_minus = 0;
2152 memset(&xpp, 0, sizeof(xpp));
2153 memset(&xecfg, 0, sizeof(xecfg));
2154 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2155 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2156 xpp.flags = 0;
2157 /* as only the hunk header will be parsed, we need a 0-context */
2158 xecfg.ctxlen = 0;
2159 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2160 diff_words, &xpp, &xecfg))
2161 die("unable to generate word diff");
2162 free(minus.ptr);
2163 free(plus.ptr);
2164 if (diff_words->current_plus != diff_words->plus.text.ptr +
2165 diff_words->plus.text.size) {
2166 if (color_words_output_graph_prefix(diff_words))
2167 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2168 line_prefix, strlen(line_prefix), 0);
2169 fn_out_diff_words_write_helper(diff_words->opt,
2170 &style->ctx, style->newline,
2171 diff_words->plus.text.ptr + diff_words->plus.text.size
2172 - diff_words->current_plus, diff_words->current_plus);
2174 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2177 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2178 static void diff_words_flush(struct emit_callback *ecbdata)
2180 struct diff_options *wo = ecbdata->diff_words->opt;
2182 if (ecbdata->diff_words->minus.text.size ||
2183 ecbdata->diff_words->plus.text.size)
2184 diff_words_show(ecbdata->diff_words);
2186 if (wo->emitted_symbols) {
2187 struct diff_options *o = ecbdata->opt;
2188 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2189 int i;
2192 * NEEDSWORK:
2193 * Instead of appending each, concat all words to a line?
2195 for (i = 0; i < wol->nr; i++)
2196 append_emitted_diff_symbol(o, &wol->buf[i]);
2198 for (i = 0; i < wol->nr; i++)
2199 free((void *)wol->buf[i].line);
2201 wol->nr = 0;
2205 static void diff_filespec_load_driver(struct diff_filespec *one,
2206 struct index_state *istate)
2208 /* Use already-loaded driver */
2209 if (one->driver)
2210 return;
2212 if (S_ISREG(one->mode))
2213 one->driver = userdiff_find_by_path(istate, one->path);
2215 /* Fallback to default settings */
2216 if (!one->driver)
2217 one->driver = userdiff_find_by_name("default");
2220 static const char *userdiff_word_regex(struct diff_filespec *one,
2221 struct index_state *istate)
2223 diff_filespec_load_driver(one, istate);
2224 return one->driver->word_regex;
2227 static void init_diff_words_data(struct emit_callback *ecbdata,
2228 struct diff_options *orig_opts,
2229 struct diff_filespec *one,
2230 struct diff_filespec *two)
2232 int i;
2233 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2234 memcpy(o, orig_opts, sizeof(struct diff_options));
2236 ecbdata->diff_words =
2237 xcalloc(1, sizeof(struct diff_words_data));
2238 ecbdata->diff_words->type = o->word_diff;
2239 ecbdata->diff_words->opt = o;
2241 if (orig_opts->emitted_symbols)
2242 o->emitted_symbols =
2243 xcalloc(1, sizeof(struct emitted_diff_symbols));
2245 if (!o->word_regex)
2246 o->word_regex = userdiff_word_regex(one, o->repo->index);
2247 if (!o->word_regex)
2248 o->word_regex = userdiff_word_regex(two, o->repo->index);
2249 if (!o->word_regex)
2250 o->word_regex = diff_word_regex_cfg;
2251 if (o->word_regex) {
2252 ecbdata->diff_words->word_regex = (regex_t *)
2253 xmalloc(sizeof(regex_t));
2254 if (regcomp(ecbdata->diff_words->word_regex,
2255 o->word_regex,
2256 REG_EXTENDED | REG_NEWLINE))
2257 die("invalid regular expression: %s",
2258 o->word_regex);
2260 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2261 if (o->word_diff == diff_words_styles[i].type) {
2262 ecbdata->diff_words->style =
2263 &diff_words_styles[i];
2264 break;
2267 if (want_color(o->use_color)) {
2268 struct diff_words_style *st = ecbdata->diff_words->style;
2269 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2270 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2271 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2275 static void free_diff_words_data(struct emit_callback *ecbdata)
2277 if (ecbdata->diff_words) {
2278 diff_words_flush(ecbdata);
2279 free (ecbdata->diff_words->opt->emitted_symbols);
2280 free (ecbdata->diff_words->opt);
2281 free (ecbdata->diff_words->minus.text.ptr);
2282 free (ecbdata->diff_words->minus.orig);
2283 free (ecbdata->diff_words->plus.text.ptr);
2284 free (ecbdata->diff_words->plus.orig);
2285 if (ecbdata->diff_words->word_regex) {
2286 regfree(ecbdata->diff_words->word_regex);
2287 free(ecbdata->diff_words->word_regex);
2289 FREE_AND_NULL(ecbdata->diff_words);
2293 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2295 if (want_color(diff_use_color))
2296 return diff_colors[ix];
2297 return "";
2300 const char *diff_line_prefix(struct diff_options *opt)
2302 struct strbuf *msgbuf;
2303 if (!opt->output_prefix)
2304 return "";
2306 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2307 return msgbuf->buf;
2310 static unsigned long sane_truncate_line(char *line, unsigned long len)
2312 const char *cp;
2313 unsigned long allot;
2314 size_t l = len;
2316 cp = line;
2317 allot = l;
2318 while (0 < l) {
2319 (void) utf8_width(&cp, &l);
2320 if (!cp)
2321 break; /* truncated in the middle? */
2323 return allot - l;
2326 static void find_lno(const char *line, struct emit_callback *ecbdata)
2328 const char *p;
2329 ecbdata->lno_in_preimage = 0;
2330 ecbdata->lno_in_postimage = 0;
2331 p = strchr(line, '-');
2332 if (!p)
2333 return; /* cannot happen */
2334 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2335 p = strchr(p, '+');
2336 if (!p)
2337 return; /* cannot happen */
2338 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2341 static void fn_out_consume(void *priv, char *line, unsigned long len)
2343 struct emit_callback *ecbdata = priv;
2344 struct diff_options *o = ecbdata->opt;
2346 o->found_changes = 1;
2348 if (ecbdata->header) {
2349 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2350 ecbdata->header->buf, ecbdata->header->len, 0);
2351 strbuf_reset(ecbdata->header);
2352 ecbdata->header = NULL;
2355 if (ecbdata->label_path[0]) {
2356 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2357 ecbdata->label_path[0],
2358 strlen(ecbdata->label_path[0]), 0);
2359 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2360 ecbdata->label_path[1],
2361 strlen(ecbdata->label_path[1]), 0);
2362 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2365 if (diff_suppress_blank_empty
2366 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2367 line[0] = '\n';
2368 len = 1;
2371 if (line[0] == '@') {
2372 if (ecbdata->diff_words)
2373 diff_words_flush(ecbdata);
2374 len = sane_truncate_line(line, len);
2375 find_lno(line, ecbdata);
2376 emit_hunk_header(ecbdata, line, len);
2377 return;
2380 if (ecbdata->diff_words) {
2381 enum diff_symbol s =
2382 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2383 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2384 if (line[0] == '-') {
2385 diff_words_append(line, len,
2386 &ecbdata->diff_words->minus);
2387 return;
2388 } else if (line[0] == '+') {
2389 diff_words_append(line, len,
2390 &ecbdata->diff_words->plus);
2391 return;
2392 } else if (starts_with(line, "\\ ")) {
2394 * Eat the "no newline at eof" marker as if we
2395 * saw a "+" or "-" line with nothing on it,
2396 * and return without diff_words_flush() to
2397 * defer processing. If this is the end of
2398 * preimage, more "+" lines may come after it.
2400 return;
2402 diff_words_flush(ecbdata);
2403 emit_diff_symbol(o, s, line, len, 0);
2404 return;
2407 switch (line[0]) {
2408 case '+':
2409 ecbdata->lno_in_postimage++;
2410 emit_add_line(ecbdata, line + 1, len - 1);
2411 break;
2412 case '-':
2413 ecbdata->lno_in_preimage++;
2414 emit_del_line(ecbdata, line + 1, len - 1);
2415 break;
2416 case ' ':
2417 ecbdata->lno_in_postimage++;
2418 ecbdata->lno_in_preimage++;
2419 emit_context_line(ecbdata, line + 1, len - 1);
2420 break;
2421 default:
2422 /* incomplete line at the end */
2423 ecbdata->lno_in_preimage++;
2424 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2425 line, len, 0);
2426 break;
2430 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2432 const char *old_name = a;
2433 const char *new_name = b;
2434 int pfx_length, sfx_length;
2435 int pfx_adjust_for_slash;
2436 int len_a = strlen(a);
2437 int len_b = strlen(b);
2438 int a_midlen, b_midlen;
2439 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2440 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2442 if (qlen_a || qlen_b) {
2443 quote_c_style(a, name, NULL, 0);
2444 strbuf_addstr(name, " => ");
2445 quote_c_style(b, name, NULL, 0);
2446 return;
2449 /* Find common prefix */
2450 pfx_length = 0;
2451 while (*old_name && *new_name && *old_name == *new_name) {
2452 if (*old_name == '/')
2453 pfx_length = old_name - a + 1;
2454 old_name++;
2455 new_name++;
2458 /* Find common suffix */
2459 old_name = a + len_a;
2460 new_name = b + len_b;
2461 sfx_length = 0;
2463 * If there is a common prefix, it must end in a slash. In
2464 * that case we let this loop run 1 into the prefix to see the
2465 * same slash.
2467 * If there is no common prefix, we cannot do this as it would
2468 * underrun the input strings.
2470 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2471 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2472 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2473 *old_name == *new_name) {
2474 if (*old_name == '/')
2475 sfx_length = len_a - (old_name - a);
2476 old_name--;
2477 new_name--;
2481 * pfx{mid-a => mid-b}sfx
2482 * {pfx-a => pfx-b}sfx
2483 * pfx{sfx-a => sfx-b}
2484 * name-a => name-b
2486 a_midlen = len_a - pfx_length - sfx_length;
2487 b_midlen = len_b - pfx_length - sfx_length;
2488 if (a_midlen < 0)
2489 a_midlen = 0;
2490 if (b_midlen < 0)
2491 b_midlen = 0;
2493 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2494 if (pfx_length + sfx_length) {
2495 strbuf_add(name, a, pfx_length);
2496 strbuf_addch(name, '{');
2498 strbuf_add(name, a + pfx_length, a_midlen);
2499 strbuf_addstr(name, " => ");
2500 strbuf_add(name, b + pfx_length, b_midlen);
2501 if (pfx_length + sfx_length) {
2502 strbuf_addch(name, '}');
2503 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2507 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2508 const char *name_a,
2509 const char *name_b)
2511 struct diffstat_file *x;
2512 x = xcalloc(1, sizeof(*x));
2513 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2514 diffstat->files[diffstat->nr++] = x;
2515 if (name_b) {
2516 x->from_name = xstrdup(name_a);
2517 x->name = xstrdup(name_b);
2518 x->is_renamed = 1;
2520 else {
2521 x->from_name = NULL;
2522 x->name = xstrdup(name_a);
2524 return x;
2527 static void diffstat_consume(void *priv, char *line, unsigned long len)
2529 struct diffstat_t *diffstat = priv;
2530 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2532 if (line[0] == '+')
2533 x->added++;
2534 else if (line[0] == '-')
2535 x->deleted++;
2538 const char mime_boundary_leader[] = "------------";
2540 static int scale_linear(int it, int width, int max_change)
2542 if (!it)
2543 return 0;
2545 * make sure that at least one '-' or '+' is printed if
2546 * there is any change to this path. The easiest way is to
2547 * scale linearly as if the allotted width is one column shorter
2548 * than it is, and then add 1 to the result.
2550 return 1 + (it * (width - 1) / max_change);
2553 static void show_graph(struct strbuf *out, char ch, int cnt,
2554 const char *set, const char *reset)
2556 if (cnt <= 0)
2557 return;
2558 strbuf_addstr(out, set);
2559 strbuf_addchars(out, ch, cnt);
2560 strbuf_addstr(out, reset);
2563 static void fill_print_name(struct diffstat_file *file)
2565 struct strbuf pname = STRBUF_INIT;
2567 if (file->print_name)
2568 return;
2570 if (file->is_renamed)
2571 pprint_rename(&pname, file->from_name, file->name);
2572 else
2573 quote_c_style(file->name, &pname, NULL, 0);
2575 if (file->comments)
2576 strbuf_addf(&pname, " (%s)", file->comments);
2578 file->print_name = strbuf_detach(&pname, NULL);
2581 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2582 int files, int insertions, int deletions)
2584 struct strbuf sb = STRBUF_INIT;
2586 if (!files) {
2587 assert(insertions == 0 && deletions == 0);
2588 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2589 NULL, 0, 0);
2590 return;
2593 strbuf_addf(&sb,
2594 (files == 1) ? " %d file changed" : " %d files changed",
2595 files);
2598 * For binary diff, the caller may want to print "x files
2599 * changed" with insertions == 0 && deletions == 0.
2601 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2602 * is probably less confusing (i.e skip over "2 files changed
2603 * but nothing about added/removed lines? Is this a bug in Git?").
2605 if (insertions || deletions == 0) {
2606 strbuf_addf(&sb,
2607 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2608 insertions);
2611 if (deletions || insertions == 0) {
2612 strbuf_addf(&sb,
2613 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2614 deletions);
2616 strbuf_addch(&sb, '\n');
2617 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2618 sb.buf, sb.len, 0);
2619 strbuf_release(&sb);
2622 void print_stat_summary(FILE *fp, int files,
2623 int insertions, int deletions)
2625 struct diff_options o;
2626 memset(&o, 0, sizeof(o));
2627 o.file = fp;
2629 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2632 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2634 int i, len, add, del, adds = 0, dels = 0;
2635 uintmax_t max_change = 0, max_len = 0;
2636 int total_files = data->nr, count;
2637 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2638 const char *reset, *add_c, *del_c;
2639 int extra_shown = 0;
2640 const char *line_prefix = diff_line_prefix(options);
2641 struct strbuf out = STRBUF_INIT;
2643 if (data->nr == 0)
2644 return;
2646 count = options->stat_count ? options->stat_count : data->nr;
2648 reset = diff_get_color_opt(options, DIFF_RESET);
2649 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2650 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2653 * Find the longest filename and max number of changes
2655 for (i = 0; (i < count) && (i < data->nr); i++) {
2656 struct diffstat_file *file = data->files[i];
2657 uintmax_t change = file->added + file->deleted;
2659 if (!file->is_interesting && (change == 0)) {
2660 count++; /* not shown == room for one more */
2661 continue;
2663 fill_print_name(file);
2664 len = strlen(file->print_name);
2665 if (max_len < len)
2666 max_len = len;
2668 if (file->is_unmerged) {
2669 /* "Unmerged" is 8 characters */
2670 bin_width = bin_width < 8 ? 8 : bin_width;
2671 continue;
2673 if (file->is_binary) {
2674 /* "Bin XXX -> YYY bytes" */
2675 int w = 14 + decimal_width(file->added)
2676 + decimal_width(file->deleted);
2677 bin_width = bin_width < w ? w : bin_width;
2678 /* Display change counts aligned with "Bin" */
2679 number_width = 3;
2680 continue;
2683 if (max_change < change)
2684 max_change = change;
2686 count = i; /* where we can stop scanning in data->files[] */
2689 * We have width = stat_width or term_columns() columns total.
2690 * We want a maximum of min(max_len, stat_name_width) for the name part.
2691 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2692 * We also need 1 for " " and 4 + decimal_width(max_change)
2693 * for " | NNNN " and one the empty column at the end, altogether
2694 * 6 + decimal_width(max_change).
2696 * If there's not enough space, we will use the smaller of
2697 * stat_name_width (if set) and 5/8*width for the filename,
2698 * and the rest for constant elements + graph part, but no more
2699 * than stat_graph_width for the graph part.
2700 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2701 * for the standard terminal size).
2703 * In other words: stat_width limits the maximum width, and
2704 * stat_name_width fixes the maximum width of the filename,
2705 * and is also used to divide available columns if there
2706 * aren't enough.
2708 * Binary files are displayed with "Bin XXX -> YYY bytes"
2709 * instead of the change count and graph. This part is treated
2710 * similarly to the graph part, except that it is not
2711 * "scaled". If total width is too small to accommodate the
2712 * guaranteed minimum width of the filename part and the
2713 * separators and this message, this message will "overflow"
2714 * making the line longer than the maximum width.
2717 if (options->stat_width == -1)
2718 width = term_columns() - strlen(line_prefix);
2719 else
2720 width = options->stat_width ? options->stat_width : 80;
2721 number_width = decimal_width(max_change) > number_width ?
2722 decimal_width(max_change) : number_width;
2724 if (options->stat_graph_width == -1)
2725 options->stat_graph_width = diff_stat_graph_width;
2728 * Guarantee 3/8*16==6 for the graph part
2729 * and 5/8*16==10 for the filename part
2731 if (width < 16 + 6 + number_width)
2732 width = 16 + 6 + number_width;
2735 * First assign sizes that are wanted, ignoring available width.
2736 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2737 * starting from "XXX" should fit in graph_width.
2739 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2740 if (options->stat_graph_width &&
2741 options->stat_graph_width < graph_width)
2742 graph_width = options->stat_graph_width;
2744 name_width = (options->stat_name_width > 0 &&
2745 options->stat_name_width < max_len) ?
2746 options->stat_name_width : max_len;
2749 * Adjust adjustable widths not to exceed maximum width
2751 if (name_width + number_width + 6 + graph_width > width) {
2752 if (graph_width > width * 3/8 - number_width - 6) {
2753 graph_width = width * 3/8 - number_width - 6;
2754 if (graph_width < 6)
2755 graph_width = 6;
2758 if (options->stat_graph_width &&
2759 graph_width > options->stat_graph_width)
2760 graph_width = options->stat_graph_width;
2761 if (name_width > width - number_width - 6 - graph_width)
2762 name_width = width - number_width - 6 - graph_width;
2763 else
2764 graph_width = width - number_width - 6 - name_width;
2768 * From here name_width is the width of the name area,
2769 * and graph_width is the width of the graph area.
2770 * max_change is used to scale graph properly.
2772 for (i = 0; i < count; i++) {
2773 const char *prefix = "";
2774 struct diffstat_file *file = data->files[i];
2775 char *name = file->print_name;
2776 uintmax_t added = file->added;
2777 uintmax_t deleted = file->deleted;
2778 int name_len;
2780 if (!file->is_interesting && (added + deleted == 0))
2781 continue;
2784 * "scale" the filename
2786 len = name_width;
2787 name_len = strlen(name);
2788 if (name_width < name_len) {
2789 char *slash;
2790 prefix = "...";
2791 len -= 3;
2792 name += name_len - len;
2793 slash = strchr(name, '/');
2794 if (slash)
2795 name = slash;
2798 if (file->is_binary) {
2799 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2800 strbuf_addf(&out, " %*s", number_width, "Bin");
2801 if (!added && !deleted) {
2802 strbuf_addch(&out, '\n');
2803 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2804 out.buf, out.len, 0);
2805 strbuf_reset(&out);
2806 continue;
2808 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2809 del_c, deleted, reset);
2810 strbuf_addstr(&out, " -> ");
2811 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2812 add_c, added, reset);
2813 strbuf_addstr(&out, " bytes\n");
2814 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2815 out.buf, out.len, 0);
2816 strbuf_reset(&out);
2817 continue;
2819 else if (file->is_unmerged) {
2820 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2821 strbuf_addstr(&out, " Unmerged\n");
2822 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2823 out.buf, out.len, 0);
2824 strbuf_reset(&out);
2825 continue;
2829 * scale the add/delete
2831 add = added;
2832 del = deleted;
2834 if (graph_width <= max_change) {
2835 int total = scale_linear(add + del, graph_width, max_change);
2836 if (total < 2 && add && del)
2837 /* width >= 2 due to the sanity check */
2838 total = 2;
2839 if (add < del) {
2840 add = scale_linear(add, graph_width, max_change);
2841 del = total - add;
2842 } else {
2843 del = scale_linear(del, graph_width, max_change);
2844 add = total - del;
2847 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2848 strbuf_addf(&out, " %*"PRIuMAX"%s",
2849 number_width, added + deleted,
2850 added + deleted ? " " : "");
2851 show_graph(&out, '+', add, add_c, reset);
2852 show_graph(&out, '-', del, del_c, reset);
2853 strbuf_addch(&out, '\n');
2854 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2855 out.buf, out.len, 0);
2856 strbuf_reset(&out);
2859 for (i = 0; i < data->nr; i++) {
2860 struct diffstat_file *file = data->files[i];
2861 uintmax_t added = file->added;
2862 uintmax_t deleted = file->deleted;
2864 if (file->is_unmerged ||
2865 (!file->is_interesting && (added + deleted == 0))) {
2866 total_files--;
2867 continue;
2870 if (!file->is_binary) {
2871 adds += added;
2872 dels += deleted;
2874 if (i < count)
2875 continue;
2876 if (!extra_shown)
2877 emit_diff_symbol(options,
2878 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2879 NULL, 0, 0);
2880 extra_shown = 1;
2883 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2884 strbuf_release(&out);
2887 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2889 int i, adds = 0, dels = 0, total_files = data->nr;
2891 if (data->nr == 0)
2892 return;
2894 for (i = 0; i < data->nr; i++) {
2895 int added = data->files[i]->added;
2896 int deleted = data->files[i]->deleted;
2898 if (data->files[i]->is_unmerged ||
2899 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2900 total_files--;
2901 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2902 adds += added;
2903 dels += deleted;
2906 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2909 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2911 int i;
2913 if (data->nr == 0)
2914 return;
2916 for (i = 0; i < data->nr; i++) {
2917 struct diffstat_file *file = data->files[i];
2919 fprintf(options->file, "%s", diff_line_prefix(options));
2921 if (file->is_binary)
2922 fprintf(options->file, "-\t-\t");
2923 else
2924 fprintf(options->file,
2925 "%"PRIuMAX"\t%"PRIuMAX"\t",
2926 file->added, file->deleted);
2927 if (options->line_termination) {
2928 fill_print_name(file);
2929 if (!file->is_renamed)
2930 write_name_quoted(file->name, options->file,
2931 options->line_termination);
2932 else {
2933 fputs(file->print_name, options->file);
2934 putc(options->line_termination, options->file);
2936 } else {
2937 if (file->is_renamed) {
2938 putc('\0', options->file);
2939 write_name_quoted(file->from_name, options->file, '\0');
2941 write_name_quoted(file->name, options->file, '\0');
2946 struct dirstat_file {
2947 const char *name;
2948 unsigned long changed;
2951 struct dirstat_dir {
2952 struct dirstat_file *files;
2953 int alloc, nr, permille, cumulative;
2956 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2957 unsigned long changed, const char *base, int baselen)
2959 unsigned long sum_changes = 0;
2960 unsigned int sources = 0;
2961 const char *line_prefix = diff_line_prefix(opt);
2963 while (dir->nr) {
2964 struct dirstat_file *f = dir->files;
2965 int namelen = strlen(f->name);
2966 unsigned long changes;
2967 char *slash;
2969 if (namelen < baselen)
2970 break;
2971 if (memcmp(f->name, base, baselen))
2972 break;
2973 slash = strchr(f->name + baselen, '/');
2974 if (slash) {
2975 int newbaselen = slash + 1 - f->name;
2976 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2977 sources++;
2978 } else {
2979 changes = f->changed;
2980 dir->files++;
2981 dir->nr--;
2982 sources += 2;
2984 sum_changes += changes;
2988 * We don't report dirstat's for
2989 * - the top level
2990 * - or cases where everything came from a single directory
2991 * under this directory (sources == 1).
2993 if (baselen && sources != 1) {
2994 if (sum_changes) {
2995 int permille = sum_changes * 1000 / changed;
2996 if (permille >= dir->permille) {
2997 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2998 permille / 10, permille % 10, baselen, base);
2999 if (!dir->cumulative)
3000 return 0;
3004 return sum_changes;
3007 static int dirstat_compare(const void *_a, const void *_b)
3009 const struct dirstat_file *a = _a;
3010 const struct dirstat_file *b = _b;
3011 return strcmp(a->name, b->name);
3014 static void show_dirstat(struct diff_options *options)
3016 int i;
3017 unsigned long changed;
3018 struct dirstat_dir dir;
3019 struct diff_queue_struct *q = &diff_queued_diff;
3021 dir.files = NULL;
3022 dir.alloc = 0;
3023 dir.nr = 0;
3024 dir.permille = options->dirstat_permille;
3025 dir.cumulative = options->flags.dirstat_cumulative;
3027 changed = 0;
3028 for (i = 0; i < q->nr; i++) {
3029 struct diff_filepair *p = q->queue[i];
3030 const char *name;
3031 unsigned long copied, added, damage;
3032 struct diff_populate_filespec_options dpf_options = {
3033 .check_size_only = 1,
3036 name = p->two->path ? p->two->path : p->one->path;
3038 if (p->one->oid_valid && p->two->oid_valid &&
3039 oideq(&p->one->oid, &p->two->oid)) {
3041 * The SHA1 has not changed, so pre-/post-content is
3042 * identical. We can therefore skip looking at the
3043 * file contents altogether.
3045 damage = 0;
3046 goto found_damage;
3049 if (options->flags.dirstat_by_file) {
3051 * In --dirstat-by-file mode, we don't really need to
3052 * look at the actual file contents at all.
3053 * The fact that the SHA1 changed is enough for us to
3054 * add this file to the list of results
3055 * (with each file contributing equal damage).
3057 damage = 1;
3058 goto found_damage;
3061 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3062 diff_populate_filespec(options->repo, p->one, NULL);
3063 diff_populate_filespec(options->repo, p->two, NULL);
3064 diffcore_count_changes(options->repo,
3065 p->one, p->two, NULL, NULL,
3066 &copied, &added);
3067 diff_free_filespec_data(p->one);
3068 diff_free_filespec_data(p->two);
3069 } else if (DIFF_FILE_VALID(p->one)) {
3070 diff_populate_filespec(options->repo, p->one, &dpf_options);
3071 copied = added = 0;
3072 diff_free_filespec_data(p->one);
3073 } else if (DIFF_FILE_VALID(p->two)) {
3074 diff_populate_filespec(options->repo, p->two, &dpf_options);
3075 copied = 0;
3076 added = p->two->size;
3077 diff_free_filespec_data(p->two);
3078 } else
3079 continue;
3082 * Original minus copied is the removed material,
3083 * added is the new material. They are both damages
3084 * made to the preimage.
3085 * If the resulting damage is zero, we know that
3086 * diffcore_count_changes() considers the two entries to
3087 * be identical, but since the oid changed, we
3088 * know that there must have been _some_ kind of change,
3089 * so we force all entries to have damage > 0.
3091 damage = (p->one->size - copied) + added;
3092 if (!damage)
3093 damage = 1;
3095 found_damage:
3096 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3097 dir.files[dir.nr].name = name;
3098 dir.files[dir.nr].changed = damage;
3099 changed += damage;
3100 dir.nr++;
3103 /* This can happen even with many files, if everything was renames */
3104 if (!changed)
3105 return;
3107 /* Show all directories with more than x% of the changes */
3108 QSORT(dir.files, dir.nr, dirstat_compare);
3109 gather_dirstat(options, &dir, changed, "", 0);
3112 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3114 int i;
3115 unsigned long changed;
3116 struct dirstat_dir dir;
3118 if (data->nr == 0)
3119 return;
3121 dir.files = NULL;
3122 dir.alloc = 0;
3123 dir.nr = 0;
3124 dir.permille = options->dirstat_permille;
3125 dir.cumulative = options->flags.dirstat_cumulative;
3127 changed = 0;
3128 for (i = 0; i < data->nr; i++) {
3129 struct diffstat_file *file = data->files[i];
3130 unsigned long damage = file->added + file->deleted;
3131 if (file->is_binary)
3133 * binary files counts bytes, not lines. Must find some
3134 * way to normalize binary bytes vs. textual lines.
3135 * The following heuristic assumes that there are 64
3136 * bytes per "line".
3137 * This is stupid and ugly, but very cheap...
3139 damage = DIV_ROUND_UP(damage, 64);
3140 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3141 dir.files[dir.nr].name = file->name;
3142 dir.files[dir.nr].changed = damage;
3143 changed += damage;
3144 dir.nr++;
3147 /* This can happen even with many files, if everything was renames */
3148 if (!changed)
3149 return;
3151 /* Show all directories with more than x% of the changes */
3152 QSORT(dir.files, dir.nr, dirstat_compare);
3153 gather_dirstat(options, &dir, changed, "", 0);
3156 static void free_diffstat_file(struct diffstat_file *f)
3158 free(f->print_name);
3159 free(f->name);
3160 free(f->from_name);
3161 free(f);
3164 void free_diffstat_info(struct diffstat_t *diffstat)
3166 int i;
3167 for (i = 0; i < diffstat->nr; i++)
3168 free_diffstat_file(diffstat->files[i]);
3169 free(diffstat->files);
3172 struct checkdiff_t {
3173 const char *filename;
3174 int lineno;
3175 int conflict_marker_size;
3176 struct diff_options *o;
3177 unsigned ws_rule;
3178 unsigned status;
3181 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3183 char firstchar;
3184 int cnt;
3186 if (len < marker_size + 1)
3187 return 0;
3188 firstchar = line[0];
3189 switch (firstchar) {
3190 case '=': case '>': case '<': case '|':
3191 break;
3192 default:
3193 return 0;
3195 for (cnt = 1; cnt < marker_size; cnt++)
3196 if (line[cnt] != firstchar)
3197 return 0;
3198 /* line[1] through line[marker_size-1] are same as firstchar */
3199 if (len < marker_size + 1 || !isspace(line[marker_size]))
3200 return 0;
3201 return 1;
3204 static void checkdiff_consume_hunk(void *priv,
3205 long ob, long on, long nb, long nn,
3206 const char *func, long funclen)
3209 struct checkdiff_t *data = priv;
3210 data->lineno = nb - 1;
3213 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3215 struct checkdiff_t *data = priv;
3216 int marker_size = data->conflict_marker_size;
3217 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3218 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3219 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3220 char *err;
3221 const char *line_prefix;
3223 assert(data->o);
3224 line_prefix = diff_line_prefix(data->o);
3226 if (line[0] == '+') {
3227 unsigned bad;
3228 data->lineno++;
3229 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3230 data->status |= 1;
3231 fprintf(data->o->file,
3232 "%s%s:%d: leftover conflict marker\n",
3233 line_prefix, data->filename, data->lineno);
3235 bad = ws_check(line + 1, len - 1, data->ws_rule);
3236 if (!bad)
3237 return;
3238 data->status |= bad;
3239 err = whitespace_error_string(bad);
3240 fprintf(data->o->file, "%s%s:%d: %s.\n",
3241 line_prefix, data->filename, data->lineno, err);
3242 free(err);
3243 emit_line(data->o, set, reset, line, 1);
3244 ws_check_emit(line + 1, len - 1, data->ws_rule,
3245 data->o->file, set, reset, ws);
3246 } else if (line[0] == ' ') {
3247 data->lineno++;
3251 static unsigned char *deflate_it(char *data,
3252 unsigned long size,
3253 unsigned long *result_size)
3255 int bound;
3256 unsigned char *deflated;
3257 git_zstream stream;
3259 git_deflate_init(&stream, zlib_compression_level);
3260 bound = git_deflate_bound(&stream, size);
3261 deflated = xmalloc(bound);
3262 stream.next_out = deflated;
3263 stream.avail_out = bound;
3265 stream.next_in = (unsigned char *)data;
3266 stream.avail_in = size;
3267 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3268 ; /* nothing */
3269 git_deflate_end(&stream);
3270 *result_size = stream.total_out;
3271 return deflated;
3274 static void emit_binary_diff_body(struct diff_options *o,
3275 mmfile_t *one, mmfile_t *two)
3277 void *cp;
3278 void *delta;
3279 void *deflated;
3280 void *data;
3281 unsigned long orig_size;
3282 unsigned long delta_size;
3283 unsigned long deflate_size;
3284 unsigned long data_size;
3286 /* We could do deflated delta, or we could do just deflated two,
3287 * whichever is smaller.
3289 delta = NULL;
3290 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3291 if (one->size && two->size) {
3292 delta = diff_delta(one->ptr, one->size,
3293 two->ptr, two->size,
3294 &delta_size, deflate_size);
3295 if (delta) {
3296 void *to_free = delta;
3297 orig_size = delta_size;
3298 delta = deflate_it(delta, delta_size, &delta_size);
3299 free(to_free);
3303 if (delta && delta_size < deflate_size) {
3304 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3305 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3306 s, strlen(s), 0);
3307 free(s);
3308 free(deflated);
3309 data = delta;
3310 data_size = delta_size;
3311 } else {
3312 char *s = xstrfmt("%lu", two->size);
3313 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3314 s, strlen(s), 0);
3315 free(s);
3316 free(delta);
3317 data = deflated;
3318 data_size = deflate_size;
3321 /* emit data encoded in base85 */
3322 cp = data;
3323 while (data_size) {
3324 int len;
3325 int bytes = (52 < data_size) ? 52 : data_size;
3326 char line[71];
3327 data_size -= bytes;
3328 if (bytes <= 26)
3329 line[0] = bytes + 'A' - 1;
3330 else
3331 line[0] = bytes - 26 + 'a' - 1;
3332 encode_85(line + 1, cp, bytes);
3333 cp = (char *) cp + bytes;
3335 len = strlen(line);
3336 line[len++] = '\n';
3337 line[len] = '\0';
3339 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3340 line, len, 0);
3342 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3343 free(data);
3346 static void emit_binary_diff(struct diff_options *o,
3347 mmfile_t *one, mmfile_t *two)
3349 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3350 emit_binary_diff_body(o, one, two);
3351 emit_binary_diff_body(o, two, one);
3354 int diff_filespec_is_binary(struct repository *r,
3355 struct diff_filespec *one)
3357 struct diff_populate_filespec_options dpf_options = {
3358 .check_binary = 1,
3361 if (one->is_binary == -1) {
3362 diff_filespec_load_driver(one, r->index);
3363 if (one->driver->binary != -1)
3364 one->is_binary = one->driver->binary;
3365 else {
3366 if (!one->data && DIFF_FILE_VALID(one))
3367 diff_populate_filespec(r, one, &dpf_options);
3368 if (one->is_binary == -1 && one->data)
3369 one->is_binary = buffer_is_binary(one->data,
3370 one->size);
3371 if (one->is_binary == -1)
3372 one->is_binary = 0;
3375 return one->is_binary;
3378 static const struct userdiff_funcname *
3379 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3381 diff_filespec_load_driver(one, o->repo->index);
3382 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3385 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3387 if (!options->a_prefix)
3388 options->a_prefix = a;
3389 if (!options->b_prefix)
3390 options->b_prefix = b;
3393 struct userdiff_driver *get_textconv(struct repository *r,
3394 struct diff_filespec *one)
3396 if (!DIFF_FILE_VALID(one))
3397 return NULL;
3399 diff_filespec_load_driver(one, r->index);
3400 return userdiff_get_textconv(r, one->driver);
3403 static void builtin_diff(const char *name_a,
3404 const char *name_b,
3405 struct diff_filespec *one,
3406 struct diff_filespec *two,
3407 const char *xfrm_msg,
3408 int must_show_header,
3409 struct diff_options *o,
3410 int complete_rewrite)
3412 mmfile_t mf1, mf2;
3413 const char *lbl[2];
3414 char *a_one, *b_two;
3415 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3416 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3417 const char *a_prefix, *b_prefix;
3418 struct userdiff_driver *textconv_one = NULL;
3419 struct userdiff_driver *textconv_two = NULL;
3420 struct strbuf header = STRBUF_INIT;
3421 const char *line_prefix = diff_line_prefix(o);
3423 diff_set_mnemonic_prefix(o, "a/", "b/");
3424 if (o->flags.reverse_diff) {
3425 a_prefix = o->b_prefix;
3426 b_prefix = o->a_prefix;
3427 } else {
3428 a_prefix = o->a_prefix;
3429 b_prefix = o->b_prefix;
3432 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3433 (!one->mode || S_ISGITLINK(one->mode)) &&
3434 (!two->mode || S_ISGITLINK(two->mode))) {
3435 show_submodule_diff_summary(o, one->path ? one->path : two->path,
3436 &one->oid, &two->oid,
3437 two->dirty_submodule);
3438 return;
3439 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3440 (!one->mode || S_ISGITLINK(one->mode)) &&
3441 (!two->mode || S_ISGITLINK(two->mode))) {
3442 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3443 &one->oid, &two->oid,
3444 two->dirty_submodule);
3445 return;
3448 if (o->flags.allow_textconv) {
3449 textconv_one = get_textconv(o->repo, one);
3450 textconv_two = get_textconv(o->repo, two);
3453 /* Never use a non-valid filename anywhere if at all possible */
3454 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3455 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3457 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3458 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3459 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3460 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3461 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3462 if (lbl[0][0] == '/') {
3463 /* /dev/null */
3464 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3465 if (xfrm_msg)
3466 strbuf_addstr(&header, xfrm_msg);
3467 must_show_header = 1;
3469 else if (lbl[1][0] == '/') {
3470 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3471 if (xfrm_msg)
3472 strbuf_addstr(&header, xfrm_msg);
3473 must_show_header = 1;
3475 else {
3476 if (one->mode != two->mode) {
3477 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3478 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3479 must_show_header = 1;
3481 if (xfrm_msg)
3482 strbuf_addstr(&header, xfrm_msg);
3485 * we do not run diff between different kind
3486 * of objects.
3488 if ((one->mode ^ two->mode) & S_IFMT)
3489 goto free_ab_and_return;
3490 if (complete_rewrite &&
3491 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3492 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3493 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3494 header.buf, header.len, 0);
3495 strbuf_reset(&header);
3496 emit_rewrite_diff(name_a, name_b, one, two,
3497 textconv_one, textconv_two, o);
3498 o->found_changes = 1;
3499 goto free_ab_and_return;
3503 if (o->irreversible_delete && lbl[1][0] == '/') {
3504 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3505 header.len, 0);
3506 strbuf_reset(&header);
3507 goto free_ab_and_return;
3508 } else if (!o->flags.text &&
3509 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3510 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3511 struct strbuf sb = STRBUF_INIT;
3512 if (!one->data && !two->data &&
3513 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3514 !o->flags.binary) {
3515 if (oideq(&one->oid, &two->oid)) {
3516 if (must_show_header)
3517 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3518 header.buf, header.len,
3520 goto free_ab_and_return;
3522 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3523 header.buf, header.len, 0);
3524 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3525 diff_line_prefix(o), lbl[0], lbl[1]);
3526 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3527 sb.buf, sb.len, 0);
3528 strbuf_release(&sb);
3529 goto free_ab_and_return;
3531 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3532 fill_mmfile(o->repo, &mf2, two) < 0)
3533 die("unable to read files to diff");
3534 /* Quite common confusing case */
3535 if (mf1.size == mf2.size &&
3536 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3537 if (must_show_header)
3538 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3539 header.buf, header.len, 0);
3540 goto free_ab_and_return;
3542 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3543 strbuf_reset(&header);
3544 if (o->flags.binary)
3545 emit_binary_diff(o, &mf1, &mf2);
3546 else {
3547 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3548 diff_line_prefix(o), lbl[0], lbl[1]);
3549 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3550 sb.buf, sb.len, 0);
3551 strbuf_release(&sb);
3553 o->found_changes = 1;
3554 } else {
3555 /* Crazy xdl interfaces.. */
3556 const char *diffopts;
3557 const char *v;
3558 xpparam_t xpp;
3559 xdemitconf_t xecfg;
3560 struct emit_callback ecbdata;
3561 const struct userdiff_funcname *pe;
3563 if (must_show_header) {
3564 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3565 header.buf, header.len, 0);
3566 strbuf_reset(&header);
3569 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3570 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3572 pe = diff_funcname_pattern(o, one);
3573 if (!pe)
3574 pe = diff_funcname_pattern(o, two);
3576 memset(&xpp, 0, sizeof(xpp));
3577 memset(&xecfg, 0, sizeof(xecfg));
3578 memset(&ecbdata, 0, sizeof(ecbdata));
3579 if (o->flags.suppress_diff_headers)
3580 lbl[0] = NULL;
3581 ecbdata.label_path = lbl;
3582 ecbdata.color_diff = want_color(o->use_color);
3583 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3584 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3585 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3586 ecbdata.opt = o;
3587 if (header.len && !o->flags.suppress_diff_headers)
3588 ecbdata.header = &header;
3589 xpp.flags = o->xdl_opts;
3590 xpp.anchors = o->anchors;
3591 xpp.anchors_nr = o->anchors_nr;
3592 xecfg.ctxlen = o->context;
3593 xecfg.interhunkctxlen = o->interhunkcontext;
3594 xecfg.flags = XDL_EMIT_FUNCNAMES;
3595 if (o->flags.funccontext)
3596 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3597 if (pe)
3598 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3600 diffopts = getenv("GIT_DIFF_OPTS");
3601 if (!diffopts)
3603 else if (skip_prefix(diffopts, "--unified=", &v))
3604 xecfg.ctxlen = strtoul(v, NULL, 10);
3605 else if (skip_prefix(diffopts, "-u", &v))
3606 xecfg.ctxlen = strtoul(v, NULL, 10);
3608 if (o->word_diff)
3609 init_diff_words_data(&ecbdata, o, one, two);
3610 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3611 &ecbdata, &xpp, &xecfg))
3612 die("unable to generate diff for %s", one->path);
3613 if (o->word_diff)
3614 free_diff_words_data(&ecbdata);
3615 if (textconv_one)
3616 free(mf1.ptr);
3617 if (textconv_two)
3618 free(mf2.ptr);
3619 xdiff_clear_find_func(&xecfg);
3622 free_ab_and_return:
3623 strbuf_release(&header);
3624 diff_free_filespec_data(one);
3625 diff_free_filespec_data(two);
3626 free(a_one);
3627 free(b_two);
3628 return;
3631 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3633 if (!is_renamed) {
3634 if (p->status == DIFF_STATUS_ADDED) {
3635 if (S_ISLNK(p->two->mode))
3636 return "new +l";
3637 else if ((p->two->mode & 0777) == 0755)
3638 return "new +x";
3639 else
3640 return "new";
3641 } else if (p->status == DIFF_STATUS_DELETED)
3642 return "gone";
3644 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3645 return "mode -l";
3646 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3647 return "mode +l";
3648 else if ((p->one->mode & 0777) == 0644 &&
3649 (p->two->mode & 0777) == 0755)
3650 return "mode +x";
3651 else if ((p->one->mode & 0777) == 0755 &&
3652 (p->two->mode & 0777) == 0644)
3653 return "mode -x";
3654 return NULL;
3657 static void builtin_diffstat(const char *name_a, const char *name_b,
3658 struct diff_filespec *one,
3659 struct diff_filespec *two,
3660 struct diffstat_t *diffstat,
3661 struct diff_options *o,
3662 struct diff_filepair *p)
3664 mmfile_t mf1, mf2;
3665 struct diffstat_file *data;
3666 int may_differ;
3667 int complete_rewrite = 0;
3669 if (!DIFF_PAIR_UNMERGED(p)) {
3670 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3671 complete_rewrite = 1;
3674 data = diffstat_add(diffstat, name_a, name_b);
3675 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3676 if (o->flags.stat_with_summary)
3677 data->comments = get_compact_summary(p, data->is_renamed);
3679 if (!one || !two) {
3680 data->is_unmerged = 1;
3681 return;
3684 /* saves some reads if true, not a guarantee of diff outcome */
3685 may_differ = !(one->oid_valid && two->oid_valid &&
3686 oideq(&one->oid, &two->oid));
3688 if (diff_filespec_is_binary(o->repo, one) ||
3689 diff_filespec_is_binary(o->repo, two)) {
3690 data->is_binary = 1;
3691 if (!may_differ) {
3692 data->added = 0;
3693 data->deleted = 0;
3694 } else {
3695 data->added = diff_filespec_size(o->repo, two);
3696 data->deleted = diff_filespec_size(o->repo, one);
3700 else if (complete_rewrite) {
3701 diff_populate_filespec(o->repo, one, NULL);
3702 diff_populate_filespec(o->repo, two, NULL);
3703 data->deleted = count_lines(one->data, one->size);
3704 data->added = count_lines(two->data, two->size);
3707 else if (may_differ) {
3708 /* Crazy xdl interfaces.. */
3709 xpparam_t xpp;
3710 xdemitconf_t xecfg;
3712 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3713 fill_mmfile(o->repo, &mf2, two) < 0)
3714 die("unable to read files to diff");
3716 memset(&xpp, 0, sizeof(xpp));
3717 memset(&xecfg, 0, sizeof(xecfg));
3718 xpp.flags = o->xdl_opts;
3719 xpp.anchors = o->anchors;
3720 xpp.anchors_nr = o->anchors_nr;
3721 xecfg.ctxlen = o->context;
3722 xecfg.interhunkctxlen = o->interhunkcontext;
3723 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3724 diffstat_consume, diffstat, &xpp, &xecfg))
3725 die("unable to generate diffstat for %s", one->path);
3727 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3728 struct diffstat_file *file =
3729 diffstat->files[diffstat->nr - 1];
3731 * Omit diffstats of modified files where nothing changed.
3732 * Even if may_differ, this might be the case due to
3733 * ignoring whitespace changes, etc.
3735 * But note that we special-case additions, deletions,
3736 * renames, and mode changes as adding an empty file,
3737 * for example is still of interest.
3739 if ((p->status == DIFF_STATUS_MODIFIED)
3740 && !file->added
3741 && !file->deleted
3742 && one->mode == two->mode) {
3743 free_diffstat_file(file);
3744 diffstat->nr--;
3749 diff_free_filespec_data(one);
3750 diff_free_filespec_data(two);
3753 static void builtin_checkdiff(const char *name_a, const char *name_b,
3754 const char *attr_path,
3755 struct diff_filespec *one,
3756 struct diff_filespec *two,
3757 struct diff_options *o)
3759 mmfile_t mf1, mf2;
3760 struct checkdiff_t data;
3762 if (!two)
3763 return;
3765 memset(&data, 0, sizeof(data));
3766 data.filename = name_b ? name_b : name_a;
3767 data.lineno = 0;
3768 data.o = o;
3769 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3770 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3772 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3773 fill_mmfile(o->repo, &mf2, two) < 0)
3774 die("unable to read files to diff");
3777 * All the other codepaths check both sides, but not checking
3778 * the "old" side here is deliberate. We are checking the newly
3779 * introduced changes, and as long as the "new" side is text, we
3780 * can and should check what it introduces.
3782 if (diff_filespec_is_binary(o->repo, two))
3783 goto free_and_return;
3784 else {
3785 /* Crazy xdl interfaces.. */
3786 xpparam_t xpp;
3787 xdemitconf_t xecfg;
3789 memset(&xpp, 0, sizeof(xpp));
3790 memset(&xecfg, 0, sizeof(xecfg));
3791 xecfg.ctxlen = 1; /* at least one context line */
3792 xpp.flags = 0;
3793 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3794 checkdiff_consume, &data,
3795 &xpp, &xecfg))
3796 die("unable to generate checkdiff for %s", one->path);
3798 if (data.ws_rule & WS_BLANK_AT_EOF) {
3799 struct emit_callback ecbdata;
3800 int blank_at_eof;
3802 ecbdata.ws_rule = data.ws_rule;
3803 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3804 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3806 if (blank_at_eof) {
3807 static char *err;
3808 if (!err)
3809 err = whitespace_error_string(WS_BLANK_AT_EOF);
3810 fprintf(o->file, "%s:%d: %s.\n",
3811 data.filename, blank_at_eof, err);
3812 data.status = 1; /* report errors */
3816 free_and_return:
3817 diff_free_filespec_data(one);
3818 diff_free_filespec_data(two);
3819 if (data.status)
3820 o->flags.check_failed = 1;
3823 struct diff_filespec *alloc_filespec(const char *path)
3825 struct diff_filespec *spec;
3827 FLEXPTR_ALLOC_STR(spec, path, path);
3828 spec->count = 1;
3829 spec->is_binary = -1;
3830 return spec;
3833 void free_filespec(struct diff_filespec *spec)
3835 if (!--spec->count) {
3836 diff_free_filespec_data(spec);
3837 free(spec);
3841 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3842 int oid_valid, unsigned short mode)
3844 if (mode) {
3845 spec->mode = canon_mode(mode);
3846 oidcpy(&spec->oid, oid);
3847 spec->oid_valid = oid_valid;
3852 * Given a name and sha1 pair, if the index tells us the file in
3853 * the work tree has that object contents, return true, so that
3854 * prepare_temp_file() does not have to inflate and extract.
3856 static int reuse_worktree_file(struct index_state *istate,
3857 const char *name,
3858 const struct object_id *oid,
3859 int want_file)
3861 const struct cache_entry *ce;
3862 struct stat st;
3863 int pos, len;
3866 * We do not read the cache ourselves here, because the
3867 * benchmark with my previous version that always reads cache
3868 * shows that it makes things worse for diff-tree comparing
3869 * two linux-2.6 kernel trees in an already checked out work
3870 * tree. This is because most diff-tree comparisons deal with
3871 * only a small number of files, while reading the cache is
3872 * expensive for a large project, and its cost outweighs the
3873 * savings we get by not inflating the object to a temporary
3874 * file. Practically, this code only helps when we are used
3875 * by diff-cache --cached, which does read the cache before
3876 * calling us.
3878 if (!istate->cache)
3879 return 0;
3881 /* We want to avoid the working directory if our caller
3882 * doesn't need the data in a normal file, this system
3883 * is rather slow with its stat/open/mmap/close syscalls,
3884 * and the object is contained in a pack file. The pack
3885 * is probably already open and will be faster to obtain
3886 * the data through than the working directory. Loose
3887 * objects however would tend to be slower as they need
3888 * to be individually opened and inflated.
3890 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3891 return 0;
3894 * Similarly, if we'd have to convert the file contents anyway, that
3895 * makes the optimization not worthwhile.
3897 if (!want_file && would_convert_to_git(istate, name))
3898 return 0;
3900 len = strlen(name);
3901 pos = index_name_pos(istate, name, len);
3902 if (pos < 0)
3903 return 0;
3904 ce = istate->cache[pos];
3907 * This is not the sha1 we are looking for, or
3908 * unreusable because it is not a regular file.
3910 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3911 return 0;
3914 * If ce is marked as "assume unchanged", there is no
3915 * guarantee that work tree matches what we are looking for.
3917 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3918 return 0;
3921 * If ce matches the file in the work tree, we can reuse it.
3923 if (ce_uptodate(ce) ||
3924 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3925 return 1;
3927 return 0;
3930 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3932 struct strbuf buf = STRBUF_INIT;
3933 char *dirty = "";
3935 /* Are we looking at the work tree? */
3936 if (s->dirty_submodule)
3937 dirty = "-dirty";
3939 strbuf_addf(&buf, "Subproject commit %s%s\n",
3940 oid_to_hex(&s->oid), dirty);
3941 s->size = buf.len;
3942 if (size_only) {
3943 s->data = NULL;
3944 strbuf_release(&buf);
3945 } else {
3946 s->data = strbuf_detach(&buf, NULL);
3947 s->should_free = 1;
3949 return 0;
3953 * While doing rename detection and pickaxe operation, we may need to
3954 * grab the data for the blob (or file) for our own in-core comparison.
3955 * diff_filespec has data and size fields for this purpose.
3957 int diff_populate_filespec(struct repository *r,
3958 struct diff_filespec *s,
3959 const struct diff_populate_filespec_options *options)
3961 int size_only = options ? options->check_size_only : 0;
3962 int check_binary = options ? options->check_binary : 0;
3963 int err = 0;
3964 int conv_flags = global_conv_flags_eol;
3966 * demote FAIL to WARN to allow inspecting the situation
3967 * instead of refusing.
3969 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3970 conv_flags = CONV_EOL_RNDTRP_WARN;
3972 if (!DIFF_FILE_VALID(s))
3973 die("internal error: asking to populate invalid file.");
3974 if (S_ISDIR(s->mode))
3975 return -1;
3977 if (s->data)
3978 return 0;
3980 if (size_only && 0 < s->size)
3981 return 0;
3983 if (S_ISGITLINK(s->mode))
3984 return diff_populate_gitlink(s, size_only);
3986 if (!s->oid_valid ||
3987 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3988 struct strbuf buf = STRBUF_INIT;
3989 struct stat st;
3990 int fd;
3992 if (lstat(s->path, &st) < 0) {
3993 err_empty:
3994 err = -1;
3995 empty:
3996 s->data = (char *)"";
3997 s->size = 0;
3998 return err;
4000 s->size = xsize_t(st.st_size);
4001 if (!s->size)
4002 goto empty;
4003 if (S_ISLNK(st.st_mode)) {
4004 struct strbuf sb = STRBUF_INIT;
4006 if (strbuf_readlink(&sb, s->path, s->size))
4007 goto err_empty;
4008 s->size = sb.len;
4009 s->data = strbuf_detach(&sb, NULL);
4010 s->should_free = 1;
4011 return 0;
4015 * Even if the caller would be happy with getting
4016 * only the size, we cannot return early at this
4017 * point if the path requires us to run the content
4018 * conversion.
4020 if (size_only && !would_convert_to_git(r->index, s->path))
4021 return 0;
4024 * Note: this check uses xsize_t(st.st_size) that may
4025 * not be the true size of the blob after it goes
4026 * through convert_to_git(). This may not strictly be
4027 * correct, but the whole point of big_file_threshold
4028 * and is_binary check being that we want to avoid
4029 * opening the file and inspecting the contents, this
4030 * is probably fine.
4032 if (check_binary &&
4033 s->size > big_file_threshold && s->is_binary == -1) {
4034 s->is_binary = 1;
4035 return 0;
4037 fd = open(s->path, O_RDONLY);
4038 if (fd < 0)
4039 goto err_empty;
4040 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4041 close(fd);
4042 s->should_munmap = 1;
4045 * Convert from working tree format to canonical git format
4047 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4048 size_t size = 0;
4049 munmap(s->data, s->size);
4050 s->should_munmap = 0;
4051 s->data = strbuf_detach(&buf, &size);
4052 s->size = size;
4053 s->should_free = 1;
4056 else {
4057 struct object_info info = {
4058 .sizep = &s->size
4061 if (!(size_only || check_binary))
4063 * Set contentp, since there is no chance that merely
4064 * the size is sufficient.
4066 info.contentp = &s->data;
4068 if (options && options->missing_object_cb) {
4069 if (!oid_object_info_extended(r, &s->oid, &info,
4070 OBJECT_INFO_LOOKUP_REPLACE |
4071 OBJECT_INFO_SKIP_FETCH_OBJECT))
4072 goto object_read;
4073 options->missing_object_cb(options->missing_object_data);
4075 if (oid_object_info_extended(r, &s->oid, &info,
4076 OBJECT_INFO_LOOKUP_REPLACE))
4077 die("unable to read %s", oid_to_hex(&s->oid));
4079 object_read:
4080 if (size_only || check_binary) {
4081 if (size_only)
4082 return 0;
4083 if (s->size > big_file_threshold && s->is_binary == -1) {
4084 s->is_binary = 1;
4085 return 0;
4088 if (!info.contentp) {
4089 info.contentp = &s->data;
4090 if (oid_object_info_extended(r, &s->oid, &info,
4091 OBJECT_INFO_LOOKUP_REPLACE))
4092 die("unable to read %s", oid_to_hex(&s->oid));
4094 s->should_free = 1;
4096 return 0;
4099 void diff_free_filespec_blob(struct diff_filespec *s)
4101 if (s->should_free)
4102 free(s->data);
4103 else if (s->should_munmap)
4104 munmap(s->data, s->size);
4106 if (s->should_free || s->should_munmap) {
4107 s->should_free = s->should_munmap = 0;
4108 s->data = NULL;
4112 void diff_free_filespec_data(struct diff_filespec *s)
4114 diff_free_filespec_blob(s);
4115 FREE_AND_NULL(s->cnt_data);
4118 static void prep_temp_blob(struct index_state *istate,
4119 const char *path, struct diff_tempfile *temp,
4120 void *blob,
4121 unsigned long size,
4122 const struct object_id *oid,
4123 int mode)
4125 struct strbuf buf = STRBUF_INIT;
4126 struct strbuf tempfile = STRBUF_INIT;
4127 char *path_dup = xstrdup(path);
4128 const char *base = basename(path_dup);
4129 struct checkout_metadata meta;
4131 init_checkout_metadata(&meta, NULL, NULL, oid);
4133 /* Generate "XXXXXX_basename.ext" */
4134 strbuf_addstr(&tempfile, "XXXXXX_");
4135 strbuf_addstr(&tempfile, base);
4137 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4138 if (!temp->tempfile)
4139 die_errno("unable to create temp-file");
4140 if (convert_to_working_tree(istate, path,
4141 (const char *)blob, (size_t)size, &buf, &meta)) {
4142 blob = buf.buf;
4143 size = buf.len;
4145 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4146 close_tempfile_gently(temp->tempfile))
4147 die_errno("unable to write temp-file");
4148 temp->name = get_tempfile_path(temp->tempfile);
4149 oid_to_hex_r(temp->hex, oid);
4150 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4151 strbuf_release(&buf);
4152 strbuf_release(&tempfile);
4153 free(path_dup);
4156 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4157 const char *name,
4158 struct diff_filespec *one)
4160 struct diff_tempfile *temp = claim_diff_tempfile();
4162 if (!DIFF_FILE_VALID(one)) {
4163 not_a_valid_file:
4164 /* A '-' entry produces this for file-2, and
4165 * a '+' entry produces this for file-1.
4167 temp->name = "/dev/null";
4168 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4169 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4170 return temp;
4173 if (!S_ISGITLINK(one->mode) &&
4174 (!one->oid_valid ||
4175 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4176 struct stat st;
4177 if (lstat(name, &st) < 0) {
4178 if (errno == ENOENT)
4179 goto not_a_valid_file;
4180 die_errno("stat(%s)", name);
4182 if (S_ISLNK(st.st_mode)) {
4183 struct strbuf sb = STRBUF_INIT;
4184 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4185 die_errno("readlink(%s)", name);
4186 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4187 (one->oid_valid ?
4188 &one->oid : &null_oid),
4189 (one->oid_valid ?
4190 one->mode : S_IFLNK));
4191 strbuf_release(&sb);
4193 else {
4194 /* we can borrow from the file in the work tree */
4195 temp->name = name;
4196 if (!one->oid_valid)
4197 oid_to_hex_r(temp->hex, &null_oid);
4198 else
4199 oid_to_hex_r(temp->hex, &one->oid);
4200 /* Even though we may sometimes borrow the
4201 * contents from the work tree, we always want
4202 * one->mode. mode is trustworthy even when
4203 * !(one->oid_valid), as long as
4204 * DIFF_FILE_VALID(one).
4206 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4208 return temp;
4210 else {
4211 if (diff_populate_filespec(r, one, NULL))
4212 die("cannot read data blob for %s", one->path);
4213 prep_temp_blob(r->index, name, temp,
4214 one->data, one->size,
4215 &one->oid, one->mode);
4217 return temp;
4220 static void add_external_diff_name(struct repository *r,
4221 struct strvec *argv,
4222 const char *name,
4223 struct diff_filespec *df)
4225 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4226 strvec_push(argv, temp->name);
4227 strvec_push(argv, temp->hex);
4228 strvec_push(argv, temp->mode);
4231 /* An external diff command takes:
4233 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4234 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4237 static void run_external_diff(const char *pgm,
4238 const char *name,
4239 const char *other,
4240 struct diff_filespec *one,
4241 struct diff_filespec *two,
4242 const char *xfrm_msg,
4243 struct diff_options *o)
4245 struct strvec argv = STRVEC_INIT;
4246 struct strvec env = STRVEC_INIT;
4247 struct diff_queue_struct *q = &diff_queued_diff;
4249 strvec_push(&argv, pgm);
4250 strvec_push(&argv, name);
4252 if (one && two) {
4253 add_external_diff_name(o->repo, &argv, name, one);
4254 if (!other)
4255 add_external_diff_name(o->repo, &argv, name, two);
4256 else {
4257 add_external_diff_name(o->repo, &argv, other, two);
4258 strvec_push(&argv, other);
4259 strvec_push(&argv, xfrm_msg);
4263 strvec_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4264 strvec_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4266 diff_free_filespec_data(one);
4267 diff_free_filespec_data(two);
4268 if (run_command_v_opt_cd_env(argv.v, RUN_USING_SHELL, NULL, env.v))
4269 die(_("external diff died, stopping at %s"), name);
4271 remove_tempfile();
4272 strvec_clear(&argv);
4273 strvec_clear(&env);
4276 static int similarity_index(struct diff_filepair *p)
4278 return p->score * 100 / MAX_SCORE;
4281 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4283 if (startup_info->have_repository)
4284 return find_unique_abbrev(oid, abbrev);
4285 else {
4286 char *hex = oid_to_hex(oid);
4287 if (abbrev < 0)
4288 abbrev = FALLBACK_DEFAULT_ABBREV;
4289 if (abbrev > the_hash_algo->hexsz)
4290 BUG("oid abbreviation out of range: %d", abbrev);
4291 if (abbrev)
4292 hex[abbrev] = '\0';
4293 return hex;
4297 static void fill_metainfo(struct strbuf *msg,
4298 const char *name,
4299 const char *other,
4300 struct diff_filespec *one,
4301 struct diff_filespec *two,
4302 struct diff_options *o,
4303 struct diff_filepair *p,
4304 int *must_show_header,
4305 int use_color)
4307 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4308 const char *reset = diff_get_color(use_color, DIFF_RESET);
4309 const char *line_prefix = diff_line_prefix(o);
4311 *must_show_header = 1;
4312 strbuf_init(msg, PATH_MAX * 2 + 300);
4313 switch (p->status) {
4314 case DIFF_STATUS_COPIED:
4315 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4316 line_prefix, set, similarity_index(p));
4317 strbuf_addf(msg, "%s\n%s%scopy from ",
4318 reset, line_prefix, set);
4319 quote_c_style(name, msg, NULL, 0);
4320 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4321 quote_c_style(other, msg, NULL, 0);
4322 strbuf_addf(msg, "%s\n", reset);
4323 break;
4324 case DIFF_STATUS_RENAMED:
4325 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4326 line_prefix, set, similarity_index(p));
4327 strbuf_addf(msg, "%s\n%s%srename from ",
4328 reset, line_prefix, set);
4329 quote_c_style(name, msg, NULL, 0);
4330 strbuf_addf(msg, "%s\n%s%srename to ",
4331 reset, line_prefix, set);
4332 quote_c_style(other, msg, NULL, 0);
4333 strbuf_addf(msg, "%s\n", reset);
4334 break;
4335 case DIFF_STATUS_MODIFIED:
4336 if (p->score) {
4337 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4338 line_prefix,
4339 set, similarity_index(p), reset);
4340 break;
4342 /* fallthru */
4343 default:
4344 *must_show_header = 0;
4346 if (one && two && !oideq(&one->oid, &two->oid)) {
4347 const unsigned hexsz = the_hash_algo->hexsz;
4348 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4350 if (o->flags.full_index)
4351 abbrev = hexsz;
4353 if (o->flags.binary) {
4354 mmfile_t mf;
4355 if ((!fill_mmfile(o->repo, &mf, one) &&
4356 diff_filespec_is_binary(o->repo, one)) ||
4357 (!fill_mmfile(o->repo, &mf, two) &&
4358 diff_filespec_is_binary(o->repo, two)))
4359 abbrev = hexsz;
4361 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4362 diff_abbrev_oid(&one->oid, abbrev),
4363 diff_abbrev_oid(&two->oid, abbrev));
4364 if (one->mode == two->mode)
4365 strbuf_addf(msg, " %06o", one->mode);
4366 strbuf_addf(msg, "%s\n", reset);
4370 static void run_diff_cmd(const char *pgm,
4371 const char *name,
4372 const char *other,
4373 const char *attr_path,
4374 struct diff_filespec *one,
4375 struct diff_filespec *two,
4376 struct strbuf *msg,
4377 struct diff_options *o,
4378 struct diff_filepair *p)
4380 const char *xfrm_msg = NULL;
4381 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4382 int must_show_header = 0;
4385 if (o->flags.allow_external) {
4386 struct userdiff_driver *drv;
4388 drv = userdiff_find_by_path(o->repo->index, attr_path);
4389 if (drv && drv->external)
4390 pgm = drv->external;
4393 if (msg) {
4395 * don't use colors when the header is intended for an
4396 * external diff driver
4398 fill_metainfo(msg, name, other, one, two, o, p,
4399 &must_show_header,
4400 want_color(o->use_color) && !pgm);
4401 xfrm_msg = msg->len ? msg->buf : NULL;
4404 if (pgm) {
4405 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4406 return;
4408 if (one && two)
4409 builtin_diff(name, other ? other : name,
4410 one, two, xfrm_msg, must_show_header,
4411 o, complete_rewrite);
4412 else
4413 fprintf(o->file, "* Unmerged path %s\n", name);
4416 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4418 if (DIFF_FILE_VALID(one)) {
4419 if (!one->oid_valid) {
4420 struct stat st;
4421 if (one->is_stdin) {
4422 oidclr(&one->oid);
4423 return;
4425 if (lstat(one->path, &st) < 0)
4426 die_errno("stat '%s'", one->path);
4427 if (index_path(istate, &one->oid, one->path, &st, 0))
4428 die("cannot hash %s", one->path);
4431 else
4432 oidclr(&one->oid);
4435 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4437 /* Strip the prefix but do not molest /dev/null and absolute paths */
4438 if (*namep && !is_absolute_path(*namep)) {
4439 *namep += prefix_length;
4440 if (**namep == '/')
4441 ++*namep;
4443 if (*otherp && !is_absolute_path(*otherp)) {
4444 *otherp += prefix_length;
4445 if (**otherp == '/')
4446 ++*otherp;
4450 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4452 const char *pgm = external_diff();
4453 struct strbuf msg;
4454 struct diff_filespec *one = p->one;
4455 struct diff_filespec *two = p->two;
4456 const char *name;
4457 const char *other;
4458 const char *attr_path;
4460 name = one->path;
4461 other = (strcmp(name, two->path) ? two->path : NULL);
4462 attr_path = name;
4463 if (o->prefix_length)
4464 strip_prefix(o->prefix_length, &name, &other);
4466 if (!o->flags.allow_external)
4467 pgm = NULL;
4469 if (DIFF_PAIR_UNMERGED(p)) {
4470 run_diff_cmd(pgm, name, NULL, attr_path,
4471 NULL, NULL, NULL, o, p);
4472 return;
4475 diff_fill_oid_info(one, o->repo->index);
4476 diff_fill_oid_info(two, o->repo->index);
4478 if (!pgm &&
4479 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4480 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4482 * a filepair that changes between file and symlink
4483 * needs to be split into deletion and creation.
4485 struct diff_filespec *null = alloc_filespec(two->path);
4486 run_diff_cmd(NULL, name, other, attr_path,
4487 one, null, &msg,
4488 o, p);
4489 free(null);
4490 strbuf_release(&msg);
4492 null = alloc_filespec(one->path);
4493 run_diff_cmd(NULL, name, other, attr_path,
4494 null, two, &msg, o, p);
4495 free(null);
4497 else
4498 run_diff_cmd(pgm, name, other, attr_path,
4499 one, two, &msg, o, p);
4501 strbuf_release(&msg);
4504 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4505 struct diffstat_t *diffstat)
4507 const char *name;
4508 const char *other;
4510 if (DIFF_PAIR_UNMERGED(p)) {
4511 /* unmerged */
4512 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4513 diffstat, o, p);
4514 return;
4517 name = p->one->path;
4518 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4520 if (o->prefix_length)
4521 strip_prefix(o->prefix_length, &name, &other);
4523 diff_fill_oid_info(p->one, o->repo->index);
4524 diff_fill_oid_info(p->two, o->repo->index);
4526 builtin_diffstat(name, other, p->one, p->two,
4527 diffstat, o, p);
4530 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4532 const char *name;
4533 const char *other;
4534 const char *attr_path;
4536 if (DIFF_PAIR_UNMERGED(p)) {
4537 /* unmerged */
4538 return;
4541 name = p->one->path;
4542 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4543 attr_path = other ? other : name;
4545 if (o->prefix_length)
4546 strip_prefix(o->prefix_length, &name, &other);
4548 diff_fill_oid_info(p->one, o->repo->index);
4549 diff_fill_oid_info(p->two, o->repo->index);
4551 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4554 static void prep_parse_options(struct diff_options *options);
4556 void repo_diff_setup(struct repository *r, struct diff_options *options)
4558 memcpy(options, &default_diff_options, sizeof(*options));
4560 options->file = stdout;
4561 options->repo = r;
4563 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4564 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4565 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4566 options->abbrev = DEFAULT_ABBREV;
4567 options->line_termination = '\n';
4568 options->break_opt = -1;
4569 options->rename_limit = -1;
4570 options->dirstat_permille = diff_dirstat_permille_default;
4571 options->context = diff_context_default;
4572 options->interhunkcontext = diff_interhunk_context_default;
4573 options->ws_error_highlight = ws_error_highlight_default;
4574 options->flags.rename_empty = 1;
4575 options->flags.relative_name = diff_relative;
4576 options->objfind = NULL;
4578 /* pathchange left =NULL by default */
4579 options->change = diff_change;
4580 options->add_remove = diff_addremove;
4581 options->use_color = diff_use_color_default;
4582 options->detect_rename = diff_detect_rename_default;
4583 options->xdl_opts |= diff_algorithm;
4584 if (diff_indent_heuristic)
4585 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4587 options->orderfile = diff_order_file_cfg;
4589 if (diff_no_prefix) {
4590 options->a_prefix = options->b_prefix = "";
4591 } else if (!diff_mnemonic_prefix) {
4592 options->a_prefix = "a/";
4593 options->b_prefix = "b/";
4596 options->color_moved = diff_color_moved_default;
4597 options->color_moved_ws_handling = diff_color_moved_ws_default;
4599 prep_parse_options(options);
4602 void diff_setup_done(struct diff_options *options)
4604 unsigned check_mask = DIFF_FORMAT_NAME |
4605 DIFF_FORMAT_NAME_STATUS |
4606 DIFF_FORMAT_CHECKDIFF |
4607 DIFF_FORMAT_NO_OUTPUT;
4609 * This must be signed because we're comparing against a potentially
4610 * negative value.
4612 const int hexsz = the_hash_algo->hexsz;
4614 if (options->set_default)
4615 options->set_default(options);
4617 if (HAS_MULTI_BITS(options->output_format & check_mask))
4618 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4620 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4621 die(_("-G, -S and --find-object are mutually exclusive"));
4624 * Most of the time we can say "there are changes"
4625 * only by checking if there are changed paths, but
4626 * --ignore-whitespace* options force us to look
4627 * inside contents.
4630 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4631 options->flags.diff_from_contents = 1;
4632 else
4633 options->flags.diff_from_contents = 0;
4635 if (options->flags.find_copies_harder)
4636 options->detect_rename = DIFF_DETECT_COPY;
4638 if (!options->flags.relative_name)
4639 options->prefix = NULL;
4640 if (options->prefix)
4641 options->prefix_length = strlen(options->prefix);
4642 else
4643 options->prefix_length = 0;
4645 if (options->output_format & (DIFF_FORMAT_NAME |
4646 DIFF_FORMAT_NAME_STATUS |
4647 DIFF_FORMAT_CHECKDIFF |
4648 DIFF_FORMAT_NO_OUTPUT))
4649 options->output_format &= ~(DIFF_FORMAT_RAW |
4650 DIFF_FORMAT_NUMSTAT |
4651 DIFF_FORMAT_DIFFSTAT |
4652 DIFF_FORMAT_SHORTSTAT |
4653 DIFF_FORMAT_DIRSTAT |
4654 DIFF_FORMAT_SUMMARY |
4655 DIFF_FORMAT_PATCH);
4658 * These cases always need recursive; we do not drop caller-supplied
4659 * recursive bits for other formats here.
4661 if (options->output_format & (DIFF_FORMAT_PATCH |
4662 DIFF_FORMAT_NUMSTAT |
4663 DIFF_FORMAT_DIFFSTAT |
4664 DIFF_FORMAT_SHORTSTAT |
4665 DIFF_FORMAT_DIRSTAT |
4666 DIFF_FORMAT_SUMMARY |
4667 DIFF_FORMAT_CHECKDIFF))
4668 options->flags.recursive = 1;
4670 * Also pickaxe would not work very well if you do not say recursive
4672 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4673 options->flags.recursive = 1;
4675 * When patches are generated, submodules diffed against the work tree
4676 * must be checked for dirtiness too so it can be shown in the output
4678 if (options->output_format & DIFF_FORMAT_PATCH)
4679 options->flags.dirty_submodules = 1;
4681 if (options->detect_rename && options->rename_limit < 0)
4682 options->rename_limit = diff_rename_limit_default;
4683 if (hexsz < options->abbrev)
4684 options->abbrev = hexsz; /* full */
4687 * It does not make sense to show the first hit we happened
4688 * to have found. It does not make sense not to return with
4689 * exit code in such a case either.
4691 if (options->flags.quick) {
4692 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4693 options->flags.exit_with_status = 1;
4696 options->diff_path_counter = 0;
4698 if (options->flags.follow_renames && options->pathspec.nr != 1)
4699 die(_("--follow requires exactly one pathspec"));
4701 if (!options->use_color || external_diff())
4702 options->color_moved = 0;
4704 FREE_AND_NULL(options->parseopts);
4707 int parse_long_opt(const char *opt, const char **argv,
4708 const char **optarg)
4710 const char *arg = argv[0];
4711 if (!skip_prefix(arg, "--", &arg))
4712 return 0;
4713 if (!skip_prefix(arg, opt, &arg))
4714 return 0;
4715 if (*arg == '=') { /* stuck form: --option=value */
4716 *optarg = arg + 1;
4717 return 1;
4719 if (*arg != '\0')
4720 return 0;
4721 /* separate form: --option value */
4722 if (!argv[1])
4723 die("Option '--%s' requires a value", opt);
4724 *optarg = argv[1];
4725 return 2;
4728 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4730 struct diff_options *options = opt->value;
4731 int width = options->stat_width;
4732 int name_width = options->stat_name_width;
4733 int graph_width = options->stat_graph_width;
4734 int count = options->stat_count;
4735 char *end;
4737 BUG_ON_OPT_NEG(unset);
4739 if (!strcmp(opt->long_name, "stat")) {
4740 if (value) {
4741 width = strtoul(value, &end, 10);
4742 if (*end == ',')
4743 name_width = strtoul(end+1, &end, 10);
4744 if (*end == ',')
4745 count = strtoul(end+1, &end, 10);
4746 if (*end)
4747 return error(_("invalid --stat value: %s"), value);
4749 } else if (!strcmp(opt->long_name, "stat-width")) {
4750 width = strtoul(value, &end, 10);
4751 if (*end)
4752 return error(_("%s expects a numerical value"),
4753 opt->long_name);
4754 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4755 name_width = strtoul(value, &end, 10);
4756 if (*end)
4757 return error(_("%s expects a numerical value"),
4758 opt->long_name);
4759 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4760 graph_width = strtoul(value, &end, 10);
4761 if (*end)
4762 return error(_("%s expects a numerical value"),
4763 opt->long_name);
4764 } else if (!strcmp(opt->long_name, "stat-count")) {
4765 count = strtoul(value, &end, 10);
4766 if (*end)
4767 return error(_("%s expects a numerical value"),
4768 opt->long_name);
4769 } else
4770 BUG("%s should not get here", opt->long_name);
4772 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4773 options->stat_name_width = name_width;
4774 options->stat_graph_width = graph_width;
4775 options->stat_width = width;
4776 options->stat_count = count;
4777 return 0;
4780 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4782 struct strbuf errmsg = STRBUF_INIT;
4783 if (parse_dirstat_params(options, params, &errmsg))
4784 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4785 errmsg.buf);
4786 strbuf_release(&errmsg);
4788 * The caller knows a dirstat-related option is given from the command
4789 * line; allow it to say "return this_function();"
4791 options->output_format |= DIFF_FORMAT_DIRSTAT;
4792 return 1;
4795 static const char diff_status_letters[] = {
4796 DIFF_STATUS_ADDED,
4797 DIFF_STATUS_COPIED,
4798 DIFF_STATUS_DELETED,
4799 DIFF_STATUS_MODIFIED,
4800 DIFF_STATUS_RENAMED,
4801 DIFF_STATUS_TYPE_CHANGED,
4802 DIFF_STATUS_UNKNOWN,
4803 DIFF_STATUS_UNMERGED,
4804 DIFF_STATUS_FILTER_AON,
4805 DIFF_STATUS_FILTER_BROKEN,
4806 '\0',
4809 static unsigned int filter_bit['Z' + 1];
4811 static void prepare_filter_bits(void)
4813 int i;
4815 if (!filter_bit[DIFF_STATUS_ADDED]) {
4816 for (i = 0; diff_status_letters[i]; i++)
4817 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4821 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4823 return opt->filter & filter_bit[(int) status];
4826 unsigned diff_filter_bit(char status)
4828 prepare_filter_bits();
4829 return filter_bit[(int) status];
4832 static int diff_opt_diff_filter(const struct option *option,
4833 const char *optarg, int unset)
4835 struct diff_options *opt = option->value;
4836 int i, optch;
4838 BUG_ON_OPT_NEG(unset);
4839 prepare_filter_bits();
4842 * If there is a negation e.g. 'd' in the input, and we haven't
4843 * initialized the filter field with another --diff-filter, start
4844 * from full set of bits, except for AON.
4846 if (!opt->filter) {
4847 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4848 if (optch < 'a' || 'z' < optch)
4849 continue;
4850 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4851 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4852 break;
4856 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4857 unsigned int bit;
4858 int negate;
4860 if ('a' <= optch && optch <= 'z') {
4861 negate = 1;
4862 optch = toupper(optch);
4863 } else {
4864 negate = 0;
4867 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4868 if (!bit)
4869 return error(_("unknown change class '%c' in --diff-filter=%s"),
4870 optarg[i], optarg);
4871 if (negate)
4872 opt->filter &= ~bit;
4873 else
4874 opt->filter |= bit;
4876 return 0;
4879 static void enable_patch_output(int *fmt)
4881 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4882 *fmt |= DIFF_FORMAT_PATCH;
4885 static int diff_opt_ws_error_highlight(const struct option *option,
4886 const char *arg, int unset)
4888 struct diff_options *opt = option->value;
4889 int val = parse_ws_error_highlight(arg);
4891 BUG_ON_OPT_NEG(unset);
4892 if (val < 0)
4893 return error(_("unknown value after ws-error-highlight=%.*s"),
4894 -1 - val, arg);
4895 opt->ws_error_highlight = val;
4896 return 0;
4899 static int diff_opt_find_object(const struct option *option,
4900 const char *arg, int unset)
4902 struct diff_options *opt = option->value;
4903 struct object_id oid;
4905 BUG_ON_OPT_NEG(unset);
4906 if (get_oid(arg, &oid))
4907 return error(_("unable to resolve '%s'"), arg);
4909 if (!opt->objfind)
4910 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4912 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4913 opt->flags.recursive = 1;
4914 opt->flags.tree_in_recursive = 1;
4915 oidset_insert(opt->objfind, &oid);
4916 return 0;
4919 static int diff_opt_anchored(const struct option *opt,
4920 const char *arg, int unset)
4922 struct diff_options *options = opt->value;
4924 BUG_ON_OPT_NEG(unset);
4925 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4926 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4927 options->anchors_alloc);
4928 options->anchors[options->anchors_nr++] = xstrdup(arg);
4929 return 0;
4932 static int diff_opt_binary(const struct option *opt,
4933 const char *arg, int unset)
4935 struct diff_options *options = opt->value;
4937 BUG_ON_OPT_NEG(unset);
4938 BUG_ON_OPT_ARG(arg);
4939 enable_patch_output(&options->output_format);
4940 options->flags.binary = 1;
4941 return 0;
4944 static int diff_opt_break_rewrites(const struct option *opt,
4945 const char *arg, int unset)
4947 int *break_opt = opt->value;
4948 int opt1, opt2;
4950 BUG_ON_OPT_NEG(unset);
4951 if (!arg)
4952 arg = "";
4953 opt1 = parse_rename_score(&arg);
4954 if (*arg == 0)
4955 opt2 = 0;
4956 else if (*arg != '/')
4957 return error(_("%s expects <n>/<m> form"), opt->long_name);
4958 else {
4959 arg++;
4960 opt2 = parse_rename_score(&arg);
4962 if (*arg != 0)
4963 return error(_("%s expects <n>/<m> form"), opt->long_name);
4964 *break_opt = opt1 | (opt2 << 16);
4965 return 0;
4968 static int diff_opt_char(const struct option *opt,
4969 const char *arg, int unset)
4971 char *value = opt->value;
4973 BUG_ON_OPT_NEG(unset);
4974 if (arg[1])
4975 return error(_("%s expects a character, got '%s'"),
4976 opt->long_name, arg);
4977 *value = arg[0];
4978 return 0;
4981 static int diff_opt_color_moved(const struct option *opt,
4982 const char *arg, int unset)
4984 struct diff_options *options = opt->value;
4986 if (unset) {
4987 options->color_moved = COLOR_MOVED_NO;
4988 } else if (!arg) {
4989 if (diff_color_moved_default)
4990 options->color_moved = diff_color_moved_default;
4991 if (options->color_moved == COLOR_MOVED_NO)
4992 options->color_moved = COLOR_MOVED_DEFAULT;
4993 } else {
4994 int cm = parse_color_moved(arg);
4995 if (cm < 0)
4996 return error(_("bad --color-moved argument: %s"), arg);
4997 options->color_moved = cm;
4999 return 0;
5002 static int diff_opt_color_moved_ws(const struct option *opt,
5003 const char *arg, int unset)
5005 struct diff_options *options = opt->value;
5006 unsigned cm;
5008 if (unset) {
5009 options->color_moved_ws_handling = 0;
5010 return 0;
5013 cm = parse_color_moved_ws(arg);
5014 if (cm & COLOR_MOVED_WS_ERROR)
5015 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5016 options->color_moved_ws_handling = cm;
5017 return 0;
5020 static int diff_opt_color_words(const struct option *opt,
5021 const char *arg, int unset)
5023 struct diff_options *options = opt->value;
5025 BUG_ON_OPT_NEG(unset);
5026 options->use_color = 1;
5027 options->word_diff = DIFF_WORDS_COLOR;
5028 options->word_regex = arg;
5029 return 0;
5032 static int diff_opt_compact_summary(const struct option *opt,
5033 const char *arg, int unset)
5035 struct diff_options *options = opt->value;
5037 BUG_ON_OPT_ARG(arg);
5038 if (unset) {
5039 options->flags.stat_with_summary = 0;
5040 } else {
5041 options->flags.stat_with_summary = 1;
5042 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5044 return 0;
5047 static int diff_opt_diff_algorithm(const struct option *opt,
5048 const char *arg, int unset)
5050 struct diff_options *options = opt->value;
5051 long value = parse_algorithm_value(arg);
5053 BUG_ON_OPT_NEG(unset);
5054 if (value < 0)
5055 return error(_("option diff-algorithm accepts \"myers\", "
5056 "\"minimal\", \"patience\" and \"histogram\""));
5058 /* clear out previous settings */
5059 DIFF_XDL_CLR(options, NEED_MINIMAL);
5060 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5061 options->xdl_opts |= value;
5062 return 0;
5065 static int diff_opt_dirstat(const struct option *opt,
5066 const char *arg, int unset)
5068 struct diff_options *options = opt->value;
5070 BUG_ON_OPT_NEG(unset);
5071 if (!strcmp(opt->long_name, "cumulative")) {
5072 if (arg)
5073 BUG("how come --cumulative take a value?");
5074 arg = "cumulative";
5075 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5076 parse_dirstat_opt(options, "files");
5077 parse_dirstat_opt(options, arg ? arg : "");
5078 return 0;
5081 static int diff_opt_find_copies(const struct option *opt,
5082 const char *arg, int unset)
5084 struct diff_options *options = opt->value;
5086 BUG_ON_OPT_NEG(unset);
5087 if (!arg)
5088 arg = "";
5089 options->rename_score = parse_rename_score(&arg);
5090 if (*arg != 0)
5091 return error(_("invalid argument to %s"), opt->long_name);
5093 if (options->detect_rename == DIFF_DETECT_COPY)
5094 options->flags.find_copies_harder = 1;
5095 else
5096 options->detect_rename = DIFF_DETECT_COPY;
5098 return 0;
5101 static int diff_opt_find_renames(const struct option *opt,
5102 const char *arg, int unset)
5104 struct diff_options *options = opt->value;
5106 BUG_ON_OPT_NEG(unset);
5107 if (!arg)
5108 arg = "";
5109 options->rename_score = parse_rename_score(&arg);
5110 if (*arg != 0)
5111 return error(_("invalid argument to %s"), opt->long_name);
5113 options->detect_rename = DIFF_DETECT_RENAME;
5114 return 0;
5117 static int diff_opt_follow(const struct option *opt,
5118 const char *arg, int unset)
5120 struct diff_options *options = opt->value;
5122 BUG_ON_OPT_ARG(arg);
5123 if (unset) {
5124 options->flags.follow_renames = 0;
5125 options->flags.default_follow_renames = 0;
5126 } else {
5127 options->flags.follow_renames = 1;
5129 return 0;
5132 static int diff_opt_ignore_submodules(const struct option *opt,
5133 const char *arg, int unset)
5135 struct diff_options *options = opt->value;
5137 BUG_ON_OPT_NEG(unset);
5138 if (!arg)
5139 arg = "all";
5140 options->flags.override_submodule_config = 1;
5141 handle_ignore_submodules_arg(options, arg);
5142 return 0;
5145 static int diff_opt_line_prefix(const struct option *opt,
5146 const char *optarg, int unset)
5148 struct diff_options *options = opt->value;
5150 BUG_ON_OPT_NEG(unset);
5151 options->line_prefix = optarg;
5152 options->line_prefix_length = strlen(options->line_prefix);
5153 graph_setup_line_prefix(options);
5154 return 0;
5157 static int diff_opt_no_prefix(const struct option *opt,
5158 const char *optarg, int unset)
5160 struct diff_options *options = opt->value;
5162 BUG_ON_OPT_NEG(unset);
5163 BUG_ON_OPT_ARG(optarg);
5164 options->a_prefix = "";
5165 options->b_prefix = "";
5166 return 0;
5169 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5170 const struct option *opt,
5171 const char *arg, int unset)
5173 struct diff_options *options = opt->value;
5174 char *path;
5176 BUG_ON_OPT_NEG(unset);
5177 path = prefix_filename(ctx->prefix, arg);
5178 options->file = xfopen(path, "w");
5179 options->close_file = 1;
5180 if (options->use_color != GIT_COLOR_ALWAYS)
5181 options->use_color = GIT_COLOR_NEVER;
5182 free(path);
5183 return 0;
5186 static int diff_opt_patience(const struct option *opt,
5187 const char *arg, int unset)
5189 struct diff_options *options = opt->value;
5190 int i;
5192 BUG_ON_OPT_NEG(unset);
5193 BUG_ON_OPT_ARG(arg);
5194 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5196 * Both --patience and --anchored use PATIENCE_DIFF
5197 * internally, so remove any anchors previously
5198 * specified.
5200 for (i = 0; i < options->anchors_nr; i++)
5201 free(options->anchors[i]);
5202 options->anchors_nr = 0;
5203 return 0;
5206 static int diff_opt_pickaxe_regex(const struct option *opt,
5207 const char *arg, int unset)
5209 struct diff_options *options = opt->value;
5211 BUG_ON_OPT_NEG(unset);
5212 options->pickaxe = arg;
5213 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5214 return 0;
5217 static int diff_opt_pickaxe_string(const struct option *opt,
5218 const char *arg, int unset)
5220 struct diff_options *options = opt->value;
5222 BUG_ON_OPT_NEG(unset);
5223 options->pickaxe = arg;
5224 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5225 return 0;
5228 static int diff_opt_relative(const struct option *opt,
5229 const char *arg, int unset)
5231 struct diff_options *options = opt->value;
5233 options->flags.relative_name = !unset;
5234 if (arg)
5235 options->prefix = arg;
5236 return 0;
5239 static int diff_opt_submodule(const struct option *opt,
5240 const char *arg, int unset)
5242 struct diff_options *options = opt->value;
5244 BUG_ON_OPT_NEG(unset);
5245 if (!arg)
5246 arg = "log";
5247 if (parse_submodule_params(options, arg))
5248 return error(_("failed to parse --submodule option parameter: '%s'"),
5249 arg);
5250 return 0;
5253 static int diff_opt_textconv(const struct option *opt,
5254 const char *arg, int unset)
5256 struct diff_options *options = opt->value;
5258 BUG_ON_OPT_ARG(arg);
5259 if (unset) {
5260 options->flags.allow_textconv = 0;
5261 } else {
5262 options->flags.allow_textconv = 1;
5263 options->flags.textconv_set_via_cmdline = 1;
5265 return 0;
5268 static int diff_opt_unified(const struct option *opt,
5269 const char *arg, int unset)
5271 struct diff_options *options = opt->value;
5272 char *s;
5274 BUG_ON_OPT_NEG(unset);
5276 if (arg) {
5277 options->context = strtol(arg, &s, 10);
5278 if (*s)
5279 return error(_("%s expects a numerical value"), "--unified");
5281 enable_patch_output(&options->output_format);
5283 return 0;
5286 static int diff_opt_word_diff(const struct option *opt,
5287 const char *arg, int unset)
5289 struct diff_options *options = opt->value;
5291 BUG_ON_OPT_NEG(unset);
5292 if (arg) {
5293 if (!strcmp(arg, "plain"))
5294 options->word_diff = DIFF_WORDS_PLAIN;
5295 else if (!strcmp(arg, "color")) {
5296 options->use_color = 1;
5297 options->word_diff = DIFF_WORDS_COLOR;
5299 else if (!strcmp(arg, "porcelain"))
5300 options->word_diff = DIFF_WORDS_PORCELAIN;
5301 else if (!strcmp(arg, "none"))
5302 options->word_diff = DIFF_WORDS_NONE;
5303 else
5304 return error(_("bad --word-diff argument: %s"), arg);
5305 } else {
5306 if (options->word_diff == DIFF_WORDS_NONE)
5307 options->word_diff = DIFF_WORDS_PLAIN;
5309 return 0;
5312 static int diff_opt_word_diff_regex(const struct option *opt,
5313 const char *arg, int unset)
5315 struct diff_options *options = opt->value;
5317 BUG_ON_OPT_NEG(unset);
5318 if (options->word_diff == DIFF_WORDS_NONE)
5319 options->word_diff = DIFF_WORDS_PLAIN;
5320 options->word_regex = arg;
5321 return 0;
5324 static void prep_parse_options(struct diff_options *options)
5326 struct option parseopts[] = {
5327 OPT_GROUP(N_("Diff output format options")),
5328 OPT_BITOP('p', "patch", &options->output_format,
5329 N_("generate patch"),
5330 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5331 OPT_BIT_F('s', "no-patch", &options->output_format,
5332 N_("suppress diff output"),
5333 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5334 OPT_BITOP('u', NULL, &options->output_format,
5335 N_("generate patch"),
5336 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5337 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5338 N_("generate diffs with <n> lines context"),
5339 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
5340 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5341 N_("generate diffs with <n> lines context")),
5342 OPT_BIT_F(0, "raw", &options->output_format,
5343 N_("generate the diff in raw format"),
5344 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5345 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5346 N_("synonym for '-p --raw'"),
5347 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5348 DIFF_FORMAT_NO_OUTPUT),
5349 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5350 N_("synonym for '-p --stat'"),
5351 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5352 DIFF_FORMAT_NO_OUTPUT),
5353 OPT_BIT_F(0, "numstat", &options->output_format,
5354 N_("machine friendly --stat"),
5355 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5356 OPT_BIT_F(0, "shortstat", &options->output_format,
5357 N_("output only the last line of --stat"),
5358 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5359 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5360 N_("output the distribution of relative amount of changes for each sub-directory"),
5361 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5362 diff_opt_dirstat),
5363 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5364 N_("synonym for --dirstat=cumulative"),
5365 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5366 diff_opt_dirstat),
5367 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5368 N_("synonym for --dirstat=files,param1,param2..."),
5369 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5370 diff_opt_dirstat),
5371 OPT_BIT_F(0, "check", &options->output_format,
5372 N_("warn if changes introduce conflict markers or whitespace errors"),
5373 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5374 OPT_BIT_F(0, "summary", &options->output_format,
5375 N_("condensed summary such as creations, renames and mode changes"),
5376 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5377 OPT_BIT_F(0, "name-only", &options->output_format,
5378 N_("show only names of changed files"),
5379 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5380 OPT_BIT_F(0, "name-status", &options->output_format,
5381 N_("show only names and status of changed files"),
5382 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5383 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5384 N_("generate diffstat"),
5385 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5386 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5387 N_("generate diffstat with a given width"),
5388 PARSE_OPT_NONEG, diff_opt_stat),
5389 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5390 N_("generate diffstat with a given name width"),
5391 PARSE_OPT_NONEG, diff_opt_stat),
5392 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5393 N_("generate diffstat with a given graph width"),
5394 PARSE_OPT_NONEG, diff_opt_stat),
5395 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5396 N_("generate diffstat with limited lines"),
5397 PARSE_OPT_NONEG, diff_opt_stat),
5398 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5399 N_("generate compact summary in diffstat"),
5400 PARSE_OPT_NOARG, diff_opt_compact_summary),
5401 OPT_CALLBACK_F(0, "binary", options, NULL,
5402 N_("output a binary diff that can be applied"),
5403 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5404 OPT_BOOL(0, "full-index", &options->flags.full_index,
5405 N_("show full pre- and post-image object names on the \"index\" lines")),
5406 OPT_COLOR_FLAG(0, "color", &options->use_color,
5407 N_("show colored diff")),
5408 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5409 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5410 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5411 OPT_SET_INT('z', NULL, &options->line_termination,
5412 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5414 OPT__ABBREV(&options->abbrev),
5415 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5416 N_("show the given source prefix instead of \"a/\""),
5417 PARSE_OPT_NONEG),
5418 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5419 N_("show the given destination prefix instead of \"b/\""),
5420 PARSE_OPT_NONEG),
5421 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5422 N_("prepend an additional prefix to every line of output"),
5423 PARSE_OPT_NONEG, diff_opt_line_prefix),
5424 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5425 N_("do not show any source or destination prefix"),
5426 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5427 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5428 N_("show context between diff hunks up to the specified number of lines"),
5429 PARSE_OPT_NONEG),
5430 OPT_CALLBACK_F(0, "output-indicator-new",
5431 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5432 N_("<char>"),
5433 N_("specify the character to indicate a new line instead of '+'"),
5434 PARSE_OPT_NONEG, diff_opt_char),
5435 OPT_CALLBACK_F(0, "output-indicator-old",
5436 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5437 N_("<char>"),
5438 N_("specify the character to indicate an old line instead of '-'"),
5439 PARSE_OPT_NONEG, diff_opt_char),
5440 OPT_CALLBACK_F(0, "output-indicator-context",
5441 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5442 N_("<char>"),
5443 N_("specify the character to indicate a context instead of ' '"),
5444 PARSE_OPT_NONEG, diff_opt_char),
5446 OPT_GROUP(N_("Diff rename options")),
5447 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5448 N_("break complete rewrite changes into pairs of delete and create"),
5449 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5450 diff_opt_break_rewrites),
5451 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5452 N_("detect renames"),
5453 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5454 diff_opt_find_renames),
5455 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5456 N_("omit the preimage for deletes"),
5457 1, PARSE_OPT_NONEG),
5458 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5459 N_("detect copies"),
5460 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5461 diff_opt_find_copies),
5462 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5463 N_("use unmodified files as source to find copies")),
5464 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5465 N_("disable rename detection"),
5466 0, PARSE_OPT_NONEG),
5467 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5468 N_("use empty blobs as rename source")),
5469 OPT_CALLBACK_F(0, "follow", options, NULL,
5470 N_("continue listing the history of a file beyond renames"),
5471 PARSE_OPT_NOARG, diff_opt_follow),
5472 OPT_INTEGER('l', NULL, &options->rename_limit,
5473 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5475 OPT_GROUP(N_("Diff algorithm options")),
5476 OPT_BIT(0, "minimal", &options->xdl_opts,
5477 N_("produce the smallest possible diff"),
5478 XDF_NEED_MINIMAL),
5479 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5480 N_("ignore whitespace when comparing lines"),
5481 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5482 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5483 N_("ignore changes in amount of whitespace"),
5484 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5485 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5486 N_("ignore changes in whitespace at EOL"),
5487 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5488 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5489 N_("ignore carrier-return at the end of line"),
5490 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5491 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5492 N_("ignore changes whose lines are all blank"),
5493 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5494 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5495 N_("heuristic to shift diff hunk boundaries for easy reading"),
5496 XDF_INDENT_HEURISTIC),
5497 OPT_CALLBACK_F(0, "patience", options, NULL,
5498 N_("generate diff using the \"patience diff\" algorithm"),
5499 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5500 diff_opt_patience),
5501 OPT_BITOP(0, "histogram", &options->xdl_opts,
5502 N_("generate diff using the \"histogram diff\" algorithm"),
5503 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5504 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5505 N_("choose a diff algorithm"),
5506 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5507 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5508 N_("generate diff using the \"anchored diff\" algorithm"),
5509 PARSE_OPT_NONEG, diff_opt_anchored),
5510 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5511 N_("show word diff, using <mode> to delimit changed words"),
5512 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5513 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5514 N_("use <regex> to decide what a word is"),
5515 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5516 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5517 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5518 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5519 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5520 N_("moved lines of code are colored differently"),
5521 PARSE_OPT_OPTARG, diff_opt_color_moved),
5522 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5523 N_("how white spaces are ignored in --color-moved"),
5524 0, diff_opt_color_moved_ws),
5526 OPT_GROUP(N_("Other diff options")),
5527 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5528 N_("when run from subdir, exclude changes outside and show relative paths"),
5529 PARSE_OPT_OPTARG,
5530 diff_opt_relative),
5531 OPT_BOOL('a', "text", &options->flags.text,
5532 N_("treat all files as text")),
5533 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5534 N_("swap two inputs, reverse the diff")),
5535 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5536 N_("exit with 1 if there were differences, 0 otherwise")),
5537 OPT_BOOL(0, "quiet", &options->flags.quick,
5538 N_("disable all output of the program")),
5539 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5540 N_("allow an external diff helper to be executed")),
5541 OPT_CALLBACK_F(0, "textconv", options, NULL,
5542 N_("run external text conversion filters when comparing binary files"),
5543 PARSE_OPT_NOARG, diff_opt_textconv),
5544 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5545 N_("ignore changes to submodules in the diff generation"),
5546 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5547 diff_opt_ignore_submodules),
5548 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5549 N_("specify how differences in submodules are shown"),
5550 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5551 diff_opt_submodule),
5552 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5553 N_("hide 'git add -N' entries from the index"),
5554 1, PARSE_OPT_NONEG),
5555 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5556 N_("treat 'git add -N' entries as real in the index"),
5557 0, PARSE_OPT_NONEG),
5558 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5559 N_("look for differences that change the number of occurrences of the specified string"),
5560 0, diff_opt_pickaxe_string),
5561 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5562 N_("look for differences that change the number of occurrences of the specified regex"),
5563 0, diff_opt_pickaxe_regex),
5564 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5565 N_("show all changes in the changeset with -S or -G"),
5566 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5567 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5568 N_("treat <string> in -S as extended POSIX regular expression"),
5569 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5570 OPT_FILENAME('O', NULL, &options->orderfile,
5571 N_("control the order in which files appear in the output")),
5572 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5573 N_("look for differences that change the number of occurrences of the specified object"),
5574 PARSE_OPT_NONEG, diff_opt_find_object),
5575 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5576 N_("select files by diff type"),
5577 PARSE_OPT_NONEG, diff_opt_diff_filter),
5578 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5579 N_("Output to a specific file"),
5580 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5582 OPT_END()
5585 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5586 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5589 int diff_opt_parse(struct diff_options *options,
5590 const char **av, int ac, const char *prefix)
5592 if (!prefix)
5593 prefix = "";
5595 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5596 PARSE_OPT_KEEP_DASHDASH |
5597 PARSE_OPT_KEEP_UNKNOWN |
5598 PARSE_OPT_NO_INTERNAL_HELP |
5599 PARSE_OPT_ONE_SHOT |
5600 PARSE_OPT_STOP_AT_NON_OPTION);
5602 return ac;
5605 int parse_rename_score(const char **cp_p)
5607 unsigned long num, scale;
5608 int ch, dot;
5609 const char *cp = *cp_p;
5611 num = 0;
5612 scale = 1;
5613 dot = 0;
5614 for (;;) {
5615 ch = *cp;
5616 if ( !dot && ch == '.' ) {
5617 scale = 1;
5618 dot = 1;
5619 } else if ( ch == '%' ) {
5620 scale = dot ? scale*100 : 100;
5621 cp++; /* % is always at the end */
5622 break;
5623 } else if ( ch >= '0' && ch <= '9' ) {
5624 if ( scale < 100000 ) {
5625 scale *= 10;
5626 num = (num*10) + (ch-'0');
5628 } else {
5629 break;
5631 cp++;
5633 *cp_p = cp;
5635 /* user says num divided by scale and we say internally that
5636 * is MAX_SCORE * num / scale.
5638 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5641 struct diff_queue_struct diff_queued_diff;
5643 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5645 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5646 queue->queue[queue->nr++] = dp;
5649 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5650 struct diff_filespec *one,
5651 struct diff_filespec *two)
5653 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5654 dp->one = one;
5655 dp->two = two;
5656 if (queue)
5657 diff_q(queue, dp);
5658 return dp;
5661 void diff_free_filepair(struct diff_filepair *p)
5663 free_filespec(p->one);
5664 free_filespec(p->two);
5665 free(p);
5668 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5670 int abblen;
5671 const char *abbrev;
5673 /* Do we want all 40 hex characters? */
5674 if (len == the_hash_algo->hexsz)
5675 return oid_to_hex(oid);
5677 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5678 abbrev = diff_abbrev_oid(oid, len);
5680 if (!print_sha1_ellipsis())
5681 return abbrev;
5683 abblen = strlen(abbrev);
5686 * In well-behaved cases, where the abbreviated result is the
5687 * same as the requested length, append three dots after the
5688 * abbreviation (hence the whole logic is limited to the case
5689 * where abblen < 37); when the actual abbreviated result is a
5690 * bit longer than the requested length, we reduce the number
5691 * of dots so that they match the well-behaved ones. However,
5692 * if the actual abbreviation is longer than the requested
5693 * length by more than three, we give up on aligning, and add
5694 * three dots anyway, to indicate that the output is not the
5695 * full object name. Yes, this may be suboptimal, but this
5696 * appears only in "diff --raw --abbrev" output and it is not
5697 * worth the effort to change it now. Note that this would
5698 * likely to work fine when the automatic sizing of default
5699 * abbreviation length is used--we would be fed -1 in "len" in
5700 * that case, and will end up always appending three-dots, but
5701 * the automatic sizing is supposed to give abblen that ensures
5702 * uniqueness across all objects (statistically speaking).
5704 if (abblen < the_hash_algo->hexsz - 3) {
5705 static char hex[GIT_MAX_HEXSZ + 1];
5706 if (len < abblen && abblen <= len + 2)
5707 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5708 else
5709 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5710 return hex;
5713 return oid_to_hex(oid);
5716 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5718 int line_termination = opt->line_termination;
5719 int inter_name_termination = line_termination ? '\t' : '\0';
5721 fprintf(opt->file, "%s", diff_line_prefix(opt));
5722 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5723 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5724 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5725 fprintf(opt->file, "%s ",
5726 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5728 if (p->score) {
5729 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5730 inter_name_termination);
5731 } else {
5732 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5735 if (p->status == DIFF_STATUS_COPIED ||
5736 p->status == DIFF_STATUS_RENAMED) {
5737 const char *name_a, *name_b;
5738 name_a = p->one->path;
5739 name_b = p->two->path;
5740 strip_prefix(opt->prefix_length, &name_a, &name_b);
5741 write_name_quoted(name_a, opt->file, inter_name_termination);
5742 write_name_quoted(name_b, opt->file, line_termination);
5743 } else {
5744 const char *name_a, *name_b;
5745 name_a = p->one->mode ? p->one->path : p->two->path;
5746 name_b = NULL;
5747 strip_prefix(opt->prefix_length, &name_a, &name_b);
5748 write_name_quoted(name_a, opt->file, line_termination);
5752 int diff_unmodified_pair(struct diff_filepair *p)
5754 /* This function is written stricter than necessary to support
5755 * the currently implemented transformers, but the idea is to
5756 * let transformers to produce diff_filepairs any way they want,
5757 * and filter and clean them up here before producing the output.
5759 struct diff_filespec *one = p->one, *two = p->two;
5761 if (DIFF_PAIR_UNMERGED(p))
5762 return 0; /* unmerged is interesting */
5764 /* deletion, addition, mode or type change
5765 * and rename are all interesting.
5767 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5768 DIFF_PAIR_MODE_CHANGED(p) ||
5769 strcmp(one->path, two->path))
5770 return 0;
5772 /* both are valid and point at the same path. that is, we are
5773 * dealing with a change.
5775 if (one->oid_valid && two->oid_valid &&
5776 oideq(&one->oid, &two->oid) &&
5777 !one->dirty_submodule && !two->dirty_submodule)
5778 return 1; /* no change */
5779 if (!one->oid_valid && !two->oid_valid)
5780 return 1; /* both look at the same file on the filesystem. */
5781 return 0;
5784 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5786 if (diff_unmodified_pair(p))
5787 return;
5789 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5790 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5791 return; /* no tree diffs in patch format */
5793 run_diff(p, o);
5796 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5797 struct diffstat_t *diffstat)
5799 if (diff_unmodified_pair(p))
5800 return;
5802 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5803 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5804 return; /* no useful stat for tree diffs */
5806 run_diffstat(p, o, diffstat);
5809 static void diff_flush_checkdiff(struct diff_filepair *p,
5810 struct diff_options *o)
5812 if (diff_unmodified_pair(p))
5813 return;
5815 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5816 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5817 return; /* nothing to check in tree diffs */
5819 run_checkdiff(p, o);
5822 int diff_queue_is_empty(void)
5824 struct diff_queue_struct *q = &diff_queued_diff;
5825 int i;
5826 for (i = 0; i < q->nr; i++)
5827 if (!diff_unmodified_pair(q->queue[i]))
5828 return 0;
5829 return 1;
5832 #if DIFF_DEBUG
5833 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5835 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5836 x, one ? one : "",
5837 s->path,
5838 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5839 s->mode,
5840 s->oid_valid ? oid_to_hex(&s->oid) : "");
5841 fprintf(stderr, "queue[%d] %s size %lu\n",
5842 x, one ? one : "",
5843 s->size);
5846 void diff_debug_filepair(const struct diff_filepair *p, int i)
5848 diff_debug_filespec(p->one, i, "one");
5849 diff_debug_filespec(p->two, i, "two");
5850 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5851 p->score, p->status ? p->status : '?',
5852 p->one->rename_used, p->broken_pair);
5855 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5857 int i;
5858 if (msg)
5859 fprintf(stderr, "%s\n", msg);
5860 fprintf(stderr, "q->nr = %d\n", q->nr);
5861 for (i = 0; i < q->nr; i++) {
5862 struct diff_filepair *p = q->queue[i];
5863 diff_debug_filepair(p, i);
5866 #endif
5868 static void diff_resolve_rename_copy(void)
5870 int i;
5871 struct diff_filepair *p;
5872 struct diff_queue_struct *q = &diff_queued_diff;
5874 diff_debug_queue("resolve-rename-copy", q);
5876 for (i = 0; i < q->nr; i++) {
5877 p = q->queue[i];
5878 p->status = 0; /* undecided */
5879 if (DIFF_PAIR_UNMERGED(p))
5880 p->status = DIFF_STATUS_UNMERGED;
5881 else if (!DIFF_FILE_VALID(p->one))
5882 p->status = DIFF_STATUS_ADDED;
5883 else if (!DIFF_FILE_VALID(p->two))
5884 p->status = DIFF_STATUS_DELETED;
5885 else if (DIFF_PAIR_TYPE_CHANGED(p))
5886 p->status = DIFF_STATUS_TYPE_CHANGED;
5888 /* from this point on, we are dealing with a pair
5889 * whose both sides are valid and of the same type, i.e.
5890 * either in-place edit or rename/copy edit.
5892 else if (DIFF_PAIR_RENAME(p)) {
5894 * A rename might have re-connected a broken
5895 * pair up, causing the pathnames to be the
5896 * same again. If so, that's not a rename at
5897 * all, just a modification..
5899 * Otherwise, see if this source was used for
5900 * multiple renames, in which case we decrement
5901 * the count, and call it a copy.
5903 if (!strcmp(p->one->path, p->two->path))
5904 p->status = DIFF_STATUS_MODIFIED;
5905 else if (--p->one->rename_used > 0)
5906 p->status = DIFF_STATUS_COPIED;
5907 else
5908 p->status = DIFF_STATUS_RENAMED;
5910 else if (!oideq(&p->one->oid, &p->two->oid) ||
5911 p->one->mode != p->two->mode ||
5912 p->one->dirty_submodule ||
5913 p->two->dirty_submodule ||
5914 is_null_oid(&p->one->oid))
5915 p->status = DIFF_STATUS_MODIFIED;
5916 else {
5917 /* This is a "no-change" entry and should not
5918 * happen anymore, but prepare for broken callers.
5920 error("feeding unmodified %s to diffcore",
5921 p->one->path);
5922 p->status = DIFF_STATUS_UNKNOWN;
5925 diff_debug_queue("resolve-rename-copy done", q);
5928 static int check_pair_status(struct diff_filepair *p)
5930 switch (p->status) {
5931 case DIFF_STATUS_UNKNOWN:
5932 return 0;
5933 case 0:
5934 die("internal error in diff-resolve-rename-copy");
5935 default:
5936 return 1;
5940 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5942 int fmt = opt->output_format;
5944 if (fmt & DIFF_FORMAT_CHECKDIFF)
5945 diff_flush_checkdiff(p, opt);
5946 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5947 diff_flush_raw(p, opt);
5948 else if (fmt & DIFF_FORMAT_NAME) {
5949 const char *name_a, *name_b;
5950 name_a = p->two->path;
5951 name_b = NULL;
5952 strip_prefix(opt->prefix_length, &name_a, &name_b);
5953 fprintf(opt->file, "%s", diff_line_prefix(opt));
5954 write_name_quoted(name_a, opt->file, opt->line_termination);
5958 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5960 struct strbuf sb = STRBUF_INIT;
5961 if (fs->mode)
5962 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5963 else
5964 strbuf_addf(&sb, " %s ", newdelete);
5966 quote_c_style(fs->path, &sb, NULL, 0);
5967 strbuf_addch(&sb, '\n');
5968 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5969 sb.buf, sb.len, 0);
5970 strbuf_release(&sb);
5973 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5974 int show_name)
5976 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5977 struct strbuf sb = STRBUF_INIT;
5978 strbuf_addf(&sb, " mode change %06o => %06o",
5979 p->one->mode, p->two->mode);
5980 if (show_name) {
5981 strbuf_addch(&sb, ' ');
5982 quote_c_style(p->two->path, &sb, NULL, 0);
5984 strbuf_addch(&sb, '\n');
5985 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5986 sb.buf, sb.len, 0);
5987 strbuf_release(&sb);
5991 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5992 struct diff_filepair *p)
5994 struct strbuf sb = STRBUF_INIT;
5995 struct strbuf names = STRBUF_INIT;
5997 pprint_rename(&names, p->one->path, p->two->path);
5998 strbuf_addf(&sb, " %s %s (%d%%)\n",
5999 renamecopy, names.buf, similarity_index(p));
6000 strbuf_release(&names);
6001 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6002 sb.buf, sb.len, 0);
6003 show_mode_change(opt, p, 0);
6004 strbuf_release(&sb);
6007 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
6009 switch(p->status) {
6010 case DIFF_STATUS_DELETED:
6011 show_file_mode_name(opt, "delete", p->one);
6012 break;
6013 case DIFF_STATUS_ADDED:
6014 show_file_mode_name(opt, "create", p->two);
6015 break;
6016 case DIFF_STATUS_COPIED:
6017 show_rename_copy(opt, "copy", p);
6018 break;
6019 case DIFF_STATUS_RENAMED:
6020 show_rename_copy(opt, "rename", p);
6021 break;
6022 default:
6023 if (p->score) {
6024 struct strbuf sb = STRBUF_INIT;
6025 strbuf_addstr(&sb, " rewrite ");
6026 quote_c_style(p->two->path, &sb, NULL, 0);
6027 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6028 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6029 sb.buf, sb.len, 0);
6030 strbuf_release(&sb);
6032 show_mode_change(opt, p, !p->score);
6033 break;
6037 struct patch_id_t {
6038 git_hash_ctx *ctx;
6039 int patchlen;
6042 static int remove_space(char *line, int len)
6044 int i;
6045 char *dst = line;
6046 unsigned char c;
6048 for (i = 0; i < len; i++)
6049 if (!isspace((c = line[i])))
6050 *dst++ = c;
6052 return dst - line;
6055 void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
6057 unsigned char hash[GIT_MAX_RAWSZ];
6058 unsigned short carry = 0;
6059 int i;
6061 the_hash_algo->final_fn(hash, ctx);
6062 the_hash_algo->init_fn(ctx);
6063 /* 20-byte sum, with carry */
6064 for (i = 0; i < the_hash_algo->rawsz; ++i) {
6065 carry += result->hash[i] + hash[i];
6066 result->hash[i] = carry;
6067 carry >>= 8;
6071 static void patch_id_consume(void *priv, char *line, unsigned long len)
6073 struct patch_id_t *data = priv;
6074 int new_len;
6076 if (len > 12 && starts_with(line, "\\ "))
6077 return;
6078 new_len = remove_space(line, len);
6080 the_hash_algo->update_fn(data->ctx, line, new_len);
6081 data->patchlen += new_len;
6084 static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
6086 the_hash_algo->update_fn(ctx, str, strlen(str));
6089 static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
6091 /* large enough for 2^32 in octal */
6092 char buf[12];
6093 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6094 the_hash_algo->update_fn(ctx, buf, len);
6097 /* returns 0 upon success, and writes result into oid */
6098 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6100 struct diff_queue_struct *q = &diff_queued_diff;
6101 int i;
6102 git_hash_ctx ctx;
6103 struct patch_id_t data;
6105 the_hash_algo->init_fn(&ctx);
6106 memset(&data, 0, sizeof(struct patch_id_t));
6107 data.ctx = &ctx;
6108 oidclr(oid);
6110 for (i = 0; i < q->nr; i++) {
6111 xpparam_t xpp;
6112 xdemitconf_t xecfg;
6113 mmfile_t mf1, mf2;
6114 struct diff_filepair *p = q->queue[i];
6115 int len1, len2;
6117 memset(&xpp, 0, sizeof(xpp));
6118 memset(&xecfg, 0, sizeof(xecfg));
6119 if (p->status == 0)
6120 return error("internal diff status error");
6121 if (p->status == DIFF_STATUS_UNKNOWN)
6122 continue;
6123 if (diff_unmodified_pair(p))
6124 continue;
6125 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6126 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6127 continue;
6128 if (DIFF_PAIR_UNMERGED(p))
6129 continue;
6131 diff_fill_oid_info(p->one, options->repo->index);
6132 diff_fill_oid_info(p->two, options->repo->index);
6134 len1 = remove_space(p->one->path, strlen(p->one->path));
6135 len2 = remove_space(p->two->path, strlen(p->two->path));
6136 patch_id_add_string(&ctx, "diff--git");
6137 patch_id_add_string(&ctx, "a/");
6138 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6139 patch_id_add_string(&ctx, "b/");
6140 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6142 if (p->one->mode == 0) {
6143 patch_id_add_string(&ctx, "newfilemode");
6144 patch_id_add_mode(&ctx, p->two->mode);
6145 patch_id_add_string(&ctx, "---/dev/null");
6146 patch_id_add_string(&ctx, "+++b/");
6147 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6148 } else if (p->two->mode == 0) {
6149 patch_id_add_string(&ctx, "deletedfilemode");
6150 patch_id_add_mode(&ctx, p->one->mode);
6151 patch_id_add_string(&ctx, "---a/");
6152 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6153 patch_id_add_string(&ctx, "+++/dev/null");
6154 } else {
6155 patch_id_add_string(&ctx, "---a/");
6156 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6157 patch_id_add_string(&ctx, "+++b/");
6158 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6161 if (diff_header_only)
6162 continue;
6164 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6165 fill_mmfile(options->repo, &mf2, p->two) < 0)
6166 return error("unable to read files to diff");
6168 if (diff_filespec_is_binary(options->repo, p->one) ||
6169 diff_filespec_is_binary(options->repo, p->two)) {
6170 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6171 the_hash_algo->hexsz);
6172 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6173 the_hash_algo->hexsz);
6174 continue;
6177 xpp.flags = 0;
6178 xecfg.ctxlen = 3;
6179 xecfg.flags = 0;
6180 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
6181 patch_id_consume, &data, &xpp, &xecfg))
6182 return error("unable to generate patch-id diff for %s",
6183 p->one->path);
6185 if (stable)
6186 flush_one_hunk(oid, &ctx);
6189 if (!stable)
6190 the_hash_algo->final_fn(oid->hash, &ctx);
6192 return 0;
6195 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
6197 struct diff_queue_struct *q = &diff_queued_diff;
6198 int i;
6199 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
6201 for (i = 0; i < q->nr; i++)
6202 diff_free_filepair(q->queue[i]);
6204 free(q->queue);
6205 DIFF_QUEUE_CLEAR(q);
6207 return result;
6210 static int is_summary_empty(const struct diff_queue_struct *q)
6212 int i;
6214 for (i = 0; i < q->nr; i++) {
6215 const struct diff_filepair *p = q->queue[i];
6217 switch (p->status) {
6218 case DIFF_STATUS_DELETED:
6219 case DIFF_STATUS_ADDED:
6220 case DIFF_STATUS_COPIED:
6221 case DIFF_STATUS_RENAMED:
6222 return 0;
6223 default:
6224 if (p->score)
6225 return 0;
6226 if (p->one->mode && p->two->mode &&
6227 p->one->mode != p->two->mode)
6228 return 0;
6229 break;
6232 return 1;
6235 static const char rename_limit_warning[] =
6236 N_("inexact rename detection was skipped due to too many files.");
6238 static const char degrade_cc_to_c_warning[] =
6239 N_("only found copies from modified paths due to too many files.");
6241 static const char rename_limit_advice[] =
6242 N_("you may want to set your %s variable to at least "
6243 "%d and retry the command.");
6245 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6247 fflush(stdout);
6248 if (degraded_cc)
6249 warning(_(degrade_cc_to_c_warning));
6250 else if (needed)
6251 warning(_(rename_limit_warning));
6252 else
6253 return;
6254 if (0 < needed)
6255 warning(_(rename_limit_advice), varname, needed);
6258 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6260 int i;
6261 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6262 struct diff_queue_struct *q = &diff_queued_diff;
6264 if (WSEH_NEW & WS_RULE_MASK)
6265 BUG("WS rules bit mask overlaps with diff symbol flags");
6267 if (o->color_moved)
6268 o->emitted_symbols = &esm;
6270 for (i = 0; i < q->nr; i++) {
6271 struct diff_filepair *p = q->queue[i];
6272 if (check_pair_status(p))
6273 diff_flush_patch(p, o);
6276 if (o->emitted_symbols) {
6277 if (o->color_moved) {
6278 struct hashmap add_lines, del_lines;
6280 if (o->color_moved_ws_handling &
6281 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
6282 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
6284 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
6285 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
6287 add_lines_to_move_detection(o, &add_lines, &del_lines);
6288 mark_color_as_moved(o, &add_lines, &del_lines);
6289 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6290 dim_moved_lines(o);
6292 hashmap_free_entries(&add_lines, struct moved_entry,
6293 ent);
6294 hashmap_free_entries(&del_lines, struct moved_entry,
6295 ent);
6298 for (i = 0; i < esm.nr; i++)
6299 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6301 for (i = 0; i < esm.nr; i++)
6302 free((void *)esm.buf[i].line);
6303 esm.nr = 0;
6305 o->emitted_symbols = NULL;
6309 void diff_flush(struct diff_options *options)
6311 struct diff_queue_struct *q = &diff_queued_diff;
6312 int i, output_format = options->output_format;
6313 int separator = 0;
6314 int dirstat_by_line = 0;
6317 * Order: raw, stat, summary, patch
6318 * or: name/name-status/checkdiff (other bits clear)
6320 if (!q->nr)
6321 goto free_queue;
6323 if (output_format & (DIFF_FORMAT_RAW |
6324 DIFF_FORMAT_NAME |
6325 DIFF_FORMAT_NAME_STATUS |
6326 DIFF_FORMAT_CHECKDIFF)) {
6327 for (i = 0; i < q->nr; i++) {
6328 struct diff_filepair *p = q->queue[i];
6329 if (check_pair_status(p))
6330 flush_one_pair(p, options);
6332 separator++;
6335 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6336 dirstat_by_line = 1;
6338 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6339 dirstat_by_line) {
6340 struct diffstat_t diffstat;
6342 compute_diffstat(options, &diffstat, q);
6343 if (output_format & DIFF_FORMAT_NUMSTAT)
6344 show_numstat(&diffstat, options);
6345 if (output_format & DIFF_FORMAT_DIFFSTAT)
6346 show_stats(&diffstat, options);
6347 if (output_format & DIFF_FORMAT_SHORTSTAT)
6348 show_shortstats(&diffstat, options);
6349 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6350 show_dirstat_by_line(&diffstat, options);
6351 free_diffstat_info(&diffstat);
6352 separator++;
6354 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6355 show_dirstat(options);
6357 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6358 for (i = 0; i < q->nr; i++) {
6359 diff_summary(options, q->queue[i]);
6361 separator++;
6364 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6365 options->flags.exit_with_status &&
6366 options->flags.diff_from_contents) {
6368 * run diff_flush_patch for the exit status. setting
6369 * options->file to /dev/null should be safe, because we
6370 * aren't supposed to produce any output anyway.
6372 if (options->close_file)
6373 fclose(options->file);
6374 options->file = xfopen("/dev/null", "w");
6375 options->close_file = 1;
6376 options->color_moved = 0;
6377 for (i = 0; i < q->nr; i++) {
6378 struct diff_filepair *p = q->queue[i];
6379 if (check_pair_status(p))
6380 diff_flush_patch(p, options);
6381 if (options->found_changes)
6382 break;
6386 if (output_format & DIFF_FORMAT_PATCH) {
6387 if (separator) {
6388 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6389 if (options->stat_sep)
6390 /* attach patch instead of inline */
6391 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6392 NULL, 0, 0);
6395 diff_flush_patch_all_file_pairs(options);
6398 if (output_format & DIFF_FORMAT_CALLBACK)
6399 options->format_callback(q, options, options->format_callback_data);
6401 for (i = 0; i < q->nr; i++)
6402 diff_free_filepair(q->queue[i]);
6403 free_queue:
6404 free(q->queue);
6405 DIFF_QUEUE_CLEAR(q);
6406 if (options->close_file)
6407 fclose(options->file);
6410 * Report the content-level differences with HAS_CHANGES;
6411 * diff_addremove/diff_change does not set the bit when
6412 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6414 if (options->flags.diff_from_contents) {
6415 if (options->found_changes)
6416 options->flags.has_changes = 1;
6417 else
6418 options->flags.has_changes = 0;
6422 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6424 return (((p->status == DIFF_STATUS_MODIFIED) &&
6425 ((p->score &&
6426 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6427 (!p->score &&
6428 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6429 ((p->status != DIFF_STATUS_MODIFIED) &&
6430 filter_bit_tst(p->status, options)));
6433 static void diffcore_apply_filter(struct diff_options *options)
6435 int i;
6436 struct diff_queue_struct *q = &diff_queued_diff;
6437 struct diff_queue_struct outq;
6439 DIFF_QUEUE_CLEAR(&outq);
6441 if (!options->filter)
6442 return;
6444 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6445 int found;
6446 for (i = found = 0; !found && i < q->nr; i++) {
6447 if (match_filter(options, q->queue[i]))
6448 found++;
6450 if (found)
6451 return;
6453 /* otherwise we will clear the whole queue
6454 * by copying the empty outq at the end of this
6455 * function, but first clear the current entries
6456 * in the queue.
6458 for (i = 0; i < q->nr; i++)
6459 diff_free_filepair(q->queue[i]);
6461 else {
6462 /* Only the matching ones */
6463 for (i = 0; i < q->nr; i++) {
6464 struct diff_filepair *p = q->queue[i];
6465 if (match_filter(options, p))
6466 diff_q(&outq, p);
6467 else
6468 diff_free_filepair(p);
6471 free(q->queue);
6472 *q = outq;
6475 /* Check whether two filespecs with the same mode and size are identical */
6476 static int diff_filespec_is_identical(struct repository *r,
6477 struct diff_filespec *one,
6478 struct diff_filespec *two)
6480 if (S_ISGITLINK(one->mode))
6481 return 0;
6482 if (diff_populate_filespec(r, one, NULL))
6483 return 0;
6484 if (diff_populate_filespec(r, two, NULL))
6485 return 0;
6486 return !memcmp(one->data, two->data, one->size);
6489 static int diff_filespec_check_stat_unmatch(struct repository *r,
6490 struct diff_filepair *p)
6492 struct diff_populate_filespec_options dpf_options = {
6493 .check_size_only = 1,
6494 .missing_object_cb = diff_queued_diff_prefetch,
6495 .missing_object_data = r,
6498 if (p->done_skip_stat_unmatch)
6499 return p->skip_stat_unmatch_result;
6501 p->done_skip_stat_unmatch = 1;
6502 p->skip_stat_unmatch_result = 0;
6504 * 1. Entries that come from stat info dirtiness
6505 * always have both sides (iow, not create/delete),
6506 * one side of the object name is unknown, with
6507 * the same mode and size. Keep the ones that
6508 * do not match these criteria. They have real
6509 * differences.
6511 * 2. At this point, the file is known to be modified,
6512 * with the same mode and size, and the object
6513 * name of one side is unknown. Need to inspect
6514 * the identical contents.
6516 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6517 !DIFF_FILE_VALID(p->two) ||
6518 (p->one->oid_valid && p->two->oid_valid) ||
6519 (p->one->mode != p->two->mode) ||
6520 diff_populate_filespec(r, p->one, &dpf_options) ||
6521 diff_populate_filespec(r, p->two, &dpf_options) ||
6522 (p->one->size != p->two->size) ||
6523 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6524 p->skip_stat_unmatch_result = 1;
6525 return p->skip_stat_unmatch_result;
6528 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6530 int i;
6531 struct diff_queue_struct *q = &diff_queued_diff;
6532 struct diff_queue_struct outq;
6533 DIFF_QUEUE_CLEAR(&outq);
6535 for (i = 0; i < q->nr; i++) {
6536 struct diff_filepair *p = q->queue[i];
6538 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6539 diff_q(&outq, p);
6540 else {
6542 * The caller can subtract 1 from skip_stat_unmatch
6543 * to determine how many paths were dirty only
6544 * due to stat info mismatch.
6546 if (!diffopt->flags.no_index)
6547 diffopt->skip_stat_unmatch++;
6548 diff_free_filepair(p);
6551 free(q->queue);
6552 *q = outq;
6555 static int diffnamecmp(const void *a_, const void *b_)
6557 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6558 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6559 const char *name_a, *name_b;
6561 name_a = a->one ? a->one->path : a->two->path;
6562 name_b = b->one ? b->one->path : b->two->path;
6563 return strcmp(name_a, name_b);
6566 void diffcore_fix_diff_index(void)
6568 struct diff_queue_struct *q = &diff_queued_diff;
6569 QSORT(q->queue, q->nr, diffnamecmp);
6572 void diff_add_if_missing(struct repository *r,
6573 struct oid_array *to_fetch,
6574 const struct diff_filespec *filespec)
6576 if (filespec && filespec->oid_valid &&
6577 !S_ISGITLINK(filespec->mode) &&
6578 oid_object_info_extended(r, &filespec->oid, NULL,
6579 OBJECT_INFO_FOR_PREFETCH))
6580 oid_array_append(to_fetch, &filespec->oid);
6583 void diff_queued_diff_prefetch(void *repository)
6585 struct repository *repo = repository;
6586 int i;
6587 struct diff_queue_struct *q = &diff_queued_diff;
6588 struct oid_array to_fetch = OID_ARRAY_INIT;
6590 for (i = 0; i < q->nr; i++) {
6591 struct diff_filepair *p = q->queue[i];
6592 diff_add_if_missing(repo, &to_fetch, p->one);
6593 diff_add_if_missing(repo, &to_fetch, p->two);
6597 * NEEDSWORK: Consider deduplicating the OIDs sent.
6599 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6601 oid_array_clear(&to_fetch);
6604 void diffcore_std(struct diff_options *options)
6606 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6607 DIFF_FORMAT_NUMSTAT |
6608 DIFF_FORMAT_PATCH |
6609 DIFF_FORMAT_SHORTSTAT |
6610 DIFF_FORMAT_DIRSTAT;
6613 * Check if the user requested a blob-data-requiring diff output and/or
6614 * break-rewrite detection (which requires blob data). If yes, prefetch
6615 * the diff pairs.
6617 * If no prefetching occurs, diffcore_rename() will prefetch if it
6618 * decides that it needs inexact rename detection.
6620 if (options->repo == the_repository && has_promisor_remote() &&
6621 (options->output_format & output_formats_to_prefetch ||
6622 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6623 diff_queued_diff_prefetch(options->repo);
6625 /* NOTE please keep the following in sync with diff_tree_combined() */
6626 if (options->skip_stat_unmatch)
6627 diffcore_skip_stat_unmatch(options);
6628 if (!options->found_follow) {
6629 /* See try_to_follow_renames() in tree-diff.c */
6630 if (options->break_opt != -1)
6631 diffcore_break(options->repo,
6632 options->break_opt);
6633 if (options->detect_rename)
6634 diffcore_rename(options);
6635 if (options->break_opt != -1)
6636 diffcore_merge_broken();
6638 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6639 diffcore_pickaxe(options);
6640 if (options->orderfile)
6641 diffcore_order(options->orderfile);
6642 if (!options->found_follow)
6643 /* See try_to_follow_renames() in tree-diff.c */
6644 diff_resolve_rename_copy();
6645 diffcore_apply_filter(options);
6647 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6648 options->flags.has_changes = 1;
6649 else
6650 options->flags.has_changes = 0;
6652 options->found_follow = 0;
6655 int diff_result_code(struct diff_options *opt, int status)
6657 int result = 0;
6659 diff_warn_rename_limit("diff.renameLimit",
6660 opt->needed_rename_limit,
6661 opt->degraded_cc_to_c);
6662 if (!opt->flags.exit_with_status &&
6663 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6664 return status;
6665 if (opt->flags.exit_with_status &&
6666 opt->flags.has_changes)
6667 result |= 01;
6668 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6669 opt->flags.check_failed)
6670 result |= 02;
6671 return result;
6674 int diff_can_quit_early(struct diff_options *opt)
6676 return (opt->flags.quick &&
6677 !opt->filter &&
6678 opt->flags.has_changes);
6682 * Shall changes to this submodule be ignored?
6684 * Submodule changes can be configured to be ignored separately for each path,
6685 * but that configuration can be overridden from the command line.
6687 static int is_submodule_ignored(const char *path, struct diff_options *options)
6689 int ignored = 0;
6690 struct diff_flags orig_flags = options->flags;
6691 if (!options->flags.override_submodule_config)
6692 set_diffopt_flags_from_submodule_config(options, path);
6693 if (options->flags.ignore_submodules)
6694 ignored = 1;
6695 options->flags = orig_flags;
6696 return ignored;
6699 void compute_diffstat(struct diff_options *options,
6700 struct diffstat_t *diffstat,
6701 struct diff_queue_struct *q)
6703 int i;
6705 memset(diffstat, 0, sizeof(struct diffstat_t));
6706 for (i = 0; i < q->nr; i++) {
6707 struct diff_filepair *p = q->queue[i];
6708 if (check_pair_status(p))
6709 diff_flush_stat(p, options, diffstat);
6713 void diff_addremove(struct diff_options *options,
6714 int addremove, unsigned mode,
6715 const struct object_id *oid,
6716 int oid_valid,
6717 const char *concatpath, unsigned dirty_submodule)
6719 struct diff_filespec *one, *two;
6721 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6722 return;
6724 /* This may look odd, but it is a preparation for
6725 * feeding "there are unchanged files which should
6726 * not produce diffs, but when you are doing copy
6727 * detection you would need them, so here they are"
6728 * entries to the diff-core. They will be prefixed
6729 * with something like '=' or '*' (I haven't decided
6730 * which but should not make any difference).
6731 * Feeding the same new and old to diff_change()
6732 * also has the same effect.
6733 * Before the final output happens, they are pruned after
6734 * merged into rename/copy pairs as appropriate.
6736 if (options->flags.reverse_diff)
6737 addremove = (addremove == '+' ? '-' :
6738 addremove == '-' ? '+' : addremove);
6740 if (options->prefix &&
6741 strncmp(concatpath, options->prefix, options->prefix_length))
6742 return;
6744 one = alloc_filespec(concatpath);
6745 two = alloc_filespec(concatpath);
6747 if (addremove != '+')
6748 fill_filespec(one, oid, oid_valid, mode);
6749 if (addremove != '-') {
6750 fill_filespec(two, oid, oid_valid, mode);
6751 two->dirty_submodule = dirty_submodule;
6754 diff_queue(&diff_queued_diff, one, two);
6755 if (!options->flags.diff_from_contents)
6756 options->flags.has_changes = 1;
6759 void diff_change(struct diff_options *options,
6760 unsigned old_mode, unsigned new_mode,
6761 const struct object_id *old_oid,
6762 const struct object_id *new_oid,
6763 int old_oid_valid, int new_oid_valid,
6764 const char *concatpath,
6765 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6767 struct diff_filespec *one, *two;
6768 struct diff_filepair *p;
6770 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6771 is_submodule_ignored(concatpath, options))
6772 return;
6774 if (options->flags.reverse_diff) {
6775 SWAP(old_mode, new_mode);
6776 SWAP(old_oid, new_oid);
6777 SWAP(old_oid_valid, new_oid_valid);
6778 SWAP(old_dirty_submodule, new_dirty_submodule);
6781 if (options->prefix &&
6782 strncmp(concatpath, options->prefix, options->prefix_length))
6783 return;
6785 one = alloc_filespec(concatpath);
6786 two = alloc_filespec(concatpath);
6787 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6788 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6789 one->dirty_submodule = old_dirty_submodule;
6790 two->dirty_submodule = new_dirty_submodule;
6791 p = diff_queue(&diff_queued_diff, one, two);
6793 if (options->flags.diff_from_contents)
6794 return;
6796 if (options->flags.quick && options->skip_stat_unmatch &&
6797 !diff_filespec_check_stat_unmatch(options->repo, p)) {
6798 diff_free_filespec_data(p->one);
6799 diff_free_filespec_data(p->two);
6800 return;
6803 options->flags.has_changes = 1;
6806 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6808 struct diff_filepair *pair;
6809 struct diff_filespec *one, *two;
6811 if (options->prefix &&
6812 strncmp(path, options->prefix, options->prefix_length))
6813 return NULL;
6815 one = alloc_filespec(path);
6816 two = alloc_filespec(path);
6817 pair = diff_queue(&diff_queued_diff, one, two);
6818 pair->is_unmerged = 1;
6819 return pair;
6822 static char *run_textconv(struct repository *r,
6823 const char *pgm,
6824 struct diff_filespec *spec,
6825 size_t *outsize)
6827 struct diff_tempfile *temp;
6828 const char *argv[3];
6829 const char **arg = argv;
6830 struct child_process child = CHILD_PROCESS_INIT;
6831 struct strbuf buf = STRBUF_INIT;
6832 int err = 0;
6834 temp = prepare_temp_file(r, spec->path, spec);
6835 *arg++ = pgm;
6836 *arg++ = temp->name;
6837 *arg = NULL;
6839 child.use_shell = 1;
6840 child.argv = argv;
6841 child.out = -1;
6842 if (start_command(&child)) {
6843 remove_tempfile();
6844 return NULL;
6847 if (strbuf_read(&buf, child.out, 0) < 0)
6848 err = error("error reading from textconv command '%s'", pgm);
6849 close(child.out);
6851 if (finish_command(&child) || err) {
6852 strbuf_release(&buf);
6853 remove_tempfile();
6854 return NULL;
6856 remove_tempfile();
6858 return strbuf_detach(&buf, outsize);
6861 size_t fill_textconv(struct repository *r,
6862 struct userdiff_driver *driver,
6863 struct diff_filespec *df,
6864 char **outbuf)
6866 size_t size;
6868 if (!driver) {
6869 if (!DIFF_FILE_VALID(df)) {
6870 *outbuf = "";
6871 return 0;
6873 if (diff_populate_filespec(r, df, NULL))
6874 die("unable to read files to diff");
6875 *outbuf = df->data;
6876 return df->size;
6879 if (!driver->textconv)
6880 BUG("fill_textconv called with non-textconv driver");
6882 if (driver->textconv_cache && df->oid_valid) {
6883 *outbuf = notes_cache_get(driver->textconv_cache,
6884 &df->oid,
6885 &size);
6886 if (*outbuf)
6887 return size;
6890 *outbuf = run_textconv(r, driver->textconv, df, &size);
6891 if (!*outbuf)
6892 die("unable to read files to diff");
6894 if (driver->textconv_cache && df->oid_valid) {
6895 /* ignore errors, as we might be in a readonly repository */
6896 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6897 size);
6899 * we could save up changes and flush them all at the end,
6900 * but we would need an extra call after all diffing is done.
6901 * Since generating a cache entry is the slow path anyway,
6902 * this extra overhead probably isn't a big deal.
6904 notes_cache_write(driver->textconv_cache);
6907 return size;
6910 int textconv_object(struct repository *r,
6911 const char *path,
6912 unsigned mode,
6913 const struct object_id *oid,
6914 int oid_valid,
6915 char **buf,
6916 unsigned long *buf_size)
6918 struct diff_filespec *df;
6919 struct userdiff_driver *textconv;
6921 df = alloc_filespec(path);
6922 fill_filespec(df, oid, oid_valid, mode);
6923 textconv = get_textconv(r, df);
6924 if (!textconv) {
6925 free_filespec(df);
6926 return 0;
6929 *buf_size = fill_textconv(r, textconv, df, buf);
6930 free_filespec(df);
6931 return 1;
6934 void setup_diff_pager(struct diff_options *opt)
6937 * If the user asked for our exit code, then either they want --quiet
6938 * or --exit-code. We should definitely not bother with a pager in the
6939 * former case, as we will generate no output. Since we still properly
6940 * report our exit code even when a pager is run, we _could_ run a
6941 * pager with --exit-code. But since we have not done so historically,
6942 * and because it is easy to find people oneline advising "git diff
6943 * --exit-code" in hooks and other scripts, we do not do so.
6945 if (!opt->flags.exit_with_status &&
6946 check_pager_config("diff") != 0)
6947 setup_pager();