Merge branch 'jk/unused-params'
[git/raj.git] / diff.c
blob62c7e5b7780eb35968eb96407e87cc1d60588496
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 "argv-array.h"
24 #include "graph.h"
25 #include "packfile.h"
26 #include "parse-options.h"
27 #include "help.h"
29 #ifdef NO_FAST_WORKING_DIRECTORY
30 #define FAST_WORKING_DIRECTORY 0
31 #else
32 #define FAST_WORKING_DIRECTORY 1
33 #endif
35 static int diff_detect_rename_default;
36 static int diff_indent_heuristic = 1;
37 static int diff_rename_limit_default = 400;
38 static int diff_suppress_blank_empty;
39 static int diff_use_color_default = -1;
40 static int diff_color_moved_default;
41 static int diff_color_moved_ws_default;
42 static int diff_context_default = 3;
43 static int diff_interhunk_context_default;
44 static const char *diff_word_regex_cfg;
45 static const char *external_diff_cmd_cfg;
46 static const char *diff_order_file_cfg;
47 int diff_auto_refresh_index = 1;
48 static int diff_mnemonic_prefix;
49 static int diff_no_prefix;
50 static int diff_stat_graph_width;
51 static int diff_dirstat_permille_default = 30;
52 static struct diff_options default_diff_options;
53 static long diff_algorithm;
54 static unsigned ws_error_highlight_default = WSEH_NEW;
56 static char diff_colors[][COLOR_MAXLEN] = {
57 GIT_COLOR_RESET,
58 GIT_COLOR_NORMAL, /* CONTEXT */
59 GIT_COLOR_BOLD, /* METAINFO */
60 GIT_COLOR_CYAN, /* FRAGINFO */
61 GIT_COLOR_RED, /* OLD */
62 GIT_COLOR_GREEN, /* NEW */
63 GIT_COLOR_YELLOW, /* COMMIT */
64 GIT_COLOR_BG_RED, /* WHITESPACE */
65 GIT_COLOR_NORMAL, /* FUNCINFO */
66 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
67 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
68 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
69 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
70 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
71 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
72 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
73 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
74 GIT_COLOR_FAINT, /* CONTEXT_DIM */
75 GIT_COLOR_FAINT_RED, /* OLD_DIM */
76 GIT_COLOR_FAINT_GREEN, /* NEW_DIM */
77 GIT_COLOR_BOLD, /* CONTEXT_BOLD */
78 GIT_COLOR_BOLD_RED, /* OLD_BOLD */
79 GIT_COLOR_BOLD_GREEN, /* NEW_BOLD */
82 static const char *color_diff_slots[] = {
83 [DIFF_CONTEXT] = "context",
84 [DIFF_METAINFO] = "meta",
85 [DIFF_FRAGINFO] = "frag",
86 [DIFF_FILE_OLD] = "old",
87 [DIFF_FILE_NEW] = "new",
88 [DIFF_COMMIT] = "commit",
89 [DIFF_WHITESPACE] = "whitespace",
90 [DIFF_FUNCINFO] = "func",
91 [DIFF_FILE_OLD_MOVED] = "oldMoved",
92 [DIFF_FILE_OLD_MOVED_ALT] = "oldMovedAlternative",
93 [DIFF_FILE_OLD_MOVED_DIM] = "oldMovedDimmed",
94 [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
95 [DIFF_FILE_NEW_MOVED] = "newMoved",
96 [DIFF_FILE_NEW_MOVED_ALT] = "newMovedAlternative",
97 [DIFF_FILE_NEW_MOVED_DIM] = "newMovedDimmed",
98 [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
99 [DIFF_CONTEXT_DIM] = "contextDimmed",
100 [DIFF_FILE_OLD_DIM] = "oldDimmed",
101 [DIFF_FILE_NEW_DIM] = "newDimmed",
102 [DIFF_CONTEXT_BOLD] = "contextBold",
103 [DIFF_FILE_OLD_BOLD] = "oldBold",
104 [DIFF_FILE_NEW_BOLD] = "newBold",
107 static NORETURN void die_want_option(const char *option_name)
109 die(_("option '%s' requires a value"), option_name);
112 define_list_config_array_extra(color_diff_slots, {"plain"});
114 static int parse_diff_color_slot(const char *var)
116 if (!strcasecmp(var, "plain"))
117 return DIFF_CONTEXT;
118 return LOOKUP_CONFIG(color_diff_slots, var);
121 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
122 struct strbuf *errmsg)
124 char *params_copy = xstrdup(params_string);
125 struct string_list params = STRING_LIST_INIT_NODUP;
126 int ret = 0;
127 int i;
129 if (*params_copy)
130 string_list_split_in_place(&params, params_copy, ',', -1);
131 for (i = 0; i < params.nr; i++) {
132 const char *p = params.items[i].string;
133 if (!strcmp(p, "changes")) {
134 options->flags.dirstat_by_line = 0;
135 options->flags.dirstat_by_file = 0;
136 } else if (!strcmp(p, "lines")) {
137 options->flags.dirstat_by_line = 1;
138 options->flags.dirstat_by_file = 0;
139 } else if (!strcmp(p, "files")) {
140 options->flags.dirstat_by_line = 0;
141 options->flags.dirstat_by_file = 1;
142 } else if (!strcmp(p, "noncumulative")) {
143 options->flags.dirstat_cumulative = 0;
144 } else if (!strcmp(p, "cumulative")) {
145 options->flags.dirstat_cumulative = 1;
146 } else if (isdigit(*p)) {
147 char *end;
148 int permille = strtoul(p, &end, 10) * 10;
149 if (*end == '.' && isdigit(*++end)) {
150 /* only use first digit */
151 permille += *end - '0';
152 /* .. and ignore any further digits */
153 while (isdigit(*++end))
154 ; /* nothing */
156 if (!*end)
157 options->dirstat_permille = permille;
158 else {
159 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
161 ret++;
163 } else {
164 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
165 ret++;
169 string_list_clear(&params, 0);
170 free(params_copy);
171 return ret;
174 static int parse_submodule_params(struct diff_options *options, const char *value)
176 if (!strcmp(value, "log"))
177 options->submodule_format = DIFF_SUBMODULE_LOG;
178 else if (!strcmp(value, "short"))
179 options->submodule_format = DIFF_SUBMODULE_SHORT;
180 else if (!strcmp(value, "diff"))
181 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
182 else
183 return -1;
184 return 0;
187 int git_config_rename(const char *var, const char *value)
189 if (!value)
190 return DIFF_DETECT_RENAME;
191 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
192 return DIFF_DETECT_COPY;
193 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
196 long parse_algorithm_value(const char *value)
198 if (!value)
199 return -1;
200 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
201 return 0;
202 else if (!strcasecmp(value, "minimal"))
203 return XDF_NEED_MINIMAL;
204 else if (!strcasecmp(value, "patience"))
205 return XDF_PATIENCE_DIFF;
206 else if (!strcasecmp(value, "histogram"))
207 return XDF_HISTOGRAM_DIFF;
208 return -1;
211 static int parse_one_token(const char **arg, const char *token)
213 const char *rest;
214 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
215 *arg = rest;
216 return 1;
218 return 0;
221 static int parse_ws_error_highlight(const char *arg)
223 const char *orig_arg = arg;
224 unsigned val = 0;
226 while (*arg) {
227 if (parse_one_token(&arg, "none"))
228 val = 0;
229 else if (parse_one_token(&arg, "default"))
230 val = WSEH_NEW;
231 else if (parse_one_token(&arg, "all"))
232 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
233 else if (parse_one_token(&arg, "new"))
234 val |= WSEH_NEW;
235 else if (parse_one_token(&arg, "old"))
236 val |= WSEH_OLD;
237 else if (parse_one_token(&arg, "context"))
238 val |= WSEH_CONTEXT;
239 else {
240 return -1 - (int)(arg - orig_arg);
242 if (*arg)
243 arg++;
245 return val;
249 * These are to give UI layer defaults.
250 * The core-level commands such as git-diff-files should
251 * never be affected by the setting of diff.renames
252 * the user happens to have in the configuration file.
254 void init_diff_ui_defaults(void)
256 diff_detect_rename_default = DIFF_DETECT_RENAME;
259 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
261 if (!strcmp(var, "diff.indentheuristic"))
262 diff_indent_heuristic = git_config_bool(var, value);
263 return 0;
266 static int parse_color_moved(const char *arg)
268 switch (git_parse_maybe_bool(arg)) {
269 case 0:
270 return COLOR_MOVED_NO;
271 case 1:
272 return COLOR_MOVED_DEFAULT;
273 default:
274 break;
277 if (!strcmp(arg, "no"))
278 return COLOR_MOVED_NO;
279 else if (!strcmp(arg, "plain"))
280 return COLOR_MOVED_PLAIN;
281 else if (!strcmp(arg, "blocks"))
282 return COLOR_MOVED_BLOCKS;
283 else if (!strcmp(arg, "zebra"))
284 return COLOR_MOVED_ZEBRA;
285 else if (!strcmp(arg, "default"))
286 return COLOR_MOVED_DEFAULT;
287 else if (!strcmp(arg, "dimmed-zebra"))
288 return COLOR_MOVED_ZEBRA_DIM;
289 else if (!strcmp(arg, "dimmed_zebra"))
290 return COLOR_MOVED_ZEBRA_DIM;
291 else
292 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
295 static unsigned parse_color_moved_ws(const char *arg)
297 int ret = 0;
298 struct string_list l = STRING_LIST_INIT_DUP;
299 struct string_list_item *i;
301 string_list_split(&l, arg, ',', -1);
303 for_each_string_list_item(i, &l) {
304 struct strbuf sb = STRBUF_INIT;
305 strbuf_addstr(&sb, i->string);
306 strbuf_trim(&sb);
308 if (!strcmp(sb.buf, "no"))
309 ret = 0;
310 else if (!strcmp(sb.buf, "ignore-space-change"))
311 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
312 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
313 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
314 else if (!strcmp(sb.buf, "ignore-all-space"))
315 ret |= XDF_IGNORE_WHITESPACE;
316 else if (!strcmp(sb.buf, "allow-indentation-change"))
317 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
318 else {
319 ret |= COLOR_MOVED_WS_ERROR;
320 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);
323 strbuf_release(&sb);
326 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
327 (ret & XDF_WHITESPACE_FLAGS)) {
328 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
329 ret |= COLOR_MOVED_WS_ERROR;
332 string_list_clear(&l, 0);
334 return ret;
337 int git_diff_ui_config(const char *var, const char *value, void *cb)
339 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
340 diff_use_color_default = git_config_colorbool(var, value);
341 return 0;
343 if (!strcmp(var, "diff.colormoved")) {
344 int cm = parse_color_moved(value);
345 if (cm < 0)
346 return -1;
347 diff_color_moved_default = cm;
348 return 0;
350 if (!strcmp(var, "diff.colormovedws")) {
351 unsigned cm = parse_color_moved_ws(value);
352 if (cm & COLOR_MOVED_WS_ERROR)
353 return -1;
354 diff_color_moved_ws_default = cm;
355 return 0;
357 if (!strcmp(var, "diff.context")) {
358 diff_context_default = git_config_int(var, value);
359 if (diff_context_default < 0)
360 return -1;
361 return 0;
363 if (!strcmp(var, "diff.interhunkcontext")) {
364 diff_interhunk_context_default = git_config_int(var, value);
365 if (diff_interhunk_context_default < 0)
366 return -1;
367 return 0;
369 if (!strcmp(var, "diff.renames")) {
370 diff_detect_rename_default = git_config_rename(var, value);
371 return 0;
373 if (!strcmp(var, "diff.autorefreshindex")) {
374 diff_auto_refresh_index = git_config_bool(var, value);
375 return 0;
377 if (!strcmp(var, "diff.mnemonicprefix")) {
378 diff_mnemonic_prefix = git_config_bool(var, value);
379 return 0;
381 if (!strcmp(var, "diff.noprefix")) {
382 diff_no_prefix = git_config_bool(var, value);
383 return 0;
385 if (!strcmp(var, "diff.statgraphwidth")) {
386 diff_stat_graph_width = git_config_int(var, value);
387 return 0;
389 if (!strcmp(var, "diff.external"))
390 return git_config_string(&external_diff_cmd_cfg, var, value);
391 if (!strcmp(var, "diff.wordregex"))
392 return git_config_string(&diff_word_regex_cfg, var, value);
393 if (!strcmp(var, "diff.orderfile"))
394 return git_config_pathname(&diff_order_file_cfg, var, value);
396 if (!strcmp(var, "diff.ignoresubmodules"))
397 handle_ignore_submodules_arg(&default_diff_options, value);
399 if (!strcmp(var, "diff.submodule")) {
400 if (parse_submodule_params(&default_diff_options, value))
401 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
402 value);
403 return 0;
406 if (!strcmp(var, "diff.algorithm")) {
407 diff_algorithm = parse_algorithm_value(value);
408 if (diff_algorithm < 0)
409 return -1;
410 return 0;
413 if (!strcmp(var, "diff.wserrorhighlight")) {
414 int val = parse_ws_error_highlight(value);
415 if (val < 0)
416 return -1;
417 ws_error_highlight_default = val;
418 return 0;
421 if (git_color_config(var, value, cb) < 0)
422 return -1;
424 return git_diff_basic_config(var, value, cb);
427 int git_diff_basic_config(const char *var, const char *value, void *cb)
429 const char *name;
431 if (!strcmp(var, "diff.renamelimit")) {
432 diff_rename_limit_default = git_config_int(var, value);
433 return 0;
436 if (userdiff_config(var, value) < 0)
437 return -1;
439 if (skip_prefix(var, "diff.color.", &name) ||
440 skip_prefix(var, "color.diff.", &name)) {
441 int slot = parse_diff_color_slot(name);
442 if (slot < 0)
443 return 0;
444 if (!value)
445 return config_error_nonbool(var);
446 return color_parse(value, diff_colors[slot]);
449 /* like GNU diff's --suppress-blank-empty option */
450 if (!strcmp(var, "diff.suppressblankempty") ||
451 /* for backwards compatibility */
452 !strcmp(var, "diff.suppress-blank-empty")) {
453 diff_suppress_blank_empty = git_config_bool(var, value);
454 return 0;
457 if (!strcmp(var, "diff.dirstat")) {
458 struct strbuf errmsg = STRBUF_INIT;
459 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
460 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
461 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
462 errmsg.buf);
463 strbuf_release(&errmsg);
464 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
465 return 0;
468 if (git_diff_heuristic_config(var, value, cb) < 0)
469 return -1;
471 return git_default_config(var, value, cb);
474 static char *quote_two(const char *one, const char *two)
476 int need_one = quote_c_style(one, NULL, NULL, 1);
477 int need_two = quote_c_style(two, NULL, NULL, 1);
478 struct strbuf res = STRBUF_INIT;
480 if (need_one + need_two) {
481 strbuf_addch(&res, '"');
482 quote_c_style(one, &res, NULL, 1);
483 quote_c_style(two, &res, NULL, 1);
484 strbuf_addch(&res, '"');
485 } else {
486 strbuf_addstr(&res, one);
487 strbuf_addstr(&res, two);
489 return strbuf_detach(&res, NULL);
492 static const char *external_diff(void)
494 static const char *external_diff_cmd = NULL;
495 static int done_preparing = 0;
497 if (done_preparing)
498 return external_diff_cmd;
499 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
500 if (!external_diff_cmd)
501 external_diff_cmd = external_diff_cmd_cfg;
502 done_preparing = 1;
503 return external_diff_cmd;
507 * Keep track of files used for diffing. Sometimes such an entry
508 * refers to a temporary file, sometimes to an existing file, and
509 * sometimes to "/dev/null".
511 static struct diff_tempfile {
513 * filename external diff should read from, or NULL if this
514 * entry is currently not in use:
516 const char *name;
518 char hex[GIT_MAX_HEXSZ + 1];
519 char mode[10];
522 * If this diff_tempfile instance refers to a temporary file,
523 * this tempfile object is used to manage its lifetime.
525 struct tempfile *tempfile;
526 } diff_temp[2];
528 struct emit_callback {
529 int color_diff;
530 unsigned ws_rule;
531 int blank_at_eof_in_preimage;
532 int blank_at_eof_in_postimage;
533 int lno_in_preimage;
534 int lno_in_postimage;
535 const char **label_path;
536 struct diff_words_data *diff_words;
537 struct diff_options *opt;
538 struct strbuf *header;
541 static int count_lines(const char *data, int size)
543 int count, ch, completely_empty = 1, nl_just_seen = 0;
544 count = 0;
545 while (0 < size--) {
546 ch = *data++;
547 if (ch == '\n') {
548 count++;
549 nl_just_seen = 1;
550 completely_empty = 0;
552 else {
553 nl_just_seen = 0;
554 completely_empty = 0;
557 if (completely_empty)
558 return 0;
559 if (!nl_just_seen)
560 count++; /* no trailing newline */
561 return count;
564 static int fill_mmfile(struct repository *r, mmfile_t *mf,
565 struct diff_filespec *one)
567 if (!DIFF_FILE_VALID(one)) {
568 mf->ptr = (char *)""; /* does not matter */
569 mf->size = 0;
570 return 0;
572 else if (diff_populate_filespec(r, one, 0))
573 return -1;
575 mf->ptr = one->data;
576 mf->size = one->size;
577 return 0;
580 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
581 static unsigned long diff_filespec_size(struct repository *r,
582 struct diff_filespec *one)
584 if (!DIFF_FILE_VALID(one))
585 return 0;
586 diff_populate_filespec(r, one, CHECK_SIZE_ONLY);
587 return one->size;
590 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
592 char *ptr = mf->ptr;
593 long size = mf->size;
594 int cnt = 0;
596 if (!size)
597 return cnt;
598 ptr += size - 1; /* pointing at the very end */
599 if (*ptr != '\n')
600 ; /* incomplete line */
601 else
602 ptr--; /* skip the last LF */
603 while (mf->ptr < ptr) {
604 char *prev_eol;
605 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
606 if (*prev_eol == '\n')
607 break;
608 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
609 break;
610 cnt++;
611 ptr = prev_eol - 1;
613 return cnt;
616 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
617 struct emit_callback *ecbdata)
619 int l1, l2, at;
620 unsigned ws_rule = ecbdata->ws_rule;
621 l1 = count_trailing_blank(mf1, ws_rule);
622 l2 = count_trailing_blank(mf2, ws_rule);
623 if (l2 <= l1) {
624 ecbdata->blank_at_eof_in_preimage = 0;
625 ecbdata->blank_at_eof_in_postimage = 0;
626 return;
628 at = count_lines(mf1->ptr, mf1->size);
629 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
631 at = count_lines(mf2->ptr, mf2->size);
632 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
635 static void emit_line_0(struct diff_options *o,
636 const char *set_sign, const char *set, unsigned reverse, const char *reset,
637 int first, const char *line, int len)
639 int has_trailing_newline, has_trailing_carriage_return;
640 int needs_reset = 0; /* at the end of the line */
641 FILE *file = o->file;
643 fputs(diff_line_prefix(o), file);
645 has_trailing_newline = (len > 0 && line[len-1] == '\n');
646 if (has_trailing_newline)
647 len--;
649 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
650 if (has_trailing_carriage_return)
651 len--;
653 if (!len && !first)
654 goto end_of_line;
656 if (reverse && want_color(o->use_color)) {
657 fputs(GIT_COLOR_REVERSE, file);
658 needs_reset = 1;
661 if (set_sign) {
662 fputs(set_sign, file);
663 needs_reset = 1;
666 if (first)
667 fputc(first, file);
669 if (!len)
670 goto end_of_line;
672 if (set) {
673 if (set_sign && set != set_sign)
674 fputs(reset, file);
675 fputs(set, file);
676 needs_reset = 1;
678 fwrite(line, len, 1, file);
679 needs_reset = 1; /* 'line' may contain color codes. */
681 end_of_line:
682 if (needs_reset)
683 fputs(reset, file);
684 if (has_trailing_carriage_return)
685 fputc('\r', file);
686 if (has_trailing_newline)
687 fputc('\n', file);
690 static void emit_line(struct diff_options *o, const char *set, const char *reset,
691 const char *line, int len)
693 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
696 enum diff_symbol {
697 DIFF_SYMBOL_BINARY_DIFF_HEADER,
698 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
699 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
700 DIFF_SYMBOL_BINARY_DIFF_BODY,
701 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
702 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
703 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
704 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
705 DIFF_SYMBOL_STATS_LINE,
706 DIFF_SYMBOL_WORD_DIFF,
707 DIFF_SYMBOL_STAT_SEP,
708 DIFF_SYMBOL_SUMMARY,
709 DIFF_SYMBOL_SUBMODULE_ADD,
710 DIFF_SYMBOL_SUBMODULE_DEL,
711 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
712 DIFF_SYMBOL_SUBMODULE_MODIFIED,
713 DIFF_SYMBOL_SUBMODULE_HEADER,
714 DIFF_SYMBOL_SUBMODULE_ERROR,
715 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
716 DIFF_SYMBOL_REWRITE_DIFF,
717 DIFF_SYMBOL_BINARY_FILES,
718 DIFF_SYMBOL_HEADER,
719 DIFF_SYMBOL_FILEPAIR_PLUS,
720 DIFF_SYMBOL_FILEPAIR_MINUS,
721 DIFF_SYMBOL_WORDS_PORCELAIN,
722 DIFF_SYMBOL_WORDS,
723 DIFF_SYMBOL_CONTEXT,
724 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
725 DIFF_SYMBOL_PLUS,
726 DIFF_SYMBOL_MINUS,
727 DIFF_SYMBOL_NO_LF_EOF,
728 DIFF_SYMBOL_CONTEXT_FRAGINFO,
729 DIFF_SYMBOL_CONTEXT_MARKER,
730 DIFF_SYMBOL_SEPARATOR
733 * Flags for content lines:
734 * 0..12 are whitespace rules
735 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
736 * 16 is marking if the line is blank at EOF
738 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
739 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
740 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
741 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
742 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
745 * This struct is used when we need to buffer the output of the diff output.
747 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
748 * into the pre/post image file. This pointer could be a union with the
749 * line pointer. By storing an offset into the file instead of the literal line,
750 * we can decrease the memory footprint for the buffered output. At first we
751 * may want to only have indirection for the content lines, but we could also
752 * enhance the state for emitting prefabricated lines, e.g. the similarity
753 * score line or hunk/file headers would only need to store a number or path
754 * and then the output can be constructed later on depending on state.
756 struct emitted_diff_symbol {
757 const char *line;
758 int len;
759 int flags;
760 int indent_off; /* Offset to first non-whitespace character */
761 int indent_width; /* The visual width of the indentation */
762 enum diff_symbol s;
764 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
766 struct emitted_diff_symbols {
767 struct emitted_diff_symbol *buf;
768 int nr, alloc;
770 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
772 static void append_emitted_diff_symbol(struct diff_options *o,
773 struct emitted_diff_symbol *e)
775 struct emitted_diff_symbol *f;
777 ALLOC_GROW(o->emitted_symbols->buf,
778 o->emitted_symbols->nr + 1,
779 o->emitted_symbols->alloc);
780 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
782 memcpy(f, e, sizeof(struct emitted_diff_symbol));
783 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
786 struct moved_entry {
787 struct hashmap_entry ent;
788 const struct emitted_diff_symbol *es;
789 struct moved_entry *next_line;
792 struct moved_block {
793 struct moved_entry *match;
794 int wsd; /* The whitespace delta of this block */
797 static void moved_block_clear(struct moved_block *b)
799 memset(b, 0, sizeof(*b));
802 #define INDENT_BLANKLINE INT_MIN
804 static void fill_es_indent_data(struct emitted_diff_symbol *es)
806 unsigned int off = 0, i;
807 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
808 const char *s = es->line;
809 const int len = es->len;
811 /* skip any \v \f \r at start of indentation */
812 while (s[off] == '\f' || s[off] == '\v' ||
813 (s[off] == '\r' && off < len - 1))
814 off++;
816 /* calculate the visual width of indentation */
817 while(1) {
818 if (s[off] == ' ') {
819 width++;
820 off++;
821 } else if (s[off] == '\t') {
822 width += tab_width - (width % tab_width);
823 while (s[++off] == '\t')
824 width += tab_width;
825 } else {
826 break;
830 /* check if this line is blank */
831 for (i = off; i < len; i++)
832 if (!isspace(s[i]))
833 break;
835 if (i == len) {
836 es->indent_width = INDENT_BLANKLINE;
837 es->indent_off = len;
838 } else {
839 es->indent_off = off;
840 es->indent_width = width;
844 static int compute_ws_delta(const struct emitted_diff_symbol *a,
845 const struct emitted_diff_symbol *b,
846 int *out)
848 int a_len = a->len,
849 b_len = b->len,
850 a_off = a->indent_off,
851 a_width = a->indent_width,
852 b_off = b->indent_off,
853 b_width = b->indent_width;
854 int delta;
856 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE) {
857 *out = INDENT_BLANKLINE;
858 return 1;
861 if (a->s == DIFF_SYMBOL_PLUS)
862 delta = a_width - b_width;
863 else
864 delta = b_width - a_width;
866 if (a_len - a_off != b_len - b_off ||
867 memcmp(a->line + a_off, b->line + b_off, a_len - a_off))
868 return 0;
870 *out = delta;
872 return 1;
875 static int cmp_in_block_with_wsd(const struct diff_options *o,
876 const struct moved_entry *cur,
877 const struct moved_entry *match,
878 struct moved_block *pmb,
879 int n)
881 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
882 int al = cur->es->len, bl = match->es->len, cl = l->len;
883 const char *a = cur->es->line,
884 *b = match->es->line,
885 *c = l->line;
886 int a_off = cur->es->indent_off,
887 a_width = cur->es->indent_width,
888 c_off = l->indent_off,
889 c_width = l->indent_width;
890 int delta;
893 * We need to check if 'cur' is equal to 'match'. As those
894 * are from the same (+/-) side, we do not need to adjust for
895 * indent changes. However these were found using fuzzy
896 * matching so we do have to check if they are equal. Here we
897 * just check the lengths. We delay calling memcmp() to check
898 * the contents until later as if the length comparison for a
899 * and c fails we can avoid the call all together.
901 if (al != bl)
902 return 1;
904 /* If 'l' and 'cur' are both blank then they match. */
905 if (a_width == INDENT_BLANKLINE && c_width == INDENT_BLANKLINE)
906 return 0;
909 * The indent changes of the block are known and stored in pmb->wsd;
910 * however we need to check if the indent changes of the current line
911 * match those of the current block and that the text of 'l' and 'cur'
912 * after the indentation match.
914 if (cur->es->s == DIFF_SYMBOL_PLUS)
915 delta = a_width - c_width;
916 else
917 delta = c_width - a_width;
920 * If the previous lines of this block were all blank then set its
921 * whitespace delta.
923 if (pmb->wsd == INDENT_BLANKLINE)
924 pmb->wsd = delta;
926 return !(delta == pmb->wsd && al - a_off == cl - c_off &&
927 !memcmp(a, b, al) && !
928 memcmp(a + a_off, c + c_off, al - a_off));
931 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
932 const void *entry,
933 const void *entry_or_key,
934 const void *keydata)
936 const struct diff_options *diffopt = hashmap_cmp_fn_data;
937 const struct moved_entry *a = entry;
938 const struct moved_entry *b = entry_or_key;
939 unsigned flags = diffopt->color_moved_ws_handling
940 & XDF_WHITESPACE_FLAGS;
942 if (diffopt->color_moved_ws_handling &
943 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
945 * As there is not specific white space config given,
946 * we'd need to check for a new block, so ignore all
947 * white space. The setup of the white space
948 * configuration for the next block is done else where
950 flags |= XDF_IGNORE_WHITESPACE;
952 return !xdiff_compare_lines(a->es->line, a->es->len,
953 b->es->line, b->es->len,
954 flags);
957 static struct moved_entry *prepare_entry(struct diff_options *o,
958 int line_no)
960 struct moved_entry *ret = xmalloc(sizeof(*ret));
961 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
962 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
964 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
965 ret->es = l;
966 ret->next_line = NULL;
968 return ret;
971 static void add_lines_to_move_detection(struct diff_options *o,
972 struct hashmap *add_lines,
973 struct hashmap *del_lines)
975 struct moved_entry *prev_line = NULL;
977 int n;
978 for (n = 0; n < o->emitted_symbols->nr; n++) {
979 struct hashmap *hm;
980 struct moved_entry *key;
982 switch (o->emitted_symbols->buf[n].s) {
983 case DIFF_SYMBOL_PLUS:
984 hm = add_lines;
985 break;
986 case DIFF_SYMBOL_MINUS:
987 hm = del_lines;
988 break;
989 default:
990 prev_line = NULL;
991 continue;
994 if (o->color_moved_ws_handling &
995 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
996 fill_es_indent_data(&o->emitted_symbols->buf[n]);
997 key = prepare_entry(o, n);
998 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
999 prev_line->next_line = key;
1001 hashmap_add(hm, key);
1002 prev_line = key;
1006 static void pmb_advance_or_null(struct diff_options *o,
1007 struct moved_entry *match,
1008 struct hashmap *hm,
1009 struct moved_block *pmb,
1010 int pmb_nr)
1012 int i;
1013 for (i = 0; i < pmb_nr; i++) {
1014 struct moved_entry *prev = pmb[i].match;
1015 struct moved_entry *cur = (prev && prev->next_line) ?
1016 prev->next_line : NULL;
1017 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
1018 pmb[i].match = cur;
1019 } else {
1020 pmb[i].match = NULL;
1025 static void pmb_advance_or_null_multi_match(struct diff_options *o,
1026 struct moved_entry *match,
1027 struct hashmap *hm,
1028 struct moved_block *pmb,
1029 int pmb_nr, int n)
1031 int i;
1032 char *got_match = xcalloc(1, pmb_nr);
1034 for (; match; match = hashmap_get_next(hm, match)) {
1035 for (i = 0; i < pmb_nr; i++) {
1036 struct moved_entry *prev = pmb[i].match;
1037 struct moved_entry *cur = (prev && prev->next_line) ?
1038 prev->next_line : NULL;
1039 if (!cur)
1040 continue;
1041 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
1042 got_match[i] |= 1;
1046 for (i = 0; i < pmb_nr; i++) {
1047 if (got_match[i]) {
1048 /* Advance to the next line */
1049 pmb[i].match = pmb[i].match->next_line;
1050 } else {
1051 moved_block_clear(&pmb[i]);
1055 free(got_match);
1058 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1059 int pmb_nr)
1061 int lp, rp;
1063 /* Shrink the set of potential block to the remaining running */
1064 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1065 while (lp < pmb_nr && pmb[lp].match)
1066 lp++;
1067 /* lp points at the first NULL now */
1069 while (rp > -1 && !pmb[rp].match)
1070 rp--;
1071 /* rp points at the last non-NULL */
1073 if (lp < pmb_nr && rp > -1 && lp < rp) {
1074 pmb[lp] = pmb[rp];
1075 memset(&pmb[rp], 0, sizeof(pmb[rp]));
1076 rp--;
1077 lp++;
1081 /* Remember the number of running sets */
1082 return rp + 1;
1086 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1088 * Otherwise, if the last block has fewer alphanumeric characters than
1089 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1090 * that block.
1092 * The last block consists of the (n - block_length)'th line up to but not
1093 * including the nth line.
1095 * Returns 0 if the last block is empty or is unset by this function, non zero
1096 * otherwise.
1098 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1099 * Think of a way to unify them.
1101 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1103 int i, alnum_count = 0;
1104 if (o->color_moved == COLOR_MOVED_PLAIN)
1105 return block_length;
1106 for (i = 1; i < block_length + 1; i++) {
1107 const char *c = o->emitted_symbols->buf[n - i].line;
1108 for (; *c; c++) {
1109 if (!isalnum(*c))
1110 continue;
1111 alnum_count++;
1112 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1113 return 1;
1116 for (i = 1; i < block_length + 1; i++)
1117 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1118 return 0;
1121 /* Find blocks of moved code, delegate actual coloring decision to helper */
1122 static void mark_color_as_moved(struct diff_options *o,
1123 struct hashmap *add_lines,
1124 struct hashmap *del_lines)
1126 struct moved_block *pmb = NULL; /* potentially moved blocks */
1127 int pmb_nr = 0, pmb_alloc = 0;
1128 int n, flipped_block = 0, block_length = 0;
1131 for (n = 0; n < o->emitted_symbols->nr; n++) {
1132 struct hashmap *hm = NULL;
1133 struct moved_entry *key;
1134 struct moved_entry *match = NULL;
1135 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1136 enum diff_symbol last_symbol = 0;
1138 switch (l->s) {
1139 case DIFF_SYMBOL_PLUS:
1140 hm = del_lines;
1141 key = prepare_entry(o, n);
1142 match = hashmap_get(hm, key, NULL);
1143 free(key);
1144 break;
1145 case DIFF_SYMBOL_MINUS:
1146 hm = add_lines;
1147 key = prepare_entry(o, n);
1148 match = hashmap_get(hm, key, NULL);
1149 free(key);
1150 break;
1151 default:
1152 flipped_block = 0;
1155 if (!match) {
1156 int i;
1158 adjust_last_block(o, n, block_length);
1159 for(i = 0; i < pmb_nr; i++)
1160 moved_block_clear(&pmb[i]);
1161 pmb_nr = 0;
1162 block_length = 0;
1163 flipped_block = 0;
1164 last_symbol = l->s;
1165 continue;
1168 if (o->color_moved == COLOR_MOVED_PLAIN) {
1169 last_symbol = l->s;
1170 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1171 continue;
1174 if (o->color_moved_ws_handling &
1175 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1176 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1177 else
1178 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1180 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1182 if (pmb_nr == 0) {
1184 * The current line is the start of a new block.
1185 * Setup the set of potential blocks.
1187 for (; match; match = hashmap_get_next(hm, match)) {
1188 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1189 if (o->color_moved_ws_handling &
1190 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1191 if (compute_ws_delta(l, match->es,
1192 &pmb[pmb_nr].wsd))
1193 pmb[pmb_nr++].match = match;
1194 } else {
1195 pmb[pmb_nr].wsd = 0;
1196 pmb[pmb_nr++].match = match;
1200 if (adjust_last_block(o, n, block_length) &&
1201 pmb_nr && last_symbol != l->s)
1202 flipped_block = (flipped_block + 1) % 2;
1203 else
1204 flipped_block = 0;
1206 block_length = 0;
1209 if (pmb_nr) {
1210 block_length++;
1211 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1212 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1213 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1215 last_symbol = l->s;
1217 adjust_last_block(o, n, block_length);
1219 for(n = 0; n < pmb_nr; n++)
1220 moved_block_clear(&pmb[n]);
1221 free(pmb);
1224 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1225 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1226 static void dim_moved_lines(struct diff_options *o)
1228 int n;
1229 for (n = 0; n < o->emitted_symbols->nr; n++) {
1230 struct emitted_diff_symbol *prev = (n != 0) ?
1231 &o->emitted_symbols->buf[n - 1] : NULL;
1232 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1233 struct emitted_diff_symbol *next =
1234 (n < o->emitted_symbols->nr - 1) ?
1235 &o->emitted_symbols->buf[n + 1] : NULL;
1237 /* Not a plus or minus line? */
1238 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1239 continue;
1241 /* Not a moved line? */
1242 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1243 continue;
1246 * If prev or next are not a plus or minus line,
1247 * pretend they don't exist
1249 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1250 prev->s != DIFF_SYMBOL_MINUS)
1251 prev = NULL;
1252 if (next && next->s != DIFF_SYMBOL_PLUS &&
1253 next->s != DIFF_SYMBOL_MINUS)
1254 next = NULL;
1256 /* Inside a block? */
1257 if ((prev &&
1258 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1259 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1260 (next &&
1261 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1262 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1263 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1264 continue;
1267 /* Check if we are at an interesting bound: */
1268 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1269 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1270 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1271 continue;
1272 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1273 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1274 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1275 continue;
1278 * The boundary to prev and next are not interesting,
1279 * so this line is not interesting as a whole
1281 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1285 static void emit_line_ws_markup(struct diff_options *o,
1286 const char *set_sign, const char *set,
1287 const char *reset,
1288 int sign_index, const char *line, int len,
1289 unsigned ws_rule, int blank_at_eof)
1291 const char *ws = NULL;
1292 int sign = o->output_indicators[sign_index];
1294 if (o->ws_error_highlight & ws_rule) {
1295 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1296 if (!*ws)
1297 ws = NULL;
1300 if (!ws && !set_sign)
1301 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1302 else if (!ws) {
1303 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1304 } else if (blank_at_eof)
1305 /* Blank line at EOF - paint '+' as well */
1306 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1307 else {
1308 /* Emit just the prefix, then the rest. */
1309 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1310 sign, "", 0);
1311 ws_check_emit(line, len, ws_rule,
1312 o->file, set, reset, ws);
1316 static void emit_diff_symbol_from_struct(struct diff_options *o,
1317 struct emitted_diff_symbol *eds)
1319 static const char *nneof = " No newline at end of file\n";
1320 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1321 struct strbuf sb = STRBUF_INIT;
1323 enum diff_symbol s = eds->s;
1324 const char *line = eds->line;
1325 int len = eds->len;
1326 unsigned flags = eds->flags;
1328 switch (s) {
1329 case DIFF_SYMBOL_NO_LF_EOF:
1330 context = diff_get_color_opt(o, DIFF_CONTEXT);
1331 reset = diff_get_color_opt(o, DIFF_RESET);
1332 putc('\n', o->file);
1333 emit_line_0(o, context, NULL, 0, reset, '\\',
1334 nneof, strlen(nneof));
1335 break;
1336 case DIFF_SYMBOL_SUBMODULE_HEADER:
1337 case DIFF_SYMBOL_SUBMODULE_ERROR:
1338 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1339 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1340 case DIFF_SYMBOL_SUMMARY:
1341 case DIFF_SYMBOL_STATS_LINE:
1342 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1343 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1344 emit_line(o, "", "", line, len);
1345 break;
1346 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1347 case DIFF_SYMBOL_CONTEXT_MARKER:
1348 context = diff_get_color_opt(o, DIFF_CONTEXT);
1349 reset = diff_get_color_opt(o, DIFF_RESET);
1350 emit_line(o, context, reset, line, len);
1351 break;
1352 case DIFF_SYMBOL_SEPARATOR:
1353 fprintf(o->file, "%s%c",
1354 diff_line_prefix(o),
1355 o->line_termination);
1356 break;
1357 case DIFF_SYMBOL_CONTEXT:
1358 set = diff_get_color_opt(o, DIFF_CONTEXT);
1359 reset = diff_get_color_opt(o, DIFF_RESET);
1360 set_sign = NULL;
1361 if (o->flags.dual_color_diffed_diffs) {
1362 char c = !len ? 0 : line[0];
1364 if (c == '+')
1365 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1366 else if (c == '@')
1367 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1368 else if (c == '-')
1369 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1371 emit_line_ws_markup(o, set_sign, set, reset,
1372 OUTPUT_INDICATOR_CONTEXT, line, len,
1373 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1374 break;
1375 case DIFF_SYMBOL_PLUS:
1376 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1377 DIFF_SYMBOL_MOVED_LINE_ALT |
1378 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1379 case DIFF_SYMBOL_MOVED_LINE |
1380 DIFF_SYMBOL_MOVED_LINE_ALT |
1381 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1382 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1383 break;
1384 case DIFF_SYMBOL_MOVED_LINE |
1385 DIFF_SYMBOL_MOVED_LINE_ALT:
1386 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1387 break;
1388 case DIFF_SYMBOL_MOVED_LINE |
1389 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1390 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1391 break;
1392 case DIFF_SYMBOL_MOVED_LINE:
1393 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1394 break;
1395 default:
1396 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1398 reset = diff_get_color_opt(o, DIFF_RESET);
1399 if (!o->flags.dual_color_diffed_diffs)
1400 set_sign = NULL;
1401 else {
1402 char c = !len ? 0 : line[0];
1404 set_sign = set;
1405 if (c == '-')
1406 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1407 else if (c == '@')
1408 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1409 else if (c == '+')
1410 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1411 else
1412 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1413 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1415 emit_line_ws_markup(o, set_sign, set, reset,
1416 OUTPUT_INDICATOR_NEW, line, len,
1417 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1418 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1419 break;
1420 case DIFF_SYMBOL_MINUS:
1421 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1422 DIFF_SYMBOL_MOVED_LINE_ALT |
1423 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1424 case DIFF_SYMBOL_MOVED_LINE |
1425 DIFF_SYMBOL_MOVED_LINE_ALT |
1426 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1427 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1428 break;
1429 case DIFF_SYMBOL_MOVED_LINE |
1430 DIFF_SYMBOL_MOVED_LINE_ALT:
1431 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1432 break;
1433 case DIFF_SYMBOL_MOVED_LINE |
1434 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1435 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1436 break;
1437 case DIFF_SYMBOL_MOVED_LINE:
1438 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1439 break;
1440 default:
1441 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1443 reset = diff_get_color_opt(o, DIFF_RESET);
1444 if (!o->flags.dual_color_diffed_diffs)
1445 set_sign = NULL;
1446 else {
1447 char c = !len ? 0 : line[0];
1449 set_sign = set;
1450 if (c == '+')
1451 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1452 else if (c == '@')
1453 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1454 else if (c == '-')
1455 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1456 else
1457 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1459 emit_line_ws_markup(o, set_sign, set, reset,
1460 OUTPUT_INDICATOR_OLD, line, len,
1461 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1462 break;
1463 case DIFF_SYMBOL_WORDS_PORCELAIN:
1464 context = diff_get_color_opt(o, DIFF_CONTEXT);
1465 reset = diff_get_color_opt(o, DIFF_RESET);
1466 emit_line(o, context, reset, line, len);
1467 fputs("~\n", o->file);
1468 break;
1469 case DIFF_SYMBOL_WORDS:
1470 context = diff_get_color_opt(o, DIFF_CONTEXT);
1471 reset = diff_get_color_opt(o, DIFF_RESET);
1473 * Skip the prefix character, if any. With
1474 * diff_suppress_blank_empty, there may be
1475 * none.
1477 if (line[0] != '\n') {
1478 line++;
1479 len--;
1481 emit_line(o, context, reset, line, len);
1482 break;
1483 case DIFF_SYMBOL_FILEPAIR_PLUS:
1484 meta = diff_get_color_opt(o, DIFF_METAINFO);
1485 reset = diff_get_color_opt(o, DIFF_RESET);
1486 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1487 line, reset,
1488 strchr(line, ' ') ? "\t" : "");
1489 break;
1490 case DIFF_SYMBOL_FILEPAIR_MINUS:
1491 meta = diff_get_color_opt(o, DIFF_METAINFO);
1492 reset = diff_get_color_opt(o, DIFF_RESET);
1493 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1494 line, reset,
1495 strchr(line, ' ') ? "\t" : "");
1496 break;
1497 case DIFF_SYMBOL_BINARY_FILES:
1498 case DIFF_SYMBOL_HEADER:
1499 fprintf(o->file, "%s", line);
1500 break;
1501 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1502 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1503 break;
1504 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1505 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1506 break;
1507 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1508 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1509 break;
1510 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1511 fputs(diff_line_prefix(o), o->file);
1512 fputc('\n', o->file);
1513 break;
1514 case DIFF_SYMBOL_REWRITE_DIFF:
1515 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1516 reset = diff_get_color_opt(o, DIFF_RESET);
1517 emit_line(o, fraginfo, reset, line, len);
1518 break;
1519 case DIFF_SYMBOL_SUBMODULE_ADD:
1520 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1521 reset = diff_get_color_opt(o, DIFF_RESET);
1522 emit_line(o, set, reset, line, len);
1523 break;
1524 case DIFF_SYMBOL_SUBMODULE_DEL:
1525 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1526 reset = diff_get_color_opt(o, DIFF_RESET);
1527 emit_line(o, set, reset, line, len);
1528 break;
1529 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1530 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1531 diff_line_prefix(o), line);
1532 break;
1533 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1534 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1535 diff_line_prefix(o), line);
1536 break;
1537 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1538 emit_line(o, "", "", " 0 files changed\n",
1539 strlen(" 0 files changed\n"));
1540 break;
1541 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1542 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1543 break;
1544 case DIFF_SYMBOL_WORD_DIFF:
1545 fprintf(o->file, "%.*s", len, line);
1546 break;
1547 case DIFF_SYMBOL_STAT_SEP:
1548 fputs(o->stat_sep, o->file);
1549 break;
1550 default:
1551 BUG("unknown diff symbol");
1553 strbuf_release(&sb);
1556 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1557 const char *line, int len, unsigned flags)
1559 struct emitted_diff_symbol e = {line, len, flags, 0, 0, s};
1561 if (o->emitted_symbols)
1562 append_emitted_diff_symbol(o, &e);
1563 else
1564 emit_diff_symbol_from_struct(o, &e);
1567 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1569 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1572 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1574 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1577 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1579 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1580 path, strlen(path), 0);
1583 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1585 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1586 path, strlen(path), 0);
1589 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1591 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1592 header, strlen(header), 0);
1595 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1597 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1600 void diff_emit_submodule_pipethrough(struct diff_options *o,
1601 const char *line, int len)
1603 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1606 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1608 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1609 ecbdata->blank_at_eof_in_preimage &&
1610 ecbdata->blank_at_eof_in_postimage &&
1611 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1612 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1613 return 0;
1614 return ws_blank_line(line, len, ecbdata->ws_rule);
1617 static void emit_add_line(struct emit_callback *ecbdata,
1618 const char *line, int len)
1620 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1621 if (new_blank_line_at_eof(ecbdata, line, len))
1622 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1624 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1627 static void emit_del_line(struct emit_callback *ecbdata,
1628 const char *line, int len)
1630 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1631 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1634 static void emit_context_line(struct emit_callback *ecbdata,
1635 const char *line, int len)
1637 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1638 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1641 static void emit_hunk_header(struct emit_callback *ecbdata,
1642 const char *line, int len)
1644 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1645 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1646 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1647 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1648 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1649 static const char atat[2] = { '@', '@' };
1650 const char *cp, *ep;
1651 struct strbuf msgbuf = STRBUF_INIT;
1652 int org_len = len;
1653 int i = 1;
1656 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1657 * it always is at least 10 bytes long.
1659 if (len < 10 ||
1660 memcmp(line, atat, 2) ||
1661 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1662 emit_diff_symbol(ecbdata->opt,
1663 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1664 return;
1666 ep += 2; /* skip over @@ */
1668 /* The hunk header in fraginfo color */
1669 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1670 strbuf_addstr(&msgbuf, reverse);
1671 strbuf_addstr(&msgbuf, frag);
1672 strbuf_add(&msgbuf, line, ep - line);
1673 strbuf_addstr(&msgbuf, reset);
1676 * trailing "\r\n"
1678 for ( ; i < 3; i++)
1679 if (line[len - i] == '\r' || line[len - i] == '\n')
1680 len--;
1682 /* blank before the func header */
1683 for (cp = ep; ep - line < len; ep++)
1684 if (*ep != ' ' && *ep != '\t')
1685 break;
1686 if (ep != cp) {
1687 strbuf_addstr(&msgbuf, context);
1688 strbuf_add(&msgbuf, cp, ep - cp);
1689 strbuf_addstr(&msgbuf, reset);
1692 if (ep < line + len) {
1693 strbuf_addstr(&msgbuf, func);
1694 strbuf_add(&msgbuf, ep, line + len - ep);
1695 strbuf_addstr(&msgbuf, reset);
1698 strbuf_add(&msgbuf, line + len, org_len - len);
1699 strbuf_complete_line(&msgbuf);
1700 emit_diff_symbol(ecbdata->opt,
1701 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1702 strbuf_release(&msgbuf);
1705 static struct diff_tempfile *claim_diff_tempfile(void)
1707 int i;
1708 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1709 if (!diff_temp[i].name)
1710 return diff_temp + i;
1711 BUG("diff is failing to clean up its tempfiles");
1714 static void remove_tempfile(void)
1716 int i;
1717 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1718 if (is_tempfile_active(diff_temp[i].tempfile))
1719 delete_tempfile(&diff_temp[i].tempfile);
1720 diff_temp[i].name = NULL;
1724 static void add_line_count(struct strbuf *out, int count)
1726 switch (count) {
1727 case 0:
1728 strbuf_addstr(out, "0,0");
1729 break;
1730 case 1:
1731 strbuf_addstr(out, "1");
1732 break;
1733 default:
1734 strbuf_addf(out, "1,%d", count);
1735 break;
1739 static void emit_rewrite_lines(struct emit_callback *ecb,
1740 int prefix, const char *data, int size)
1742 const char *endp = NULL;
1744 while (0 < size) {
1745 int len;
1747 endp = memchr(data, '\n', size);
1748 len = endp ? (endp - data + 1) : size;
1749 if (prefix != '+') {
1750 ecb->lno_in_preimage++;
1751 emit_del_line(ecb, data, len);
1752 } else {
1753 ecb->lno_in_postimage++;
1754 emit_add_line(ecb, data, len);
1756 size -= len;
1757 data += len;
1759 if (!endp)
1760 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1763 static void emit_rewrite_diff(const char *name_a,
1764 const char *name_b,
1765 struct diff_filespec *one,
1766 struct diff_filespec *two,
1767 struct userdiff_driver *textconv_one,
1768 struct userdiff_driver *textconv_two,
1769 struct diff_options *o)
1771 int lc_a, lc_b;
1772 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1773 const char *a_prefix, *b_prefix;
1774 char *data_one, *data_two;
1775 size_t size_one, size_two;
1776 struct emit_callback ecbdata;
1777 struct strbuf out = STRBUF_INIT;
1779 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1780 a_prefix = o->b_prefix;
1781 b_prefix = o->a_prefix;
1782 } else {
1783 a_prefix = o->a_prefix;
1784 b_prefix = o->b_prefix;
1787 name_a += (*name_a == '/');
1788 name_b += (*name_b == '/');
1790 strbuf_reset(&a_name);
1791 strbuf_reset(&b_name);
1792 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1793 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1795 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1796 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1798 memset(&ecbdata, 0, sizeof(ecbdata));
1799 ecbdata.color_diff = want_color(o->use_color);
1800 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1801 ecbdata.opt = o;
1802 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1803 mmfile_t mf1, mf2;
1804 mf1.ptr = (char *)data_one;
1805 mf2.ptr = (char *)data_two;
1806 mf1.size = size_one;
1807 mf2.size = size_two;
1808 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1810 ecbdata.lno_in_preimage = 1;
1811 ecbdata.lno_in_postimage = 1;
1813 lc_a = count_lines(data_one, size_one);
1814 lc_b = count_lines(data_two, size_two);
1816 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1817 a_name.buf, a_name.len, 0);
1818 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1819 b_name.buf, b_name.len, 0);
1821 strbuf_addstr(&out, "@@ -");
1822 if (!o->irreversible_delete)
1823 add_line_count(&out, lc_a);
1824 else
1825 strbuf_addstr(&out, "?,?");
1826 strbuf_addstr(&out, " +");
1827 add_line_count(&out, lc_b);
1828 strbuf_addstr(&out, " @@\n");
1829 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1830 strbuf_release(&out);
1832 if (lc_a && !o->irreversible_delete)
1833 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1834 if (lc_b)
1835 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1836 if (textconv_one)
1837 free((char *)data_one);
1838 if (textconv_two)
1839 free((char *)data_two);
1842 struct diff_words_buffer {
1843 mmfile_t text;
1844 unsigned long alloc;
1845 struct diff_words_orig {
1846 const char *begin, *end;
1847 } *orig;
1848 int orig_nr, orig_alloc;
1851 static void diff_words_append(char *line, unsigned long len,
1852 struct diff_words_buffer *buffer)
1854 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1855 line++;
1856 len--;
1857 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1858 buffer->text.size += len;
1859 buffer->text.ptr[buffer->text.size] = '\0';
1862 struct diff_words_style_elem {
1863 const char *prefix;
1864 const char *suffix;
1865 const char *color; /* NULL; filled in by the setup code if
1866 * color is enabled */
1869 struct diff_words_style {
1870 enum diff_words_type type;
1871 struct diff_words_style_elem new_word, old_word, ctx;
1872 const char *newline;
1875 static struct diff_words_style diff_words_styles[] = {
1876 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1877 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1878 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1881 struct diff_words_data {
1882 struct diff_words_buffer minus, plus;
1883 const char *current_plus;
1884 int last_minus;
1885 struct diff_options *opt;
1886 regex_t *word_regex;
1887 enum diff_words_type type;
1888 struct diff_words_style *style;
1891 static int fn_out_diff_words_write_helper(struct diff_options *o,
1892 struct diff_words_style_elem *st_el,
1893 const char *newline,
1894 size_t count, const char *buf)
1896 int print = 0;
1897 struct strbuf sb = STRBUF_INIT;
1899 while (count) {
1900 char *p = memchr(buf, '\n', count);
1901 if (print)
1902 strbuf_addstr(&sb, diff_line_prefix(o));
1904 if (p != buf) {
1905 const char *reset = st_el->color && *st_el->color ?
1906 GIT_COLOR_RESET : NULL;
1907 if (st_el->color && *st_el->color)
1908 strbuf_addstr(&sb, st_el->color);
1909 strbuf_addstr(&sb, st_el->prefix);
1910 strbuf_add(&sb, buf, p ? p - buf : count);
1911 strbuf_addstr(&sb, st_el->suffix);
1912 if (reset)
1913 strbuf_addstr(&sb, reset);
1915 if (!p)
1916 goto out;
1918 strbuf_addstr(&sb, newline);
1919 count -= p + 1 - buf;
1920 buf = p + 1;
1921 print = 1;
1922 if (count) {
1923 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1924 sb.buf, sb.len, 0);
1925 strbuf_reset(&sb);
1929 out:
1930 if (sb.len)
1931 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1932 sb.buf, sb.len, 0);
1933 strbuf_release(&sb);
1934 return 0;
1938 * '--color-words' algorithm can be described as:
1940 * 1. collect the minus/plus lines of a diff hunk, divided into
1941 * minus-lines and plus-lines;
1943 * 2. break both minus-lines and plus-lines into words and
1944 * place them into two mmfile_t with one word for each line;
1946 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1948 * And for the common parts of the both file, we output the plus side text.
1949 * diff_words->current_plus is used to trace the current position of the plus file
1950 * which printed. diff_words->last_minus is used to trace the last minus word
1951 * printed.
1953 * For '--graph' to work with '--color-words', we need to output the graph prefix
1954 * on each line of color words output. Generally, there are two conditions on
1955 * which we should output the prefix.
1957 * 1. diff_words->last_minus == 0 &&
1958 * diff_words->current_plus == diff_words->plus.text.ptr
1960 * that is: the plus text must start as a new line, and if there is no minus
1961 * word printed, a graph prefix must be printed.
1963 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1964 * *(diff_words->current_plus - 1) == '\n'
1966 * that is: a graph prefix must be printed following a '\n'
1968 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1970 if ((diff_words->last_minus == 0 &&
1971 diff_words->current_plus == diff_words->plus.text.ptr) ||
1972 (diff_words->current_plus > diff_words->plus.text.ptr &&
1973 *(diff_words->current_plus - 1) == '\n')) {
1974 return 1;
1975 } else {
1976 return 0;
1980 static void fn_out_diff_words_aux(void *priv,
1981 long minus_first, long minus_len,
1982 long plus_first, long plus_len,
1983 const char *func, long funclen)
1985 struct diff_words_data *diff_words = priv;
1986 struct diff_words_style *style = diff_words->style;
1987 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1988 struct diff_options *opt = diff_words->opt;
1989 const char *line_prefix;
1991 assert(opt);
1992 line_prefix = diff_line_prefix(opt);
1994 /* POSIX requires that first be decremented by one if len == 0... */
1995 if (minus_len) {
1996 minus_begin = diff_words->minus.orig[minus_first].begin;
1997 minus_end =
1998 diff_words->minus.orig[minus_first + minus_len - 1].end;
1999 } else
2000 minus_begin = minus_end =
2001 diff_words->minus.orig[minus_first].end;
2003 if (plus_len) {
2004 plus_begin = diff_words->plus.orig[plus_first].begin;
2005 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2006 } else
2007 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2009 if (color_words_output_graph_prefix(diff_words)) {
2010 fputs(line_prefix, diff_words->opt->file);
2012 if (diff_words->current_plus != plus_begin) {
2013 fn_out_diff_words_write_helper(diff_words->opt,
2014 &style->ctx, style->newline,
2015 plus_begin - diff_words->current_plus,
2016 diff_words->current_plus);
2018 if (minus_begin != minus_end) {
2019 fn_out_diff_words_write_helper(diff_words->opt,
2020 &style->old_word, style->newline,
2021 minus_end - minus_begin, minus_begin);
2023 if (plus_begin != plus_end) {
2024 fn_out_diff_words_write_helper(diff_words->opt,
2025 &style->new_word, style->newline,
2026 plus_end - plus_begin, plus_begin);
2029 diff_words->current_plus = plus_end;
2030 diff_words->last_minus = minus_first;
2033 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2034 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2035 int *begin, int *end)
2037 if (word_regex && *begin < buffer->size) {
2038 regmatch_t match[1];
2039 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2040 buffer->size - *begin, 1, match, 0)) {
2041 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2042 '\n', match[0].rm_eo - match[0].rm_so);
2043 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2044 *begin += match[0].rm_so;
2045 return *begin >= *end;
2047 return -1;
2050 /* find the next word */
2051 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2052 (*begin)++;
2053 if (*begin >= buffer->size)
2054 return -1;
2056 /* find the end of the word */
2057 *end = *begin + 1;
2058 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2059 (*end)++;
2061 return 0;
2065 * This function splits the words in buffer->text, stores the list with
2066 * newline separator into out, and saves the offsets of the original words
2067 * in buffer->orig.
2069 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2070 regex_t *word_regex)
2072 int i, j;
2073 long alloc = 0;
2075 out->size = 0;
2076 out->ptr = NULL;
2078 /* fake an empty "0th" word */
2079 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2080 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2081 buffer->orig_nr = 1;
2083 for (i = 0; i < buffer->text.size; i++) {
2084 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2085 return;
2087 /* store original boundaries */
2088 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2089 buffer->orig_alloc);
2090 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2091 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2092 buffer->orig_nr++;
2094 /* store one word */
2095 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2096 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2097 out->ptr[out->size + j - i] = '\n';
2098 out->size += j - i + 1;
2100 i = j - 1;
2104 /* this executes the word diff on the accumulated buffers */
2105 static void diff_words_show(struct diff_words_data *diff_words)
2107 xpparam_t xpp;
2108 xdemitconf_t xecfg;
2109 mmfile_t minus, plus;
2110 struct diff_words_style *style = diff_words->style;
2112 struct diff_options *opt = diff_words->opt;
2113 const char *line_prefix;
2115 assert(opt);
2116 line_prefix = diff_line_prefix(opt);
2118 /* special case: only removal */
2119 if (!diff_words->plus.text.size) {
2120 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2121 line_prefix, strlen(line_prefix), 0);
2122 fn_out_diff_words_write_helper(diff_words->opt,
2123 &style->old_word, style->newline,
2124 diff_words->minus.text.size,
2125 diff_words->minus.text.ptr);
2126 diff_words->minus.text.size = 0;
2127 return;
2130 diff_words->current_plus = diff_words->plus.text.ptr;
2131 diff_words->last_minus = 0;
2133 memset(&xpp, 0, sizeof(xpp));
2134 memset(&xecfg, 0, sizeof(xecfg));
2135 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2136 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2137 xpp.flags = 0;
2138 /* as only the hunk header will be parsed, we need a 0-context */
2139 xecfg.ctxlen = 0;
2140 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2141 diff_words, &xpp, &xecfg))
2142 die("unable to generate word diff");
2143 free(minus.ptr);
2144 free(plus.ptr);
2145 if (diff_words->current_plus != diff_words->plus.text.ptr +
2146 diff_words->plus.text.size) {
2147 if (color_words_output_graph_prefix(diff_words))
2148 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2149 line_prefix, strlen(line_prefix), 0);
2150 fn_out_diff_words_write_helper(diff_words->opt,
2151 &style->ctx, style->newline,
2152 diff_words->plus.text.ptr + diff_words->plus.text.size
2153 - diff_words->current_plus, diff_words->current_plus);
2155 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2158 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2159 static void diff_words_flush(struct emit_callback *ecbdata)
2161 struct diff_options *wo = ecbdata->diff_words->opt;
2163 if (ecbdata->diff_words->minus.text.size ||
2164 ecbdata->diff_words->plus.text.size)
2165 diff_words_show(ecbdata->diff_words);
2167 if (wo->emitted_symbols) {
2168 struct diff_options *o = ecbdata->opt;
2169 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2170 int i;
2173 * NEEDSWORK:
2174 * Instead of appending each, concat all words to a line?
2176 for (i = 0; i < wol->nr; i++)
2177 append_emitted_diff_symbol(o, &wol->buf[i]);
2179 for (i = 0; i < wol->nr; i++)
2180 free((void *)wol->buf[i].line);
2182 wol->nr = 0;
2186 static void diff_filespec_load_driver(struct diff_filespec *one,
2187 struct index_state *istate)
2189 /* Use already-loaded driver */
2190 if (one->driver)
2191 return;
2193 if (S_ISREG(one->mode))
2194 one->driver = userdiff_find_by_path(istate, one->path);
2196 /* Fallback to default settings */
2197 if (!one->driver)
2198 one->driver = userdiff_find_by_name("default");
2201 static const char *userdiff_word_regex(struct diff_filespec *one,
2202 struct index_state *istate)
2204 diff_filespec_load_driver(one, istate);
2205 return one->driver->word_regex;
2208 static void init_diff_words_data(struct emit_callback *ecbdata,
2209 struct diff_options *orig_opts,
2210 struct diff_filespec *one,
2211 struct diff_filespec *two)
2213 int i;
2214 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2215 memcpy(o, orig_opts, sizeof(struct diff_options));
2217 ecbdata->diff_words =
2218 xcalloc(1, sizeof(struct diff_words_data));
2219 ecbdata->diff_words->type = o->word_diff;
2220 ecbdata->diff_words->opt = o;
2222 if (orig_opts->emitted_symbols)
2223 o->emitted_symbols =
2224 xcalloc(1, sizeof(struct emitted_diff_symbols));
2226 if (!o->word_regex)
2227 o->word_regex = userdiff_word_regex(one, o->repo->index);
2228 if (!o->word_regex)
2229 o->word_regex = userdiff_word_regex(two, o->repo->index);
2230 if (!o->word_regex)
2231 o->word_regex = diff_word_regex_cfg;
2232 if (o->word_regex) {
2233 ecbdata->diff_words->word_regex = (regex_t *)
2234 xmalloc(sizeof(regex_t));
2235 if (regcomp(ecbdata->diff_words->word_regex,
2236 o->word_regex,
2237 REG_EXTENDED | REG_NEWLINE))
2238 die("invalid regular expression: %s",
2239 o->word_regex);
2241 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2242 if (o->word_diff == diff_words_styles[i].type) {
2243 ecbdata->diff_words->style =
2244 &diff_words_styles[i];
2245 break;
2248 if (want_color(o->use_color)) {
2249 struct diff_words_style *st = ecbdata->diff_words->style;
2250 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2251 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2252 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2256 static void free_diff_words_data(struct emit_callback *ecbdata)
2258 if (ecbdata->diff_words) {
2259 diff_words_flush(ecbdata);
2260 free (ecbdata->diff_words->opt->emitted_symbols);
2261 free (ecbdata->diff_words->opt);
2262 free (ecbdata->diff_words->minus.text.ptr);
2263 free (ecbdata->diff_words->minus.orig);
2264 free (ecbdata->diff_words->plus.text.ptr);
2265 free (ecbdata->diff_words->plus.orig);
2266 if (ecbdata->diff_words->word_regex) {
2267 regfree(ecbdata->diff_words->word_regex);
2268 free(ecbdata->diff_words->word_regex);
2270 FREE_AND_NULL(ecbdata->diff_words);
2274 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2276 if (want_color(diff_use_color))
2277 return diff_colors[ix];
2278 return "";
2281 const char *diff_line_prefix(struct diff_options *opt)
2283 struct strbuf *msgbuf;
2284 if (!opt->output_prefix)
2285 return "";
2287 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2288 return msgbuf->buf;
2291 static unsigned long sane_truncate_line(char *line, unsigned long len)
2293 const char *cp;
2294 unsigned long allot;
2295 size_t l = len;
2297 cp = line;
2298 allot = l;
2299 while (0 < l) {
2300 (void) utf8_width(&cp, &l);
2301 if (!cp)
2302 break; /* truncated in the middle? */
2304 return allot - l;
2307 static void find_lno(const char *line, struct emit_callback *ecbdata)
2309 const char *p;
2310 ecbdata->lno_in_preimage = 0;
2311 ecbdata->lno_in_postimage = 0;
2312 p = strchr(line, '-');
2313 if (!p)
2314 return; /* cannot happen */
2315 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2316 p = strchr(p, '+');
2317 if (!p)
2318 return; /* cannot happen */
2319 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2322 static void fn_out_consume(void *priv, char *line, unsigned long len)
2324 struct emit_callback *ecbdata = priv;
2325 struct diff_options *o = ecbdata->opt;
2327 o->found_changes = 1;
2329 if (ecbdata->header) {
2330 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2331 ecbdata->header->buf, ecbdata->header->len, 0);
2332 strbuf_reset(ecbdata->header);
2333 ecbdata->header = NULL;
2336 if (ecbdata->label_path[0]) {
2337 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2338 ecbdata->label_path[0],
2339 strlen(ecbdata->label_path[0]), 0);
2340 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2341 ecbdata->label_path[1],
2342 strlen(ecbdata->label_path[1]), 0);
2343 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2346 if (diff_suppress_blank_empty
2347 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2348 line[0] = '\n';
2349 len = 1;
2352 if (line[0] == '@') {
2353 if (ecbdata->diff_words)
2354 diff_words_flush(ecbdata);
2355 len = sane_truncate_line(line, len);
2356 find_lno(line, ecbdata);
2357 emit_hunk_header(ecbdata, line, len);
2358 return;
2361 if (ecbdata->diff_words) {
2362 enum diff_symbol s =
2363 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2364 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2365 if (line[0] == '-') {
2366 diff_words_append(line, len,
2367 &ecbdata->diff_words->minus);
2368 return;
2369 } else if (line[0] == '+') {
2370 diff_words_append(line, len,
2371 &ecbdata->diff_words->plus);
2372 return;
2373 } else if (starts_with(line, "\\ ")) {
2375 * Eat the "no newline at eof" marker as if we
2376 * saw a "+" or "-" line with nothing on it,
2377 * and return without diff_words_flush() to
2378 * defer processing. If this is the end of
2379 * preimage, more "+" lines may come after it.
2381 return;
2383 diff_words_flush(ecbdata);
2384 emit_diff_symbol(o, s, line, len, 0);
2385 return;
2388 switch (line[0]) {
2389 case '+':
2390 ecbdata->lno_in_postimage++;
2391 emit_add_line(ecbdata, line + 1, len - 1);
2392 break;
2393 case '-':
2394 ecbdata->lno_in_preimage++;
2395 emit_del_line(ecbdata, line + 1, len - 1);
2396 break;
2397 case ' ':
2398 ecbdata->lno_in_postimage++;
2399 ecbdata->lno_in_preimage++;
2400 emit_context_line(ecbdata, line + 1, len - 1);
2401 break;
2402 default:
2403 /* incomplete line at the end */
2404 ecbdata->lno_in_preimage++;
2405 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2406 line, len, 0);
2407 break;
2411 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2413 const char *old_name = a;
2414 const char *new_name = b;
2415 int pfx_length, sfx_length;
2416 int pfx_adjust_for_slash;
2417 int len_a = strlen(a);
2418 int len_b = strlen(b);
2419 int a_midlen, b_midlen;
2420 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2421 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2423 if (qlen_a || qlen_b) {
2424 quote_c_style(a, name, NULL, 0);
2425 strbuf_addstr(name, " => ");
2426 quote_c_style(b, name, NULL, 0);
2427 return;
2430 /* Find common prefix */
2431 pfx_length = 0;
2432 while (*old_name && *new_name && *old_name == *new_name) {
2433 if (*old_name == '/')
2434 pfx_length = old_name - a + 1;
2435 old_name++;
2436 new_name++;
2439 /* Find common suffix */
2440 old_name = a + len_a;
2441 new_name = b + len_b;
2442 sfx_length = 0;
2444 * If there is a common prefix, it must end in a slash. In
2445 * that case we let this loop run 1 into the prefix to see the
2446 * same slash.
2448 * If there is no common prefix, we cannot do this as it would
2449 * underrun the input strings.
2451 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2452 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2453 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2454 *old_name == *new_name) {
2455 if (*old_name == '/')
2456 sfx_length = len_a - (old_name - a);
2457 old_name--;
2458 new_name--;
2462 * pfx{mid-a => mid-b}sfx
2463 * {pfx-a => pfx-b}sfx
2464 * pfx{sfx-a => sfx-b}
2465 * name-a => name-b
2467 a_midlen = len_a - pfx_length - sfx_length;
2468 b_midlen = len_b - pfx_length - sfx_length;
2469 if (a_midlen < 0)
2470 a_midlen = 0;
2471 if (b_midlen < 0)
2472 b_midlen = 0;
2474 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2475 if (pfx_length + sfx_length) {
2476 strbuf_add(name, a, pfx_length);
2477 strbuf_addch(name, '{');
2479 strbuf_add(name, a + pfx_length, a_midlen);
2480 strbuf_addstr(name, " => ");
2481 strbuf_add(name, b + pfx_length, b_midlen);
2482 if (pfx_length + sfx_length) {
2483 strbuf_addch(name, '}');
2484 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2488 struct diffstat_t {
2489 int nr;
2490 int alloc;
2491 struct diffstat_file {
2492 char *from_name;
2493 char *name;
2494 char *print_name;
2495 const char *comments;
2496 unsigned is_unmerged:1;
2497 unsigned is_binary:1;
2498 unsigned is_renamed:1;
2499 unsigned is_interesting:1;
2500 uintmax_t added, deleted;
2501 } **files;
2504 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2505 const char *name_a,
2506 const char *name_b)
2508 struct diffstat_file *x;
2509 x = xcalloc(1, sizeof(*x));
2510 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2511 diffstat->files[diffstat->nr++] = x;
2512 if (name_b) {
2513 x->from_name = xstrdup(name_a);
2514 x->name = xstrdup(name_b);
2515 x->is_renamed = 1;
2517 else {
2518 x->from_name = NULL;
2519 x->name = xstrdup(name_a);
2521 return x;
2524 static void diffstat_consume(void *priv, char *line, unsigned long len)
2526 struct diffstat_t *diffstat = priv;
2527 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2529 if (line[0] == '+')
2530 x->added++;
2531 else if (line[0] == '-')
2532 x->deleted++;
2535 const char mime_boundary_leader[] = "------------";
2537 static int scale_linear(int it, int width, int max_change)
2539 if (!it)
2540 return 0;
2542 * make sure that at least one '-' or '+' is printed if
2543 * there is any change to this path. The easiest way is to
2544 * scale linearly as if the alloted width is one column shorter
2545 * than it is, and then add 1 to the result.
2547 return 1 + (it * (width - 1) / max_change);
2550 static void show_graph(struct strbuf *out, char ch, int cnt,
2551 const char *set, const char *reset)
2553 if (cnt <= 0)
2554 return;
2555 strbuf_addstr(out, set);
2556 strbuf_addchars(out, ch, cnt);
2557 strbuf_addstr(out, reset);
2560 static void fill_print_name(struct diffstat_file *file)
2562 struct strbuf pname = STRBUF_INIT;
2564 if (file->print_name)
2565 return;
2567 if (file->is_renamed)
2568 pprint_rename(&pname, file->from_name, file->name);
2569 else
2570 quote_c_style(file->name, &pname, NULL, 0);
2572 if (file->comments)
2573 strbuf_addf(&pname, " (%s)", file->comments);
2575 file->print_name = strbuf_detach(&pname, NULL);
2578 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2579 int files, int insertions, int deletions)
2581 struct strbuf sb = STRBUF_INIT;
2583 if (!files) {
2584 assert(insertions == 0 && deletions == 0);
2585 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2586 NULL, 0, 0);
2587 return;
2590 strbuf_addf(&sb,
2591 (files == 1) ? " %d file changed" : " %d files changed",
2592 files);
2595 * For binary diff, the caller may want to print "x files
2596 * changed" with insertions == 0 && deletions == 0.
2598 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2599 * is probably less confusing (i.e skip over "2 files changed
2600 * but nothing about added/removed lines? Is this a bug in Git?").
2602 if (insertions || deletions == 0) {
2603 strbuf_addf(&sb,
2604 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2605 insertions);
2608 if (deletions || insertions == 0) {
2609 strbuf_addf(&sb,
2610 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2611 deletions);
2613 strbuf_addch(&sb, '\n');
2614 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2615 sb.buf, sb.len, 0);
2616 strbuf_release(&sb);
2619 void print_stat_summary(FILE *fp, int files,
2620 int insertions, int deletions)
2622 struct diff_options o;
2623 memset(&o, 0, sizeof(o));
2624 o.file = fp;
2626 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2629 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2631 int i, len, add, del, adds = 0, dels = 0;
2632 uintmax_t max_change = 0, max_len = 0;
2633 int total_files = data->nr, count;
2634 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2635 const char *reset, *add_c, *del_c;
2636 int extra_shown = 0;
2637 const char *line_prefix = diff_line_prefix(options);
2638 struct strbuf out = STRBUF_INIT;
2640 if (data->nr == 0)
2641 return;
2643 count = options->stat_count ? options->stat_count : data->nr;
2645 reset = diff_get_color_opt(options, DIFF_RESET);
2646 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2647 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2650 * Find the longest filename and max number of changes
2652 for (i = 0; (i < count) && (i < data->nr); i++) {
2653 struct diffstat_file *file = data->files[i];
2654 uintmax_t change = file->added + file->deleted;
2656 if (!file->is_interesting && (change == 0)) {
2657 count++; /* not shown == room for one more */
2658 continue;
2660 fill_print_name(file);
2661 len = strlen(file->print_name);
2662 if (max_len < len)
2663 max_len = len;
2665 if (file->is_unmerged) {
2666 /* "Unmerged" is 8 characters */
2667 bin_width = bin_width < 8 ? 8 : bin_width;
2668 continue;
2670 if (file->is_binary) {
2671 /* "Bin XXX -> YYY bytes" */
2672 int w = 14 + decimal_width(file->added)
2673 + decimal_width(file->deleted);
2674 bin_width = bin_width < w ? w : bin_width;
2675 /* Display change counts aligned with "Bin" */
2676 number_width = 3;
2677 continue;
2680 if (max_change < change)
2681 max_change = change;
2683 count = i; /* where we can stop scanning in data->files[] */
2686 * We have width = stat_width or term_columns() columns total.
2687 * We want a maximum of min(max_len, stat_name_width) for the name part.
2688 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2689 * We also need 1 for " " and 4 + decimal_width(max_change)
2690 * for " | NNNN " and one the empty column at the end, altogether
2691 * 6 + decimal_width(max_change).
2693 * If there's not enough space, we will use the smaller of
2694 * stat_name_width (if set) and 5/8*width for the filename,
2695 * and the rest for constant elements + graph part, but no more
2696 * than stat_graph_width for the graph part.
2697 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2698 * for the standard terminal size).
2700 * In other words: stat_width limits the maximum width, and
2701 * stat_name_width fixes the maximum width of the filename,
2702 * and is also used to divide available columns if there
2703 * aren't enough.
2705 * Binary files are displayed with "Bin XXX -> YYY bytes"
2706 * instead of the change count and graph. This part is treated
2707 * similarly to the graph part, except that it is not
2708 * "scaled". If total width is too small to accommodate the
2709 * guaranteed minimum width of the filename part and the
2710 * separators and this message, this message will "overflow"
2711 * making the line longer than the maximum width.
2714 if (options->stat_width == -1)
2715 width = term_columns() - strlen(line_prefix);
2716 else
2717 width = options->stat_width ? options->stat_width : 80;
2718 number_width = decimal_width(max_change) > number_width ?
2719 decimal_width(max_change) : number_width;
2721 if (options->stat_graph_width == -1)
2722 options->stat_graph_width = diff_stat_graph_width;
2725 * Guarantee 3/8*16==6 for the graph part
2726 * and 5/8*16==10 for the filename part
2728 if (width < 16 + 6 + number_width)
2729 width = 16 + 6 + number_width;
2732 * First assign sizes that are wanted, ignoring available width.
2733 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2734 * starting from "XXX" should fit in graph_width.
2736 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2737 if (options->stat_graph_width &&
2738 options->stat_graph_width < graph_width)
2739 graph_width = options->stat_graph_width;
2741 name_width = (options->stat_name_width > 0 &&
2742 options->stat_name_width < max_len) ?
2743 options->stat_name_width : max_len;
2746 * Adjust adjustable widths not to exceed maximum width
2748 if (name_width + number_width + 6 + graph_width > width) {
2749 if (graph_width > width * 3/8 - number_width - 6) {
2750 graph_width = width * 3/8 - number_width - 6;
2751 if (graph_width < 6)
2752 graph_width = 6;
2755 if (options->stat_graph_width &&
2756 graph_width > options->stat_graph_width)
2757 graph_width = options->stat_graph_width;
2758 if (name_width > width - number_width - 6 - graph_width)
2759 name_width = width - number_width - 6 - graph_width;
2760 else
2761 graph_width = width - number_width - 6 - name_width;
2765 * From here name_width is the width of the name area,
2766 * and graph_width is the width of the graph area.
2767 * max_change is used to scale graph properly.
2769 for (i = 0; i < count; i++) {
2770 const char *prefix = "";
2771 struct diffstat_file *file = data->files[i];
2772 char *name = file->print_name;
2773 uintmax_t added = file->added;
2774 uintmax_t deleted = file->deleted;
2775 int name_len;
2777 if (!file->is_interesting && (added + deleted == 0))
2778 continue;
2781 * "scale" the filename
2783 len = name_width;
2784 name_len = strlen(name);
2785 if (name_width < name_len) {
2786 char *slash;
2787 prefix = "...";
2788 len -= 3;
2789 name += name_len - len;
2790 slash = strchr(name, '/');
2791 if (slash)
2792 name = slash;
2795 if (file->is_binary) {
2796 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2797 strbuf_addf(&out, " %*s", number_width, "Bin");
2798 if (!added && !deleted) {
2799 strbuf_addch(&out, '\n');
2800 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2801 out.buf, out.len, 0);
2802 strbuf_reset(&out);
2803 continue;
2805 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2806 del_c, deleted, reset);
2807 strbuf_addstr(&out, " -> ");
2808 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2809 add_c, added, reset);
2810 strbuf_addstr(&out, " bytes\n");
2811 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2812 out.buf, out.len, 0);
2813 strbuf_reset(&out);
2814 continue;
2816 else if (file->is_unmerged) {
2817 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2818 strbuf_addstr(&out, " Unmerged\n");
2819 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2820 out.buf, out.len, 0);
2821 strbuf_reset(&out);
2822 continue;
2826 * scale the add/delete
2828 add = added;
2829 del = deleted;
2831 if (graph_width <= max_change) {
2832 int total = scale_linear(add + del, graph_width, max_change);
2833 if (total < 2 && add && del)
2834 /* width >= 2 due to the sanity check */
2835 total = 2;
2836 if (add < del) {
2837 add = scale_linear(add, graph_width, max_change);
2838 del = total - add;
2839 } else {
2840 del = scale_linear(del, graph_width, max_change);
2841 add = total - del;
2844 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2845 strbuf_addf(&out, " %*"PRIuMAX"%s",
2846 number_width, added + deleted,
2847 added + deleted ? " " : "");
2848 show_graph(&out, '+', add, add_c, reset);
2849 show_graph(&out, '-', del, del_c, reset);
2850 strbuf_addch(&out, '\n');
2851 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2852 out.buf, out.len, 0);
2853 strbuf_reset(&out);
2856 for (i = 0; i < data->nr; i++) {
2857 struct diffstat_file *file = data->files[i];
2858 uintmax_t added = file->added;
2859 uintmax_t deleted = file->deleted;
2861 if (file->is_unmerged ||
2862 (!file->is_interesting && (added + deleted == 0))) {
2863 total_files--;
2864 continue;
2867 if (!file->is_binary) {
2868 adds += added;
2869 dels += deleted;
2871 if (i < count)
2872 continue;
2873 if (!extra_shown)
2874 emit_diff_symbol(options,
2875 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2876 NULL, 0, 0);
2877 extra_shown = 1;
2880 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2881 strbuf_release(&out);
2884 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2886 int i, adds = 0, dels = 0, total_files = data->nr;
2888 if (data->nr == 0)
2889 return;
2891 for (i = 0; i < data->nr; i++) {
2892 int added = data->files[i]->added;
2893 int deleted = data->files[i]->deleted;
2895 if (data->files[i]->is_unmerged ||
2896 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2897 total_files--;
2898 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2899 adds += added;
2900 dels += deleted;
2903 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2906 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2908 int i;
2910 if (data->nr == 0)
2911 return;
2913 for (i = 0; i < data->nr; i++) {
2914 struct diffstat_file *file = data->files[i];
2916 fprintf(options->file, "%s", diff_line_prefix(options));
2918 if (file->is_binary)
2919 fprintf(options->file, "-\t-\t");
2920 else
2921 fprintf(options->file,
2922 "%"PRIuMAX"\t%"PRIuMAX"\t",
2923 file->added, file->deleted);
2924 if (options->line_termination) {
2925 fill_print_name(file);
2926 if (!file->is_renamed)
2927 write_name_quoted(file->name, options->file,
2928 options->line_termination);
2929 else {
2930 fputs(file->print_name, options->file);
2931 putc(options->line_termination, options->file);
2933 } else {
2934 if (file->is_renamed) {
2935 putc('\0', options->file);
2936 write_name_quoted(file->from_name, options->file, '\0');
2938 write_name_quoted(file->name, options->file, '\0');
2943 struct dirstat_file {
2944 const char *name;
2945 unsigned long changed;
2948 struct dirstat_dir {
2949 struct dirstat_file *files;
2950 int alloc, nr, permille, cumulative;
2953 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2954 unsigned long changed, const char *base, int baselen)
2956 unsigned long sum_changes = 0;
2957 unsigned int sources = 0;
2958 const char *line_prefix = diff_line_prefix(opt);
2960 while (dir->nr) {
2961 struct dirstat_file *f = dir->files;
2962 int namelen = strlen(f->name);
2963 unsigned long changes;
2964 char *slash;
2966 if (namelen < baselen)
2967 break;
2968 if (memcmp(f->name, base, baselen))
2969 break;
2970 slash = strchr(f->name + baselen, '/');
2971 if (slash) {
2972 int newbaselen = slash + 1 - f->name;
2973 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2974 sources++;
2975 } else {
2976 changes = f->changed;
2977 dir->files++;
2978 dir->nr--;
2979 sources += 2;
2981 sum_changes += changes;
2985 * We don't report dirstat's for
2986 * - the top level
2987 * - or cases where everything came from a single directory
2988 * under this directory (sources == 1).
2990 if (baselen && sources != 1) {
2991 if (sum_changes) {
2992 int permille = sum_changes * 1000 / changed;
2993 if (permille >= dir->permille) {
2994 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2995 permille / 10, permille % 10, baselen, base);
2996 if (!dir->cumulative)
2997 return 0;
3001 return sum_changes;
3004 static int dirstat_compare(const void *_a, const void *_b)
3006 const struct dirstat_file *a = _a;
3007 const struct dirstat_file *b = _b;
3008 return strcmp(a->name, b->name);
3011 static void show_dirstat(struct diff_options *options)
3013 int i;
3014 unsigned long changed;
3015 struct dirstat_dir dir;
3016 struct diff_queue_struct *q = &diff_queued_diff;
3018 dir.files = NULL;
3019 dir.alloc = 0;
3020 dir.nr = 0;
3021 dir.permille = options->dirstat_permille;
3022 dir.cumulative = options->flags.dirstat_cumulative;
3024 changed = 0;
3025 for (i = 0; i < q->nr; i++) {
3026 struct diff_filepair *p = q->queue[i];
3027 const char *name;
3028 unsigned long copied, added, damage;
3030 name = p->two->path ? p->two->path : p->one->path;
3032 if (p->one->oid_valid && p->two->oid_valid &&
3033 oideq(&p->one->oid, &p->two->oid)) {
3035 * The SHA1 has not changed, so pre-/post-content is
3036 * identical. We can therefore skip looking at the
3037 * file contents altogether.
3039 damage = 0;
3040 goto found_damage;
3043 if (options->flags.dirstat_by_file) {
3045 * In --dirstat-by-file mode, we don't really need to
3046 * look at the actual file contents at all.
3047 * The fact that the SHA1 changed is enough for us to
3048 * add this file to the list of results
3049 * (with each file contributing equal damage).
3051 damage = 1;
3052 goto found_damage;
3055 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3056 diff_populate_filespec(options->repo, p->one, 0);
3057 diff_populate_filespec(options->repo, p->two, 0);
3058 diffcore_count_changes(options->repo,
3059 p->one, p->two, NULL, NULL,
3060 &copied, &added);
3061 diff_free_filespec_data(p->one);
3062 diff_free_filespec_data(p->two);
3063 } else if (DIFF_FILE_VALID(p->one)) {
3064 diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
3065 copied = added = 0;
3066 diff_free_filespec_data(p->one);
3067 } else if (DIFF_FILE_VALID(p->two)) {
3068 diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
3069 copied = 0;
3070 added = p->two->size;
3071 diff_free_filespec_data(p->two);
3072 } else
3073 continue;
3076 * Original minus copied is the removed material,
3077 * added is the new material. They are both damages
3078 * made to the preimage.
3079 * If the resulting damage is zero, we know that
3080 * diffcore_count_changes() considers the two entries to
3081 * be identical, but since the oid changed, we
3082 * know that there must have been _some_ kind of change,
3083 * so we force all entries to have damage > 0.
3085 damage = (p->one->size - copied) + added;
3086 if (!damage)
3087 damage = 1;
3089 found_damage:
3090 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3091 dir.files[dir.nr].name = name;
3092 dir.files[dir.nr].changed = damage;
3093 changed += damage;
3094 dir.nr++;
3097 /* This can happen even with many files, if everything was renames */
3098 if (!changed)
3099 return;
3101 /* Show all directories with more than x% of the changes */
3102 QSORT(dir.files, dir.nr, dirstat_compare);
3103 gather_dirstat(options, &dir, changed, "", 0);
3106 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3108 int i;
3109 unsigned long changed;
3110 struct dirstat_dir dir;
3112 if (data->nr == 0)
3113 return;
3115 dir.files = NULL;
3116 dir.alloc = 0;
3117 dir.nr = 0;
3118 dir.permille = options->dirstat_permille;
3119 dir.cumulative = options->flags.dirstat_cumulative;
3121 changed = 0;
3122 for (i = 0; i < data->nr; i++) {
3123 struct diffstat_file *file = data->files[i];
3124 unsigned long damage = file->added + file->deleted;
3125 if (file->is_binary)
3127 * binary files counts bytes, not lines. Must find some
3128 * way to normalize binary bytes vs. textual lines.
3129 * The following heuristic assumes that there are 64
3130 * bytes per "line".
3131 * This is stupid and ugly, but very cheap...
3133 damage = DIV_ROUND_UP(damage, 64);
3134 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3135 dir.files[dir.nr].name = file->name;
3136 dir.files[dir.nr].changed = damage;
3137 changed += damage;
3138 dir.nr++;
3141 /* This can happen even with many files, if everything was renames */
3142 if (!changed)
3143 return;
3145 /* Show all directories with more than x% of the changes */
3146 QSORT(dir.files, dir.nr, dirstat_compare);
3147 gather_dirstat(options, &dir, changed, "", 0);
3150 static void free_diffstat_info(struct diffstat_t *diffstat)
3152 int i;
3153 for (i = 0; i < diffstat->nr; i++) {
3154 struct diffstat_file *f = diffstat->files[i];
3155 free(f->print_name);
3156 free(f->name);
3157 free(f->from_name);
3158 free(f);
3160 free(diffstat->files);
3163 struct checkdiff_t {
3164 const char *filename;
3165 int lineno;
3166 int conflict_marker_size;
3167 struct diff_options *o;
3168 unsigned ws_rule;
3169 unsigned status;
3172 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3174 char firstchar;
3175 int cnt;
3177 if (len < marker_size + 1)
3178 return 0;
3179 firstchar = line[0];
3180 switch (firstchar) {
3181 case '=': case '>': case '<': case '|':
3182 break;
3183 default:
3184 return 0;
3186 for (cnt = 1; cnt < marker_size; cnt++)
3187 if (line[cnt] != firstchar)
3188 return 0;
3189 /* line[1] thru line[marker_size-1] are same as firstchar */
3190 if (len < marker_size + 1 || !isspace(line[marker_size]))
3191 return 0;
3192 return 1;
3195 static void checkdiff_consume_hunk(void *priv,
3196 long ob, long on, long nb, long nn,
3197 const char *func, long funclen)
3200 struct checkdiff_t *data = priv;
3201 data->lineno = nb - 1;
3204 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3206 struct checkdiff_t *data = priv;
3207 int marker_size = data->conflict_marker_size;
3208 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3209 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3210 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3211 char *err;
3212 const char *line_prefix;
3214 assert(data->o);
3215 line_prefix = diff_line_prefix(data->o);
3217 if (line[0] == '+') {
3218 unsigned bad;
3219 data->lineno++;
3220 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3221 data->status |= 1;
3222 fprintf(data->o->file,
3223 "%s%s:%d: leftover conflict marker\n",
3224 line_prefix, data->filename, data->lineno);
3226 bad = ws_check(line + 1, len - 1, data->ws_rule);
3227 if (!bad)
3228 return;
3229 data->status |= bad;
3230 err = whitespace_error_string(bad);
3231 fprintf(data->o->file, "%s%s:%d: %s.\n",
3232 line_prefix, data->filename, data->lineno, err);
3233 free(err);
3234 emit_line(data->o, set, reset, line, 1);
3235 ws_check_emit(line + 1, len - 1, data->ws_rule,
3236 data->o->file, set, reset, ws);
3237 } else if (line[0] == ' ') {
3238 data->lineno++;
3242 static unsigned char *deflate_it(char *data,
3243 unsigned long size,
3244 unsigned long *result_size)
3246 int bound;
3247 unsigned char *deflated;
3248 git_zstream stream;
3250 git_deflate_init(&stream, zlib_compression_level);
3251 bound = git_deflate_bound(&stream, size);
3252 deflated = xmalloc(bound);
3253 stream.next_out = deflated;
3254 stream.avail_out = bound;
3256 stream.next_in = (unsigned char *)data;
3257 stream.avail_in = size;
3258 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3259 ; /* nothing */
3260 git_deflate_end(&stream);
3261 *result_size = stream.total_out;
3262 return deflated;
3265 static void emit_binary_diff_body(struct diff_options *o,
3266 mmfile_t *one, mmfile_t *two)
3268 void *cp;
3269 void *delta;
3270 void *deflated;
3271 void *data;
3272 unsigned long orig_size;
3273 unsigned long delta_size;
3274 unsigned long deflate_size;
3275 unsigned long data_size;
3277 /* We could do deflated delta, or we could do just deflated two,
3278 * whichever is smaller.
3280 delta = NULL;
3281 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3282 if (one->size && two->size) {
3283 delta = diff_delta(one->ptr, one->size,
3284 two->ptr, two->size,
3285 &delta_size, deflate_size);
3286 if (delta) {
3287 void *to_free = delta;
3288 orig_size = delta_size;
3289 delta = deflate_it(delta, delta_size, &delta_size);
3290 free(to_free);
3294 if (delta && delta_size < deflate_size) {
3295 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3296 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3297 s, strlen(s), 0);
3298 free(s);
3299 free(deflated);
3300 data = delta;
3301 data_size = delta_size;
3302 } else {
3303 char *s = xstrfmt("%lu", two->size);
3304 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3305 s, strlen(s), 0);
3306 free(s);
3307 free(delta);
3308 data = deflated;
3309 data_size = deflate_size;
3312 /* emit data encoded in base85 */
3313 cp = data;
3314 while (data_size) {
3315 int len;
3316 int bytes = (52 < data_size) ? 52 : data_size;
3317 char line[71];
3318 data_size -= bytes;
3319 if (bytes <= 26)
3320 line[0] = bytes + 'A' - 1;
3321 else
3322 line[0] = bytes - 26 + 'a' - 1;
3323 encode_85(line + 1, cp, bytes);
3324 cp = (char *) cp + bytes;
3326 len = strlen(line);
3327 line[len++] = '\n';
3328 line[len] = '\0';
3330 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3331 line, len, 0);
3333 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3334 free(data);
3337 static void emit_binary_diff(struct diff_options *o,
3338 mmfile_t *one, mmfile_t *two)
3340 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3341 emit_binary_diff_body(o, one, two);
3342 emit_binary_diff_body(o, two, one);
3345 int diff_filespec_is_binary(struct repository *r,
3346 struct diff_filespec *one)
3348 if (one->is_binary == -1) {
3349 diff_filespec_load_driver(one, r->index);
3350 if (one->driver->binary != -1)
3351 one->is_binary = one->driver->binary;
3352 else {
3353 if (!one->data && DIFF_FILE_VALID(one))
3354 diff_populate_filespec(r, one, CHECK_BINARY);
3355 if (one->is_binary == -1 && one->data)
3356 one->is_binary = buffer_is_binary(one->data,
3357 one->size);
3358 if (one->is_binary == -1)
3359 one->is_binary = 0;
3362 return one->is_binary;
3365 static const struct userdiff_funcname *
3366 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3368 diff_filespec_load_driver(one, o->repo->index);
3369 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3372 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3374 if (!options->a_prefix)
3375 options->a_prefix = a;
3376 if (!options->b_prefix)
3377 options->b_prefix = b;
3380 struct userdiff_driver *get_textconv(struct repository *r,
3381 struct diff_filespec *one)
3383 if (!DIFF_FILE_VALID(one))
3384 return NULL;
3386 diff_filespec_load_driver(one, r->index);
3387 return userdiff_get_textconv(r, one->driver);
3390 static void builtin_diff(const char *name_a,
3391 const char *name_b,
3392 struct diff_filespec *one,
3393 struct diff_filespec *two,
3394 const char *xfrm_msg,
3395 int must_show_header,
3396 struct diff_options *o,
3397 int complete_rewrite)
3399 mmfile_t mf1, mf2;
3400 const char *lbl[2];
3401 char *a_one, *b_two;
3402 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3403 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3404 const char *a_prefix, *b_prefix;
3405 struct userdiff_driver *textconv_one = NULL;
3406 struct userdiff_driver *textconv_two = NULL;
3407 struct strbuf header = STRBUF_INIT;
3408 const char *line_prefix = diff_line_prefix(o);
3410 diff_set_mnemonic_prefix(o, "a/", "b/");
3411 if (o->flags.reverse_diff) {
3412 a_prefix = o->b_prefix;
3413 b_prefix = o->a_prefix;
3414 } else {
3415 a_prefix = o->a_prefix;
3416 b_prefix = o->b_prefix;
3419 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3420 (!one->mode || S_ISGITLINK(one->mode)) &&
3421 (!two->mode || S_ISGITLINK(two->mode))) {
3422 show_submodule_summary(o, one->path ? one->path : two->path,
3423 &one->oid, &two->oid,
3424 two->dirty_submodule);
3425 return;
3426 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3427 (!one->mode || S_ISGITLINK(one->mode)) &&
3428 (!two->mode || S_ISGITLINK(two->mode))) {
3429 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3430 &one->oid, &two->oid,
3431 two->dirty_submodule);
3432 return;
3435 if (o->flags.allow_textconv) {
3436 textconv_one = get_textconv(o->repo, one);
3437 textconv_two = get_textconv(o->repo, two);
3440 /* Never use a non-valid filename anywhere if at all possible */
3441 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3442 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3444 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3445 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3446 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3447 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3448 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3449 if (lbl[0][0] == '/') {
3450 /* /dev/null */
3451 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3452 if (xfrm_msg)
3453 strbuf_addstr(&header, xfrm_msg);
3454 must_show_header = 1;
3456 else if (lbl[1][0] == '/') {
3457 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3458 if (xfrm_msg)
3459 strbuf_addstr(&header, xfrm_msg);
3460 must_show_header = 1;
3462 else {
3463 if (one->mode != two->mode) {
3464 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3465 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3466 must_show_header = 1;
3468 if (xfrm_msg)
3469 strbuf_addstr(&header, xfrm_msg);
3472 * we do not run diff between different kind
3473 * of objects.
3475 if ((one->mode ^ two->mode) & S_IFMT)
3476 goto free_ab_and_return;
3477 if (complete_rewrite &&
3478 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3479 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3480 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3481 header.buf, header.len, 0);
3482 strbuf_reset(&header);
3483 emit_rewrite_diff(name_a, name_b, one, two,
3484 textconv_one, textconv_two, o);
3485 o->found_changes = 1;
3486 goto free_ab_and_return;
3490 if (o->irreversible_delete && lbl[1][0] == '/') {
3491 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3492 header.len, 0);
3493 strbuf_reset(&header);
3494 goto free_ab_and_return;
3495 } else if (!o->flags.text &&
3496 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3497 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3498 struct strbuf sb = STRBUF_INIT;
3499 if (!one->data && !two->data &&
3500 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3501 !o->flags.binary) {
3502 if (oideq(&one->oid, &two->oid)) {
3503 if (must_show_header)
3504 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3505 header.buf, header.len,
3507 goto free_ab_and_return;
3509 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3510 header.buf, header.len, 0);
3511 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3512 diff_line_prefix(o), lbl[0], lbl[1]);
3513 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3514 sb.buf, sb.len, 0);
3515 strbuf_release(&sb);
3516 goto free_ab_and_return;
3518 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3519 fill_mmfile(o->repo, &mf2, two) < 0)
3520 die("unable to read files to diff");
3521 /* Quite common confusing case */
3522 if (mf1.size == mf2.size &&
3523 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3524 if (must_show_header)
3525 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3526 header.buf, header.len, 0);
3527 goto free_ab_and_return;
3529 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3530 strbuf_reset(&header);
3531 if (o->flags.binary)
3532 emit_binary_diff(o, &mf1, &mf2);
3533 else {
3534 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3535 diff_line_prefix(o), lbl[0], lbl[1]);
3536 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3537 sb.buf, sb.len, 0);
3538 strbuf_release(&sb);
3540 o->found_changes = 1;
3541 } else {
3542 /* Crazy xdl interfaces.. */
3543 const char *diffopts;
3544 const char *v;
3545 xpparam_t xpp;
3546 xdemitconf_t xecfg;
3547 struct emit_callback ecbdata;
3548 const struct userdiff_funcname *pe;
3550 if (must_show_header) {
3551 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3552 header.buf, header.len, 0);
3553 strbuf_reset(&header);
3556 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3557 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3559 pe = diff_funcname_pattern(o, one);
3560 if (!pe)
3561 pe = diff_funcname_pattern(o, two);
3563 memset(&xpp, 0, sizeof(xpp));
3564 memset(&xecfg, 0, sizeof(xecfg));
3565 memset(&ecbdata, 0, sizeof(ecbdata));
3566 if (o->flags.suppress_diff_headers)
3567 lbl[0] = NULL;
3568 ecbdata.label_path = lbl;
3569 ecbdata.color_diff = want_color(o->use_color);
3570 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3571 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3572 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3573 ecbdata.opt = o;
3574 if (header.len && !o->flags.suppress_diff_headers)
3575 ecbdata.header = &header;
3576 xpp.flags = o->xdl_opts;
3577 xpp.anchors = o->anchors;
3578 xpp.anchors_nr = o->anchors_nr;
3579 xecfg.ctxlen = o->context;
3580 xecfg.interhunkctxlen = o->interhunkcontext;
3581 xecfg.flags = XDL_EMIT_FUNCNAMES;
3582 if (o->flags.funccontext)
3583 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3584 if (pe)
3585 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3587 diffopts = getenv("GIT_DIFF_OPTS");
3588 if (!diffopts)
3590 else if (skip_prefix(diffopts, "--unified=", &v))
3591 xecfg.ctxlen = strtoul(v, NULL, 10);
3592 else if (skip_prefix(diffopts, "-u", &v))
3593 xecfg.ctxlen = strtoul(v, NULL, 10);
3595 if (o->word_diff)
3596 init_diff_words_data(&ecbdata, o, one, two);
3597 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3598 &ecbdata, &xpp, &xecfg))
3599 die("unable to generate diff for %s", one->path);
3600 if (o->word_diff)
3601 free_diff_words_data(&ecbdata);
3602 if (textconv_one)
3603 free(mf1.ptr);
3604 if (textconv_two)
3605 free(mf2.ptr);
3606 xdiff_clear_find_func(&xecfg);
3609 free_ab_and_return:
3610 strbuf_release(&header);
3611 diff_free_filespec_data(one);
3612 diff_free_filespec_data(two);
3613 free(a_one);
3614 free(b_two);
3615 return;
3618 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3620 if (!is_renamed) {
3621 if (p->status == DIFF_STATUS_ADDED) {
3622 if (S_ISLNK(p->two->mode))
3623 return "new +l";
3624 else if ((p->two->mode & 0777) == 0755)
3625 return "new +x";
3626 else
3627 return "new";
3628 } else if (p->status == DIFF_STATUS_DELETED)
3629 return "gone";
3631 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3632 return "mode -l";
3633 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3634 return "mode +l";
3635 else if ((p->one->mode & 0777) == 0644 &&
3636 (p->two->mode & 0777) == 0755)
3637 return "mode +x";
3638 else if ((p->one->mode & 0777) == 0755 &&
3639 (p->two->mode & 0777) == 0644)
3640 return "mode -x";
3641 return NULL;
3644 static void builtin_diffstat(const char *name_a, const char *name_b,
3645 struct diff_filespec *one,
3646 struct diff_filespec *two,
3647 struct diffstat_t *diffstat,
3648 struct diff_options *o,
3649 struct diff_filepair *p)
3651 mmfile_t mf1, mf2;
3652 struct diffstat_file *data;
3653 int same_contents;
3654 int complete_rewrite = 0;
3656 if (!DIFF_PAIR_UNMERGED(p)) {
3657 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3658 complete_rewrite = 1;
3661 data = diffstat_add(diffstat, name_a, name_b);
3662 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3663 if (o->flags.stat_with_summary)
3664 data->comments = get_compact_summary(p, data->is_renamed);
3666 if (!one || !two) {
3667 data->is_unmerged = 1;
3668 return;
3671 same_contents = oideq(&one->oid, &two->oid);
3673 if (diff_filespec_is_binary(o->repo, one) ||
3674 diff_filespec_is_binary(o->repo, two)) {
3675 data->is_binary = 1;
3676 if (same_contents) {
3677 data->added = 0;
3678 data->deleted = 0;
3679 } else {
3680 data->added = diff_filespec_size(o->repo, two);
3681 data->deleted = diff_filespec_size(o->repo, one);
3685 else if (complete_rewrite) {
3686 diff_populate_filespec(o->repo, one, 0);
3687 diff_populate_filespec(o->repo, two, 0);
3688 data->deleted = count_lines(one->data, one->size);
3689 data->added = count_lines(two->data, two->size);
3692 else if (!same_contents) {
3693 /* Crazy xdl interfaces.. */
3694 xpparam_t xpp;
3695 xdemitconf_t xecfg;
3697 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3698 fill_mmfile(o->repo, &mf2, two) < 0)
3699 die("unable to read files to diff");
3701 memset(&xpp, 0, sizeof(xpp));
3702 memset(&xecfg, 0, sizeof(xecfg));
3703 xpp.flags = o->xdl_opts;
3704 xpp.anchors = o->anchors;
3705 xpp.anchors_nr = o->anchors_nr;
3706 xecfg.ctxlen = o->context;
3707 xecfg.interhunkctxlen = o->interhunkcontext;
3708 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3709 diffstat_consume, diffstat, &xpp, &xecfg))
3710 die("unable to generate diffstat for %s", one->path);
3713 diff_free_filespec_data(one);
3714 diff_free_filespec_data(two);
3717 static void builtin_checkdiff(const char *name_a, const char *name_b,
3718 const char *attr_path,
3719 struct diff_filespec *one,
3720 struct diff_filespec *two,
3721 struct diff_options *o)
3723 mmfile_t mf1, mf2;
3724 struct checkdiff_t data;
3726 if (!two)
3727 return;
3729 memset(&data, 0, sizeof(data));
3730 data.filename = name_b ? name_b : name_a;
3731 data.lineno = 0;
3732 data.o = o;
3733 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3734 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3736 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3737 fill_mmfile(o->repo, &mf2, two) < 0)
3738 die("unable to read files to diff");
3741 * All the other codepaths check both sides, but not checking
3742 * the "old" side here is deliberate. We are checking the newly
3743 * introduced changes, and as long as the "new" side is text, we
3744 * can and should check what it introduces.
3746 if (diff_filespec_is_binary(o->repo, two))
3747 goto free_and_return;
3748 else {
3749 /* Crazy xdl interfaces.. */
3750 xpparam_t xpp;
3751 xdemitconf_t xecfg;
3753 memset(&xpp, 0, sizeof(xpp));
3754 memset(&xecfg, 0, sizeof(xecfg));
3755 xecfg.ctxlen = 1; /* at least one context line */
3756 xpp.flags = 0;
3757 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3758 checkdiff_consume, &data,
3759 &xpp, &xecfg))
3760 die("unable to generate checkdiff for %s", one->path);
3762 if (data.ws_rule & WS_BLANK_AT_EOF) {
3763 struct emit_callback ecbdata;
3764 int blank_at_eof;
3766 ecbdata.ws_rule = data.ws_rule;
3767 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3768 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3770 if (blank_at_eof) {
3771 static char *err;
3772 if (!err)
3773 err = whitespace_error_string(WS_BLANK_AT_EOF);
3774 fprintf(o->file, "%s:%d: %s.\n",
3775 data.filename, blank_at_eof, err);
3776 data.status = 1; /* report errors */
3780 free_and_return:
3781 diff_free_filespec_data(one);
3782 diff_free_filespec_data(two);
3783 if (data.status)
3784 o->flags.check_failed = 1;
3787 struct diff_filespec *alloc_filespec(const char *path)
3789 struct diff_filespec *spec;
3791 FLEXPTR_ALLOC_STR(spec, path, path);
3792 spec->count = 1;
3793 spec->is_binary = -1;
3794 return spec;
3797 void free_filespec(struct diff_filespec *spec)
3799 if (!--spec->count) {
3800 diff_free_filespec_data(spec);
3801 free(spec);
3805 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3806 int oid_valid, unsigned short mode)
3808 if (mode) {
3809 spec->mode = canon_mode(mode);
3810 oidcpy(&spec->oid, oid);
3811 spec->oid_valid = oid_valid;
3816 * Given a name and sha1 pair, if the index tells us the file in
3817 * the work tree has that object contents, return true, so that
3818 * prepare_temp_file() does not have to inflate and extract.
3820 static int reuse_worktree_file(struct index_state *istate,
3821 const char *name,
3822 const struct object_id *oid,
3823 int want_file)
3825 const struct cache_entry *ce;
3826 struct stat st;
3827 int pos, len;
3830 * We do not read the cache ourselves here, because the
3831 * benchmark with my previous version that always reads cache
3832 * shows that it makes things worse for diff-tree comparing
3833 * two linux-2.6 kernel trees in an already checked out work
3834 * tree. This is because most diff-tree comparisons deal with
3835 * only a small number of files, while reading the cache is
3836 * expensive for a large project, and its cost outweighs the
3837 * savings we get by not inflating the object to a temporary
3838 * file. Practically, this code only helps when we are used
3839 * by diff-cache --cached, which does read the cache before
3840 * calling us.
3842 if (!istate->cache)
3843 return 0;
3845 /* We want to avoid the working directory if our caller
3846 * doesn't need the data in a normal file, this system
3847 * is rather slow with its stat/open/mmap/close syscalls,
3848 * and the object is contained in a pack file. The pack
3849 * is probably already open and will be faster to obtain
3850 * the data through than the working directory. Loose
3851 * objects however would tend to be slower as they need
3852 * to be individually opened and inflated.
3854 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3855 return 0;
3858 * Similarly, if we'd have to convert the file contents anyway, that
3859 * makes the optimization not worthwhile.
3861 if (!want_file && would_convert_to_git(istate, name))
3862 return 0;
3864 len = strlen(name);
3865 pos = index_name_pos(istate, name, len);
3866 if (pos < 0)
3867 return 0;
3868 ce = istate->cache[pos];
3871 * This is not the sha1 we are looking for, or
3872 * unreusable because it is not a regular file.
3874 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3875 return 0;
3878 * If ce is marked as "assume unchanged", there is no
3879 * guarantee that work tree matches what we are looking for.
3881 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3882 return 0;
3885 * If ce matches the file in the work tree, we can reuse it.
3887 if (ce_uptodate(ce) ||
3888 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3889 return 1;
3891 return 0;
3894 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3896 struct strbuf buf = STRBUF_INIT;
3897 char *dirty = "";
3899 /* Are we looking at the work tree? */
3900 if (s->dirty_submodule)
3901 dirty = "-dirty";
3903 strbuf_addf(&buf, "Subproject commit %s%s\n",
3904 oid_to_hex(&s->oid), dirty);
3905 s->size = buf.len;
3906 if (size_only) {
3907 s->data = NULL;
3908 strbuf_release(&buf);
3909 } else {
3910 s->data = strbuf_detach(&buf, NULL);
3911 s->should_free = 1;
3913 return 0;
3917 * While doing rename detection and pickaxe operation, we may need to
3918 * grab the data for the blob (or file) for our own in-core comparison.
3919 * diff_filespec has data and size fields for this purpose.
3921 int diff_populate_filespec(struct repository *r,
3922 struct diff_filespec *s,
3923 unsigned int flags)
3925 int size_only = flags & CHECK_SIZE_ONLY;
3926 int err = 0;
3927 int conv_flags = global_conv_flags_eol;
3929 * demote FAIL to WARN to allow inspecting the situation
3930 * instead of refusing.
3932 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3933 conv_flags = CONV_EOL_RNDTRP_WARN;
3935 if (!DIFF_FILE_VALID(s))
3936 die("internal error: asking to populate invalid file.");
3937 if (S_ISDIR(s->mode))
3938 return -1;
3940 if (s->data)
3941 return 0;
3943 if (size_only && 0 < s->size)
3944 return 0;
3946 if (S_ISGITLINK(s->mode))
3947 return diff_populate_gitlink(s, size_only);
3949 if (!s->oid_valid ||
3950 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3951 struct strbuf buf = STRBUF_INIT;
3952 struct stat st;
3953 int fd;
3955 if (lstat(s->path, &st) < 0) {
3956 err_empty:
3957 err = -1;
3958 empty:
3959 s->data = (char *)"";
3960 s->size = 0;
3961 return err;
3963 s->size = xsize_t(st.st_size);
3964 if (!s->size)
3965 goto empty;
3966 if (S_ISLNK(st.st_mode)) {
3967 struct strbuf sb = STRBUF_INIT;
3969 if (strbuf_readlink(&sb, s->path, s->size))
3970 goto err_empty;
3971 s->size = sb.len;
3972 s->data = strbuf_detach(&sb, NULL);
3973 s->should_free = 1;
3974 return 0;
3978 * Even if the caller would be happy with getting
3979 * only the size, we cannot return early at this
3980 * point if the path requires us to run the content
3981 * conversion.
3983 if (size_only && !would_convert_to_git(r->index, s->path))
3984 return 0;
3987 * Note: this check uses xsize_t(st.st_size) that may
3988 * not be the true size of the blob after it goes
3989 * through convert_to_git(). This may not strictly be
3990 * correct, but the whole point of big_file_threshold
3991 * and is_binary check being that we want to avoid
3992 * opening the file and inspecting the contents, this
3993 * is probably fine.
3995 if ((flags & CHECK_BINARY) &&
3996 s->size > big_file_threshold && s->is_binary == -1) {
3997 s->is_binary = 1;
3998 return 0;
4000 fd = open(s->path, O_RDONLY);
4001 if (fd < 0)
4002 goto err_empty;
4003 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4004 close(fd);
4005 s->should_munmap = 1;
4008 * Convert from working tree format to canonical git format
4010 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4011 size_t size = 0;
4012 munmap(s->data, s->size);
4013 s->should_munmap = 0;
4014 s->data = strbuf_detach(&buf, &size);
4015 s->size = size;
4016 s->should_free = 1;
4019 else {
4020 enum object_type type;
4021 if (size_only || (flags & CHECK_BINARY)) {
4022 type = oid_object_info(r, &s->oid, &s->size);
4023 if (type < 0)
4024 die("unable to read %s",
4025 oid_to_hex(&s->oid));
4026 if (size_only)
4027 return 0;
4028 if (s->size > big_file_threshold && s->is_binary == -1) {
4029 s->is_binary = 1;
4030 return 0;
4033 s->data = read_object_file(&s->oid, &type, &s->size);
4034 if (!s->data)
4035 die("unable to read %s", oid_to_hex(&s->oid));
4036 s->should_free = 1;
4038 return 0;
4041 void diff_free_filespec_blob(struct diff_filespec *s)
4043 if (s->should_free)
4044 free(s->data);
4045 else if (s->should_munmap)
4046 munmap(s->data, s->size);
4048 if (s->should_free || s->should_munmap) {
4049 s->should_free = s->should_munmap = 0;
4050 s->data = NULL;
4054 void diff_free_filespec_data(struct diff_filespec *s)
4056 diff_free_filespec_blob(s);
4057 FREE_AND_NULL(s->cnt_data);
4060 static void prep_temp_blob(struct index_state *istate,
4061 const char *path, struct diff_tempfile *temp,
4062 void *blob,
4063 unsigned long size,
4064 const struct object_id *oid,
4065 int mode)
4067 struct strbuf buf = STRBUF_INIT;
4068 struct strbuf tempfile = STRBUF_INIT;
4069 char *path_dup = xstrdup(path);
4070 const char *base = basename(path_dup);
4072 /* Generate "XXXXXX_basename.ext" */
4073 strbuf_addstr(&tempfile, "XXXXXX_");
4074 strbuf_addstr(&tempfile, base);
4076 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4077 if (!temp->tempfile)
4078 die_errno("unable to create temp-file");
4079 if (convert_to_working_tree(istate, path,
4080 (const char *)blob, (size_t)size, &buf)) {
4081 blob = buf.buf;
4082 size = buf.len;
4084 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4085 close_tempfile_gently(temp->tempfile))
4086 die_errno("unable to write temp-file");
4087 temp->name = get_tempfile_path(temp->tempfile);
4088 oid_to_hex_r(temp->hex, oid);
4089 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4090 strbuf_release(&buf);
4091 strbuf_release(&tempfile);
4092 free(path_dup);
4095 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4096 const char *name,
4097 struct diff_filespec *one)
4099 struct diff_tempfile *temp = claim_diff_tempfile();
4101 if (!DIFF_FILE_VALID(one)) {
4102 not_a_valid_file:
4103 /* A '-' entry produces this for file-2, and
4104 * a '+' entry produces this for file-1.
4106 temp->name = "/dev/null";
4107 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4108 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4109 return temp;
4112 if (!S_ISGITLINK(one->mode) &&
4113 (!one->oid_valid ||
4114 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4115 struct stat st;
4116 if (lstat(name, &st) < 0) {
4117 if (errno == ENOENT)
4118 goto not_a_valid_file;
4119 die_errno("stat(%s)", name);
4121 if (S_ISLNK(st.st_mode)) {
4122 struct strbuf sb = STRBUF_INIT;
4123 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4124 die_errno("readlink(%s)", name);
4125 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4126 (one->oid_valid ?
4127 &one->oid : &null_oid),
4128 (one->oid_valid ?
4129 one->mode : S_IFLNK));
4130 strbuf_release(&sb);
4132 else {
4133 /* we can borrow from the file in the work tree */
4134 temp->name = name;
4135 if (!one->oid_valid)
4136 oid_to_hex_r(temp->hex, &null_oid);
4137 else
4138 oid_to_hex_r(temp->hex, &one->oid);
4139 /* Even though we may sometimes borrow the
4140 * contents from the work tree, we always want
4141 * one->mode. mode is trustworthy even when
4142 * !(one->oid_valid), as long as
4143 * DIFF_FILE_VALID(one).
4145 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4147 return temp;
4149 else {
4150 if (diff_populate_filespec(r, one, 0))
4151 die("cannot read data blob for %s", one->path);
4152 prep_temp_blob(r->index, name, temp,
4153 one->data, one->size,
4154 &one->oid, one->mode);
4156 return temp;
4159 static void add_external_diff_name(struct repository *r,
4160 struct argv_array *argv,
4161 const char *name,
4162 struct diff_filespec *df)
4164 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4165 argv_array_push(argv, temp->name);
4166 argv_array_push(argv, temp->hex);
4167 argv_array_push(argv, temp->mode);
4170 /* An external diff command takes:
4172 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4173 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4176 static void run_external_diff(const char *pgm,
4177 const char *name,
4178 const char *other,
4179 struct diff_filespec *one,
4180 struct diff_filespec *two,
4181 const char *xfrm_msg,
4182 struct diff_options *o)
4184 struct argv_array argv = ARGV_ARRAY_INIT;
4185 struct argv_array env = ARGV_ARRAY_INIT;
4186 struct diff_queue_struct *q = &diff_queued_diff;
4188 argv_array_push(&argv, pgm);
4189 argv_array_push(&argv, name);
4191 if (one && two) {
4192 add_external_diff_name(o->repo, &argv, name, one);
4193 if (!other)
4194 add_external_diff_name(o->repo, &argv, name, two);
4195 else {
4196 add_external_diff_name(o->repo, &argv, other, two);
4197 argv_array_push(&argv, other);
4198 argv_array_push(&argv, xfrm_msg);
4202 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4203 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4205 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4206 die(_("external diff died, stopping at %s"), name);
4208 remove_tempfile();
4209 argv_array_clear(&argv);
4210 argv_array_clear(&env);
4213 static int similarity_index(struct diff_filepair *p)
4215 return p->score * 100 / MAX_SCORE;
4218 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4220 if (startup_info->have_repository)
4221 return find_unique_abbrev(oid, abbrev);
4222 else {
4223 char *hex = oid_to_hex(oid);
4224 if (abbrev < 0)
4225 abbrev = FALLBACK_DEFAULT_ABBREV;
4226 if (abbrev > the_hash_algo->hexsz)
4227 BUG("oid abbreviation out of range: %d", abbrev);
4228 if (abbrev)
4229 hex[abbrev] = '\0';
4230 return hex;
4234 static void fill_metainfo(struct strbuf *msg,
4235 const char *name,
4236 const char *other,
4237 struct diff_filespec *one,
4238 struct diff_filespec *two,
4239 struct diff_options *o,
4240 struct diff_filepair *p,
4241 int *must_show_header,
4242 int use_color)
4244 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4245 const char *reset = diff_get_color(use_color, DIFF_RESET);
4246 const char *line_prefix = diff_line_prefix(o);
4248 *must_show_header = 1;
4249 strbuf_init(msg, PATH_MAX * 2 + 300);
4250 switch (p->status) {
4251 case DIFF_STATUS_COPIED:
4252 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4253 line_prefix, set, similarity_index(p));
4254 strbuf_addf(msg, "%s\n%s%scopy from ",
4255 reset, line_prefix, set);
4256 quote_c_style(name, msg, NULL, 0);
4257 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4258 quote_c_style(other, msg, NULL, 0);
4259 strbuf_addf(msg, "%s\n", reset);
4260 break;
4261 case DIFF_STATUS_RENAMED:
4262 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4263 line_prefix, set, similarity_index(p));
4264 strbuf_addf(msg, "%s\n%s%srename from ",
4265 reset, line_prefix, set);
4266 quote_c_style(name, msg, NULL, 0);
4267 strbuf_addf(msg, "%s\n%s%srename to ",
4268 reset, line_prefix, set);
4269 quote_c_style(other, msg, NULL, 0);
4270 strbuf_addf(msg, "%s\n", reset);
4271 break;
4272 case DIFF_STATUS_MODIFIED:
4273 if (p->score) {
4274 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4275 line_prefix,
4276 set, similarity_index(p), reset);
4277 break;
4279 /* fallthru */
4280 default:
4281 *must_show_header = 0;
4283 if (one && two && !oideq(&one->oid, &two->oid)) {
4284 const unsigned hexsz = the_hash_algo->hexsz;
4285 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
4287 if (o->flags.binary) {
4288 mmfile_t mf;
4289 if ((!fill_mmfile(o->repo, &mf, one) &&
4290 diff_filespec_is_binary(o->repo, one)) ||
4291 (!fill_mmfile(o->repo, &mf, two) &&
4292 diff_filespec_is_binary(o->repo, two)))
4293 abbrev = hexsz;
4295 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4296 diff_abbrev_oid(&one->oid, abbrev),
4297 diff_abbrev_oid(&two->oid, abbrev));
4298 if (one->mode == two->mode)
4299 strbuf_addf(msg, " %06o", one->mode);
4300 strbuf_addf(msg, "%s\n", reset);
4304 static void run_diff_cmd(const char *pgm,
4305 const char *name,
4306 const char *other,
4307 const char *attr_path,
4308 struct diff_filespec *one,
4309 struct diff_filespec *two,
4310 struct strbuf *msg,
4311 struct diff_options *o,
4312 struct diff_filepair *p)
4314 const char *xfrm_msg = NULL;
4315 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4316 int must_show_header = 0;
4319 if (o->flags.allow_external) {
4320 struct userdiff_driver *drv;
4322 drv = userdiff_find_by_path(o->repo->index, attr_path);
4323 if (drv && drv->external)
4324 pgm = drv->external;
4327 if (msg) {
4329 * don't use colors when the header is intended for an
4330 * external diff driver
4332 fill_metainfo(msg, name, other, one, two, o, p,
4333 &must_show_header,
4334 want_color(o->use_color) && !pgm);
4335 xfrm_msg = msg->len ? msg->buf : NULL;
4338 if (pgm) {
4339 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4340 return;
4342 if (one && two)
4343 builtin_diff(name, other ? other : name,
4344 one, two, xfrm_msg, must_show_header,
4345 o, complete_rewrite);
4346 else
4347 fprintf(o->file, "* Unmerged path %s\n", name);
4350 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4352 if (DIFF_FILE_VALID(one)) {
4353 if (!one->oid_valid) {
4354 struct stat st;
4355 if (one->is_stdin) {
4356 oidclr(&one->oid);
4357 return;
4359 if (lstat(one->path, &st) < 0)
4360 die_errno("stat '%s'", one->path);
4361 if (index_path(istate, &one->oid, one->path, &st, 0))
4362 die("cannot hash %s", one->path);
4365 else
4366 oidclr(&one->oid);
4369 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4371 /* Strip the prefix but do not molest /dev/null and absolute paths */
4372 if (*namep && !is_absolute_path(*namep)) {
4373 *namep += prefix_length;
4374 if (**namep == '/')
4375 ++*namep;
4377 if (*otherp && !is_absolute_path(*otherp)) {
4378 *otherp += prefix_length;
4379 if (**otherp == '/')
4380 ++*otherp;
4384 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4386 const char *pgm = external_diff();
4387 struct strbuf msg;
4388 struct diff_filespec *one = p->one;
4389 struct diff_filespec *two = p->two;
4390 const char *name;
4391 const char *other;
4392 const char *attr_path;
4394 name = one->path;
4395 other = (strcmp(name, two->path) ? two->path : NULL);
4396 attr_path = name;
4397 if (o->prefix_length)
4398 strip_prefix(o->prefix_length, &name, &other);
4400 if (!o->flags.allow_external)
4401 pgm = NULL;
4403 if (DIFF_PAIR_UNMERGED(p)) {
4404 run_diff_cmd(pgm, name, NULL, attr_path,
4405 NULL, NULL, NULL, o, p);
4406 return;
4409 diff_fill_oid_info(one, o->repo->index);
4410 diff_fill_oid_info(two, o->repo->index);
4412 if (!pgm &&
4413 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4414 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4416 * a filepair that changes between file and symlink
4417 * needs to be split into deletion and creation.
4419 struct diff_filespec *null = alloc_filespec(two->path);
4420 run_diff_cmd(NULL, name, other, attr_path,
4421 one, null, &msg,
4422 o, p);
4423 free(null);
4424 strbuf_release(&msg);
4426 null = alloc_filespec(one->path);
4427 run_diff_cmd(NULL, name, other, attr_path,
4428 null, two, &msg, o, p);
4429 free(null);
4431 else
4432 run_diff_cmd(pgm, name, other, attr_path,
4433 one, two, &msg, o, p);
4435 strbuf_release(&msg);
4438 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4439 struct diffstat_t *diffstat)
4441 const char *name;
4442 const char *other;
4444 if (DIFF_PAIR_UNMERGED(p)) {
4445 /* unmerged */
4446 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4447 diffstat, o, p);
4448 return;
4451 name = p->one->path;
4452 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4454 if (o->prefix_length)
4455 strip_prefix(o->prefix_length, &name, &other);
4457 diff_fill_oid_info(p->one, o->repo->index);
4458 diff_fill_oid_info(p->two, o->repo->index);
4460 builtin_diffstat(name, other, p->one, p->two,
4461 diffstat, o, p);
4464 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4466 const char *name;
4467 const char *other;
4468 const char *attr_path;
4470 if (DIFF_PAIR_UNMERGED(p)) {
4471 /* unmerged */
4472 return;
4475 name = p->one->path;
4476 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4477 attr_path = other ? other : name;
4479 if (o->prefix_length)
4480 strip_prefix(o->prefix_length, &name, &other);
4482 diff_fill_oid_info(p->one, o->repo->index);
4483 diff_fill_oid_info(p->two, o->repo->index);
4485 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4488 static void prep_parse_options(struct diff_options *options);
4490 void repo_diff_setup(struct repository *r, struct diff_options *options)
4492 memcpy(options, &default_diff_options, sizeof(*options));
4494 options->file = stdout;
4495 options->repo = r;
4497 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4498 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4499 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4500 options->abbrev = DEFAULT_ABBREV;
4501 options->line_termination = '\n';
4502 options->break_opt = -1;
4503 options->rename_limit = -1;
4504 options->dirstat_permille = diff_dirstat_permille_default;
4505 options->context = diff_context_default;
4506 options->interhunkcontext = diff_interhunk_context_default;
4507 options->ws_error_highlight = ws_error_highlight_default;
4508 options->flags.rename_empty = 1;
4509 options->objfind = NULL;
4511 /* pathchange left =NULL by default */
4512 options->change = diff_change;
4513 options->add_remove = diff_addremove;
4514 options->use_color = diff_use_color_default;
4515 options->detect_rename = diff_detect_rename_default;
4516 options->xdl_opts |= diff_algorithm;
4517 if (diff_indent_heuristic)
4518 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4520 options->orderfile = diff_order_file_cfg;
4522 if (diff_no_prefix) {
4523 options->a_prefix = options->b_prefix = "";
4524 } else if (!diff_mnemonic_prefix) {
4525 options->a_prefix = "a/";
4526 options->b_prefix = "b/";
4529 options->color_moved = diff_color_moved_default;
4530 options->color_moved_ws_handling = diff_color_moved_ws_default;
4532 prep_parse_options(options);
4535 void diff_setup_done(struct diff_options *options)
4537 unsigned check_mask = DIFF_FORMAT_NAME |
4538 DIFF_FORMAT_NAME_STATUS |
4539 DIFF_FORMAT_CHECKDIFF |
4540 DIFF_FORMAT_NO_OUTPUT;
4542 * This must be signed because we're comparing against a potentially
4543 * negative value.
4545 const int hexsz = the_hash_algo->hexsz;
4547 if (options->set_default)
4548 options->set_default(options);
4550 if (HAS_MULTI_BITS(options->output_format & check_mask))
4551 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4553 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4554 die(_("-G, -S and --find-object are mutually exclusive"));
4557 * Most of the time we can say "there are changes"
4558 * only by checking if there are changed paths, but
4559 * --ignore-whitespace* options force us to look
4560 * inside contents.
4563 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4564 options->flags.diff_from_contents = 1;
4565 else
4566 options->flags.diff_from_contents = 0;
4568 if (options->flags.find_copies_harder)
4569 options->detect_rename = DIFF_DETECT_COPY;
4571 if (!options->flags.relative_name)
4572 options->prefix = NULL;
4573 if (options->prefix)
4574 options->prefix_length = strlen(options->prefix);
4575 else
4576 options->prefix_length = 0;
4578 if (options->output_format & (DIFF_FORMAT_NAME |
4579 DIFF_FORMAT_NAME_STATUS |
4580 DIFF_FORMAT_CHECKDIFF |
4581 DIFF_FORMAT_NO_OUTPUT))
4582 options->output_format &= ~(DIFF_FORMAT_RAW |
4583 DIFF_FORMAT_NUMSTAT |
4584 DIFF_FORMAT_DIFFSTAT |
4585 DIFF_FORMAT_SHORTSTAT |
4586 DIFF_FORMAT_DIRSTAT |
4587 DIFF_FORMAT_SUMMARY |
4588 DIFF_FORMAT_PATCH);
4591 * These cases always need recursive; we do not drop caller-supplied
4592 * recursive bits for other formats here.
4594 if (options->output_format & (DIFF_FORMAT_PATCH |
4595 DIFF_FORMAT_NUMSTAT |
4596 DIFF_FORMAT_DIFFSTAT |
4597 DIFF_FORMAT_SHORTSTAT |
4598 DIFF_FORMAT_DIRSTAT |
4599 DIFF_FORMAT_SUMMARY |
4600 DIFF_FORMAT_CHECKDIFF))
4601 options->flags.recursive = 1;
4603 * Also pickaxe would not work very well if you do not say recursive
4605 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4606 options->flags.recursive = 1;
4608 * When patches are generated, submodules diffed against the work tree
4609 * must be checked for dirtiness too so it can be shown in the output
4611 if (options->output_format & DIFF_FORMAT_PATCH)
4612 options->flags.dirty_submodules = 1;
4614 if (options->detect_rename && options->rename_limit < 0)
4615 options->rename_limit = diff_rename_limit_default;
4616 if (hexsz < options->abbrev)
4617 options->abbrev = hexsz; /* full */
4620 * It does not make sense to show the first hit we happened
4621 * to have found. It does not make sense not to return with
4622 * exit code in such a case either.
4624 if (options->flags.quick) {
4625 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4626 options->flags.exit_with_status = 1;
4629 options->diff_path_counter = 0;
4631 if (options->flags.follow_renames && options->pathspec.nr != 1)
4632 die(_("--follow requires exactly one pathspec"));
4634 if (!options->use_color || external_diff())
4635 options->color_moved = 0;
4637 FREE_AND_NULL(options->parseopts);
4640 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4642 char c, *eq;
4643 int len;
4645 if (*arg != '-')
4646 return 0;
4647 c = *++arg;
4648 if (!c)
4649 return 0;
4650 if (c == arg_short) {
4651 c = *++arg;
4652 if (!c)
4653 return 1;
4654 if (val && isdigit(c)) {
4655 char *end;
4656 int n = strtoul(arg, &end, 10);
4657 if (*end)
4658 return 0;
4659 *val = n;
4660 return 1;
4662 return 0;
4664 if (c != '-')
4665 return 0;
4666 arg++;
4667 eq = strchrnul(arg, '=');
4668 len = eq - arg;
4669 if (!len || strncmp(arg, arg_long, len))
4670 return 0;
4671 if (*eq) {
4672 int n;
4673 char *end;
4674 if (!isdigit(*++eq))
4675 return 0;
4676 n = strtoul(eq, &end, 10);
4677 if (*end)
4678 return 0;
4679 *val = n;
4681 return 1;
4684 static int diff_scoreopt_parse(const char *opt);
4686 static inline int short_opt(char opt, const char **argv,
4687 const char **optarg)
4689 const char *arg = argv[0];
4690 if (arg[0] != '-' || arg[1] != opt)
4691 return 0;
4692 if (arg[2] != '\0') {
4693 *optarg = arg + 2;
4694 return 1;
4696 if (!argv[1])
4697 die("Option '%c' requires a value", opt);
4698 *optarg = argv[1];
4699 return 2;
4702 int parse_long_opt(const char *opt, const char **argv,
4703 const char **optarg)
4705 const char *arg = argv[0];
4706 if (!skip_prefix(arg, "--", &arg))
4707 return 0;
4708 if (!skip_prefix(arg, opt, &arg))
4709 return 0;
4710 if (*arg == '=') { /* stuck form: --option=value */
4711 *optarg = arg + 1;
4712 return 1;
4714 if (*arg != '\0')
4715 return 0;
4716 /* separate form: --option value */
4717 if (!argv[1])
4718 die("Option '--%s' requires a value", opt);
4719 *optarg = argv[1];
4720 return 2;
4723 static int stat_opt(struct diff_options *options, const char **av)
4725 const char *arg = av[0];
4726 char *end;
4727 int width = options->stat_width;
4728 int name_width = options->stat_name_width;
4729 int graph_width = options->stat_graph_width;
4730 int count = options->stat_count;
4731 int argcount = 1;
4733 if (!skip_prefix(arg, "--stat", &arg))
4734 BUG("stat option does not begin with --stat: %s", arg);
4735 end = (char *)arg;
4737 switch (*arg) {
4738 case '-':
4739 if (skip_prefix(arg, "-width", &arg)) {
4740 if (*arg == '=')
4741 width = strtoul(arg + 1, &end, 10);
4742 else if (!*arg && !av[1])
4743 die_want_option("--stat-width");
4744 else if (!*arg) {
4745 width = strtoul(av[1], &end, 10);
4746 argcount = 2;
4748 } else if (skip_prefix(arg, "-name-width", &arg)) {
4749 if (*arg == '=')
4750 name_width = strtoul(arg + 1, &end, 10);
4751 else if (!*arg && !av[1])
4752 die_want_option("--stat-name-width");
4753 else if (!*arg) {
4754 name_width = strtoul(av[1], &end, 10);
4755 argcount = 2;
4757 } else if (skip_prefix(arg, "-graph-width", &arg)) {
4758 if (*arg == '=')
4759 graph_width = strtoul(arg + 1, &end, 10);
4760 else if (!*arg && !av[1])
4761 die_want_option("--stat-graph-width");
4762 else if (!*arg) {
4763 graph_width = strtoul(av[1], &end, 10);
4764 argcount = 2;
4766 } else if (skip_prefix(arg, "-count", &arg)) {
4767 if (*arg == '=')
4768 count = strtoul(arg + 1, &end, 10);
4769 else if (!*arg && !av[1])
4770 die_want_option("--stat-count");
4771 else if (!*arg) {
4772 count = strtoul(av[1], &end, 10);
4773 argcount = 2;
4776 break;
4777 case '=':
4778 width = strtoul(arg+1, &end, 10);
4779 if (*end == ',')
4780 name_width = strtoul(end+1, &end, 10);
4781 if (*end == ',')
4782 count = strtoul(end+1, &end, 10);
4785 /* Important! This checks all the error cases! */
4786 if (*end)
4787 return 0;
4788 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4789 options->stat_name_width = name_width;
4790 options->stat_graph_width = graph_width;
4791 options->stat_width = width;
4792 options->stat_count = count;
4793 return argcount;
4796 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4798 struct strbuf errmsg = STRBUF_INIT;
4799 if (parse_dirstat_params(options, params, &errmsg))
4800 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4801 errmsg.buf);
4802 strbuf_release(&errmsg);
4804 * The caller knows a dirstat-related option is given from the command
4805 * line; allow it to say "return this_function();"
4807 options->output_format |= DIFF_FORMAT_DIRSTAT;
4808 return 1;
4811 static int parse_submodule_opt(struct diff_options *options, const char *value)
4813 if (parse_submodule_params(options, value))
4814 die(_("Failed to parse --submodule option parameter: '%s'"),
4815 value);
4816 return 1;
4819 static const char diff_status_letters[] = {
4820 DIFF_STATUS_ADDED,
4821 DIFF_STATUS_COPIED,
4822 DIFF_STATUS_DELETED,
4823 DIFF_STATUS_MODIFIED,
4824 DIFF_STATUS_RENAMED,
4825 DIFF_STATUS_TYPE_CHANGED,
4826 DIFF_STATUS_UNKNOWN,
4827 DIFF_STATUS_UNMERGED,
4828 DIFF_STATUS_FILTER_AON,
4829 DIFF_STATUS_FILTER_BROKEN,
4830 '\0',
4833 static unsigned int filter_bit['Z' + 1];
4835 static void prepare_filter_bits(void)
4837 int i;
4839 if (!filter_bit[DIFF_STATUS_ADDED]) {
4840 for (i = 0; diff_status_letters[i]; i++)
4841 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4845 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4847 return opt->filter & filter_bit[(int) status];
4850 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4852 int i, optch;
4854 prepare_filter_bits();
4857 * If there is a negation e.g. 'd' in the input, and we haven't
4858 * initialized the filter field with another --diff-filter, start
4859 * from full set of bits, except for AON.
4861 if (!opt->filter) {
4862 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4863 if (optch < 'a' || 'z' < optch)
4864 continue;
4865 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4866 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4867 break;
4871 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4872 unsigned int bit;
4873 int negate;
4875 if ('a' <= optch && optch <= 'z') {
4876 negate = 1;
4877 optch = toupper(optch);
4878 } else {
4879 negate = 0;
4882 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4883 if (!bit)
4884 return optarg[i];
4885 if (negate)
4886 opt->filter &= ~bit;
4887 else
4888 opt->filter |= bit;
4890 return 0;
4893 static void enable_patch_output(int *fmt)
4895 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4896 *fmt |= DIFF_FORMAT_PATCH;
4899 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4901 int val = parse_ws_error_highlight(arg);
4903 if (val < 0) {
4904 error("unknown value after ws-error-highlight=%.*s",
4905 -1 - val, arg);
4906 return 0;
4908 opt->ws_error_highlight = val;
4909 return 1;
4912 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4914 struct object_id oid;
4916 if (get_oid(arg, &oid))
4917 return error("unable to resolve '%s'", arg);
4919 if (!opt->objfind)
4920 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4922 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4923 opt->flags.recursive = 1;
4924 opt->flags.tree_in_recursive = 1;
4925 oidset_insert(opt->objfind, &oid);
4926 return 1;
4929 static int diff_opt_unified(const struct option *opt,
4930 const char *arg, int unset)
4932 struct diff_options *options = opt->value;
4933 char *s;
4935 BUG_ON_OPT_NEG(unset);
4937 options->context = strtol(arg, &s, 10);
4938 if (*s)
4939 return error(_("%s expects a numerical value"), "--unified");
4940 enable_patch_output(&options->output_format);
4942 return 0;
4945 static void prep_parse_options(struct diff_options *options)
4947 struct option parseopts[] = {
4948 OPT_GROUP(N_("Diff output format options")),
4949 OPT_BITOP('p', "patch", &options->output_format,
4950 N_("generate patch"),
4951 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
4952 OPT_BITOP('u', NULL, &options->output_format,
4953 N_("generate patch"),
4954 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
4955 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
4956 N_("generate diffs with <n> lines context"),
4957 PARSE_OPT_NONEG, diff_opt_unified),
4958 OPT_BOOL('W', "function-context", &options->flags.funccontext,
4959 N_("generate diffs with <n> lines context")),
4960 OPT_BIT_F(0, "raw", &options->output_format,
4961 N_("generate the diff in raw format"),
4962 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
4963 OPT_END()
4966 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
4967 memcpy(options->parseopts, parseopts, sizeof(parseopts));
4970 int diff_opt_parse(struct diff_options *options,
4971 const char **av, int ac, const char *prefix)
4973 const char *arg = av[0];
4974 const char *optarg;
4975 int argcount;
4977 if (!prefix)
4978 prefix = "";
4980 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
4981 PARSE_OPT_KEEP_DASHDASH |
4982 PARSE_OPT_KEEP_UNKNOWN |
4983 PARSE_OPT_NO_INTERNAL_HELP |
4984 PARSE_OPT_ONE_SHOT |
4985 PARSE_OPT_STOP_AT_NON_OPTION);
4987 if (ac)
4988 return ac;
4990 /* Output format options */
4991 if (!strcmp(arg, "--patch-with-raw")) {
4992 enable_patch_output(&options->output_format);
4993 options->output_format |= DIFF_FORMAT_RAW;
4994 } else if (!strcmp(arg, "--numstat"))
4995 options->output_format |= DIFF_FORMAT_NUMSTAT;
4996 else if (!strcmp(arg, "--shortstat"))
4997 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4998 else if (skip_prefix(arg, "-X", &arg) ||
4999 skip_to_optional_arg(arg, "--dirstat", &arg))
5000 return parse_dirstat_opt(options, arg);
5001 else if (!strcmp(arg, "--cumulative"))
5002 return parse_dirstat_opt(options, "cumulative");
5003 else if (skip_to_optional_arg(arg, "--dirstat-by-file", &arg)) {
5004 parse_dirstat_opt(options, "files");
5005 return parse_dirstat_opt(options, arg);
5007 else if (!strcmp(arg, "--check"))
5008 options->output_format |= DIFF_FORMAT_CHECKDIFF;
5009 else if (!strcmp(arg, "--summary"))
5010 options->output_format |= DIFF_FORMAT_SUMMARY;
5011 else if (!strcmp(arg, "--patch-with-stat")) {
5012 enable_patch_output(&options->output_format);
5013 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5014 } else if (!strcmp(arg, "--name-only"))
5015 options->output_format |= DIFF_FORMAT_NAME;
5016 else if (!strcmp(arg, "--name-status"))
5017 options->output_format |= DIFF_FORMAT_NAME_STATUS;
5018 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
5019 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
5020 else if (starts_with(arg, "--stat"))
5021 /* --stat, --stat-width, --stat-name-width, or --stat-count */
5022 return stat_opt(options, av);
5023 else if (!strcmp(arg, "--compact-summary")) {
5024 options->flags.stat_with_summary = 1;
5025 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5026 } else if (!strcmp(arg, "--no-compact-summary"))
5027 options->flags.stat_with_summary = 0;
5028 else if (skip_prefix(arg, "--output-indicator-new=", &arg))
5029 options->output_indicators[OUTPUT_INDICATOR_NEW] = arg[0];
5030 else if (skip_prefix(arg, "--output-indicator-old=", &arg))
5031 options->output_indicators[OUTPUT_INDICATOR_OLD] = arg[0];
5032 else if (skip_prefix(arg, "--output-indicator-context=", &arg))
5033 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = arg[0];
5035 /* renames options */
5036 else if (starts_with(arg, "-B") ||
5037 skip_to_optional_arg(arg, "--break-rewrites", NULL)) {
5038 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
5039 return error("invalid argument to -B: %s", arg+2);
5041 else if (starts_with(arg, "-M") ||
5042 skip_to_optional_arg(arg, "--find-renames", NULL)) {
5043 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
5044 return error("invalid argument to -M: %s", arg+2);
5045 options->detect_rename = DIFF_DETECT_RENAME;
5047 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
5048 options->irreversible_delete = 1;
5050 else if (starts_with(arg, "-C") ||
5051 skip_to_optional_arg(arg, "--find-copies", NULL)) {
5052 if (options->detect_rename == DIFF_DETECT_COPY)
5053 options->flags.find_copies_harder = 1;
5054 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
5055 return error("invalid argument to -C: %s", arg+2);
5056 options->detect_rename = DIFF_DETECT_COPY;
5058 else if (!strcmp(arg, "--no-renames"))
5059 options->detect_rename = 0;
5060 else if (!strcmp(arg, "--rename-empty"))
5061 options->flags.rename_empty = 1;
5062 else if (!strcmp(arg, "--no-rename-empty"))
5063 options->flags.rename_empty = 0;
5064 else if (skip_to_optional_arg_default(arg, "--relative", &arg, NULL)) {
5065 options->flags.relative_name = 1;
5066 if (arg)
5067 options->prefix = arg;
5070 /* xdiff options */
5071 else if (!strcmp(arg, "--minimal"))
5072 DIFF_XDL_SET(options, NEED_MINIMAL);
5073 else if (!strcmp(arg, "--no-minimal"))
5074 DIFF_XDL_CLR(options, NEED_MINIMAL);
5075 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
5076 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
5077 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
5078 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
5079 else if (!strcmp(arg, "--ignore-space-at-eol"))
5080 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
5081 else if (!strcmp(arg, "--ignore-cr-at-eol"))
5082 DIFF_XDL_SET(options, IGNORE_CR_AT_EOL);
5083 else if (!strcmp(arg, "--ignore-blank-lines"))
5084 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
5085 else if (!strcmp(arg, "--indent-heuristic"))
5086 DIFF_XDL_SET(options, INDENT_HEURISTIC);
5087 else if (!strcmp(arg, "--no-indent-heuristic"))
5088 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
5089 else if (!strcmp(arg, "--patience")) {
5090 int i;
5091 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5093 * Both --patience and --anchored use PATIENCE_DIFF
5094 * internally, so remove any anchors previously
5095 * specified.
5097 for (i = 0; i < options->anchors_nr; i++)
5098 free(options->anchors[i]);
5099 options->anchors_nr = 0;
5100 } else if (!strcmp(arg, "--histogram"))
5101 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
5102 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
5103 long value = parse_algorithm_value(optarg);
5104 if (value < 0)
5105 return error("option diff-algorithm accepts \"myers\", "
5106 "\"minimal\", \"patience\" and \"histogram\"");
5107 /* clear out previous settings */
5108 DIFF_XDL_CLR(options, NEED_MINIMAL);
5109 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5110 options->xdl_opts |= value;
5111 return argcount;
5112 } else if (skip_prefix(arg, "--anchored=", &arg)) {
5113 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5114 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5115 options->anchors_alloc);
5116 options->anchors[options->anchors_nr++] = xstrdup(arg);
5119 /* flags options */
5120 else if (!strcmp(arg, "--binary")) {
5121 enable_patch_output(&options->output_format);
5122 options->flags.binary = 1;
5124 else if (!strcmp(arg, "--full-index"))
5125 options->flags.full_index = 1;
5126 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
5127 options->flags.text = 1;
5128 else if (!strcmp(arg, "-R"))
5129 options->flags.reverse_diff = 1;
5130 else if (!strcmp(arg, "--find-copies-harder"))
5131 options->flags.find_copies_harder = 1;
5132 else if (!strcmp(arg, "--follow"))
5133 options->flags.follow_renames = 1;
5134 else if (!strcmp(arg, "--no-follow")) {
5135 options->flags.follow_renames = 0;
5136 options->flags.default_follow_renames = 0;
5137 } else if (skip_to_optional_arg_default(arg, "--color", &arg, "always")) {
5138 int value = git_config_colorbool(NULL, arg);
5139 if (value < 0)
5140 return error("option `color' expects \"always\", \"auto\", or \"never\"");
5141 options->use_color = value;
5143 else if (!strcmp(arg, "--no-color"))
5144 options->use_color = 0;
5145 else if (!strcmp(arg, "--color-moved")) {
5146 if (diff_color_moved_default)
5147 options->color_moved = diff_color_moved_default;
5148 if (options->color_moved == COLOR_MOVED_NO)
5149 options->color_moved = COLOR_MOVED_DEFAULT;
5150 } else if (!strcmp(arg, "--no-color-moved"))
5151 options->color_moved = COLOR_MOVED_NO;
5152 else if (skip_prefix(arg, "--color-moved=", &arg)) {
5153 int cm = parse_color_moved(arg);
5154 if (cm < 0)
5155 return error("bad --color-moved argument: %s", arg);
5156 options->color_moved = cm;
5157 } else if (!strcmp(arg, "--no-color-moved-ws")) {
5158 options->color_moved_ws_handling = 0;
5159 } else if (skip_prefix(arg, "--color-moved-ws=", &arg)) {
5160 unsigned cm = parse_color_moved_ws(arg);
5161 if (cm & COLOR_MOVED_WS_ERROR)
5162 return -1;
5163 options->color_moved_ws_handling = cm;
5164 } else if (skip_to_optional_arg_default(arg, "--color-words", &options->word_regex, NULL)) {
5165 options->use_color = 1;
5166 options->word_diff = DIFF_WORDS_COLOR;
5168 else if (!strcmp(arg, "--word-diff")) {
5169 if (options->word_diff == DIFF_WORDS_NONE)
5170 options->word_diff = DIFF_WORDS_PLAIN;
5172 else if (skip_prefix(arg, "--word-diff=", &arg)) {
5173 if (!strcmp(arg, "plain"))
5174 options->word_diff = DIFF_WORDS_PLAIN;
5175 else if (!strcmp(arg, "color")) {
5176 options->use_color = 1;
5177 options->word_diff = DIFF_WORDS_COLOR;
5179 else if (!strcmp(arg, "porcelain"))
5180 options->word_diff = DIFF_WORDS_PORCELAIN;
5181 else if (!strcmp(arg, "none"))
5182 options->word_diff = DIFF_WORDS_NONE;
5183 else
5184 die("bad --word-diff argument: %s", arg);
5186 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
5187 if (options->word_diff == DIFF_WORDS_NONE)
5188 options->word_diff = DIFF_WORDS_PLAIN;
5189 options->word_regex = optarg;
5190 return argcount;
5192 else if (!strcmp(arg, "--exit-code"))
5193 options->flags.exit_with_status = 1;
5194 else if (!strcmp(arg, "--quiet"))
5195 options->flags.quick = 1;
5196 else if (!strcmp(arg, "--ext-diff"))
5197 options->flags.allow_external = 1;
5198 else if (!strcmp(arg, "--no-ext-diff"))
5199 options->flags.allow_external = 0;
5200 else if (!strcmp(arg, "--textconv")) {
5201 options->flags.allow_textconv = 1;
5202 options->flags.textconv_set_via_cmdline = 1;
5203 } else if (!strcmp(arg, "--no-textconv"))
5204 options->flags.allow_textconv = 0;
5205 else if (skip_to_optional_arg_default(arg, "--ignore-submodules", &arg, "all")) {
5206 options->flags.override_submodule_config = 1;
5207 handle_ignore_submodules_arg(options, arg);
5208 } else if (skip_to_optional_arg_default(arg, "--submodule", &arg, "log"))
5209 return parse_submodule_opt(options, arg);
5210 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
5211 return parse_ws_error_highlight_opt(options, arg);
5212 else if (!strcmp(arg, "--ita-invisible-in-index"))
5213 options->ita_invisible_in_index = 1;
5214 else if (!strcmp(arg, "--ita-visible-in-index"))
5215 options->ita_invisible_in_index = 0;
5217 /* misc options */
5218 else if (!strcmp(arg, "-z"))
5219 options->line_termination = 0;
5220 else if ((argcount = short_opt('l', av, &optarg))) {
5221 options->rename_limit = strtoul(optarg, NULL, 10);
5222 return argcount;
5224 else if ((argcount = short_opt('S', av, &optarg))) {
5225 options->pickaxe = optarg;
5226 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5227 return argcount;
5228 } else if ((argcount = short_opt('G', av, &optarg))) {
5229 options->pickaxe = optarg;
5230 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5231 return argcount;
5233 else if (!strcmp(arg, "--pickaxe-all"))
5234 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
5235 else if (!strcmp(arg, "--pickaxe-regex"))
5236 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
5237 else if ((argcount = short_opt('O', av, &optarg))) {
5238 options->orderfile = prefix_filename(prefix, optarg);
5239 return argcount;
5240 } else if (skip_prefix(arg, "--find-object=", &arg))
5241 return parse_objfind_opt(options, arg);
5242 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
5243 int offending = parse_diff_filter_opt(optarg, options);
5244 if (offending)
5245 die("unknown change class '%c' in --diff-filter=%s",
5246 offending, optarg);
5247 return argcount;
5249 else if (!strcmp(arg, "--no-abbrev"))
5250 options->abbrev = 0;
5251 else if (!strcmp(arg, "--abbrev"))
5252 options->abbrev = DEFAULT_ABBREV;
5253 else if (skip_prefix(arg, "--abbrev=", &arg)) {
5254 options->abbrev = strtoul(arg, NULL, 10);
5255 if (options->abbrev < MINIMUM_ABBREV)
5256 options->abbrev = MINIMUM_ABBREV;
5257 else if (the_hash_algo->hexsz < options->abbrev)
5258 options->abbrev = the_hash_algo->hexsz;
5260 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
5261 options->a_prefix = optarg;
5262 return argcount;
5264 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
5265 options->line_prefix = optarg;
5266 options->line_prefix_length = strlen(options->line_prefix);
5267 graph_setup_line_prefix(options);
5268 return argcount;
5270 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
5271 options->b_prefix = optarg;
5272 return argcount;
5274 else if (!strcmp(arg, "--no-prefix"))
5275 options->a_prefix = options->b_prefix = "";
5276 else if (opt_arg(arg, '\0', "inter-hunk-context",
5277 &options->interhunkcontext))
5279 else if ((argcount = parse_long_opt("output", av, &optarg))) {
5280 char *path = prefix_filename(prefix, optarg);
5281 options->file = xfopen(path, "w");
5282 options->close_file = 1;
5283 if (options->use_color != GIT_COLOR_ALWAYS)
5284 options->use_color = GIT_COLOR_NEVER;
5285 free(path);
5286 return argcount;
5287 } else
5288 return 0;
5289 return 1;
5292 int parse_rename_score(const char **cp_p)
5294 unsigned long num, scale;
5295 int ch, dot;
5296 const char *cp = *cp_p;
5298 num = 0;
5299 scale = 1;
5300 dot = 0;
5301 for (;;) {
5302 ch = *cp;
5303 if ( !dot && ch == '.' ) {
5304 scale = 1;
5305 dot = 1;
5306 } else if ( ch == '%' ) {
5307 scale = dot ? scale*100 : 100;
5308 cp++; /* % is always at the end */
5309 break;
5310 } else if ( ch >= '0' && ch <= '9' ) {
5311 if ( scale < 100000 ) {
5312 scale *= 10;
5313 num = (num*10) + (ch-'0');
5315 } else {
5316 break;
5318 cp++;
5320 *cp_p = cp;
5322 /* user says num divided by scale and we say internally that
5323 * is MAX_SCORE * num / scale.
5325 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5328 static int diff_scoreopt_parse(const char *opt)
5330 int opt1, opt2, cmd;
5332 if (*opt++ != '-')
5333 return -1;
5334 cmd = *opt++;
5335 if (cmd == '-') {
5336 /* convert the long-form arguments into short-form versions */
5337 if (skip_prefix(opt, "break-rewrites", &opt)) {
5338 if (*opt == 0 || *opt++ == '=')
5339 cmd = 'B';
5340 } else if (skip_prefix(opt, "find-copies", &opt)) {
5341 if (*opt == 0 || *opt++ == '=')
5342 cmd = 'C';
5343 } else if (skip_prefix(opt, "find-renames", &opt)) {
5344 if (*opt == 0 || *opt++ == '=')
5345 cmd = 'M';
5348 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
5349 return -1; /* that is not a -M, -C, or -B option */
5351 opt1 = parse_rename_score(&opt);
5352 if (cmd != 'B')
5353 opt2 = 0;
5354 else {
5355 if (*opt == 0)
5356 opt2 = 0;
5357 else if (*opt != '/')
5358 return -1; /* we expect -B80/99 or -B80 */
5359 else {
5360 opt++;
5361 opt2 = parse_rename_score(&opt);
5364 if (*opt != 0)
5365 return -1;
5366 return opt1 | (opt2 << 16);
5369 struct diff_queue_struct diff_queued_diff;
5371 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5373 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5374 queue->queue[queue->nr++] = dp;
5377 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5378 struct diff_filespec *one,
5379 struct diff_filespec *two)
5381 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5382 dp->one = one;
5383 dp->two = two;
5384 if (queue)
5385 diff_q(queue, dp);
5386 return dp;
5389 void diff_free_filepair(struct diff_filepair *p)
5391 free_filespec(p->one);
5392 free_filespec(p->two);
5393 free(p);
5396 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5398 int abblen;
5399 const char *abbrev;
5401 /* Do we want all 40 hex characters? */
5402 if (len == the_hash_algo->hexsz)
5403 return oid_to_hex(oid);
5405 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5406 abbrev = diff_abbrev_oid(oid, len);
5408 if (!print_sha1_ellipsis())
5409 return abbrev;
5411 abblen = strlen(abbrev);
5414 * In well-behaved cases, where the abbreviated result is the
5415 * same as the requested length, append three dots after the
5416 * abbreviation (hence the whole logic is limited to the case
5417 * where abblen < 37); when the actual abbreviated result is a
5418 * bit longer than the requested length, we reduce the number
5419 * of dots so that they match the well-behaved ones. However,
5420 * if the actual abbreviation is longer than the requested
5421 * length by more than three, we give up on aligning, and add
5422 * three dots anyway, to indicate that the output is not the
5423 * full object name. Yes, this may be suboptimal, but this
5424 * appears only in "diff --raw --abbrev" output and it is not
5425 * worth the effort to change it now. Note that this would
5426 * likely to work fine when the automatic sizing of default
5427 * abbreviation length is used--we would be fed -1 in "len" in
5428 * that case, and will end up always appending three-dots, but
5429 * the automatic sizing is supposed to give abblen that ensures
5430 * uniqueness across all objects (statistically speaking).
5432 if (abblen < the_hash_algo->hexsz - 3) {
5433 static char hex[GIT_MAX_HEXSZ + 1];
5434 if (len < abblen && abblen <= len + 2)
5435 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5436 else
5437 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5438 return hex;
5441 return oid_to_hex(oid);
5444 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5446 int line_termination = opt->line_termination;
5447 int inter_name_termination = line_termination ? '\t' : '\0';
5449 fprintf(opt->file, "%s", diff_line_prefix(opt));
5450 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5451 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5452 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5453 fprintf(opt->file, "%s ",
5454 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5456 if (p->score) {
5457 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5458 inter_name_termination);
5459 } else {
5460 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5463 if (p->status == DIFF_STATUS_COPIED ||
5464 p->status == DIFF_STATUS_RENAMED) {
5465 const char *name_a, *name_b;
5466 name_a = p->one->path;
5467 name_b = p->two->path;
5468 strip_prefix(opt->prefix_length, &name_a, &name_b);
5469 write_name_quoted(name_a, opt->file, inter_name_termination);
5470 write_name_quoted(name_b, opt->file, line_termination);
5471 } else {
5472 const char *name_a, *name_b;
5473 name_a = p->one->mode ? p->one->path : p->two->path;
5474 name_b = NULL;
5475 strip_prefix(opt->prefix_length, &name_a, &name_b);
5476 write_name_quoted(name_a, opt->file, line_termination);
5480 int diff_unmodified_pair(struct diff_filepair *p)
5482 /* This function is written stricter than necessary to support
5483 * the currently implemented transformers, but the idea is to
5484 * let transformers to produce diff_filepairs any way they want,
5485 * and filter and clean them up here before producing the output.
5487 struct diff_filespec *one = p->one, *two = p->two;
5489 if (DIFF_PAIR_UNMERGED(p))
5490 return 0; /* unmerged is interesting */
5492 /* deletion, addition, mode or type change
5493 * and rename are all interesting.
5495 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5496 DIFF_PAIR_MODE_CHANGED(p) ||
5497 strcmp(one->path, two->path))
5498 return 0;
5500 /* both are valid and point at the same path. that is, we are
5501 * dealing with a change.
5503 if (one->oid_valid && two->oid_valid &&
5504 oideq(&one->oid, &two->oid) &&
5505 !one->dirty_submodule && !two->dirty_submodule)
5506 return 1; /* no change */
5507 if (!one->oid_valid && !two->oid_valid)
5508 return 1; /* both look at the same file on the filesystem. */
5509 return 0;
5512 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5514 if (diff_unmodified_pair(p))
5515 return;
5517 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5518 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5519 return; /* no tree diffs in patch format */
5521 run_diff(p, o);
5524 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5525 struct diffstat_t *diffstat)
5527 if (diff_unmodified_pair(p))
5528 return;
5530 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5531 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5532 return; /* no useful stat for tree diffs */
5534 run_diffstat(p, o, diffstat);
5537 static void diff_flush_checkdiff(struct diff_filepair *p,
5538 struct diff_options *o)
5540 if (diff_unmodified_pair(p))
5541 return;
5543 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5544 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5545 return; /* nothing to check in tree diffs */
5547 run_checkdiff(p, o);
5550 int diff_queue_is_empty(void)
5552 struct diff_queue_struct *q = &diff_queued_diff;
5553 int i;
5554 for (i = 0; i < q->nr; i++)
5555 if (!diff_unmodified_pair(q->queue[i]))
5556 return 0;
5557 return 1;
5560 #if DIFF_DEBUG
5561 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5563 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5564 x, one ? one : "",
5565 s->path,
5566 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5567 s->mode,
5568 s->oid_valid ? oid_to_hex(&s->oid) : "");
5569 fprintf(stderr, "queue[%d] %s size %lu\n",
5570 x, one ? one : "",
5571 s->size);
5574 void diff_debug_filepair(const struct diff_filepair *p, int i)
5576 diff_debug_filespec(p->one, i, "one");
5577 diff_debug_filespec(p->two, i, "two");
5578 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5579 p->score, p->status ? p->status : '?',
5580 p->one->rename_used, p->broken_pair);
5583 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5585 int i;
5586 if (msg)
5587 fprintf(stderr, "%s\n", msg);
5588 fprintf(stderr, "q->nr = %d\n", q->nr);
5589 for (i = 0; i < q->nr; i++) {
5590 struct diff_filepair *p = q->queue[i];
5591 diff_debug_filepair(p, i);
5594 #endif
5596 static void diff_resolve_rename_copy(void)
5598 int i;
5599 struct diff_filepair *p;
5600 struct diff_queue_struct *q = &diff_queued_diff;
5602 diff_debug_queue("resolve-rename-copy", q);
5604 for (i = 0; i < q->nr; i++) {
5605 p = q->queue[i];
5606 p->status = 0; /* undecided */
5607 if (DIFF_PAIR_UNMERGED(p))
5608 p->status = DIFF_STATUS_UNMERGED;
5609 else if (!DIFF_FILE_VALID(p->one))
5610 p->status = DIFF_STATUS_ADDED;
5611 else if (!DIFF_FILE_VALID(p->two))
5612 p->status = DIFF_STATUS_DELETED;
5613 else if (DIFF_PAIR_TYPE_CHANGED(p))
5614 p->status = DIFF_STATUS_TYPE_CHANGED;
5616 /* from this point on, we are dealing with a pair
5617 * whose both sides are valid and of the same type, i.e.
5618 * either in-place edit or rename/copy edit.
5620 else if (DIFF_PAIR_RENAME(p)) {
5622 * A rename might have re-connected a broken
5623 * pair up, causing the pathnames to be the
5624 * same again. If so, that's not a rename at
5625 * all, just a modification..
5627 * Otherwise, see if this source was used for
5628 * multiple renames, in which case we decrement
5629 * the count, and call it a copy.
5631 if (!strcmp(p->one->path, p->two->path))
5632 p->status = DIFF_STATUS_MODIFIED;
5633 else if (--p->one->rename_used > 0)
5634 p->status = DIFF_STATUS_COPIED;
5635 else
5636 p->status = DIFF_STATUS_RENAMED;
5638 else if (!oideq(&p->one->oid, &p->two->oid) ||
5639 p->one->mode != p->two->mode ||
5640 p->one->dirty_submodule ||
5641 p->two->dirty_submodule ||
5642 is_null_oid(&p->one->oid))
5643 p->status = DIFF_STATUS_MODIFIED;
5644 else {
5645 /* This is a "no-change" entry and should not
5646 * happen anymore, but prepare for broken callers.
5648 error("feeding unmodified %s to diffcore",
5649 p->one->path);
5650 p->status = DIFF_STATUS_UNKNOWN;
5653 diff_debug_queue("resolve-rename-copy done", q);
5656 static int check_pair_status(struct diff_filepair *p)
5658 switch (p->status) {
5659 case DIFF_STATUS_UNKNOWN:
5660 return 0;
5661 case 0:
5662 die("internal error in diff-resolve-rename-copy");
5663 default:
5664 return 1;
5668 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5670 int fmt = opt->output_format;
5672 if (fmt & DIFF_FORMAT_CHECKDIFF)
5673 diff_flush_checkdiff(p, opt);
5674 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5675 diff_flush_raw(p, opt);
5676 else if (fmt & DIFF_FORMAT_NAME) {
5677 const char *name_a, *name_b;
5678 name_a = p->two->path;
5679 name_b = NULL;
5680 strip_prefix(opt->prefix_length, &name_a, &name_b);
5681 fprintf(opt->file, "%s", diff_line_prefix(opt));
5682 write_name_quoted(name_a, opt->file, opt->line_termination);
5686 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5688 struct strbuf sb = STRBUF_INIT;
5689 if (fs->mode)
5690 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5691 else
5692 strbuf_addf(&sb, " %s ", newdelete);
5694 quote_c_style(fs->path, &sb, NULL, 0);
5695 strbuf_addch(&sb, '\n');
5696 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5697 sb.buf, sb.len, 0);
5698 strbuf_release(&sb);
5701 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5702 int show_name)
5704 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5705 struct strbuf sb = STRBUF_INIT;
5706 strbuf_addf(&sb, " mode change %06o => %06o",
5707 p->one->mode, p->two->mode);
5708 if (show_name) {
5709 strbuf_addch(&sb, ' ');
5710 quote_c_style(p->two->path, &sb, NULL, 0);
5712 strbuf_addch(&sb, '\n');
5713 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5714 sb.buf, sb.len, 0);
5715 strbuf_release(&sb);
5719 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5720 struct diff_filepair *p)
5722 struct strbuf sb = STRBUF_INIT;
5723 struct strbuf names = STRBUF_INIT;
5725 pprint_rename(&names, p->one->path, p->two->path);
5726 strbuf_addf(&sb, " %s %s (%d%%)\n",
5727 renamecopy, names.buf, similarity_index(p));
5728 strbuf_release(&names);
5729 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5730 sb.buf, sb.len, 0);
5731 show_mode_change(opt, p, 0);
5732 strbuf_release(&sb);
5735 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5737 switch(p->status) {
5738 case DIFF_STATUS_DELETED:
5739 show_file_mode_name(opt, "delete", p->one);
5740 break;
5741 case DIFF_STATUS_ADDED:
5742 show_file_mode_name(opt, "create", p->two);
5743 break;
5744 case DIFF_STATUS_COPIED:
5745 show_rename_copy(opt, "copy", p);
5746 break;
5747 case DIFF_STATUS_RENAMED:
5748 show_rename_copy(opt, "rename", p);
5749 break;
5750 default:
5751 if (p->score) {
5752 struct strbuf sb = STRBUF_INIT;
5753 strbuf_addstr(&sb, " rewrite ");
5754 quote_c_style(p->two->path, &sb, NULL, 0);
5755 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5756 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5757 sb.buf, sb.len, 0);
5758 strbuf_release(&sb);
5760 show_mode_change(opt, p, !p->score);
5761 break;
5765 struct patch_id_t {
5766 git_SHA_CTX *ctx;
5767 int patchlen;
5770 static int remove_space(char *line, int len)
5772 int i;
5773 char *dst = line;
5774 unsigned char c;
5776 for (i = 0; i < len; i++)
5777 if (!isspace((c = line[i])))
5778 *dst++ = c;
5780 return dst - line;
5783 static void patch_id_consume(void *priv, char *line, unsigned long len)
5785 struct patch_id_t *data = priv;
5786 int new_len;
5788 new_len = remove_space(line, len);
5790 git_SHA1_Update(data->ctx, line, new_len);
5791 data->patchlen += new_len;
5794 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
5796 git_SHA1_Update(ctx, str, strlen(str));
5799 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
5801 /* large enough for 2^32 in octal */
5802 char buf[12];
5803 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
5804 git_SHA1_Update(ctx, buf, len);
5807 /* returns 0 upon success, and writes result into sha1 */
5808 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5810 struct diff_queue_struct *q = &diff_queued_diff;
5811 int i;
5812 git_SHA_CTX ctx;
5813 struct patch_id_t data;
5815 git_SHA1_Init(&ctx);
5816 memset(&data, 0, sizeof(struct patch_id_t));
5817 data.ctx = &ctx;
5819 for (i = 0; i < q->nr; i++) {
5820 xpparam_t xpp;
5821 xdemitconf_t xecfg;
5822 mmfile_t mf1, mf2;
5823 struct diff_filepair *p = q->queue[i];
5824 int len1, len2;
5826 memset(&xpp, 0, sizeof(xpp));
5827 memset(&xecfg, 0, sizeof(xecfg));
5828 if (p->status == 0)
5829 return error("internal diff status error");
5830 if (p->status == DIFF_STATUS_UNKNOWN)
5831 continue;
5832 if (diff_unmodified_pair(p))
5833 continue;
5834 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5835 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5836 continue;
5837 if (DIFF_PAIR_UNMERGED(p))
5838 continue;
5840 diff_fill_oid_info(p->one, options->repo->index);
5841 diff_fill_oid_info(p->two, options->repo->index);
5843 len1 = remove_space(p->one->path, strlen(p->one->path));
5844 len2 = remove_space(p->two->path, strlen(p->two->path));
5845 patch_id_add_string(&ctx, "diff--git");
5846 patch_id_add_string(&ctx, "a/");
5847 git_SHA1_Update(&ctx, p->one->path, len1);
5848 patch_id_add_string(&ctx, "b/");
5849 git_SHA1_Update(&ctx, p->two->path, len2);
5851 if (p->one->mode == 0) {
5852 patch_id_add_string(&ctx, "newfilemode");
5853 patch_id_add_mode(&ctx, p->two->mode);
5854 patch_id_add_string(&ctx, "---/dev/null");
5855 patch_id_add_string(&ctx, "+++b/");
5856 git_SHA1_Update(&ctx, p->two->path, len2);
5857 } else if (p->two->mode == 0) {
5858 patch_id_add_string(&ctx, "deletedfilemode");
5859 patch_id_add_mode(&ctx, p->one->mode);
5860 patch_id_add_string(&ctx, "---a/");
5861 git_SHA1_Update(&ctx, p->one->path, len1);
5862 patch_id_add_string(&ctx, "+++/dev/null");
5863 } else {
5864 patch_id_add_string(&ctx, "---a/");
5865 git_SHA1_Update(&ctx, p->one->path, len1);
5866 patch_id_add_string(&ctx, "+++b/");
5867 git_SHA1_Update(&ctx, p->two->path, len2);
5870 if (diff_header_only)
5871 continue;
5873 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
5874 fill_mmfile(options->repo, &mf2, p->two) < 0)
5875 return error("unable to read files to diff");
5877 if (diff_filespec_is_binary(options->repo, p->one) ||
5878 diff_filespec_is_binary(options->repo, p->two)) {
5879 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5880 GIT_SHA1_HEXSZ);
5881 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5882 GIT_SHA1_HEXSZ);
5883 continue;
5886 xpp.flags = 0;
5887 xecfg.ctxlen = 3;
5888 xecfg.flags = 0;
5889 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
5890 patch_id_consume, &data, &xpp, &xecfg))
5891 return error("unable to generate patch-id diff for %s",
5892 p->one->path);
5895 git_SHA1_Final(oid->hash, &ctx);
5896 return 0;
5899 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5901 struct diff_queue_struct *q = &diff_queued_diff;
5902 int i;
5903 int result = diff_get_patch_id(options, oid, diff_header_only);
5905 for (i = 0; i < q->nr; i++)
5906 diff_free_filepair(q->queue[i]);
5908 free(q->queue);
5909 DIFF_QUEUE_CLEAR(q);
5911 return result;
5914 static int is_summary_empty(const struct diff_queue_struct *q)
5916 int i;
5918 for (i = 0; i < q->nr; i++) {
5919 const struct diff_filepair *p = q->queue[i];
5921 switch (p->status) {
5922 case DIFF_STATUS_DELETED:
5923 case DIFF_STATUS_ADDED:
5924 case DIFF_STATUS_COPIED:
5925 case DIFF_STATUS_RENAMED:
5926 return 0;
5927 default:
5928 if (p->score)
5929 return 0;
5930 if (p->one->mode && p->two->mode &&
5931 p->one->mode != p->two->mode)
5932 return 0;
5933 break;
5936 return 1;
5939 static const char rename_limit_warning[] =
5940 N_("inexact rename detection was skipped due to too many files.");
5942 static const char degrade_cc_to_c_warning[] =
5943 N_("only found copies from modified paths due to too many files.");
5945 static const char rename_limit_advice[] =
5946 N_("you may want to set your %s variable to at least "
5947 "%d and retry the command.");
5949 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5951 fflush(stdout);
5952 if (degraded_cc)
5953 warning(_(degrade_cc_to_c_warning));
5954 else if (needed)
5955 warning(_(rename_limit_warning));
5956 else
5957 return;
5958 if (0 < needed)
5959 warning(_(rename_limit_advice), varname, needed);
5962 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5964 int i;
5965 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5966 struct diff_queue_struct *q = &diff_queued_diff;
5968 if (WSEH_NEW & WS_RULE_MASK)
5969 BUG("WS rules bit mask overlaps with diff symbol flags");
5971 if (o->color_moved)
5972 o->emitted_symbols = &esm;
5974 for (i = 0; i < q->nr; i++) {
5975 struct diff_filepair *p = q->queue[i];
5976 if (check_pair_status(p))
5977 diff_flush_patch(p, o);
5980 if (o->emitted_symbols) {
5981 if (o->color_moved) {
5982 struct hashmap add_lines, del_lines;
5984 if (o->color_moved_ws_handling &
5985 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
5986 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
5988 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
5989 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
5991 add_lines_to_move_detection(o, &add_lines, &del_lines);
5992 mark_color_as_moved(o, &add_lines, &del_lines);
5993 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
5994 dim_moved_lines(o);
5996 hashmap_free(&add_lines, 1);
5997 hashmap_free(&del_lines, 1);
6000 for (i = 0; i < esm.nr; i++)
6001 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6003 for (i = 0; i < esm.nr; i++)
6004 free((void *)esm.buf[i].line);
6005 esm.nr = 0;
6007 o->emitted_symbols = NULL;
6011 void diff_flush(struct diff_options *options)
6013 struct diff_queue_struct *q = &diff_queued_diff;
6014 int i, output_format = options->output_format;
6015 int separator = 0;
6016 int dirstat_by_line = 0;
6019 * Order: raw, stat, summary, patch
6020 * or: name/name-status/checkdiff (other bits clear)
6022 if (!q->nr)
6023 goto free_queue;
6025 if (output_format & (DIFF_FORMAT_RAW |
6026 DIFF_FORMAT_NAME |
6027 DIFF_FORMAT_NAME_STATUS |
6028 DIFF_FORMAT_CHECKDIFF)) {
6029 for (i = 0; i < q->nr; i++) {
6030 struct diff_filepair *p = q->queue[i];
6031 if (check_pair_status(p))
6032 flush_one_pair(p, options);
6034 separator++;
6037 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6038 dirstat_by_line = 1;
6040 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6041 dirstat_by_line) {
6042 struct diffstat_t diffstat;
6044 memset(&diffstat, 0, sizeof(struct diffstat_t));
6045 for (i = 0; i < q->nr; i++) {
6046 struct diff_filepair *p = q->queue[i];
6047 if (check_pair_status(p))
6048 diff_flush_stat(p, options, &diffstat);
6050 if (output_format & DIFF_FORMAT_NUMSTAT)
6051 show_numstat(&diffstat, options);
6052 if (output_format & DIFF_FORMAT_DIFFSTAT)
6053 show_stats(&diffstat, options);
6054 if (output_format & DIFF_FORMAT_SHORTSTAT)
6055 show_shortstats(&diffstat, options);
6056 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6057 show_dirstat_by_line(&diffstat, options);
6058 free_diffstat_info(&diffstat);
6059 separator++;
6061 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6062 show_dirstat(options);
6064 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6065 for (i = 0; i < q->nr; i++) {
6066 diff_summary(options, q->queue[i]);
6068 separator++;
6071 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6072 options->flags.exit_with_status &&
6073 options->flags.diff_from_contents) {
6075 * run diff_flush_patch for the exit status. setting
6076 * options->file to /dev/null should be safe, because we
6077 * aren't supposed to produce any output anyway.
6079 if (options->close_file)
6080 fclose(options->file);
6081 options->file = xfopen("/dev/null", "w");
6082 options->close_file = 1;
6083 options->color_moved = 0;
6084 for (i = 0; i < q->nr; i++) {
6085 struct diff_filepair *p = q->queue[i];
6086 if (check_pair_status(p))
6087 diff_flush_patch(p, options);
6088 if (options->found_changes)
6089 break;
6093 if (output_format & DIFF_FORMAT_PATCH) {
6094 if (separator) {
6095 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6096 if (options->stat_sep)
6097 /* attach patch instead of inline */
6098 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6099 NULL, 0, 0);
6102 diff_flush_patch_all_file_pairs(options);
6105 if (output_format & DIFF_FORMAT_CALLBACK)
6106 options->format_callback(q, options, options->format_callback_data);
6108 for (i = 0; i < q->nr; i++)
6109 diff_free_filepair(q->queue[i]);
6110 free_queue:
6111 free(q->queue);
6112 DIFF_QUEUE_CLEAR(q);
6113 if (options->close_file)
6114 fclose(options->file);
6117 * Report the content-level differences with HAS_CHANGES;
6118 * diff_addremove/diff_change does not set the bit when
6119 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6121 if (options->flags.diff_from_contents) {
6122 if (options->found_changes)
6123 options->flags.has_changes = 1;
6124 else
6125 options->flags.has_changes = 0;
6129 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6131 return (((p->status == DIFF_STATUS_MODIFIED) &&
6132 ((p->score &&
6133 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6134 (!p->score &&
6135 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6136 ((p->status != DIFF_STATUS_MODIFIED) &&
6137 filter_bit_tst(p->status, options)));
6140 static void diffcore_apply_filter(struct diff_options *options)
6142 int i;
6143 struct diff_queue_struct *q = &diff_queued_diff;
6144 struct diff_queue_struct outq;
6146 DIFF_QUEUE_CLEAR(&outq);
6148 if (!options->filter)
6149 return;
6151 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6152 int found;
6153 for (i = found = 0; !found && i < q->nr; i++) {
6154 if (match_filter(options, q->queue[i]))
6155 found++;
6157 if (found)
6158 return;
6160 /* otherwise we will clear the whole queue
6161 * by copying the empty outq at the end of this
6162 * function, but first clear the current entries
6163 * in the queue.
6165 for (i = 0; i < q->nr; i++)
6166 diff_free_filepair(q->queue[i]);
6168 else {
6169 /* Only the matching ones */
6170 for (i = 0; i < q->nr; i++) {
6171 struct diff_filepair *p = q->queue[i];
6172 if (match_filter(options, p))
6173 diff_q(&outq, p);
6174 else
6175 diff_free_filepair(p);
6178 free(q->queue);
6179 *q = outq;
6182 /* Check whether two filespecs with the same mode and size are identical */
6183 static int diff_filespec_is_identical(struct repository *r,
6184 struct diff_filespec *one,
6185 struct diff_filespec *two)
6187 if (S_ISGITLINK(one->mode))
6188 return 0;
6189 if (diff_populate_filespec(r, one, 0))
6190 return 0;
6191 if (diff_populate_filespec(r, two, 0))
6192 return 0;
6193 return !memcmp(one->data, two->data, one->size);
6196 static int diff_filespec_check_stat_unmatch(struct repository *r,
6197 struct diff_filepair *p)
6199 if (p->done_skip_stat_unmatch)
6200 return p->skip_stat_unmatch_result;
6202 p->done_skip_stat_unmatch = 1;
6203 p->skip_stat_unmatch_result = 0;
6205 * 1. Entries that come from stat info dirtiness
6206 * always have both sides (iow, not create/delete),
6207 * one side of the object name is unknown, with
6208 * the same mode and size. Keep the ones that
6209 * do not match these criteria. They have real
6210 * differences.
6212 * 2. At this point, the file is known to be modified,
6213 * with the same mode and size, and the object
6214 * name of one side is unknown. Need to inspect
6215 * the identical contents.
6217 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6218 !DIFF_FILE_VALID(p->two) ||
6219 (p->one->oid_valid && p->two->oid_valid) ||
6220 (p->one->mode != p->two->mode) ||
6221 diff_populate_filespec(r, p->one, CHECK_SIZE_ONLY) ||
6222 diff_populate_filespec(r, p->two, CHECK_SIZE_ONLY) ||
6223 (p->one->size != p->two->size) ||
6224 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6225 p->skip_stat_unmatch_result = 1;
6226 return p->skip_stat_unmatch_result;
6229 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6231 int i;
6232 struct diff_queue_struct *q = &diff_queued_diff;
6233 struct diff_queue_struct outq;
6234 DIFF_QUEUE_CLEAR(&outq);
6236 for (i = 0; i < q->nr; i++) {
6237 struct diff_filepair *p = q->queue[i];
6239 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6240 diff_q(&outq, p);
6241 else {
6243 * The caller can subtract 1 from skip_stat_unmatch
6244 * to determine how many paths were dirty only
6245 * due to stat info mismatch.
6247 if (!diffopt->flags.no_index)
6248 diffopt->skip_stat_unmatch++;
6249 diff_free_filepair(p);
6252 free(q->queue);
6253 *q = outq;
6256 static int diffnamecmp(const void *a_, const void *b_)
6258 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6259 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6260 const char *name_a, *name_b;
6262 name_a = a->one ? a->one->path : a->two->path;
6263 name_b = b->one ? b->one->path : b->two->path;
6264 return strcmp(name_a, name_b);
6267 void diffcore_fix_diff_index(void)
6269 struct diff_queue_struct *q = &diff_queued_diff;
6270 QSORT(q->queue, q->nr, diffnamecmp);
6273 void diffcore_std(struct diff_options *options)
6275 /* NOTE please keep the following in sync with diff_tree_combined() */
6276 if (options->skip_stat_unmatch)
6277 diffcore_skip_stat_unmatch(options);
6278 if (!options->found_follow) {
6279 /* See try_to_follow_renames() in tree-diff.c */
6280 if (options->break_opt != -1)
6281 diffcore_break(options->repo,
6282 options->break_opt);
6283 if (options->detect_rename)
6284 diffcore_rename(options);
6285 if (options->break_opt != -1)
6286 diffcore_merge_broken();
6288 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6289 diffcore_pickaxe(options);
6290 if (options->orderfile)
6291 diffcore_order(options->orderfile);
6292 if (!options->found_follow)
6293 /* See try_to_follow_renames() in tree-diff.c */
6294 diff_resolve_rename_copy();
6295 diffcore_apply_filter(options);
6297 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6298 options->flags.has_changes = 1;
6299 else
6300 options->flags.has_changes = 0;
6302 options->found_follow = 0;
6305 int diff_result_code(struct diff_options *opt, int status)
6307 int result = 0;
6309 diff_warn_rename_limit("diff.renameLimit",
6310 opt->needed_rename_limit,
6311 opt->degraded_cc_to_c);
6312 if (!opt->flags.exit_with_status &&
6313 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6314 return status;
6315 if (opt->flags.exit_with_status &&
6316 opt->flags.has_changes)
6317 result |= 01;
6318 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6319 opt->flags.check_failed)
6320 result |= 02;
6321 return result;
6324 int diff_can_quit_early(struct diff_options *opt)
6326 return (opt->flags.quick &&
6327 !opt->filter &&
6328 opt->flags.has_changes);
6332 * Shall changes to this submodule be ignored?
6334 * Submodule changes can be configured to be ignored separately for each path,
6335 * but that configuration can be overridden from the command line.
6337 static int is_submodule_ignored(const char *path, struct diff_options *options)
6339 int ignored = 0;
6340 struct diff_flags orig_flags = options->flags;
6341 if (!options->flags.override_submodule_config)
6342 set_diffopt_flags_from_submodule_config(options, path);
6343 if (options->flags.ignore_submodules)
6344 ignored = 1;
6345 options->flags = orig_flags;
6346 return ignored;
6349 void diff_addremove(struct diff_options *options,
6350 int addremove, unsigned mode,
6351 const struct object_id *oid,
6352 int oid_valid,
6353 const char *concatpath, unsigned dirty_submodule)
6355 struct diff_filespec *one, *two;
6357 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6358 return;
6360 /* This may look odd, but it is a preparation for
6361 * feeding "there are unchanged files which should
6362 * not produce diffs, but when you are doing copy
6363 * detection you would need them, so here they are"
6364 * entries to the diff-core. They will be prefixed
6365 * with something like '=' or '*' (I haven't decided
6366 * which but should not make any difference).
6367 * Feeding the same new and old to diff_change()
6368 * also has the same effect.
6369 * Before the final output happens, they are pruned after
6370 * merged into rename/copy pairs as appropriate.
6372 if (options->flags.reverse_diff)
6373 addremove = (addremove == '+' ? '-' :
6374 addremove == '-' ? '+' : addremove);
6376 if (options->prefix &&
6377 strncmp(concatpath, options->prefix, options->prefix_length))
6378 return;
6380 one = alloc_filespec(concatpath);
6381 two = alloc_filespec(concatpath);
6383 if (addremove != '+')
6384 fill_filespec(one, oid, oid_valid, mode);
6385 if (addremove != '-') {
6386 fill_filespec(two, oid, oid_valid, mode);
6387 two->dirty_submodule = dirty_submodule;
6390 diff_queue(&diff_queued_diff, one, two);
6391 if (!options->flags.diff_from_contents)
6392 options->flags.has_changes = 1;
6395 void diff_change(struct diff_options *options,
6396 unsigned old_mode, unsigned new_mode,
6397 const struct object_id *old_oid,
6398 const struct object_id *new_oid,
6399 int old_oid_valid, int new_oid_valid,
6400 const char *concatpath,
6401 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6403 struct diff_filespec *one, *two;
6404 struct diff_filepair *p;
6406 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6407 is_submodule_ignored(concatpath, options))
6408 return;
6410 if (options->flags.reverse_diff) {
6411 SWAP(old_mode, new_mode);
6412 SWAP(old_oid, new_oid);
6413 SWAP(old_oid_valid, new_oid_valid);
6414 SWAP(old_dirty_submodule, new_dirty_submodule);
6417 if (options->prefix &&
6418 strncmp(concatpath, options->prefix, options->prefix_length))
6419 return;
6421 one = alloc_filespec(concatpath);
6422 two = alloc_filespec(concatpath);
6423 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6424 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6425 one->dirty_submodule = old_dirty_submodule;
6426 two->dirty_submodule = new_dirty_submodule;
6427 p = diff_queue(&diff_queued_diff, one, two);
6429 if (options->flags.diff_from_contents)
6430 return;
6432 if (options->flags.quick && options->skip_stat_unmatch &&
6433 !diff_filespec_check_stat_unmatch(options->repo, p))
6434 return;
6436 options->flags.has_changes = 1;
6439 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6441 struct diff_filepair *pair;
6442 struct diff_filespec *one, *two;
6444 if (options->prefix &&
6445 strncmp(path, options->prefix, options->prefix_length))
6446 return NULL;
6448 one = alloc_filespec(path);
6449 two = alloc_filespec(path);
6450 pair = diff_queue(&diff_queued_diff, one, two);
6451 pair->is_unmerged = 1;
6452 return pair;
6455 static char *run_textconv(struct repository *r,
6456 const char *pgm,
6457 struct diff_filespec *spec,
6458 size_t *outsize)
6460 struct diff_tempfile *temp;
6461 const char *argv[3];
6462 const char **arg = argv;
6463 struct child_process child = CHILD_PROCESS_INIT;
6464 struct strbuf buf = STRBUF_INIT;
6465 int err = 0;
6467 temp = prepare_temp_file(r, spec->path, spec);
6468 *arg++ = pgm;
6469 *arg++ = temp->name;
6470 *arg = NULL;
6472 child.use_shell = 1;
6473 child.argv = argv;
6474 child.out = -1;
6475 if (start_command(&child)) {
6476 remove_tempfile();
6477 return NULL;
6480 if (strbuf_read(&buf, child.out, 0) < 0)
6481 err = error("error reading from textconv command '%s'", pgm);
6482 close(child.out);
6484 if (finish_command(&child) || err) {
6485 strbuf_release(&buf);
6486 remove_tempfile();
6487 return NULL;
6489 remove_tempfile();
6491 return strbuf_detach(&buf, outsize);
6494 size_t fill_textconv(struct repository *r,
6495 struct userdiff_driver *driver,
6496 struct diff_filespec *df,
6497 char **outbuf)
6499 size_t size;
6501 if (!driver) {
6502 if (!DIFF_FILE_VALID(df)) {
6503 *outbuf = "";
6504 return 0;
6506 if (diff_populate_filespec(r, df, 0))
6507 die("unable to read files to diff");
6508 *outbuf = df->data;
6509 return df->size;
6512 if (!driver->textconv)
6513 BUG("fill_textconv called with non-textconv driver");
6515 if (driver->textconv_cache && df->oid_valid) {
6516 *outbuf = notes_cache_get(driver->textconv_cache,
6517 &df->oid,
6518 &size);
6519 if (*outbuf)
6520 return size;
6523 *outbuf = run_textconv(r, driver->textconv, df, &size);
6524 if (!*outbuf)
6525 die("unable to read files to diff");
6527 if (driver->textconv_cache && df->oid_valid) {
6528 /* ignore errors, as we might be in a readonly repository */
6529 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6530 size);
6532 * we could save up changes and flush them all at the end,
6533 * but we would need an extra call after all diffing is done.
6534 * Since generating a cache entry is the slow path anyway,
6535 * this extra overhead probably isn't a big deal.
6537 notes_cache_write(driver->textconv_cache);
6540 return size;
6543 int textconv_object(struct repository *r,
6544 const char *path,
6545 unsigned mode,
6546 const struct object_id *oid,
6547 int oid_valid,
6548 char **buf,
6549 unsigned long *buf_size)
6551 struct diff_filespec *df;
6552 struct userdiff_driver *textconv;
6554 df = alloc_filespec(path);
6555 fill_filespec(df, oid, oid_valid, mode);
6556 textconv = get_textconv(r, df);
6557 if (!textconv) {
6558 free_filespec(df);
6559 return 0;
6562 *buf_size = fill_textconv(r, textconv, df, buf);
6563 free_filespec(df);
6564 return 1;
6567 void setup_diff_pager(struct diff_options *opt)
6570 * If the user asked for our exit code, then either they want --quiet
6571 * or --exit-code. We should definitely not bother with a pager in the
6572 * former case, as we will generate no output. Since we still properly
6573 * report our exit code even when a pager is run, we _could_ run a
6574 * pager with --exit-code. But since we have not done so historically,
6575 * and because it is easy to find people oneline advising "git diff
6576 * --exit-code" in hooks and other scripts, we do not do so.
6578 if (!opt->flags.exit_with_status &&
6579 check_pager_config("diff") != 0)
6580 setup_pager();