Merge branch 'bc/hash-transition-16'
[alt-git.git] / diff.c
blobe30a645d9e01ecab1c12d8d14def7de5f6b8d2ed
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 define_list_config_array_extra(color_diff_slots, {"plain"});
109 static int parse_diff_color_slot(const char *var)
111 if (!strcasecmp(var, "plain"))
112 return DIFF_CONTEXT;
113 return LOOKUP_CONFIG(color_diff_slots, var);
116 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
117 struct strbuf *errmsg)
119 char *params_copy = xstrdup(params_string);
120 struct string_list params = STRING_LIST_INIT_NODUP;
121 int ret = 0;
122 int i;
124 if (*params_copy)
125 string_list_split_in_place(&params, params_copy, ',', -1);
126 for (i = 0; i < params.nr; i++) {
127 const char *p = params.items[i].string;
128 if (!strcmp(p, "changes")) {
129 options->flags.dirstat_by_line = 0;
130 options->flags.dirstat_by_file = 0;
131 } else if (!strcmp(p, "lines")) {
132 options->flags.dirstat_by_line = 1;
133 options->flags.dirstat_by_file = 0;
134 } else if (!strcmp(p, "files")) {
135 options->flags.dirstat_by_line = 0;
136 options->flags.dirstat_by_file = 1;
137 } else if (!strcmp(p, "noncumulative")) {
138 options->flags.dirstat_cumulative = 0;
139 } else if (!strcmp(p, "cumulative")) {
140 options->flags.dirstat_cumulative = 1;
141 } else if (isdigit(*p)) {
142 char *end;
143 int permille = strtoul(p, &end, 10) * 10;
144 if (*end == '.' && isdigit(*++end)) {
145 /* only use first digit */
146 permille += *end - '0';
147 /* .. and ignore any further digits */
148 while (isdigit(*++end))
149 ; /* nothing */
151 if (!*end)
152 options->dirstat_permille = permille;
153 else {
154 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
156 ret++;
158 } else {
159 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
160 ret++;
164 string_list_clear(&params, 0);
165 free(params_copy);
166 return ret;
169 static int parse_submodule_params(struct diff_options *options, const char *value)
171 if (!strcmp(value, "log"))
172 options->submodule_format = DIFF_SUBMODULE_LOG;
173 else if (!strcmp(value, "short"))
174 options->submodule_format = DIFF_SUBMODULE_SHORT;
175 else if (!strcmp(value, "diff"))
176 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
178 * Please update $__git_diff_submodule_formats in
179 * git-completion.bash when you add new formats.
181 else
182 return -1;
183 return 0;
186 int git_config_rename(const char *var, const char *value)
188 if (!value)
189 return DIFF_DETECT_RENAME;
190 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
191 return DIFF_DETECT_COPY;
192 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
195 long parse_algorithm_value(const char *value)
197 if (!value)
198 return -1;
199 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
200 return 0;
201 else if (!strcasecmp(value, "minimal"))
202 return XDF_NEED_MINIMAL;
203 else if (!strcasecmp(value, "patience"))
204 return XDF_PATIENCE_DIFF;
205 else if (!strcasecmp(value, "histogram"))
206 return XDF_HISTOGRAM_DIFF;
208 * Please update $__git_diff_algorithms in git-completion.bash
209 * when you add new algorithms.
211 return -1;
214 static int parse_one_token(const char **arg, const char *token)
216 const char *rest;
217 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
218 *arg = rest;
219 return 1;
221 return 0;
224 static int parse_ws_error_highlight(const char *arg)
226 const char *orig_arg = arg;
227 unsigned val = 0;
229 while (*arg) {
230 if (parse_one_token(&arg, "none"))
231 val = 0;
232 else if (parse_one_token(&arg, "default"))
233 val = WSEH_NEW;
234 else if (parse_one_token(&arg, "all"))
235 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
236 else if (parse_one_token(&arg, "new"))
237 val |= WSEH_NEW;
238 else if (parse_one_token(&arg, "old"))
239 val |= WSEH_OLD;
240 else if (parse_one_token(&arg, "context"))
241 val |= WSEH_CONTEXT;
242 else {
243 return -1 - (int)(arg - orig_arg);
245 if (*arg)
246 arg++;
248 return val;
252 * These are to give UI layer defaults.
253 * The core-level commands such as git-diff-files should
254 * never be affected by the setting of diff.renames
255 * the user happens to have in the configuration file.
257 void init_diff_ui_defaults(void)
259 diff_detect_rename_default = DIFF_DETECT_RENAME;
262 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
264 if (!strcmp(var, "diff.indentheuristic"))
265 diff_indent_heuristic = git_config_bool(var, value);
266 return 0;
269 static int parse_color_moved(const char *arg)
271 switch (git_parse_maybe_bool(arg)) {
272 case 0:
273 return COLOR_MOVED_NO;
274 case 1:
275 return COLOR_MOVED_DEFAULT;
276 default:
277 break;
280 if (!strcmp(arg, "no"))
281 return COLOR_MOVED_NO;
282 else if (!strcmp(arg, "plain"))
283 return COLOR_MOVED_PLAIN;
284 else if (!strcmp(arg, "blocks"))
285 return COLOR_MOVED_BLOCKS;
286 else if (!strcmp(arg, "zebra"))
287 return COLOR_MOVED_ZEBRA;
288 else if (!strcmp(arg, "default"))
289 return COLOR_MOVED_DEFAULT;
290 else if (!strcmp(arg, "dimmed-zebra"))
291 return COLOR_MOVED_ZEBRA_DIM;
292 else if (!strcmp(arg, "dimmed_zebra"))
293 return COLOR_MOVED_ZEBRA_DIM;
294 else
295 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
298 static unsigned parse_color_moved_ws(const char *arg)
300 int ret = 0;
301 struct string_list l = STRING_LIST_INIT_DUP;
302 struct string_list_item *i;
304 string_list_split(&l, arg, ',', -1);
306 for_each_string_list_item(i, &l) {
307 struct strbuf sb = STRBUF_INIT;
308 strbuf_addstr(&sb, i->string);
309 strbuf_trim(&sb);
311 if (!strcmp(sb.buf, "no"))
312 ret = 0;
313 else if (!strcmp(sb.buf, "ignore-space-change"))
314 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
315 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
316 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
317 else if (!strcmp(sb.buf, "ignore-all-space"))
318 ret |= XDF_IGNORE_WHITESPACE;
319 else if (!strcmp(sb.buf, "allow-indentation-change"))
320 ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
321 else {
322 ret |= COLOR_MOVED_WS_ERROR;
323 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);
326 strbuf_release(&sb);
329 if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
330 (ret & XDF_WHITESPACE_FLAGS)) {
331 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
332 ret |= COLOR_MOVED_WS_ERROR;
335 string_list_clear(&l, 0);
337 return ret;
340 int git_diff_ui_config(const char *var, const char *value, void *cb)
342 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
343 diff_use_color_default = git_config_colorbool(var, value);
344 return 0;
346 if (!strcmp(var, "diff.colormoved")) {
347 int cm = parse_color_moved(value);
348 if (cm < 0)
349 return -1;
350 diff_color_moved_default = cm;
351 return 0;
353 if (!strcmp(var, "diff.colormovedws")) {
354 unsigned cm = parse_color_moved_ws(value);
355 if (cm & COLOR_MOVED_WS_ERROR)
356 return -1;
357 diff_color_moved_ws_default = cm;
358 return 0;
360 if (!strcmp(var, "diff.context")) {
361 diff_context_default = git_config_int(var, value);
362 if (diff_context_default < 0)
363 return -1;
364 return 0;
366 if (!strcmp(var, "diff.interhunkcontext")) {
367 diff_interhunk_context_default = git_config_int(var, value);
368 if (diff_interhunk_context_default < 0)
369 return -1;
370 return 0;
372 if (!strcmp(var, "diff.renames")) {
373 diff_detect_rename_default = git_config_rename(var, value);
374 return 0;
376 if (!strcmp(var, "diff.autorefreshindex")) {
377 diff_auto_refresh_index = git_config_bool(var, value);
378 return 0;
380 if (!strcmp(var, "diff.mnemonicprefix")) {
381 diff_mnemonic_prefix = git_config_bool(var, value);
382 return 0;
384 if (!strcmp(var, "diff.noprefix")) {
385 diff_no_prefix = git_config_bool(var, value);
386 return 0;
388 if (!strcmp(var, "diff.statgraphwidth")) {
389 diff_stat_graph_width = git_config_int(var, value);
390 return 0;
392 if (!strcmp(var, "diff.external"))
393 return git_config_string(&external_diff_cmd_cfg, var, value);
394 if (!strcmp(var, "diff.wordregex"))
395 return git_config_string(&diff_word_regex_cfg, var, value);
396 if (!strcmp(var, "diff.orderfile"))
397 return git_config_pathname(&diff_order_file_cfg, var, value);
399 if (!strcmp(var, "diff.ignoresubmodules"))
400 handle_ignore_submodules_arg(&default_diff_options, value);
402 if (!strcmp(var, "diff.submodule")) {
403 if (parse_submodule_params(&default_diff_options, value))
404 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
405 value);
406 return 0;
409 if (!strcmp(var, "diff.algorithm")) {
410 diff_algorithm = parse_algorithm_value(value);
411 if (diff_algorithm < 0)
412 return -1;
413 return 0;
416 if (!strcmp(var, "diff.wserrorhighlight")) {
417 int val = parse_ws_error_highlight(value);
418 if (val < 0)
419 return -1;
420 ws_error_highlight_default = val;
421 return 0;
424 if (git_color_config(var, value, cb) < 0)
425 return -1;
427 return git_diff_basic_config(var, value, cb);
430 int git_diff_basic_config(const char *var, const char *value, void *cb)
432 const char *name;
434 if (!strcmp(var, "diff.renamelimit")) {
435 diff_rename_limit_default = git_config_int(var, value);
436 return 0;
439 if (userdiff_config(var, value) < 0)
440 return -1;
442 if (skip_prefix(var, "diff.color.", &name) ||
443 skip_prefix(var, "color.diff.", &name)) {
444 int slot = parse_diff_color_slot(name);
445 if (slot < 0)
446 return 0;
447 if (!value)
448 return config_error_nonbool(var);
449 return color_parse(value, diff_colors[slot]);
452 /* like GNU diff's --suppress-blank-empty option */
453 if (!strcmp(var, "diff.suppressblankempty") ||
454 /* for backwards compatibility */
455 !strcmp(var, "diff.suppress-blank-empty")) {
456 diff_suppress_blank_empty = git_config_bool(var, value);
457 return 0;
460 if (!strcmp(var, "diff.dirstat")) {
461 struct strbuf errmsg = STRBUF_INIT;
462 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
463 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
464 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
465 errmsg.buf);
466 strbuf_release(&errmsg);
467 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
468 return 0;
471 if (git_diff_heuristic_config(var, value, cb) < 0)
472 return -1;
474 return git_default_config(var, value, cb);
477 static char *quote_two(const char *one, const char *two)
479 int need_one = quote_c_style(one, NULL, NULL, 1);
480 int need_two = quote_c_style(two, NULL, NULL, 1);
481 struct strbuf res = STRBUF_INIT;
483 if (need_one + need_two) {
484 strbuf_addch(&res, '"');
485 quote_c_style(one, &res, NULL, 1);
486 quote_c_style(two, &res, NULL, 1);
487 strbuf_addch(&res, '"');
488 } else {
489 strbuf_addstr(&res, one);
490 strbuf_addstr(&res, two);
492 return strbuf_detach(&res, NULL);
495 static const char *external_diff(void)
497 static const char *external_diff_cmd = NULL;
498 static int done_preparing = 0;
500 if (done_preparing)
501 return external_diff_cmd;
502 external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
503 if (!external_diff_cmd)
504 external_diff_cmd = external_diff_cmd_cfg;
505 done_preparing = 1;
506 return external_diff_cmd;
510 * Keep track of files used for diffing. Sometimes such an entry
511 * refers to a temporary file, sometimes to an existing file, and
512 * sometimes to "/dev/null".
514 static struct diff_tempfile {
516 * filename external diff should read from, or NULL if this
517 * entry is currently not in use:
519 const char *name;
521 char hex[GIT_MAX_HEXSZ + 1];
522 char mode[10];
525 * If this diff_tempfile instance refers to a temporary file,
526 * this tempfile object is used to manage its lifetime.
528 struct tempfile *tempfile;
529 } diff_temp[2];
531 struct emit_callback {
532 int color_diff;
533 unsigned ws_rule;
534 int blank_at_eof_in_preimage;
535 int blank_at_eof_in_postimage;
536 int lno_in_preimage;
537 int lno_in_postimage;
538 const char **label_path;
539 struct diff_words_data *diff_words;
540 struct diff_options *opt;
541 struct strbuf *header;
544 static int count_lines(const char *data, int size)
546 int count, ch, completely_empty = 1, nl_just_seen = 0;
547 count = 0;
548 while (0 < size--) {
549 ch = *data++;
550 if (ch == '\n') {
551 count++;
552 nl_just_seen = 1;
553 completely_empty = 0;
555 else {
556 nl_just_seen = 0;
557 completely_empty = 0;
560 if (completely_empty)
561 return 0;
562 if (!nl_just_seen)
563 count++; /* no trailing newline */
564 return count;
567 static int fill_mmfile(struct repository *r, mmfile_t *mf,
568 struct diff_filespec *one)
570 if (!DIFF_FILE_VALID(one)) {
571 mf->ptr = (char *)""; /* does not matter */
572 mf->size = 0;
573 return 0;
575 else if (diff_populate_filespec(r, one, 0))
576 return -1;
578 mf->ptr = one->data;
579 mf->size = one->size;
580 return 0;
583 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
584 static unsigned long diff_filespec_size(struct repository *r,
585 struct diff_filespec *one)
587 if (!DIFF_FILE_VALID(one))
588 return 0;
589 diff_populate_filespec(r, one, CHECK_SIZE_ONLY);
590 return one->size;
593 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
595 char *ptr = mf->ptr;
596 long size = mf->size;
597 int cnt = 0;
599 if (!size)
600 return cnt;
601 ptr += size - 1; /* pointing at the very end */
602 if (*ptr != '\n')
603 ; /* incomplete line */
604 else
605 ptr--; /* skip the last LF */
606 while (mf->ptr < ptr) {
607 char *prev_eol;
608 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
609 if (*prev_eol == '\n')
610 break;
611 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
612 break;
613 cnt++;
614 ptr = prev_eol - 1;
616 return cnt;
619 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
620 struct emit_callback *ecbdata)
622 int l1, l2, at;
623 unsigned ws_rule = ecbdata->ws_rule;
624 l1 = count_trailing_blank(mf1, ws_rule);
625 l2 = count_trailing_blank(mf2, ws_rule);
626 if (l2 <= l1) {
627 ecbdata->blank_at_eof_in_preimage = 0;
628 ecbdata->blank_at_eof_in_postimage = 0;
629 return;
631 at = count_lines(mf1->ptr, mf1->size);
632 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
634 at = count_lines(mf2->ptr, mf2->size);
635 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
638 static void emit_line_0(struct diff_options *o,
639 const char *set_sign, const char *set, unsigned reverse, const char *reset,
640 int first, const char *line, int len)
642 int has_trailing_newline, has_trailing_carriage_return;
643 int needs_reset = 0; /* at the end of the line */
644 FILE *file = o->file;
646 fputs(diff_line_prefix(o), file);
648 has_trailing_newline = (len > 0 && line[len-1] == '\n');
649 if (has_trailing_newline)
650 len--;
652 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
653 if (has_trailing_carriage_return)
654 len--;
656 if (!len && !first)
657 goto end_of_line;
659 if (reverse && want_color(o->use_color)) {
660 fputs(GIT_COLOR_REVERSE, file);
661 needs_reset = 1;
664 if (set_sign) {
665 fputs(set_sign, file);
666 needs_reset = 1;
669 if (first)
670 fputc(first, file);
672 if (!len)
673 goto end_of_line;
675 if (set) {
676 if (set_sign && set != set_sign)
677 fputs(reset, file);
678 fputs(set, file);
679 needs_reset = 1;
681 fwrite(line, len, 1, file);
682 needs_reset = 1; /* 'line' may contain color codes. */
684 end_of_line:
685 if (needs_reset)
686 fputs(reset, file);
687 if (has_trailing_carriage_return)
688 fputc('\r', file);
689 if (has_trailing_newline)
690 fputc('\n', file);
693 static void emit_line(struct diff_options *o, const char *set, const char *reset,
694 const char *line, int len)
696 emit_line_0(o, set, NULL, 0, reset, 0, line, len);
699 enum diff_symbol {
700 DIFF_SYMBOL_BINARY_DIFF_HEADER,
701 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
702 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
703 DIFF_SYMBOL_BINARY_DIFF_BODY,
704 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
705 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
706 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
707 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
708 DIFF_SYMBOL_STATS_LINE,
709 DIFF_SYMBOL_WORD_DIFF,
710 DIFF_SYMBOL_STAT_SEP,
711 DIFF_SYMBOL_SUMMARY,
712 DIFF_SYMBOL_SUBMODULE_ADD,
713 DIFF_SYMBOL_SUBMODULE_DEL,
714 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
715 DIFF_SYMBOL_SUBMODULE_MODIFIED,
716 DIFF_SYMBOL_SUBMODULE_HEADER,
717 DIFF_SYMBOL_SUBMODULE_ERROR,
718 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
719 DIFF_SYMBOL_REWRITE_DIFF,
720 DIFF_SYMBOL_BINARY_FILES,
721 DIFF_SYMBOL_HEADER,
722 DIFF_SYMBOL_FILEPAIR_PLUS,
723 DIFF_SYMBOL_FILEPAIR_MINUS,
724 DIFF_SYMBOL_WORDS_PORCELAIN,
725 DIFF_SYMBOL_WORDS,
726 DIFF_SYMBOL_CONTEXT,
727 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
728 DIFF_SYMBOL_PLUS,
729 DIFF_SYMBOL_MINUS,
730 DIFF_SYMBOL_NO_LF_EOF,
731 DIFF_SYMBOL_CONTEXT_FRAGINFO,
732 DIFF_SYMBOL_CONTEXT_MARKER,
733 DIFF_SYMBOL_SEPARATOR
736 * Flags for content lines:
737 * 0..12 are whitespace rules
738 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
739 * 16 is marking if the line is blank at EOF
741 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
742 #define DIFF_SYMBOL_MOVED_LINE (1<<17)
743 #define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
744 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
745 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
748 * This struct is used when we need to buffer the output of the diff output.
750 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
751 * into the pre/post image file. This pointer could be a union with the
752 * line pointer. By storing an offset into the file instead of the literal line,
753 * we can decrease the memory footprint for the buffered output. At first we
754 * may want to only have indirection for the content lines, but we could also
755 * enhance the state for emitting prefabricated lines, e.g. the similarity
756 * score line or hunk/file headers would only need to store a number or path
757 * and then the output can be constructed later on depending on state.
759 struct emitted_diff_symbol {
760 const char *line;
761 int len;
762 int flags;
763 int indent_off; /* Offset to first non-whitespace character */
764 int indent_width; /* The visual width of the indentation */
765 enum diff_symbol s;
767 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
769 struct emitted_diff_symbols {
770 struct emitted_diff_symbol *buf;
771 int nr, alloc;
773 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
775 static void append_emitted_diff_symbol(struct diff_options *o,
776 struct emitted_diff_symbol *e)
778 struct emitted_diff_symbol *f;
780 ALLOC_GROW(o->emitted_symbols->buf,
781 o->emitted_symbols->nr + 1,
782 o->emitted_symbols->alloc);
783 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
785 memcpy(f, e, sizeof(struct emitted_diff_symbol));
786 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
789 struct moved_entry {
790 struct hashmap_entry ent;
791 const struct emitted_diff_symbol *es;
792 struct moved_entry *next_line;
795 struct moved_block {
796 struct moved_entry *match;
797 int wsd; /* The whitespace delta of this block */
800 static void moved_block_clear(struct moved_block *b)
802 memset(b, 0, sizeof(*b));
805 #define INDENT_BLANKLINE INT_MIN
807 static void fill_es_indent_data(struct emitted_diff_symbol *es)
809 unsigned int off = 0, i;
810 int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
811 const char *s = es->line;
812 const int len = es->len;
814 /* skip any \v \f \r at start of indentation */
815 while (s[off] == '\f' || s[off] == '\v' ||
816 (s[off] == '\r' && off < len - 1))
817 off++;
819 /* calculate the visual width of indentation */
820 while(1) {
821 if (s[off] == ' ') {
822 width++;
823 off++;
824 } else if (s[off] == '\t') {
825 width += tab_width - (width % tab_width);
826 while (s[++off] == '\t')
827 width += tab_width;
828 } else {
829 break;
833 /* check if this line is blank */
834 for (i = off; i < len; i++)
835 if (!isspace(s[i]))
836 break;
838 if (i == len) {
839 es->indent_width = INDENT_BLANKLINE;
840 es->indent_off = len;
841 } else {
842 es->indent_off = off;
843 es->indent_width = width;
847 static int compute_ws_delta(const struct emitted_diff_symbol *a,
848 const struct emitted_diff_symbol *b,
849 int *out)
851 int a_len = a->len,
852 b_len = b->len,
853 a_off = a->indent_off,
854 a_width = a->indent_width,
855 b_off = b->indent_off,
856 b_width = b->indent_width;
857 int delta;
859 if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE) {
860 *out = INDENT_BLANKLINE;
861 return 1;
864 if (a->s == DIFF_SYMBOL_PLUS)
865 delta = a_width - b_width;
866 else
867 delta = b_width - a_width;
869 if (a_len - a_off != b_len - b_off ||
870 memcmp(a->line + a_off, b->line + b_off, a_len - a_off))
871 return 0;
873 *out = delta;
875 return 1;
878 static int cmp_in_block_with_wsd(const struct diff_options *o,
879 const struct moved_entry *cur,
880 const struct moved_entry *match,
881 struct moved_block *pmb,
882 int n)
884 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
885 int al = cur->es->len, bl = match->es->len, cl = l->len;
886 const char *a = cur->es->line,
887 *b = match->es->line,
888 *c = l->line;
889 int a_off = cur->es->indent_off,
890 a_width = cur->es->indent_width,
891 c_off = l->indent_off,
892 c_width = l->indent_width;
893 int delta;
896 * We need to check if 'cur' is equal to 'match'. As those
897 * are from the same (+/-) side, we do not need to adjust for
898 * indent changes. However these were found using fuzzy
899 * matching so we do have to check if they are equal. Here we
900 * just check the lengths. We delay calling memcmp() to check
901 * the contents until later as if the length comparison for a
902 * and c fails we can avoid the call all together.
904 if (al != bl)
905 return 1;
907 /* If 'l' and 'cur' are both blank then they match. */
908 if (a_width == INDENT_BLANKLINE && c_width == INDENT_BLANKLINE)
909 return 0;
912 * The indent changes of the block are known and stored in pmb->wsd;
913 * however we need to check if the indent changes of the current line
914 * match those of the current block and that the text of 'l' and 'cur'
915 * after the indentation match.
917 if (cur->es->s == DIFF_SYMBOL_PLUS)
918 delta = a_width - c_width;
919 else
920 delta = c_width - a_width;
923 * If the previous lines of this block were all blank then set its
924 * whitespace delta.
926 if (pmb->wsd == INDENT_BLANKLINE)
927 pmb->wsd = delta;
929 return !(delta == pmb->wsd && al - a_off == cl - c_off &&
930 !memcmp(a, b, al) && !
931 memcmp(a + a_off, c + c_off, al - a_off));
934 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
935 const void *entry,
936 const void *entry_or_key,
937 const void *keydata)
939 const struct diff_options *diffopt = hashmap_cmp_fn_data;
940 const struct moved_entry *a = entry;
941 const struct moved_entry *b = entry_or_key;
942 unsigned flags = diffopt->color_moved_ws_handling
943 & XDF_WHITESPACE_FLAGS;
945 if (diffopt->color_moved_ws_handling &
946 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
948 * As there is not specific white space config given,
949 * we'd need to check for a new block, so ignore all
950 * white space. The setup of the white space
951 * configuration for the next block is done else where
953 flags |= XDF_IGNORE_WHITESPACE;
955 return !xdiff_compare_lines(a->es->line, a->es->len,
956 b->es->line, b->es->len,
957 flags);
960 static struct moved_entry *prepare_entry(struct diff_options *o,
961 int line_no)
963 struct moved_entry *ret = xmalloc(sizeof(*ret));
964 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
965 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
967 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
968 ret->es = l;
969 ret->next_line = NULL;
971 return ret;
974 static void add_lines_to_move_detection(struct diff_options *o,
975 struct hashmap *add_lines,
976 struct hashmap *del_lines)
978 struct moved_entry *prev_line = NULL;
980 int n;
981 for (n = 0; n < o->emitted_symbols->nr; n++) {
982 struct hashmap *hm;
983 struct moved_entry *key;
985 switch (o->emitted_symbols->buf[n].s) {
986 case DIFF_SYMBOL_PLUS:
987 hm = add_lines;
988 break;
989 case DIFF_SYMBOL_MINUS:
990 hm = del_lines;
991 break;
992 default:
993 prev_line = NULL;
994 continue;
997 if (o->color_moved_ws_handling &
998 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
999 fill_es_indent_data(&o->emitted_symbols->buf[n]);
1000 key = prepare_entry(o, n);
1001 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
1002 prev_line->next_line = key;
1004 hashmap_add(hm, key);
1005 prev_line = key;
1009 static void pmb_advance_or_null(struct diff_options *o,
1010 struct moved_entry *match,
1011 struct hashmap *hm,
1012 struct moved_block *pmb,
1013 int pmb_nr)
1015 int i;
1016 for (i = 0; i < pmb_nr; i++) {
1017 struct moved_entry *prev = pmb[i].match;
1018 struct moved_entry *cur = (prev && prev->next_line) ?
1019 prev->next_line : NULL;
1020 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
1021 pmb[i].match = cur;
1022 } else {
1023 pmb[i].match = NULL;
1028 static void pmb_advance_or_null_multi_match(struct diff_options *o,
1029 struct moved_entry *match,
1030 struct hashmap *hm,
1031 struct moved_block *pmb,
1032 int pmb_nr, int n)
1034 int i;
1035 char *got_match = xcalloc(1, pmb_nr);
1037 for (; match; match = hashmap_get_next(hm, match)) {
1038 for (i = 0; i < pmb_nr; i++) {
1039 struct moved_entry *prev = pmb[i].match;
1040 struct moved_entry *cur = (prev && prev->next_line) ?
1041 prev->next_line : NULL;
1042 if (!cur)
1043 continue;
1044 if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
1045 got_match[i] |= 1;
1049 for (i = 0; i < pmb_nr; i++) {
1050 if (got_match[i]) {
1051 /* Advance to the next line */
1052 pmb[i].match = pmb[i].match->next_line;
1053 } else {
1054 moved_block_clear(&pmb[i]);
1058 free(got_match);
1061 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1062 int pmb_nr)
1064 int lp, rp;
1066 /* Shrink the set of potential block to the remaining running */
1067 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1068 while (lp < pmb_nr && pmb[lp].match)
1069 lp++;
1070 /* lp points at the first NULL now */
1072 while (rp > -1 && !pmb[rp].match)
1073 rp--;
1074 /* rp points at the last non-NULL */
1076 if (lp < pmb_nr && rp > -1 && lp < rp) {
1077 pmb[lp] = pmb[rp];
1078 memset(&pmb[rp], 0, sizeof(pmb[rp]));
1079 rp--;
1080 lp++;
1084 /* Remember the number of running sets */
1085 return rp + 1;
1089 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1091 * Otherwise, if the last block has fewer alphanumeric characters than
1092 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1093 * that block.
1095 * The last block consists of the (n - block_length)'th line up to but not
1096 * including the nth line.
1098 * Returns 0 if the last block is empty or is unset by this function, non zero
1099 * otherwise.
1101 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1102 * Think of a way to unify them.
1104 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1106 int i, alnum_count = 0;
1107 if (o->color_moved == COLOR_MOVED_PLAIN)
1108 return block_length;
1109 for (i = 1; i < block_length + 1; i++) {
1110 const char *c = o->emitted_symbols->buf[n - i].line;
1111 for (; *c; c++) {
1112 if (!isalnum(*c))
1113 continue;
1114 alnum_count++;
1115 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1116 return 1;
1119 for (i = 1; i < block_length + 1; i++)
1120 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1121 return 0;
1124 /* Find blocks of moved code, delegate actual coloring decision to helper */
1125 static void mark_color_as_moved(struct diff_options *o,
1126 struct hashmap *add_lines,
1127 struct hashmap *del_lines)
1129 struct moved_block *pmb = NULL; /* potentially moved blocks */
1130 int pmb_nr = 0, pmb_alloc = 0;
1131 int n, flipped_block = 0, block_length = 0;
1134 for (n = 0; n < o->emitted_symbols->nr; n++) {
1135 struct hashmap *hm = NULL;
1136 struct moved_entry *key;
1137 struct moved_entry *match = NULL;
1138 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1139 enum diff_symbol last_symbol = 0;
1141 switch (l->s) {
1142 case DIFF_SYMBOL_PLUS:
1143 hm = del_lines;
1144 key = prepare_entry(o, n);
1145 match = hashmap_get(hm, key, NULL);
1146 free(key);
1147 break;
1148 case DIFF_SYMBOL_MINUS:
1149 hm = add_lines;
1150 key = prepare_entry(o, n);
1151 match = hashmap_get(hm, key, NULL);
1152 free(key);
1153 break;
1154 default:
1155 flipped_block = 0;
1158 if (!match) {
1159 int i;
1161 adjust_last_block(o, n, block_length);
1162 for(i = 0; i < pmb_nr; i++)
1163 moved_block_clear(&pmb[i]);
1164 pmb_nr = 0;
1165 block_length = 0;
1166 flipped_block = 0;
1167 last_symbol = l->s;
1168 continue;
1171 if (o->color_moved == COLOR_MOVED_PLAIN) {
1172 last_symbol = l->s;
1173 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1174 continue;
1177 if (o->color_moved_ws_handling &
1178 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1179 pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1180 else
1181 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1183 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1185 if (pmb_nr == 0) {
1187 * The current line is the start of a new block.
1188 * Setup the set of potential blocks.
1190 for (; match; match = hashmap_get_next(hm, match)) {
1191 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1192 if (o->color_moved_ws_handling &
1193 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1194 if (compute_ws_delta(l, match->es,
1195 &pmb[pmb_nr].wsd))
1196 pmb[pmb_nr++].match = match;
1197 } else {
1198 pmb[pmb_nr].wsd = 0;
1199 pmb[pmb_nr++].match = match;
1203 if (adjust_last_block(o, n, block_length) &&
1204 pmb_nr && last_symbol != l->s)
1205 flipped_block = (flipped_block + 1) % 2;
1206 else
1207 flipped_block = 0;
1209 block_length = 0;
1212 if (pmb_nr) {
1213 block_length++;
1214 l->flags |= DIFF_SYMBOL_MOVED_LINE;
1215 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1216 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1218 last_symbol = l->s;
1220 adjust_last_block(o, n, block_length);
1222 for(n = 0; n < pmb_nr; n++)
1223 moved_block_clear(&pmb[n]);
1224 free(pmb);
1227 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1228 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1229 static void dim_moved_lines(struct diff_options *o)
1231 int n;
1232 for (n = 0; n < o->emitted_symbols->nr; n++) {
1233 struct emitted_diff_symbol *prev = (n != 0) ?
1234 &o->emitted_symbols->buf[n - 1] : NULL;
1235 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1236 struct emitted_diff_symbol *next =
1237 (n < o->emitted_symbols->nr - 1) ?
1238 &o->emitted_symbols->buf[n + 1] : NULL;
1240 /* Not a plus or minus line? */
1241 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1242 continue;
1244 /* Not a moved line? */
1245 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1246 continue;
1249 * If prev or next are not a plus or minus line,
1250 * pretend they don't exist
1252 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1253 prev->s != DIFF_SYMBOL_MINUS)
1254 prev = NULL;
1255 if (next && next->s != DIFF_SYMBOL_PLUS &&
1256 next->s != DIFF_SYMBOL_MINUS)
1257 next = NULL;
1259 /* Inside a block? */
1260 if ((prev &&
1261 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1262 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1263 (next &&
1264 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1265 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1266 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1267 continue;
1270 /* Check if we are at an interesting bound: */
1271 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1272 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1273 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1274 continue;
1275 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1276 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1277 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1278 continue;
1281 * The boundary to prev and next are not interesting,
1282 * so this line is not interesting as a whole
1284 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1288 static void emit_line_ws_markup(struct diff_options *o,
1289 const char *set_sign, const char *set,
1290 const char *reset,
1291 int sign_index, const char *line, int len,
1292 unsigned ws_rule, int blank_at_eof)
1294 const char *ws = NULL;
1295 int sign = o->output_indicators[sign_index];
1297 if (o->ws_error_highlight & ws_rule) {
1298 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1299 if (!*ws)
1300 ws = NULL;
1303 if (!ws && !set_sign)
1304 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1305 else if (!ws) {
1306 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1307 } else if (blank_at_eof)
1308 /* Blank line at EOF - paint '+' as well */
1309 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1310 else {
1311 /* Emit just the prefix, then the rest. */
1312 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1313 sign, "", 0);
1314 ws_check_emit(line, len, ws_rule,
1315 o->file, set, reset, ws);
1319 static void emit_diff_symbol_from_struct(struct diff_options *o,
1320 struct emitted_diff_symbol *eds)
1322 static const char *nneof = " No newline at end of file\n";
1323 const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1324 struct strbuf sb = STRBUF_INIT;
1326 enum diff_symbol s = eds->s;
1327 const char *line = eds->line;
1328 int len = eds->len;
1329 unsigned flags = eds->flags;
1331 switch (s) {
1332 case DIFF_SYMBOL_NO_LF_EOF:
1333 context = diff_get_color_opt(o, DIFF_CONTEXT);
1334 reset = diff_get_color_opt(o, DIFF_RESET);
1335 putc('\n', o->file);
1336 emit_line_0(o, context, NULL, 0, reset, '\\',
1337 nneof, strlen(nneof));
1338 break;
1339 case DIFF_SYMBOL_SUBMODULE_HEADER:
1340 case DIFF_SYMBOL_SUBMODULE_ERROR:
1341 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1342 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1343 case DIFF_SYMBOL_SUMMARY:
1344 case DIFF_SYMBOL_STATS_LINE:
1345 case DIFF_SYMBOL_BINARY_DIFF_BODY:
1346 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1347 emit_line(o, "", "", line, len);
1348 break;
1349 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1350 case DIFF_SYMBOL_CONTEXT_MARKER:
1351 context = diff_get_color_opt(o, DIFF_CONTEXT);
1352 reset = diff_get_color_opt(o, DIFF_RESET);
1353 emit_line(o, context, reset, line, len);
1354 break;
1355 case DIFF_SYMBOL_SEPARATOR:
1356 fprintf(o->file, "%s%c",
1357 diff_line_prefix(o),
1358 o->line_termination);
1359 break;
1360 case DIFF_SYMBOL_CONTEXT:
1361 set = diff_get_color_opt(o, DIFF_CONTEXT);
1362 reset = diff_get_color_opt(o, DIFF_RESET);
1363 set_sign = NULL;
1364 if (o->flags.dual_color_diffed_diffs) {
1365 char c = !len ? 0 : line[0];
1367 if (c == '+')
1368 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1369 else if (c == '@')
1370 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1371 else if (c == '-')
1372 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1374 emit_line_ws_markup(o, set_sign, set, reset,
1375 OUTPUT_INDICATOR_CONTEXT, line, len,
1376 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1377 break;
1378 case DIFF_SYMBOL_PLUS:
1379 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1380 DIFF_SYMBOL_MOVED_LINE_ALT |
1381 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1382 case DIFF_SYMBOL_MOVED_LINE |
1383 DIFF_SYMBOL_MOVED_LINE_ALT |
1384 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1385 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1386 break;
1387 case DIFF_SYMBOL_MOVED_LINE |
1388 DIFF_SYMBOL_MOVED_LINE_ALT:
1389 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1390 break;
1391 case DIFF_SYMBOL_MOVED_LINE |
1392 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1393 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1394 break;
1395 case DIFF_SYMBOL_MOVED_LINE:
1396 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1397 break;
1398 default:
1399 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1401 reset = diff_get_color_opt(o, DIFF_RESET);
1402 if (!o->flags.dual_color_diffed_diffs)
1403 set_sign = NULL;
1404 else {
1405 char c = !len ? 0 : line[0];
1407 set_sign = set;
1408 if (c == '-')
1409 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1410 else if (c == '@')
1411 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1412 else if (c == '+')
1413 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1414 else
1415 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1416 flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1418 emit_line_ws_markup(o, set_sign, set, reset,
1419 OUTPUT_INDICATOR_NEW, line, len,
1420 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1421 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1422 break;
1423 case DIFF_SYMBOL_MINUS:
1424 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1425 DIFF_SYMBOL_MOVED_LINE_ALT |
1426 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1427 case DIFF_SYMBOL_MOVED_LINE |
1428 DIFF_SYMBOL_MOVED_LINE_ALT |
1429 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1430 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1431 break;
1432 case DIFF_SYMBOL_MOVED_LINE |
1433 DIFF_SYMBOL_MOVED_LINE_ALT:
1434 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1435 break;
1436 case DIFF_SYMBOL_MOVED_LINE |
1437 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1438 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1439 break;
1440 case DIFF_SYMBOL_MOVED_LINE:
1441 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1442 break;
1443 default:
1444 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1446 reset = diff_get_color_opt(o, DIFF_RESET);
1447 if (!o->flags.dual_color_diffed_diffs)
1448 set_sign = NULL;
1449 else {
1450 char c = !len ? 0 : line[0];
1452 set_sign = set;
1453 if (c == '+')
1454 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1455 else if (c == '@')
1456 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1457 else if (c == '-')
1458 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1459 else
1460 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1462 emit_line_ws_markup(o, set_sign, set, reset,
1463 OUTPUT_INDICATOR_OLD, line, len,
1464 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1465 break;
1466 case DIFF_SYMBOL_WORDS_PORCELAIN:
1467 context = diff_get_color_opt(o, DIFF_CONTEXT);
1468 reset = diff_get_color_opt(o, DIFF_RESET);
1469 emit_line(o, context, reset, line, len);
1470 fputs("~\n", o->file);
1471 break;
1472 case DIFF_SYMBOL_WORDS:
1473 context = diff_get_color_opt(o, DIFF_CONTEXT);
1474 reset = diff_get_color_opt(o, DIFF_RESET);
1476 * Skip the prefix character, if any. With
1477 * diff_suppress_blank_empty, there may be
1478 * none.
1480 if (line[0] != '\n') {
1481 line++;
1482 len--;
1484 emit_line(o, context, reset, line, len);
1485 break;
1486 case DIFF_SYMBOL_FILEPAIR_PLUS:
1487 meta = diff_get_color_opt(o, DIFF_METAINFO);
1488 reset = diff_get_color_opt(o, DIFF_RESET);
1489 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1490 line, reset,
1491 strchr(line, ' ') ? "\t" : "");
1492 break;
1493 case DIFF_SYMBOL_FILEPAIR_MINUS:
1494 meta = diff_get_color_opt(o, DIFF_METAINFO);
1495 reset = diff_get_color_opt(o, DIFF_RESET);
1496 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1497 line, reset,
1498 strchr(line, ' ') ? "\t" : "");
1499 break;
1500 case DIFF_SYMBOL_BINARY_FILES:
1501 case DIFF_SYMBOL_HEADER:
1502 fprintf(o->file, "%s", line);
1503 break;
1504 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1505 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1506 break;
1507 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1508 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1509 break;
1510 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1511 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1512 break;
1513 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1514 fputs(diff_line_prefix(o), o->file);
1515 fputc('\n', o->file);
1516 break;
1517 case DIFF_SYMBOL_REWRITE_DIFF:
1518 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1519 reset = diff_get_color_opt(o, DIFF_RESET);
1520 emit_line(o, fraginfo, reset, line, len);
1521 break;
1522 case DIFF_SYMBOL_SUBMODULE_ADD:
1523 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1524 reset = diff_get_color_opt(o, DIFF_RESET);
1525 emit_line(o, set, reset, line, len);
1526 break;
1527 case DIFF_SYMBOL_SUBMODULE_DEL:
1528 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1529 reset = diff_get_color_opt(o, DIFF_RESET);
1530 emit_line(o, set, reset, line, len);
1531 break;
1532 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1533 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1534 diff_line_prefix(o), line);
1535 break;
1536 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1537 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1538 diff_line_prefix(o), line);
1539 break;
1540 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1541 emit_line(o, "", "", " 0 files changed\n",
1542 strlen(" 0 files changed\n"));
1543 break;
1544 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1545 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1546 break;
1547 case DIFF_SYMBOL_WORD_DIFF:
1548 fprintf(o->file, "%.*s", len, line);
1549 break;
1550 case DIFF_SYMBOL_STAT_SEP:
1551 fputs(o->stat_sep, o->file);
1552 break;
1553 default:
1554 BUG("unknown diff symbol");
1556 strbuf_release(&sb);
1559 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1560 const char *line, int len, unsigned flags)
1562 struct emitted_diff_symbol e = {line, len, flags, 0, 0, s};
1564 if (o->emitted_symbols)
1565 append_emitted_diff_symbol(o, &e);
1566 else
1567 emit_diff_symbol_from_struct(o, &e);
1570 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1572 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1575 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1577 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1580 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1582 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1583 path, strlen(path), 0);
1586 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1588 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1589 path, strlen(path), 0);
1592 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1594 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1595 header, strlen(header), 0);
1598 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1600 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1603 void diff_emit_submodule_pipethrough(struct diff_options *o,
1604 const char *line, int len)
1606 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1609 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1611 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1612 ecbdata->blank_at_eof_in_preimage &&
1613 ecbdata->blank_at_eof_in_postimage &&
1614 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1615 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1616 return 0;
1617 return ws_blank_line(line, len, ecbdata->ws_rule);
1620 static void emit_add_line(struct emit_callback *ecbdata,
1621 const char *line, int len)
1623 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1624 if (new_blank_line_at_eof(ecbdata, line, len))
1625 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1627 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1630 static void emit_del_line(struct emit_callback *ecbdata,
1631 const char *line, int len)
1633 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1634 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1637 static void emit_context_line(struct emit_callback *ecbdata,
1638 const char *line, int len)
1640 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1641 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1644 static void emit_hunk_header(struct emit_callback *ecbdata,
1645 const char *line, int len)
1647 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1648 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1649 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1650 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1651 const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1652 static const char atat[2] = { '@', '@' };
1653 const char *cp, *ep;
1654 struct strbuf msgbuf = STRBUF_INIT;
1655 int org_len = len;
1656 int i = 1;
1659 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1660 * it always is at least 10 bytes long.
1662 if (len < 10 ||
1663 memcmp(line, atat, 2) ||
1664 !(ep = memmem(line + 2, len - 2, atat, 2))) {
1665 emit_diff_symbol(ecbdata->opt,
1666 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1667 return;
1669 ep += 2; /* skip over @@ */
1671 /* The hunk header in fraginfo color */
1672 if (ecbdata->opt->flags.dual_color_diffed_diffs)
1673 strbuf_addstr(&msgbuf, reverse);
1674 strbuf_addstr(&msgbuf, frag);
1675 strbuf_add(&msgbuf, line, ep - line);
1676 strbuf_addstr(&msgbuf, reset);
1679 * trailing "\r\n"
1681 for ( ; i < 3; i++)
1682 if (line[len - i] == '\r' || line[len - i] == '\n')
1683 len--;
1685 /* blank before the func header */
1686 for (cp = ep; ep - line < len; ep++)
1687 if (*ep != ' ' && *ep != '\t')
1688 break;
1689 if (ep != cp) {
1690 strbuf_addstr(&msgbuf, context);
1691 strbuf_add(&msgbuf, cp, ep - cp);
1692 strbuf_addstr(&msgbuf, reset);
1695 if (ep < line + len) {
1696 strbuf_addstr(&msgbuf, func);
1697 strbuf_add(&msgbuf, ep, line + len - ep);
1698 strbuf_addstr(&msgbuf, reset);
1701 strbuf_add(&msgbuf, line + len, org_len - len);
1702 strbuf_complete_line(&msgbuf);
1703 emit_diff_symbol(ecbdata->opt,
1704 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1705 strbuf_release(&msgbuf);
1708 static struct diff_tempfile *claim_diff_tempfile(void)
1710 int i;
1711 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1712 if (!diff_temp[i].name)
1713 return diff_temp + i;
1714 BUG("diff is failing to clean up its tempfiles");
1717 static void remove_tempfile(void)
1719 int i;
1720 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1721 if (is_tempfile_active(diff_temp[i].tempfile))
1722 delete_tempfile(&diff_temp[i].tempfile);
1723 diff_temp[i].name = NULL;
1727 static void add_line_count(struct strbuf *out, int count)
1729 switch (count) {
1730 case 0:
1731 strbuf_addstr(out, "0,0");
1732 break;
1733 case 1:
1734 strbuf_addstr(out, "1");
1735 break;
1736 default:
1737 strbuf_addf(out, "1,%d", count);
1738 break;
1742 static void emit_rewrite_lines(struct emit_callback *ecb,
1743 int prefix, const char *data, int size)
1745 const char *endp = NULL;
1747 while (0 < size) {
1748 int len;
1750 endp = memchr(data, '\n', size);
1751 len = endp ? (endp - data + 1) : size;
1752 if (prefix != '+') {
1753 ecb->lno_in_preimage++;
1754 emit_del_line(ecb, data, len);
1755 } else {
1756 ecb->lno_in_postimage++;
1757 emit_add_line(ecb, data, len);
1759 size -= len;
1760 data += len;
1762 if (!endp)
1763 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1766 static void emit_rewrite_diff(const char *name_a,
1767 const char *name_b,
1768 struct diff_filespec *one,
1769 struct diff_filespec *two,
1770 struct userdiff_driver *textconv_one,
1771 struct userdiff_driver *textconv_two,
1772 struct diff_options *o)
1774 int lc_a, lc_b;
1775 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1776 const char *a_prefix, *b_prefix;
1777 char *data_one, *data_two;
1778 size_t size_one, size_two;
1779 struct emit_callback ecbdata;
1780 struct strbuf out = STRBUF_INIT;
1782 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1783 a_prefix = o->b_prefix;
1784 b_prefix = o->a_prefix;
1785 } else {
1786 a_prefix = o->a_prefix;
1787 b_prefix = o->b_prefix;
1790 name_a += (*name_a == '/');
1791 name_b += (*name_b == '/');
1793 strbuf_reset(&a_name);
1794 strbuf_reset(&b_name);
1795 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1796 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1798 size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1799 size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1801 memset(&ecbdata, 0, sizeof(ecbdata));
1802 ecbdata.color_diff = want_color(o->use_color);
1803 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1804 ecbdata.opt = o;
1805 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1806 mmfile_t mf1, mf2;
1807 mf1.ptr = (char *)data_one;
1808 mf2.ptr = (char *)data_two;
1809 mf1.size = size_one;
1810 mf2.size = size_two;
1811 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1813 ecbdata.lno_in_preimage = 1;
1814 ecbdata.lno_in_postimage = 1;
1816 lc_a = count_lines(data_one, size_one);
1817 lc_b = count_lines(data_two, size_two);
1819 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1820 a_name.buf, a_name.len, 0);
1821 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1822 b_name.buf, b_name.len, 0);
1824 strbuf_addstr(&out, "@@ -");
1825 if (!o->irreversible_delete)
1826 add_line_count(&out, lc_a);
1827 else
1828 strbuf_addstr(&out, "?,?");
1829 strbuf_addstr(&out, " +");
1830 add_line_count(&out, lc_b);
1831 strbuf_addstr(&out, " @@\n");
1832 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1833 strbuf_release(&out);
1835 if (lc_a && !o->irreversible_delete)
1836 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1837 if (lc_b)
1838 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1839 if (textconv_one)
1840 free((char *)data_one);
1841 if (textconv_two)
1842 free((char *)data_two);
1845 struct diff_words_buffer {
1846 mmfile_t text;
1847 unsigned long alloc;
1848 struct diff_words_orig {
1849 const char *begin, *end;
1850 } *orig;
1851 int orig_nr, orig_alloc;
1854 static void diff_words_append(char *line, unsigned long len,
1855 struct diff_words_buffer *buffer)
1857 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1858 line++;
1859 len--;
1860 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1861 buffer->text.size += len;
1862 buffer->text.ptr[buffer->text.size] = '\0';
1865 struct diff_words_style_elem {
1866 const char *prefix;
1867 const char *suffix;
1868 const char *color; /* NULL; filled in by the setup code if
1869 * color is enabled */
1872 struct diff_words_style {
1873 enum diff_words_type type;
1874 struct diff_words_style_elem new_word, old_word, ctx;
1875 const char *newline;
1878 static struct diff_words_style diff_words_styles[] = {
1879 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1880 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1881 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1884 struct diff_words_data {
1885 struct diff_words_buffer minus, plus;
1886 const char *current_plus;
1887 int last_minus;
1888 struct diff_options *opt;
1889 regex_t *word_regex;
1890 enum diff_words_type type;
1891 struct diff_words_style *style;
1894 static int fn_out_diff_words_write_helper(struct diff_options *o,
1895 struct diff_words_style_elem *st_el,
1896 const char *newline,
1897 size_t count, const char *buf)
1899 int print = 0;
1900 struct strbuf sb = STRBUF_INIT;
1902 while (count) {
1903 char *p = memchr(buf, '\n', count);
1904 if (print)
1905 strbuf_addstr(&sb, diff_line_prefix(o));
1907 if (p != buf) {
1908 const char *reset = st_el->color && *st_el->color ?
1909 GIT_COLOR_RESET : NULL;
1910 if (st_el->color && *st_el->color)
1911 strbuf_addstr(&sb, st_el->color);
1912 strbuf_addstr(&sb, st_el->prefix);
1913 strbuf_add(&sb, buf, p ? p - buf : count);
1914 strbuf_addstr(&sb, st_el->suffix);
1915 if (reset)
1916 strbuf_addstr(&sb, reset);
1918 if (!p)
1919 goto out;
1921 strbuf_addstr(&sb, newline);
1922 count -= p + 1 - buf;
1923 buf = p + 1;
1924 print = 1;
1925 if (count) {
1926 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1927 sb.buf, sb.len, 0);
1928 strbuf_reset(&sb);
1932 out:
1933 if (sb.len)
1934 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1935 sb.buf, sb.len, 0);
1936 strbuf_release(&sb);
1937 return 0;
1941 * '--color-words' algorithm can be described as:
1943 * 1. collect the minus/plus lines of a diff hunk, divided into
1944 * minus-lines and plus-lines;
1946 * 2. break both minus-lines and plus-lines into words and
1947 * place them into two mmfile_t with one word for each line;
1949 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1951 * And for the common parts of the both file, we output the plus side text.
1952 * diff_words->current_plus is used to trace the current position of the plus file
1953 * which printed. diff_words->last_minus is used to trace the last minus word
1954 * printed.
1956 * For '--graph' to work with '--color-words', we need to output the graph prefix
1957 * on each line of color words output. Generally, there are two conditions on
1958 * which we should output the prefix.
1960 * 1. diff_words->last_minus == 0 &&
1961 * diff_words->current_plus == diff_words->plus.text.ptr
1963 * that is: the plus text must start as a new line, and if there is no minus
1964 * word printed, a graph prefix must be printed.
1966 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1967 * *(diff_words->current_plus - 1) == '\n'
1969 * that is: a graph prefix must be printed following a '\n'
1971 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1973 if ((diff_words->last_minus == 0 &&
1974 diff_words->current_plus == diff_words->plus.text.ptr) ||
1975 (diff_words->current_plus > diff_words->plus.text.ptr &&
1976 *(diff_words->current_plus - 1) == '\n')) {
1977 return 1;
1978 } else {
1979 return 0;
1983 static void fn_out_diff_words_aux(void *priv,
1984 long minus_first, long minus_len,
1985 long plus_first, long plus_len,
1986 const char *func, long funclen)
1988 struct diff_words_data *diff_words = priv;
1989 struct diff_words_style *style = diff_words->style;
1990 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1991 struct diff_options *opt = diff_words->opt;
1992 const char *line_prefix;
1994 assert(opt);
1995 line_prefix = diff_line_prefix(opt);
1997 /* POSIX requires that first be decremented by one if len == 0... */
1998 if (minus_len) {
1999 minus_begin = diff_words->minus.orig[minus_first].begin;
2000 minus_end =
2001 diff_words->minus.orig[minus_first + minus_len - 1].end;
2002 } else
2003 minus_begin = minus_end =
2004 diff_words->minus.orig[minus_first].end;
2006 if (plus_len) {
2007 plus_begin = diff_words->plus.orig[plus_first].begin;
2008 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2009 } else
2010 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2012 if (color_words_output_graph_prefix(diff_words)) {
2013 fputs(line_prefix, diff_words->opt->file);
2015 if (diff_words->current_plus != plus_begin) {
2016 fn_out_diff_words_write_helper(diff_words->opt,
2017 &style->ctx, style->newline,
2018 plus_begin - diff_words->current_plus,
2019 diff_words->current_plus);
2021 if (minus_begin != minus_end) {
2022 fn_out_diff_words_write_helper(diff_words->opt,
2023 &style->old_word, style->newline,
2024 minus_end - minus_begin, minus_begin);
2026 if (plus_begin != plus_end) {
2027 fn_out_diff_words_write_helper(diff_words->opt,
2028 &style->new_word, style->newline,
2029 plus_end - plus_begin, plus_begin);
2032 diff_words->current_plus = plus_end;
2033 diff_words->last_minus = minus_first;
2036 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2037 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2038 int *begin, int *end)
2040 if (word_regex && *begin < buffer->size) {
2041 regmatch_t match[1];
2042 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2043 buffer->size - *begin, 1, match, 0)) {
2044 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2045 '\n', match[0].rm_eo - match[0].rm_so);
2046 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2047 *begin += match[0].rm_so;
2048 return *begin >= *end;
2050 return -1;
2053 /* find the next word */
2054 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2055 (*begin)++;
2056 if (*begin >= buffer->size)
2057 return -1;
2059 /* find the end of the word */
2060 *end = *begin + 1;
2061 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2062 (*end)++;
2064 return 0;
2068 * This function splits the words in buffer->text, stores the list with
2069 * newline separator into out, and saves the offsets of the original words
2070 * in buffer->orig.
2072 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2073 regex_t *word_regex)
2075 int i, j;
2076 long alloc = 0;
2078 out->size = 0;
2079 out->ptr = NULL;
2081 /* fake an empty "0th" word */
2082 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2083 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2084 buffer->orig_nr = 1;
2086 for (i = 0; i < buffer->text.size; i++) {
2087 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2088 return;
2090 /* store original boundaries */
2091 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2092 buffer->orig_alloc);
2093 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2094 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2095 buffer->orig_nr++;
2097 /* store one word */
2098 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2099 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2100 out->ptr[out->size + j - i] = '\n';
2101 out->size += j - i + 1;
2103 i = j - 1;
2107 /* this executes the word diff on the accumulated buffers */
2108 static void diff_words_show(struct diff_words_data *diff_words)
2110 xpparam_t xpp;
2111 xdemitconf_t xecfg;
2112 mmfile_t minus, plus;
2113 struct diff_words_style *style = diff_words->style;
2115 struct diff_options *opt = diff_words->opt;
2116 const char *line_prefix;
2118 assert(opt);
2119 line_prefix = diff_line_prefix(opt);
2121 /* special case: only removal */
2122 if (!diff_words->plus.text.size) {
2123 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2124 line_prefix, strlen(line_prefix), 0);
2125 fn_out_diff_words_write_helper(diff_words->opt,
2126 &style->old_word, style->newline,
2127 diff_words->minus.text.size,
2128 diff_words->minus.text.ptr);
2129 diff_words->minus.text.size = 0;
2130 return;
2133 diff_words->current_plus = diff_words->plus.text.ptr;
2134 diff_words->last_minus = 0;
2136 memset(&xpp, 0, sizeof(xpp));
2137 memset(&xecfg, 0, sizeof(xecfg));
2138 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2139 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2140 xpp.flags = 0;
2141 /* as only the hunk header will be parsed, we need a 0-context */
2142 xecfg.ctxlen = 0;
2143 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2144 diff_words, &xpp, &xecfg))
2145 die("unable to generate word diff");
2146 free(minus.ptr);
2147 free(plus.ptr);
2148 if (diff_words->current_plus != diff_words->plus.text.ptr +
2149 diff_words->plus.text.size) {
2150 if (color_words_output_graph_prefix(diff_words))
2151 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2152 line_prefix, strlen(line_prefix), 0);
2153 fn_out_diff_words_write_helper(diff_words->opt,
2154 &style->ctx, style->newline,
2155 diff_words->plus.text.ptr + diff_words->plus.text.size
2156 - diff_words->current_plus, diff_words->current_plus);
2158 diff_words->minus.text.size = diff_words->plus.text.size = 0;
2161 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2162 static void diff_words_flush(struct emit_callback *ecbdata)
2164 struct diff_options *wo = ecbdata->diff_words->opt;
2166 if (ecbdata->diff_words->minus.text.size ||
2167 ecbdata->diff_words->plus.text.size)
2168 diff_words_show(ecbdata->diff_words);
2170 if (wo->emitted_symbols) {
2171 struct diff_options *o = ecbdata->opt;
2172 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2173 int i;
2176 * NEEDSWORK:
2177 * Instead of appending each, concat all words to a line?
2179 for (i = 0; i < wol->nr; i++)
2180 append_emitted_diff_symbol(o, &wol->buf[i]);
2182 for (i = 0; i < wol->nr; i++)
2183 free((void *)wol->buf[i].line);
2185 wol->nr = 0;
2189 static void diff_filespec_load_driver(struct diff_filespec *one,
2190 struct index_state *istate)
2192 /* Use already-loaded driver */
2193 if (one->driver)
2194 return;
2196 if (S_ISREG(one->mode))
2197 one->driver = userdiff_find_by_path(istate, one->path);
2199 /* Fallback to default settings */
2200 if (!one->driver)
2201 one->driver = userdiff_find_by_name("default");
2204 static const char *userdiff_word_regex(struct diff_filespec *one,
2205 struct index_state *istate)
2207 diff_filespec_load_driver(one, istate);
2208 return one->driver->word_regex;
2211 static void init_diff_words_data(struct emit_callback *ecbdata,
2212 struct diff_options *orig_opts,
2213 struct diff_filespec *one,
2214 struct diff_filespec *two)
2216 int i;
2217 struct diff_options *o = xmalloc(sizeof(struct diff_options));
2218 memcpy(o, orig_opts, sizeof(struct diff_options));
2220 ecbdata->diff_words =
2221 xcalloc(1, sizeof(struct diff_words_data));
2222 ecbdata->diff_words->type = o->word_diff;
2223 ecbdata->diff_words->opt = o;
2225 if (orig_opts->emitted_symbols)
2226 o->emitted_symbols =
2227 xcalloc(1, sizeof(struct emitted_diff_symbols));
2229 if (!o->word_regex)
2230 o->word_regex = userdiff_word_regex(one, o->repo->index);
2231 if (!o->word_regex)
2232 o->word_regex = userdiff_word_regex(two, o->repo->index);
2233 if (!o->word_regex)
2234 o->word_regex = diff_word_regex_cfg;
2235 if (o->word_regex) {
2236 ecbdata->diff_words->word_regex = (regex_t *)
2237 xmalloc(sizeof(regex_t));
2238 if (regcomp(ecbdata->diff_words->word_regex,
2239 o->word_regex,
2240 REG_EXTENDED | REG_NEWLINE))
2241 die("invalid regular expression: %s",
2242 o->word_regex);
2244 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2245 if (o->word_diff == diff_words_styles[i].type) {
2246 ecbdata->diff_words->style =
2247 &diff_words_styles[i];
2248 break;
2251 if (want_color(o->use_color)) {
2252 struct diff_words_style *st = ecbdata->diff_words->style;
2253 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2254 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2255 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2259 static void free_diff_words_data(struct emit_callback *ecbdata)
2261 if (ecbdata->diff_words) {
2262 diff_words_flush(ecbdata);
2263 free (ecbdata->diff_words->opt->emitted_symbols);
2264 free (ecbdata->diff_words->opt);
2265 free (ecbdata->diff_words->minus.text.ptr);
2266 free (ecbdata->diff_words->minus.orig);
2267 free (ecbdata->diff_words->plus.text.ptr);
2268 free (ecbdata->diff_words->plus.orig);
2269 if (ecbdata->diff_words->word_regex) {
2270 regfree(ecbdata->diff_words->word_regex);
2271 free(ecbdata->diff_words->word_regex);
2273 FREE_AND_NULL(ecbdata->diff_words);
2277 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2279 if (want_color(diff_use_color))
2280 return diff_colors[ix];
2281 return "";
2284 const char *diff_line_prefix(struct diff_options *opt)
2286 struct strbuf *msgbuf;
2287 if (!opt->output_prefix)
2288 return "";
2290 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2291 return msgbuf->buf;
2294 static unsigned long sane_truncate_line(char *line, unsigned long len)
2296 const char *cp;
2297 unsigned long allot;
2298 size_t l = len;
2300 cp = line;
2301 allot = l;
2302 while (0 < l) {
2303 (void) utf8_width(&cp, &l);
2304 if (!cp)
2305 break; /* truncated in the middle? */
2307 return allot - l;
2310 static void find_lno(const char *line, struct emit_callback *ecbdata)
2312 const char *p;
2313 ecbdata->lno_in_preimage = 0;
2314 ecbdata->lno_in_postimage = 0;
2315 p = strchr(line, '-');
2316 if (!p)
2317 return; /* cannot happen */
2318 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2319 p = strchr(p, '+');
2320 if (!p)
2321 return; /* cannot happen */
2322 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2325 static void fn_out_consume(void *priv, char *line, unsigned long len)
2327 struct emit_callback *ecbdata = priv;
2328 struct diff_options *o = ecbdata->opt;
2330 o->found_changes = 1;
2332 if (ecbdata->header) {
2333 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2334 ecbdata->header->buf, ecbdata->header->len, 0);
2335 strbuf_reset(ecbdata->header);
2336 ecbdata->header = NULL;
2339 if (ecbdata->label_path[0]) {
2340 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2341 ecbdata->label_path[0],
2342 strlen(ecbdata->label_path[0]), 0);
2343 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2344 ecbdata->label_path[1],
2345 strlen(ecbdata->label_path[1]), 0);
2346 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2349 if (diff_suppress_blank_empty
2350 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2351 line[0] = '\n';
2352 len = 1;
2355 if (line[0] == '@') {
2356 if (ecbdata->diff_words)
2357 diff_words_flush(ecbdata);
2358 len = sane_truncate_line(line, len);
2359 find_lno(line, ecbdata);
2360 emit_hunk_header(ecbdata, line, len);
2361 return;
2364 if (ecbdata->diff_words) {
2365 enum diff_symbol s =
2366 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2367 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2368 if (line[0] == '-') {
2369 diff_words_append(line, len,
2370 &ecbdata->diff_words->minus);
2371 return;
2372 } else if (line[0] == '+') {
2373 diff_words_append(line, len,
2374 &ecbdata->diff_words->plus);
2375 return;
2376 } else if (starts_with(line, "\\ ")) {
2378 * Eat the "no newline at eof" marker as if we
2379 * saw a "+" or "-" line with nothing on it,
2380 * and return without diff_words_flush() to
2381 * defer processing. If this is the end of
2382 * preimage, more "+" lines may come after it.
2384 return;
2386 diff_words_flush(ecbdata);
2387 emit_diff_symbol(o, s, line, len, 0);
2388 return;
2391 switch (line[0]) {
2392 case '+':
2393 ecbdata->lno_in_postimage++;
2394 emit_add_line(ecbdata, line + 1, len - 1);
2395 break;
2396 case '-':
2397 ecbdata->lno_in_preimage++;
2398 emit_del_line(ecbdata, line + 1, len - 1);
2399 break;
2400 case ' ':
2401 ecbdata->lno_in_postimage++;
2402 ecbdata->lno_in_preimage++;
2403 emit_context_line(ecbdata, line + 1, len - 1);
2404 break;
2405 default:
2406 /* incomplete line at the end */
2407 ecbdata->lno_in_preimage++;
2408 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2409 line, len, 0);
2410 break;
2414 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2416 const char *old_name = a;
2417 const char *new_name = b;
2418 int pfx_length, sfx_length;
2419 int pfx_adjust_for_slash;
2420 int len_a = strlen(a);
2421 int len_b = strlen(b);
2422 int a_midlen, b_midlen;
2423 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2424 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2426 if (qlen_a || qlen_b) {
2427 quote_c_style(a, name, NULL, 0);
2428 strbuf_addstr(name, " => ");
2429 quote_c_style(b, name, NULL, 0);
2430 return;
2433 /* Find common prefix */
2434 pfx_length = 0;
2435 while (*old_name && *new_name && *old_name == *new_name) {
2436 if (*old_name == '/')
2437 pfx_length = old_name - a + 1;
2438 old_name++;
2439 new_name++;
2442 /* Find common suffix */
2443 old_name = a + len_a;
2444 new_name = b + len_b;
2445 sfx_length = 0;
2447 * If there is a common prefix, it must end in a slash. In
2448 * that case we let this loop run 1 into the prefix to see the
2449 * same slash.
2451 * If there is no common prefix, we cannot do this as it would
2452 * underrun the input strings.
2454 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2455 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2456 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2457 *old_name == *new_name) {
2458 if (*old_name == '/')
2459 sfx_length = len_a - (old_name - a);
2460 old_name--;
2461 new_name--;
2465 * pfx{mid-a => mid-b}sfx
2466 * {pfx-a => pfx-b}sfx
2467 * pfx{sfx-a => sfx-b}
2468 * name-a => name-b
2470 a_midlen = len_a - pfx_length - sfx_length;
2471 b_midlen = len_b - pfx_length - sfx_length;
2472 if (a_midlen < 0)
2473 a_midlen = 0;
2474 if (b_midlen < 0)
2475 b_midlen = 0;
2477 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2478 if (pfx_length + sfx_length) {
2479 strbuf_add(name, a, pfx_length);
2480 strbuf_addch(name, '{');
2482 strbuf_add(name, a + pfx_length, a_midlen);
2483 strbuf_addstr(name, " => ");
2484 strbuf_add(name, b + pfx_length, b_midlen);
2485 if (pfx_length + sfx_length) {
2486 strbuf_addch(name, '}');
2487 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2491 struct diffstat_t {
2492 int nr;
2493 int alloc;
2494 struct diffstat_file {
2495 char *from_name;
2496 char *name;
2497 char *print_name;
2498 const char *comments;
2499 unsigned is_unmerged:1;
2500 unsigned is_binary:1;
2501 unsigned is_renamed:1;
2502 unsigned is_interesting:1;
2503 uintmax_t added, deleted;
2504 } **files;
2507 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2508 const char *name_a,
2509 const char *name_b)
2511 struct diffstat_file *x;
2512 x = xcalloc(1, sizeof(*x));
2513 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2514 diffstat->files[diffstat->nr++] = x;
2515 if (name_b) {
2516 x->from_name = xstrdup(name_a);
2517 x->name = xstrdup(name_b);
2518 x->is_renamed = 1;
2520 else {
2521 x->from_name = NULL;
2522 x->name = xstrdup(name_a);
2524 return x;
2527 static void diffstat_consume(void *priv, char *line, unsigned long len)
2529 struct diffstat_t *diffstat = priv;
2530 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2532 if (line[0] == '+')
2533 x->added++;
2534 else if (line[0] == '-')
2535 x->deleted++;
2538 const char mime_boundary_leader[] = "------------";
2540 static int scale_linear(int it, int width, int max_change)
2542 if (!it)
2543 return 0;
2545 * make sure that at least one '-' or '+' is printed if
2546 * there is any change to this path. The easiest way is to
2547 * scale linearly as if the alloted width is one column shorter
2548 * than it is, and then add 1 to the result.
2550 return 1 + (it * (width - 1) / max_change);
2553 static void show_graph(struct strbuf *out, char ch, int cnt,
2554 const char *set, const char *reset)
2556 if (cnt <= 0)
2557 return;
2558 strbuf_addstr(out, set);
2559 strbuf_addchars(out, ch, cnt);
2560 strbuf_addstr(out, reset);
2563 static void fill_print_name(struct diffstat_file *file)
2565 struct strbuf pname = STRBUF_INIT;
2567 if (file->print_name)
2568 return;
2570 if (file->is_renamed)
2571 pprint_rename(&pname, file->from_name, file->name);
2572 else
2573 quote_c_style(file->name, &pname, NULL, 0);
2575 if (file->comments)
2576 strbuf_addf(&pname, " (%s)", file->comments);
2578 file->print_name = strbuf_detach(&pname, NULL);
2581 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2582 int files, int insertions, int deletions)
2584 struct strbuf sb = STRBUF_INIT;
2586 if (!files) {
2587 assert(insertions == 0 && deletions == 0);
2588 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2589 NULL, 0, 0);
2590 return;
2593 strbuf_addf(&sb,
2594 (files == 1) ? " %d file changed" : " %d files changed",
2595 files);
2598 * For binary diff, the caller may want to print "x files
2599 * changed" with insertions == 0 && deletions == 0.
2601 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2602 * is probably less confusing (i.e skip over "2 files changed
2603 * but nothing about added/removed lines? Is this a bug in Git?").
2605 if (insertions || deletions == 0) {
2606 strbuf_addf(&sb,
2607 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2608 insertions);
2611 if (deletions || insertions == 0) {
2612 strbuf_addf(&sb,
2613 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2614 deletions);
2616 strbuf_addch(&sb, '\n');
2617 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2618 sb.buf, sb.len, 0);
2619 strbuf_release(&sb);
2622 void print_stat_summary(FILE *fp, int files,
2623 int insertions, int deletions)
2625 struct diff_options o;
2626 memset(&o, 0, sizeof(o));
2627 o.file = fp;
2629 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2632 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2634 int i, len, add, del, adds = 0, dels = 0;
2635 uintmax_t max_change = 0, max_len = 0;
2636 int total_files = data->nr, count;
2637 int width, name_width, graph_width, number_width = 0, bin_width = 0;
2638 const char *reset, *add_c, *del_c;
2639 int extra_shown = 0;
2640 const char *line_prefix = diff_line_prefix(options);
2641 struct strbuf out = STRBUF_INIT;
2643 if (data->nr == 0)
2644 return;
2646 count = options->stat_count ? options->stat_count : data->nr;
2648 reset = diff_get_color_opt(options, DIFF_RESET);
2649 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2650 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2653 * Find the longest filename and max number of changes
2655 for (i = 0; (i < count) && (i < data->nr); i++) {
2656 struct diffstat_file *file = data->files[i];
2657 uintmax_t change = file->added + file->deleted;
2659 if (!file->is_interesting && (change == 0)) {
2660 count++; /* not shown == room for one more */
2661 continue;
2663 fill_print_name(file);
2664 len = strlen(file->print_name);
2665 if (max_len < len)
2666 max_len = len;
2668 if (file->is_unmerged) {
2669 /* "Unmerged" is 8 characters */
2670 bin_width = bin_width < 8 ? 8 : bin_width;
2671 continue;
2673 if (file->is_binary) {
2674 /* "Bin XXX -> YYY bytes" */
2675 int w = 14 + decimal_width(file->added)
2676 + decimal_width(file->deleted);
2677 bin_width = bin_width < w ? w : bin_width;
2678 /* Display change counts aligned with "Bin" */
2679 number_width = 3;
2680 continue;
2683 if (max_change < change)
2684 max_change = change;
2686 count = i; /* where we can stop scanning in data->files[] */
2689 * We have width = stat_width or term_columns() columns total.
2690 * We want a maximum of min(max_len, stat_name_width) for the name part.
2691 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2692 * We also need 1 for " " and 4 + decimal_width(max_change)
2693 * for " | NNNN " and one the empty column at the end, altogether
2694 * 6 + decimal_width(max_change).
2696 * If there's not enough space, we will use the smaller of
2697 * stat_name_width (if set) and 5/8*width for the filename,
2698 * and the rest for constant elements + graph part, but no more
2699 * than stat_graph_width for the graph part.
2700 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2701 * for the standard terminal size).
2703 * In other words: stat_width limits the maximum width, and
2704 * stat_name_width fixes the maximum width of the filename,
2705 * and is also used to divide available columns if there
2706 * aren't enough.
2708 * Binary files are displayed with "Bin XXX -> YYY bytes"
2709 * instead of the change count and graph. This part is treated
2710 * similarly to the graph part, except that it is not
2711 * "scaled". If total width is too small to accommodate the
2712 * guaranteed minimum width of the filename part and the
2713 * separators and this message, this message will "overflow"
2714 * making the line longer than the maximum width.
2717 if (options->stat_width == -1)
2718 width = term_columns() - strlen(line_prefix);
2719 else
2720 width = options->stat_width ? options->stat_width : 80;
2721 number_width = decimal_width(max_change) > number_width ?
2722 decimal_width(max_change) : number_width;
2724 if (options->stat_graph_width == -1)
2725 options->stat_graph_width = diff_stat_graph_width;
2728 * Guarantee 3/8*16==6 for the graph part
2729 * and 5/8*16==10 for the filename part
2731 if (width < 16 + 6 + number_width)
2732 width = 16 + 6 + number_width;
2735 * First assign sizes that are wanted, ignoring available width.
2736 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2737 * starting from "XXX" should fit in graph_width.
2739 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2740 if (options->stat_graph_width &&
2741 options->stat_graph_width < graph_width)
2742 graph_width = options->stat_graph_width;
2744 name_width = (options->stat_name_width > 0 &&
2745 options->stat_name_width < max_len) ?
2746 options->stat_name_width : max_len;
2749 * Adjust adjustable widths not to exceed maximum width
2751 if (name_width + number_width + 6 + graph_width > width) {
2752 if (graph_width > width * 3/8 - number_width - 6) {
2753 graph_width = width * 3/8 - number_width - 6;
2754 if (graph_width < 6)
2755 graph_width = 6;
2758 if (options->stat_graph_width &&
2759 graph_width > options->stat_graph_width)
2760 graph_width = options->stat_graph_width;
2761 if (name_width > width - number_width - 6 - graph_width)
2762 name_width = width - number_width - 6 - graph_width;
2763 else
2764 graph_width = width - number_width - 6 - name_width;
2768 * From here name_width is the width of the name area,
2769 * and graph_width is the width of the graph area.
2770 * max_change is used to scale graph properly.
2772 for (i = 0; i < count; i++) {
2773 const char *prefix = "";
2774 struct diffstat_file *file = data->files[i];
2775 char *name = file->print_name;
2776 uintmax_t added = file->added;
2777 uintmax_t deleted = file->deleted;
2778 int name_len;
2780 if (!file->is_interesting && (added + deleted == 0))
2781 continue;
2784 * "scale" the filename
2786 len = name_width;
2787 name_len = strlen(name);
2788 if (name_width < name_len) {
2789 char *slash;
2790 prefix = "...";
2791 len -= 3;
2792 name += name_len - len;
2793 slash = strchr(name, '/');
2794 if (slash)
2795 name = slash;
2798 if (file->is_binary) {
2799 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2800 strbuf_addf(&out, " %*s", number_width, "Bin");
2801 if (!added && !deleted) {
2802 strbuf_addch(&out, '\n');
2803 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2804 out.buf, out.len, 0);
2805 strbuf_reset(&out);
2806 continue;
2808 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2809 del_c, deleted, reset);
2810 strbuf_addstr(&out, " -> ");
2811 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2812 add_c, added, reset);
2813 strbuf_addstr(&out, " bytes\n");
2814 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2815 out.buf, out.len, 0);
2816 strbuf_reset(&out);
2817 continue;
2819 else if (file->is_unmerged) {
2820 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2821 strbuf_addstr(&out, " Unmerged\n");
2822 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2823 out.buf, out.len, 0);
2824 strbuf_reset(&out);
2825 continue;
2829 * scale the add/delete
2831 add = added;
2832 del = deleted;
2834 if (graph_width <= max_change) {
2835 int total = scale_linear(add + del, graph_width, max_change);
2836 if (total < 2 && add && del)
2837 /* width >= 2 due to the sanity check */
2838 total = 2;
2839 if (add < del) {
2840 add = scale_linear(add, graph_width, max_change);
2841 del = total - add;
2842 } else {
2843 del = scale_linear(del, graph_width, max_change);
2844 add = total - del;
2847 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2848 strbuf_addf(&out, " %*"PRIuMAX"%s",
2849 number_width, added + deleted,
2850 added + deleted ? " " : "");
2851 show_graph(&out, '+', add, add_c, reset);
2852 show_graph(&out, '-', del, del_c, reset);
2853 strbuf_addch(&out, '\n');
2854 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2855 out.buf, out.len, 0);
2856 strbuf_reset(&out);
2859 for (i = 0; i < data->nr; i++) {
2860 struct diffstat_file *file = data->files[i];
2861 uintmax_t added = file->added;
2862 uintmax_t deleted = file->deleted;
2864 if (file->is_unmerged ||
2865 (!file->is_interesting && (added + deleted == 0))) {
2866 total_files--;
2867 continue;
2870 if (!file->is_binary) {
2871 adds += added;
2872 dels += deleted;
2874 if (i < count)
2875 continue;
2876 if (!extra_shown)
2877 emit_diff_symbol(options,
2878 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2879 NULL, 0, 0);
2880 extra_shown = 1;
2883 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2884 strbuf_release(&out);
2887 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2889 int i, adds = 0, dels = 0, total_files = data->nr;
2891 if (data->nr == 0)
2892 return;
2894 for (i = 0; i < data->nr; i++) {
2895 int added = data->files[i]->added;
2896 int deleted = data->files[i]->deleted;
2898 if (data->files[i]->is_unmerged ||
2899 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2900 total_files--;
2901 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2902 adds += added;
2903 dels += deleted;
2906 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2909 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2911 int i;
2913 if (data->nr == 0)
2914 return;
2916 for (i = 0; i < data->nr; i++) {
2917 struct diffstat_file *file = data->files[i];
2919 fprintf(options->file, "%s", diff_line_prefix(options));
2921 if (file->is_binary)
2922 fprintf(options->file, "-\t-\t");
2923 else
2924 fprintf(options->file,
2925 "%"PRIuMAX"\t%"PRIuMAX"\t",
2926 file->added, file->deleted);
2927 if (options->line_termination) {
2928 fill_print_name(file);
2929 if (!file->is_renamed)
2930 write_name_quoted(file->name, options->file,
2931 options->line_termination);
2932 else {
2933 fputs(file->print_name, options->file);
2934 putc(options->line_termination, options->file);
2936 } else {
2937 if (file->is_renamed) {
2938 putc('\0', options->file);
2939 write_name_quoted(file->from_name, options->file, '\0');
2941 write_name_quoted(file->name, options->file, '\0');
2946 struct dirstat_file {
2947 const char *name;
2948 unsigned long changed;
2951 struct dirstat_dir {
2952 struct dirstat_file *files;
2953 int alloc, nr, permille, cumulative;
2956 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2957 unsigned long changed, const char *base, int baselen)
2959 unsigned long sum_changes = 0;
2960 unsigned int sources = 0;
2961 const char *line_prefix = diff_line_prefix(opt);
2963 while (dir->nr) {
2964 struct dirstat_file *f = dir->files;
2965 int namelen = strlen(f->name);
2966 unsigned long changes;
2967 char *slash;
2969 if (namelen < baselen)
2970 break;
2971 if (memcmp(f->name, base, baselen))
2972 break;
2973 slash = strchr(f->name + baselen, '/');
2974 if (slash) {
2975 int newbaselen = slash + 1 - f->name;
2976 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2977 sources++;
2978 } else {
2979 changes = f->changed;
2980 dir->files++;
2981 dir->nr--;
2982 sources += 2;
2984 sum_changes += changes;
2988 * We don't report dirstat's for
2989 * - the top level
2990 * - or cases where everything came from a single directory
2991 * under this directory (sources == 1).
2993 if (baselen && sources != 1) {
2994 if (sum_changes) {
2995 int permille = sum_changes * 1000 / changed;
2996 if (permille >= dir->permille) {
2997 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2998 permille / 10, permille % 10, baselen, base);
2999 if (!dir->cumulative)
3000 return 0;
3004 return sum_changes;
3007 static int dirstat_compare(const void *_a, const void *_b)
3009 const struct dirstat_file *a = _a;
3010 const struct dirstat_file *b = _b;
3011 return strcmp(a->name, b->name);
3014 static void show_dirstat(struct diff_options *options)
3016 int i;
3017 unsigned long changed;
3018 struct dirstat_dir dir;
3019 struct diff_queue_struct *q = &diff_queued_diff;
3021 dir.files = NULL;
3022 dir.alloc = 0;
3023 dir.nr = 0;
3024 dir.permille = options->dirstat_permille;
3025 dir.cumulative = options->flags.dirstat_cumulative;
3027 changed = 0;
3028 for (i = 0; i < q->nr; i++) {
3029 struct diff_filepair *p = q->queue[i];
3030 const char *name;
3031 unsigned long copied, added, damage;
3033 name = p->two->path ? p->two->path : p->one->path;
3035 if (p->one->oid_valid && p->two->oid_valid &&
3036 oideq(&p->one->oid, &p->two->oid)) {
3038 * The SHA1 has not changed, so pre-/post-content is
3039 * identical. We can therefore skip looking at the
3040 * file contents altogether.
3042 damage = 0;
3043 goto found_damage;
3046 if (options->flags.dirstat_by_file) {
3048 * In --dirstat-by-file mode, we don't really need to
3049 * look at the actual file contents at all.
3050 * The fact that the SHA1 changed is enough for us to
3051 * add this file to the list of results
3052 * (with each file contributing equal damage).
3054 damage = 1;
3055 goto found_damage;
3058 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3059 diff_populate_filespec(options->repo, p->one, 0);
3060 diff_populate_filespec(options->repo, p->two, 0);
3061 diffcore_count_changes(options->repo,
3062 p->one, p->two, NULL, NULL,
3063 &copied, &added);
3064 diff_free_filespec_data(p->one);
3065 diff_free_filespec_data(p->two);
3066 } else if (DIFF_FILE_VALID(p->one)) {
3067 diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
3068 copied = added = 0;
3069 diff_free_filespec_data(p->one);
3070 } else if (DIFF_FILE_VALID(p->two)) {
3071 diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
3072 copied = 0;
3073 added = p->two->size;
3074 diff_free_filespec_data(p->two);
3075 } else
3076 continue;
3079 * Original minus copied is the removed material,
3080 * added is the new material. They are both damages
3081 * made to the preimage.
3082 * If the resulting damage is zero, we know that
3083 * diffcore_count_changes() considers the two entries to
3084 * be identical, but since the oid changed, we
3085 * know that there must have been _some_ kind of change,
3086 * so we force all entries to have damage > 0.
3088 damage = (p->one->size - copied) + added;
3089 if (!damage)
3090 damage = 1;
3092 found_damage:
3093 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3094 dir.files[dir.nr].name = name;
3095 dir.files[dir.nr].changed = damage;
3096 changed += damage;
3097 dir.nr++;
3100 /* This can happen even with many files, if everything was renames */
3101 if (!changed)
3102 return;
3104 /* Show all directories with more than x% of the changes */
3105 QSORT(dir.files, dir.nr, dirstat_compare);
3106 gather_dirstat(options, &dir, changed, "", 0);
3109 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3111 int i;
3112 unsigned long changed;
3113 struct dirstat_dir dir;
3115 if (data->nr == 0)
3116 return;
3118 dir.files = NULL;
3119 dir.alloc = 0;
3120 dir.nr = 0;
3121 dir.permille = options->dirstat_permille;
3122 dir.cumulative = options->flags.dirstat_cumulative;
3124 changed = 0;
3125 for (i = 0; i < data->nr; i++) {
3126 struct diffstat_file *file = data->files[i];
3127 unsigned long damage = file->added + file->deleted;
3128 if (file->is_binary)
3130 * binary files counts bytes, not lines. Must find some
3131 * way to normalize binary bytes vs. textual lines.
3132 * The following heuristic assumes that there are 64
3133 * bytes per "line".
3134 * This is stupid and ugly, but very cheap...
3136 damage = DIV_ROUND_UP(damage, 64);
3137 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3138 dir.files[dir.nr].name = file->name;
3139 dir.files[dir.nr].changed = damage;
3140 changed += damage;
3141 dir.nr++;
3144 /* This can happen even with many files, if everything was renames */
3145 if (!changed)
3146 return;
3148 /* Show all directories with more than x% of the changes */
3149 QSORT(dir.files, dir.nr, dirstat_compare);
3150 gather_dirstat(options, &dir, changed, "", 0);
3153 static void free_diffstat_info(struct diffstat_t *diffstat)
3155 int i;
3156 for (i = 0; i < diffstat->nr; i++) {
3157 struct diffstat_file *f = diffstat->files[i];
3158 free(f->print_name);
3159 free(f->name);
3160 free(f->from_name);
3161 free(f);
3163 free(diffstat->files);
3166 struct checkdiff_t {
3167 const char *filename;
3168 int lineno;
3169 int conflict_marker_size;
3170 struct diff_options *o;
3171 unsigned ws_rule;
3172 unsigned status;
3175 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3177 char firstchar;
3178 int cnt;
3180 if (len < marker_size + 1)
3181 return 0;
3182 firstchar = line[0];
3183 switch (firstchar) {
3184 case '=': case '>': case '<': case '|':
3185 break;
3186 default:
3187 return 0;
3189 for (cnt = 1; cnt < marker_size; cnt++)
3190 if (line[cnt] != firstchar)
3191 return 0;
3192 /* line[1] thru line[marker_size-1] are same as firstchar */
3193 if (len < marker_size + 1 || !isspace(line[marker_size]))
3194 return 0;
3195 return 1;
3198 static void checkdiff_consume_hunk(void *priv,
3199 long ob, long on, long nb, long nn,
3200 const char *func, long funclen)
3203 struct checkdiff_t *data = priv;
3204 data->lineno = nb - 1;
3207 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3209 struct checkdiff_t *data = priv;
3210 int marker_size = data->conflict_marker_size;
3211 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3212 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3213 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3214 char *err;
3215 const char *line_prefix;
3217 assert(data->o);
3218 line_prefix = diff_line_prefix(data->o);
3220 if (line[0] == '+') {
3221 unsigned bad;
3222 data->lineno++;
3223 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3224 data->status |= 1;
3225 fprintf(data->o->file,
3226 "%s%s:%d: leftover conflict marker\n",
3227 line_prefix, data->filename, data->lineno);
3229 bad = ws_check(line + 1, len - 1, data->ws_rule);
3230 if (!bad)
3231 return;
3232 data->status |= bad;
3233 err = whitespace_error_string(bad);
3234 fprintf(data->o->file, "%s%s:%d: %s.\n",
3235 line_prefix, data->filename, data->lineno, err);
3236 free(err);
3237 emit_line(data->o, set, reset, line, 1);
3238 ws_check_emit(line + 1, len - 1, data->ws_rule,
3239 data->o->file, set, reset, ws);
3240 } else if (line[0] == ' ') {
3241 data->lineno++;
3245 static unsigned char *deflate_it(char *data,
3246 unsigned long size,
3247 unsigned long *result_size)
3249 int bound;
3250 unsigned char *deflated;
3251 git_zstream stream;
3253 git_deflate_init(&stream, zlib_compression_level);
3254 bound = git_deflate_bound(&stream, size);
3255 deflated = xmalloc(bound);
3256 stream.next_out = deflated;
3257 stream.avail_out = bound;
3259 stream.next_in = (unsigned char *)data;
3260 stream.avail_in = size;
3261 while (git_deflate(&stream, Z_FINISH) == Z_OK)
3262 ; /* nothing */
3263 git_deflate_end(&stream);
3264 *result_size = stream.total_out;
3265 return deflated;
3268 static void emit_binary_diff_body(struct diff_options *o,
3269 mmfile_t *one, mmfile_t *two)
3271 void *cp;
3272 void *delta;
3273 void *deflated;
3274 void *data;
3275 unsigned long orig_size;
3276 unsigned long delta_size;
3277 unsigned long deflate_size;
3278 unsigned long data_size;
3280 /* We could do deflated delta, or we could do just deflated two,
3281 * whichever is smaller.
3283 delta = NULL;
3284 deflated = deflate_it(two->ptr, two->size, &deflate_size);
3285 if (one->size && two->size) {
3286 delta = diff_delta(one->ptr, one->size,
3287 two->ptr, two->size,
3288 &delta_size, deflate_size);
3289 if (delta) {
3290 void *to_free = delta;
3291 orig_size = delta_size;
3292 delta = deflate_it(delta, delta_size, &delta_size);
3293 free(to_free);
3297 if (delta && delta_size < deflate_size) {
3298 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3299 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3300 s, strlen(s), 0);
3301 free(s);
3302 free(deflated);
3303 data = delta;
3304 data_size = delta_size;
3305 } else {
3306 char *s = xstrfmt("%lu", two->size);
3307 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3308 s, strlen(s), 0);
3309 free(s);
3310 free(delta);
3311 data = deflated;
3312 data_size = deflate_size;
3315 /* emit data encoded in base85 */
3316 cp = data;
3317 while (data_size) {
3318 int len;
3319 int bytes = (52 < data_size) ? 52 : data_size;
3320 char line[71];
3321 data_size -= bytes;
3322 if (bytes <= 26)
3323 line[0] = bytes + 'A' - 1;
3324 else
3325 line[0] = bytes - 26 + 'a' - 1;
3326 encode_85(line + 1, cp, bytes);
3327 cp = (char *) cp + bytes;
3329 len = strlen(line);
3330 line[len++] = '\n';
3331 line[len] = '\0';
3333 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3334 line, len, 0);
3336 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3337 free(data);
3340 static void emit_binary_diff(struct diff_options *o,
3341 mmfile_t *one, mmfile_t *two)
3343 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3344 emit_binary_diff_body(o, one, two);
3345 emit_binary_diff_body(o, two, one);
3348 int diff_filespec_is_binary(struct repository *r,
3349 struct diff_filespec *one)
3351 if (one->is_binary == -1) {
3352 diff_filespec_load_driver(one, r->index);
3353 if (one->driver->binary != -1)
3354 one->is_binary = one->driver->binary;
3355 else {
3356 if (!one->data && DIFF_FILE_VALID(one))
3357 diff_populate_filespec(r, one, CHECK_BINARY);
3358 if (one->is_binary == -1 && one->data)
3359 one->is_binary = buffer_is_binary(one->data,
3360 one->size);
3361 if (one->is_binary == -1)
3362 one->is_binary = 0;
3365 return one->is_binary;
3368 static const struct userdiff_funcname *
3369 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3371 diff_filespec_load_driver(one, o->repo->index);
3372 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3375 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3377 if (!options->a_prefix)
3378 options->a_prefix = a;
3379 if (!options->b_prefix)
3380 options->b_prefix = b;
3383 struct userdiff_driver *get_textconv(struct repository *r,
3384 struct diff_filespec *one)
3386 if (!DIFF_FILE_VALID(one))
3387 return NULL;
3389 diff_filespec_load_driver(one, r->index);
3390 return userdiff_get_textconv(r, one->driver);
3393 static void builtin_diff(const char *name_a,
3394 const char *name_b,
3395 struct diff_filespec *one,
3396 struct diff_filespec *two,
3397 const char *xfrm_msg,
3398 int must_show_header,
3399 struct diff_options *o,
3400 int complete_rewrite)
3402 mmfile_t mf1, mf2;
3403 const char *lbl[2];
3404 char *a_one, *b_two;
3405 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3406 const char *reset = diff_get_color_opt(o, DIFF_RESET);
3407 const char *a_prefix, *b_prefix;
3408 struct userdiff_driver *textconv_one = NULL;
3409 struct userdiff_driver *textconv_two = NULL;
3410 struct strbuf header = STRBUF_INIT;
3411 const char *line_prefix = diff_line_prefix(o);
3413 diff_set_mnemonic_prefix(o, "a/", "b/");
3414 if (o->flags.reverse_diff) {
3415 a_prefix = o->b_prefix;
3416 b_prefix = o->a_prefix;
3417 } else {
3418 a_prefix = o->a_prefix;
3419 b_prefix = o->b_prefix;
3422 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3423 (!one->mode || S_ISGITLINK(one->mode)) &&
3424 (!two->mode || S_ISGITLINK(two->mode))) {
3425 show_submodule_summary(o, one->path ? one->path : two->path,
3426 &one->oid, &two->oid,
3427 two->dirty_submodule);
3428 return;
3429 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3430 (!one->mode || S_ISGITLINK(one->mode)) &&
3431 (!two->mode || S_ISGITLINK(two->mode))) {
3432 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3433 &one->oid, &two->oid,
3434 two->dirty_submodule);
3435 return;
3438 if (o->flags.allow_textconv) {
3439 textconv_one = get_textconv(o->repo, one);
3440 textconv_two = get_textconv(o->repo, two);
3443 /* Never use a non-valid filename anywhere if at all possible */
3444 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3445 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3447 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3448 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3449 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3450 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3451 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3452 if (lbl[0][0] == '/') {
3453 /* /dev/null */
3454 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3455 if (xfrm_msg)
3456 strbuf_addstr(&header, xfrm_msg);
3457 must_show_header = 1;
3459 else if (lbl[1][0] == '/') {
3460 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3461 if (xfrm_msg)
3462 strbuf_addstr(&header, xfrm_msg);
3463 must_show_header = 1;
3465 else {
3466 if (one->mode != two->mode) {
3467 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3468 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3469 must_show_header = 1;
3471 if (xfrm_msg)
3472 strbuf_addstr(&header, xfrm_msg);
3475 * we do not run diff between different kind
3476 * of objects.
3478 if ((one->mode ^ two->mode) & S_IFMT)
3479 goto free_ab_and_return;
3480 if (complete_rewrite &&
3481 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3482 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3483 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3484 header.buf, header.len, 0);
3485 strbuf_reset(&header);
3486 emit_rewrite_diff(name_a, name_b, one, two,
3487 textconv_one, textconv_two, o);
3488 o->found_changes = 1;
3489 goto free_ab_and_return;
3493 if (o->irreversible_delete && lbl[1][0] == '/') {
3494 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3495 header.len, 0);
3496 strbuf_reset(&header);
3497 goto free_ab_and_return;
3498 } else if (!o->flags.text &&
3499 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3500 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3501 struct strbuf sb = STRBUF_INIT;
3502 if (!one->data && !two->data &&
3503 S_ISREG(one->mode) && S_ISREG(two->mode) &&
3504 !o->flags.binary) {
3505 if (oideq(&one->oid, &two->oid)) {
3506 if (must_show_header)
3507 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3508 header.buf, header.len,
3510 goto free_ab_and_return;
3512 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3513 header.buf, header.len, 0);
3514 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3515 diff_line_prefix(o), lbl[0], lbl[1]);
3516 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3517 sb.buf, sb.len, 0);
3518 strbuf_release(&sb);
3519 goto free_ab_and_return;
3521 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3522 fill_mmfile(o->repo, &mf2, two) < 0)
3523 die("unable to read files to diff");
3524 /* Quite common confusing case */
3525 if (mf1.size == mf2.size &&
3526 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3527 if (must_show_header)
3528 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3529 header.buf, header.len, 0);
3530 goto free_ab_and_return;
3532 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3533 strbuf_reset(&header);
3534 if (o->flags.binary)
3535 emit_binary_diff(o, &mf1, &mf2);
3536 else {
3537 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3538 diff_line_prefix(o), lbl[0], lbl[1]);
3539 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3540 sb.buf, sb.len, 0);
3541 strbuf_release(&sb);
3543 o->found_changes = 1;
3544 } else {
3545 /* Crazy xdl interfaces.. */
3546 const char *diffopts;
3547 const char *v;
3548 xpparam_t xpp;
3549 xdemitconf_t xecfg;
3550 struct emit_callback ecbdata;
3551 const struct userdiff_funcname *pe;
3553 if (must_show_header) {
3554 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3555 header.buf, header.len, 0);
3556 strbuf_reset(&header);
3559 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3560 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3562 pe = diff_funcname_pattern(o, one);
3563 if (!pe)
3564 pe = diff_funcname_pattern(o, two);
3566 memset(&xpp, 0, sizeof(xpp));
3567 memset(&xecfg, 0, sizeof(xecfg));
3568 memset(&ecbdata, 0, sizeof(ecbdata));
3569 if (o->flags.suppress_diff_headers)
3570 lbl[0] = NULL;
3571 ecbdata.label_path = lbl;
3572 ecbdata.color_diff = want_color(o->use_color);
3573 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3574 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3575 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3576 ecbdata.opt = o;
3577 if (header.len && !o->flags.suppress_diff_headers)
3578 ecbdata.header = &header;
3579 xpp.flags = o->xdl_opts;
3580 xpp.anchors = o->anchors;
3581 xpp.anchors_nr = o->anchors_nr;
3582 xecfg.ctxlen = o->context;
3583 xecfg.interhunkctxlen = o->interhunkcontext;
3584 xecfg.flags = XDL_EMIT_FUNCNAMES;
3585 if (o->flags.funccontext)
3586 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3587 if (pe)
3588 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3590 diffopts = getenv("GIT_DIFF_OPTS");
3591 if (!diffopts)
3593 else if (skip_prefix(diffopts, "--unified=", &v))
3594 xecfg.ctxlen = strtoul(v, NULL, 10);
3595 else if (skip_prefix(diffopts, "-u", &v))
3596 xecfg.ctxlen = strtoul(v, NULL, 10);
3598 if (o->word_diff)
3599 init_diff_words_data(&ecbdata, o, one, two);
3600 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3601 &ecbdata, &xpp, &xecfg))
3602 die("unable to generate diff for %s", one->path);
3603 if (o->word_diff)
3604 free_diff_words_data(&ecbdata);
3605 if (textconv_one)
3606 free(mf1.ptr);
3607 if (textconv_two)
3608 free(mf2.ptr);
3609 xdiff_clear_find_func(&xecfg);
3612 free_ab_and_return:
3613 strbuf_release(&header);
3614 diff_free_filespec_data(one);
3615 diff_free_filespec_data(two);
3616 free(a_one);
3617 free(b_two);
3618 return;
3621 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3623 if (!is_renamed) {
3624 if (p->status == DIFF_STATUS_ADDED) {
3625 if (S_ISLNK(p->two->mode))
3626 return "new +l";
3627 else if ((p->two->mode & 0777) == 0755)
3628 return "new +x";
3629 else
3630 return "new";
3631 } else if (p->status == DIFF_STATUS_DELETED)
3632 return "gone";
3634 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3635 return "mode -l";
3636 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3637 return "mode +l";
3638 else if ((p->one->mode & 0777) == 0644 &&
3639 (p->two->mode & 0777) == 0755)
3640 return "mode +x";
3641 else if ((p->one->mode & 0777) == 0755 &&
3642 (p->two->mode & 0777) == 0644)
3643 return "mode -x";
3644 return NULL;
3647 static void builtin_diffstat(const char *name_a, const char *name_b,
3648 struct diff_filespec *one,
3649 struct diff_filespec *two,
3650 struct diffstat_t *diffstat,
3651 struct diff_options *o,
3652 struct diff_filepair *p)
3654 mmfile_t mf1, mf2;
3655 struct diffstat_file *data;
3656 int same_contents;
3657 int complete_rewrite = 0;
3659 if (!DIFF_PAIR_UNMERGED(p)) {
3660 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3661 complete_rewrite = 1;
3664 data = diffstat_add(diffstat, name_a, name_b);
3665 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3666 if (o->flags.stat_with_summary)
3667 data->comments = get_compact_summary(p, data->is_renamed);
3669 if (!one || !two) {
3670 data->is_unmerged = 1;
3671 return;
3674 same_contents = oideq(&one->oid, &two->oid);
3676 if (diff_filespec_is_binary(o->repo, one) ||
3677 diff_filespec_is_binary(o->repo, two)) {
3678 data->is_binary = 1;
3679 if (same_contents) {
3680 data->added = 0;
3681 data->deleted = 0;
3682 } else {
3683 data->added = diff_filespec_size(o->repo, two);
3684 data->deleted = diff_filespec_size(o->repo, one);
3688 else if (complete_rewrite) {
3689 diff_populate_filespec(o->repo, one, 0);
3690 diff_populate_filespec(o->repo, two, 0);
3691 data->deleted = count_lines(one->data, one->size);
3692 data->added = count_lines(two->data, two->size);
3695 else if (!same_contents) {
3696 /* Crazy xdl interfaces.. */
3697 xpparam_t xpp;
3698 xdemitconf_t xecfg;
3700 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3701 fill_mmfile(o->repo, &mf2, two) < 0)
3702 die("unable to read files to diff");
3704 memset(&xpp, 0, sizeof(xpp));
3705 memset(&xecfg, 0, sizeof(xecfg));
3706 xpp.flags = o->xdl_opts;
3707 xpp.anchors = o->anchors;
3708 xpp.anchors_nr = o->anchors_nr;
3709 xecfg.ctxlen = o->context;
3710 xecfg.interhunkctxlen = o->interhunkcontext;
3711 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3712 diffstat_consume, diffstat, &xpp, &xecfg))
3713 die("unable to generate diffstat for %s", one->path);
3716 diff_free_filespec_data(one);
3717 diff_free_filespec_data(two);
3720 static void builtin_checkdiff(const char *name_a, const char *name_b,
3721 const char *attr_path,
3722 struct diff_filespec *one,
3723 struct diff_filespec *two,
3724 struct diff_options *o)
3726 mmfile_t mf1, mf2;
3727 struct checkdiff_t data;
3729 if (!two)
3730 return;
3732 memset(&data, 0, sizeof(data));
3733 data.filename = name_b ? name_b : name_a;
3734 data.lineno = 0;
3735 data.o = o;
3736 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3737 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3739 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3740 fill_mmfile(o->repo, &mf2, two) < 0)
3741 die("unable to read files to diff");
3744 * All the other codepaths check both sides, but not checking
3745 * the "old" side here is deliberate. We are checking the newly
3746 * introduced changes, and as long as the "new" side is text, we
3747 * can and should check what it introduces.
3749 if (diff_filespec_is_binary(o->repo, two))
3750 goto free_and_return;
3751 else {
3752 /* Crazy xdl interfaces.. */
3753 xpparam_t xpp;
3754 xdemitconf_t xecfg;
3756 memset(&xpp, 0, sizeof(xpp));
3757 memset(&xecfg, 0, sizeof(xecfg));
3758 xecfg.ctxlen = 1; /* at least one context line */
3759 xpp.flags = 0;
3760 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3761 checkdiff_consume, &data,
3762 &xpp, &xecfg))
3763 die("unable to generate checkdiff for %s", one->path);
3765 if (data.ws_rule & WS_BLANK_AT_EOF) {
3766 struct emit_callback ecbdata;
3767 int blank_at_eof;
3769 ecbdata.ws_rule = data.ws_rule;
3770 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3771 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3773 if (blank_at_eof) {
3774 static char *err;
3775 if (!err)
3776 err = whitespace_error_string(WS_BLANK_AT_EOF);
3777 fprintf(o->file, "%s:%d: %s.\n",
3778 data.filename, blank_at_eof, err);
3779 data.status = 1; /* report errors */
3783 free_and_return:
3784 diff_free_filespec_data(one);
3785 diff_free_filespec_data(two);
3786 if (data.status)
3787 o->flags.check_failed = 1;
3790 struct diff_filespec *alloc_filespec(const char *path)
3792 struct diff_filespec *spec;
3794 FLEXPTR_ALLOC_STR(spec, path, path);
3795 spec->count = 1;
3796 spec->is_binary = -1;
3797 return spec;
3800 void free_filespec(struct diff_filespec *spec)
3802 if (!--spec->count) {
3803 diff_free_filespec_data(spec);
3804 free(spec);
3808 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3809 int oid_valid, unsigned short mode)
3811 if (mode) {
3812 spec->mode = canon_mode(mode);
3813 oidcpy(&spec->oid, oid);
3814 spec->oid_valid = oid_valid;
3819 * Given a name and sha1 pair, if the index tells us the file in
3820 * the work tree has that object contents, return true, so that
3821 * prepare_temp_file() does not have to inflate and extract.
3823 static int reuse_worktree_file(struct index_state *istate,
3824 const char *name,
3825 const struct object_id *oid,
3826 int want_file)
3828 const struct cache_entry *ce;
3829 struct stat st;
3830 int pos, len;
3833 * We do not read the cache ourselves here, because the
3834 * benchmark with my previous version that always reads cache
3835 * shows that it makes things worse for diff-tree comparing
3836 * two linux-2.6 kernel trees in an already checked out work
3837 * tree. This is because most diff-tree comparisons deal with
3838 * only a small number of files, while reading the cache is
3839 * expensive for a large project, and its cost outweighs the
3840 * savings we get by not inflating the object to a temporary
3841 * file. Practically, this code only helps when we are used
3842 * by diff-cache --cached, which does read the cache before
3843 * calling us.
3845 if (!istate->cache)
3846 return 0;
3848 /* We want to avoid the working directory if our caller
3849 * doesn't need the data in a normal file, this system
3850 * is rather slow with its stat/open/mmap/close syscalls,
3851 * and the object is contained in a pack file. The pack
3852 * is probably already open and will be faster to obtain
3853 * the data through than the working directory. Loose
3854 * objects however would tend to be slower as they need
3855 * to be individually opened and inflated.
3857 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3858 return 0;
3861 * Similarly, if we'd have to convert the file contents anyway, that
3862 * makes the optimization not worthwhile.
3864 if (!want_file && would_convert_to_git(istate, name))
3865 return 0;
3867 len = strlen(name);
3868 pos = index_name_pos(istate, name, len);
3869 if (pos < 0)
3870 return 0;
3871 ce = istate->cache[pos];
3874 * This is not the sha1 we are looking for, or
3875 * unreusable because it is not a regular file.
3877 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3878 return 0;
3881 * If ce is marked as "assume unchanged", there is no
3882 * guarantee that work tree matches what we are looking for.
3884 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3885 return 0;
3888 * If ce matches the file in the work tree, we can reuse it.
3890 if (ce_uptodate(ce) ||
3891 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3892 return 1;
3894 return 0;
3897 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3899 struct strbuf buf = STRBUF_INIT;
3900 char *dirty = "";
3902 /* Are we looking at the work tree? */
3903 if (s->dirty_submodule)
3904 dirty = "-dirty";
3906 strbuf_addf(&buf, "Subproject commit %s%s\n",
3907 oid_to_hex(&s->oid), dirty);
3908 s->size = buf.len;
3909 if (size_only) {
3910 s->data = NULL;
3911 strbuf_release(&buf);
3912 } else {
3913 s->data = strbuf_detach(&buf, NULL);
3914 s->should_free = 1;
3916 return 0;
3920 * While doing rename detection and pickaxe operation, we may need to
3921 * grab the data for the blob (or file) for our own in-core comparison.
3922 * diff_filespec has data and size fields for this purpose.
3924 int diff_populate_filespec(struct repository *r,
3925 struct diff_filespec *s,
3926 unsigned int flags)
3928 int size_only = flags & CHECK_SIZE_ONLY;
3929 int err = 0;
3930 int conv_flags = global_conv_flags_eol;
3932 * demote FAIL to WARN to allow inspecting the situation
3933 * instead of refusing.
3935 if (conv_flags & CONV_EOL_RNDTRP_DIE)
3936 conv_flags = CONV_EOL_RNDTRP_WARN;
3938 if (!DIFF_FILE_VALID(s))
3939 die("internal error: asking to populate invalid file.");
3940 if (S_ISDIR(s->mode))
3941 return -1;
3943 if (s->data)
3944 return 0;
3946 if (size_only && 0 < s->size)
3947 return 0;
3949 if (S_ISGITLINK(s->mode))
3950 return diff_populate_gitlink(s, size_only);
3952 if (!s->oid_valid ||
3953 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3954 struct strbuf buf = STRBUF_INIT;
3955 struct stat st;
3956 int fd;
3958 if (lstat(s->path, &st) < 0) {
3959 err_empty:
3960 err = -1;
3961 empty:
3962 s->data = (char *)"";
3963 s->size = 0;
3964 return err;
3966 s->size = xsize_t(st.st_size);
3967 if (!s->size)
3968 goto empty;
3969 if (S_ISLNK(st.st_mode)) {
3970 struct strbuf sb = STRBUF_INIT;
3972 if (strbuf_readlink(&sb, s->path, s->size))
3973 goto err_empty;
3974 s->size = sb.len;
3975 s->data = strbuf_detach(&sb, NULL);
3976 s->should_free = 1;
3977 return 0;
3981 * Even if the caller would be happy with getting
3982 * only the size, we cannot return early at this
3983 * point if the path requires us to run the content
3984 * conversion.
3986 if (size_only && !would_convert_to_git(r->index, s->path))
3987 return 0;
3990 * Note: this check uses xsize_t(st.st_size) that may
3991 * not be the true size of the blob after it goes
3992 * through convert_to_git(). This may not strictly be
3993 * correct, but the whole point of big_file_threshold
3994 * and is_binary check being that we want to avoid
3995 * opening the file and inspecting the contents, this
3996 * is probably fine.
3998 if ((flags & CHECK_BINARY) &&
3999 s->size > big_file_threshold && s->is_binary == -1) {
4000 s->is_binary = 1;
4001 return 0;
4003 fd = open(s->path, O_RDONLY);
4004 if (fd < 0)
4005 goto err_empty;
4006 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4007 close(fd);
4008 s->should_munmap = 1;
4011 * Convert from working tree format to canonical git format
4013 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4014 size_t size = 0;
4015 munmap(s->data, s->size);
4016 s->should_munmap = 0;
4017 s->data = strbuf_detach(&buf, &size);
4018 s->size = size;
4019 s->should_free = 1;
4022 else {
4023 enum object_type type;
4024 if (size_only || (flags & CHECK_BINARY)) {
4025 type = oid_object_info(r, &s->oid, &s->size);
4026 if (type < 0)
4027 die("unable to read %s",
4028 oid_to_hex(&s->oid));
4029 if (size_only)
4030 return 0;
4031 if (s->size > big_file_threshold && s->is_binary == -1) {
4032 s->is_binary = 1;
4033 return 0;
4036 s->data = read_object_file(&s->oid, &type, &s->size);
4037 if (!s->data)
4038 die("unable to read %s", oid_to_hex(&s->oid));
4039 s->should_free = 1;
4041 return 0;
4044 void diff_free_filespec_blob(struct diff_filespec *s)
4046 if (s->should_free)
4047 free(s->data);
4048 else if (s->should_munmap)
4049 munmap(s->data, s->size);
4051 if (s->should_free || s->should_munmap) {
4052 s->should_free = s->should_munmap = 0;
4053 s->data = NULL;
4057 void diff_free_filespec_data(struct diff_filespec *s)
4059 diff_free_filespec_blob(s);
4060 FREE_AND_NULL(s->cnt_data);
4063 static void prep_temp_blob(struct index_state *istate,
4064 const char *path, struct diff_tempfile *temp,
4065 void *blob,
4066 unsigned long size,
4067 const struct object_id *oid,
4068 int mode)
4070 struct strbuf buf = STRBUF_INIT;
4071 struct strbuf tempfile = STRBUF_INIT;
4072 char *path_dup = xstrdup(path);
4073 const char *base = basename(path_dup);
4075 /* Generate "XXXXXX_basename.ext" */
4076 strbuf_addstr(&tempfile, "XXXXXX_");
4077 strbuf_addstr(&tempfile, base);
4079 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4080 if (!temp->tempfile)
4081 die_errno("unable to create temp-file");
4082 if (convert_to_working_tree(istate, path,
4083 (const char *)blob, (size_t)size, &buf)) {
4084 blob = buf.buf;
4085 size = buf.len;
4087 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4088 close_tempfile_gently(temp->tempfile))
4089 die_errno("unable to write temp-file");
4090 temp->name = get_tempfile_path(temp->tempfile);
4091 oid_to_hex_r(temp->hex, oid);
4092 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4093 strbuf_release(&buf);
4094 strbuf_release(&tempfile);
4095 free(path_dup);
4098 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4099 const char *name,
4100 struct diff_filespec *one)
4102 struct diff_tempfile *temp = claim_diff_tempfile();
4104 if (!DIFF_FILE_VALID(one)) {
4105 not_a_valid_file:
4106 /* A '-' entry produces this for file-2, and
4107 * a '+' entry produces this for file-1.
4109 temp->name = "/dev/null";
4110 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4111 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4112 return temp;
4115 if (!S_ISGITLINK(one->mode) &&
4116 (!one->oid_valid ||
4117 reuse_worktree_file(r->index, name, &one->oid, 1))) {
4118 struct stat st;
4119 if (lstat(name, &st) < 0) {
4120 if (errno == ENOENT)
4121 goto not_a_valid_file;
4122 die_errno("stat(%s)", name);
4124 if (S_ISLNK(st.st_mode)) {
4125 struct strbuf sb = STRBUF_INIT;
4126 if (strbuf_readlink(&sb, name, st.st_size) < 0)
4127 die_errno("readlink(%s)", name);
4128 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4129 (one->oid_valid ?
4130 &one->oid : &null_oid),
4131 (one->oid_valid ?
4132 one->mode : S_IFLNK));
4133 strbuf_release(&sb);
4135 else {
4136 /* we can borrow from the file in the work tree */
4137 temp->name = name;
4138 if (!one->oid_valid)
4139 oid_to_hex_r(temp->hex, &null_oid);
4140 else
4141 oid_to_hex_r(temp->hex, &one->oid);
4142 /* Even though we may sometimes borrow the
4143 * contents from the work tree, we always want
4144 * one->mode. mode is trustworthy even when
4145 * !(one->oid_valid), as long as
4146 * DIFF_FILE_VALID(one).
4148 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4150 return temp;
4152 else {
4153 if (diff_populate_filespec(r, one, 0))
4154 die("cannot read data blob for %s", one->path);
4155 prep_temp_blob(r->index, name, temp,
4156 one->data, one->size,
4157 &one->oid, one->mode);
4159 return temp;
4162 static void add_external_diff_name(struct repository *r,
4163 struct argv_array *argv,
4164 const char *name,
4165 struct diff_filespec *df)
4167 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4168 argv_array_push(argv, temp->name);
4169 argv_array_push(argv, temp->hex);
4170 argv_array_push(argv, temp->mode);
4173 /* An external diff command takes:
4175 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4176 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4179 static void run_external_diff(const char *pgm,
4180 const char *name,
4181 const char *other,
4182 struct diff_filespec *one,
4183 struct diff_filespec *two,
4184 const char *xfrm_msg,
4185 struct diff_options *o)
4187 struct argv_array argv = ARGV_ARRAY_INIT;
4188 struct argv_array env = ARGV_ARRAY_INIT;
4189 struct diff_queue_struct *q = &diff_queued_diff;
4191 argv_array_push(&argv, pgm);
4192 argv_array_push(&argv, name);
4194 if (one && two) {
4195 add_external_diff_name(o->repo, &argv, name, one);
4196 if (!other)
4197 add_external_diff_name(o->repo, &argv, name, two);
4198 else {
4199 add_external_diff_name(o->repo, &argv, other, two);
4200 argv_array_push(&argv, other);
4201 argv_array_push(&argv, xfrm_msg);
4205 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4206 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4208 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4209 die(_("external diff died, stopping at %s"), name);
4211 remove_tempfile();
4212 argv_array_clear(&argv);
4213 argv_array_clear(&env);
4216 static int similarity_index(struct diff_filepair *p)
4218 return p->score * 100 / MAX_SCORE;
4221 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4223 if (startup_info->have_repository)
4224 return find_unique_abbrev(oid, abbrev);
4225 else {
4226 char *hex = oid_to_hex(oid);
4227 if (abbrev < 0)
4228 abbrev = FALLBACK_DEFAULT_ABBREV;
4229 if (abbrev > the_hash_algo->hexsz)
4230 BUG("oid abbreviation out of range: %d", abbrev);
4231 if (abbrev)
4232 hex[abbrev] = '\0';
4233 return hex;
4237 static void fill_metainfo(struct strbuf *msg,
4238 const char *name,
4239 const char *other,
4240 struct diff_filespec *one,
4241 struct diff_filespec *two,
4242 struct diff_options *o,
4243 struct diff_filepair *p,
4244 int *must_show_header,
4245 int use_color)
4247 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4248 const char *reset = diff_get_color(use_color, DIFF_RESET);
4249 const char *line_prefix = diff_line_prefix(o);
4251 *must_show_header = 1;
4252 strbuf_init(msg, PATH_MAX * 2 + 300);
4253 switch (p->status) {
4254 case DIFF_STATUS_COPIED:
4255 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4256 line_prefix, set, similarity_index(p));
4257 strbuf_addf(msg, "%s\n%s%scopy from ",
4258 reset, line_prefix, set);
4259 quote_c_style(name, msg, NULL, 0);
4260 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4261 quote_c_style(other, msg, NULL, 0);
4262 strbuf_addf(msg, "%s\n", reset);
4263 break;
4264 case DIFF_STATUS_RENAMED:
4265 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4266 line_prefix, set, similarity_index(p));
4267 strbuf_addf(msg, "%s\n%s%srename from ",
4268 reset, line_prefix, set);
4269 quote_c_style(name, msg, NULL, 0);
4270 strbuf_addf(msg, "%s\n%s%srename to ",
4271 reset, line_prefix, set);
4272 quote_c_style(other, msg, NULL, 0);
4273 strbuf_addf(msg, "%s\n", reset);
4274 break;
4275 case DIFF_STATUS_MODIFIED:
4276 if (p->score) {
4277 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4278 line_prefix,
4279 set, similarity_index(p), reset);
4280 break;
4282 /* fallthru */
4283 default:
4284 *must_show_header = 0;
4286 if (one && two && !oideq(&one->oid, &two->oid)) {
4287 const unsigned hexsz = the_hash_algo->hexsz;
4288 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
4290 if (o->flags.binary) {
4291 mmfile_t mf;
4292 if ((!fill_mmfile(o->repo, &mf, one) &&
4293 diff_filespec_is_binary(o->repo, one)) ||
4294 (!fill_mmfile(o->repo, &mf, two) &&
4295 diff_filespec_is_binary(o->repo, two)))
4296 abbrev = hexsz;
4298 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4299 diff_abbrev_oid(&one->oid, abbrev),
4300 diff_abbrev_oid(&two->oid, abbrev));
4301 if (one->mode == two->mode)
4302 strbuf_addf(msg, " %06o", one->mode);
4303 strbuf_addf(msg, "%s\n", reset);
4307 static void run_diff_cmd(const char *pgm,
4308 const char *name,
4309 const char *other,
4310 const char *attr_path,
4311 struct diff_filespec *one,
4312 struct diff_filespec *two,
4313 struct strbuf *msg,
4314 struct diff_options *o,
4315 struct diff_filepair *p)
4317 const char *xfrm_msg = NULL;
4318 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4319 int must_show_header = 0;
4322 if (o->flags.allow_external) {
4323 struct userdiff_driver *drv;
4325 drv = userdiff_find_by_path(o->repo->index, attr_path);
4326 if (drv && drv->external)
4327 pgm = drv->external;
4330 if (msg) {
4332 * don't use colors when the header is intended for an
4333 * external diff driver
4335 fill_metainfo(msg, name, other, one, two, o, p,
4336 &must_show_header,
4337 want_color(o->use_color) && !pgm);
4338 xfrm_msg = msg->len ? msg->buf : NULL;
4341 if (pgm) {
4342 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4343 return;
4345 if (one && two)
4346 builtin_diff(name, other ? other : name,
4347 one, two, xfrm_msg, must_show_header,
4348 o, complete_rewrite);
4349 else
4350 fprintf(o->file, "* Unmerged path %s\n", name);
4353 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4355 if (DIFF_FILE_VALID(one)) {
4356 if (!one->oid_valid) {
4357 struct stat st;
4358 if (one->is_stdin) {
4359 oidclr(&one->oid);
4360 return;
4362 if (lstat(one->path, &st) < 0)
4363 die_errno("stat '%s'", one->path);
4364 if (index_path(istate, &one->oid, one->path, &st, 0))
4365 die("cannot hash %s", one->path);
4368 else
4369 oidclr(&one->oid);
4372 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4374 /* Strip the prefix but do not molest /dev/null and absolute paths */
4375 if (*namep && !is_absolute_path(*namep)) {
4376 *namep += prefix_length;
4377 if (**namep == '/')
4378 ++*namep;
4380 if (*otherp && !is_absolute_path(*otherp)) {
4381 *otherp += prefix_length;
4382 if (**otherp == '/')
4383 ++*otherp;
4387 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4389 const char *pgm = external_diff();
4390 struct strbuf msg;
4391 struct diff_filespec *one = p->one;
4392 struct diff_filespec *two = p->two;
4393 const char *name;
4394 const char *other;
4395 const char *attr_path;
4397 name = one->path;
4398 other = (strcmp(name, two->path) ? two->path : NULL);
4399 attr_path = name;
4400 if (o->prefix_length)
4401 strip_prefix(o->prefix_length, &name, &other);
4403 if (!o->flags.allow_external)
4404 pgm = NULL;
4406 if (DIFF_PAIR_UNMERGED(p)) {
4407 run_diff_cmd(pgm, name, NULL, attr_path,
4408 NULL, NULL, NULL, o, p);
4409 return;
4412 diff_fill_oid_info(one, o->repo->index);
4413 diff_fill_oid_info(two, o->repo->index);
4415 if (!pgm &&
4416 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4417 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4419 * a filepair that changes between file and symlink
4420 * needs to be split into deletion and creation.
4422 struct diff_filespec *null = alloc_filespec(two->path);
4423 run_diff_cmd(NULL, name, other, attr_path,
4424 one, null, &msg,
4425 o, p);
4426 free(null);
4427 strbuf_release(&msg);
4429 null = alloc_filespec(one->path);
4430 run_diff_cmd(NULL, name, other, attr_path,
4431 null, two, &msg, o, p);
4432 free(null);
4434 else
4435 run_diff_cmd(pgm, name, other, attr_path,
4436 one, two, &msg, o, p);
4438 strbuf_release(&msg);
4441 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4442 struct diffstat_t *diffstat)
4444 const char *name;
4445 const char *other;
4447 if (DIFF_PAIR_UNMERGED(p)) {
4448 /* unmerged */
4449 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4450 diffstat, o, p);
4451 return;
4454 name = p->one->path;
4455 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4457 if (o->prefix_length)
4458 strip_prefix(o->prefix_length, &name, &other);
4460 diff_fill_oid_info(p->one, o->repo->index);
4461 diff_fill_oid_info(p->two, o->repo->index);
4463 builtin_diffstat(name, other, p->one, p->two,
4464 diffstat, o, p);
4467 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4469 const char *name;
4470 const char *other;
4471 const char *attr_path;
4473 if (DIFF_PAIR_UNMERGED(p)) {
4474 /* unmerged */
4475 return;
4478 name = p->one->path;
4479 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4480 attr_path = other ? other : name;
4482 if (o->prefix_length)
4483 strip_prefix(o->prefix_length, &name, &other);
4485 diff_fill_oid_info(p->one, o->repo->index);
4486 diff_fill_oid_info(p->two, o->repo->index);
4488 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4491 static void prep_parse_options(struct diff_options *options);
4493 void repo_diff_setup(struct repository *r, struct diff_options *options)
4495 memcpy(options, &default_diff_options, sizeof(*options));
4497 options->file = stdout;
4498 options->repo = r;
4500 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4501 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4502 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4503 options->abbrev = DEFAULT_ABBREV;
4504 options->line_termination = '\n';
4505 options->break_opt = -1;
4506 options->rename_limit = -1;
4507 options->dirstat_permille = diff_dirstat_permille_default;
4508 options->context = diff_context_default;
4509 options->interhunkcontext = diff_interhunk_context_default;
4510 options->ws_error_highlight = ws_error_highlight_default;
4511 options->flags.rename_empty = 1;
4512 options->objfind = NULL;
4514 /* pathchange left =NULL by default */
4515 options->change = diff_change;
4516 options->add_remove = diff_addremove;
4517 options->use_color = diff_use_color_default;
4518 options->detect_rename = diff_detect_rename_default;
4519 options->xdl_opts |= diff_algorithm;
4520 if (diff_indent_heuristic)
4521 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4523 options->orderfile = diff_order_file_cfg;
4525 if (diff_no_prefix) {
4526 options->a_prefix = options->b_prefix = "";
4527 } else if (!diff_mnemonic_prefix) {
4528 options->a_prefix = "a/";
4529 options->b_prefix = "b/";
4532 options->color_moved = diff_color_moved_default;
4533 options->color_moved_ws_handling = diff_color_moved_ws_default;
4535 prep_parse_options(options);
4538 void diff_setup_done(struct diff_options *options)
4540 unsigned check_mask = DIFF_FORMAT_NAME |
4541 DIFF_FORMAT_NAME_STATUS |
4542 DIFF_FORMAT_CHECKDIFF |
4543 DIFF_FORMAT_NO_OUTPUT;
4545 * This must be signed because we're comparing against a potentially
4546 * negative value.
4548 const int hexsz = the_hash_algo->hexsz;
4550 if (options->set_default)
4551 options->set_default(options);
4553 if (HAS_MULTI_BITS(options->output_format & check_mask))
4554 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4556 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4557 die(_("-G, -S and --find-object are mutually exclusive"));
4560 * Most of the time we can say "there are changes"
4561 * only by checking if there are changed paths, but
4562 * --ignore-whitespace* options force us to look
4563 * inside contents.
4566 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4567 options->flags.diff_from_contents = 1;
4568 else
4569 options->flags.diff_from_contents = 0;
4571 if (options->flags.find_copies_harder)
4572 options->detect_rename = DIFF_DETECT_COPY;
4574 if (!options->flags.relative_name)
4575 options->prefix = NULL;
4576 if (options->prefix)
4577 options->prefix_length = strlen(options->prefix);
4578 else
4579 options->prefix_length = 0;
4581 if (options->output_format & (DIFF_FORMAT_NAME |
4582 DIFF_FORMAT_NAME_STATUS |
4583 DIFF_FORMAT_CHECKDIFF |
4584 DIFF_FORMAT_NO_OUTPUT))
4585 options->output_format &= ~(DIFF_FORMAT_RAW |
4586 DIFF_FORMAT_NUMSTAT |
4587 DIFF_FORMAT_DIFFSTAT |
4588 DIFF_FORMAT_SHORTSTAT |
4589 DIFF_FORMAT_DIRSTAT |
4590 DIFF_FORMAT_SUMMARY |
4591 DIFF_FORMAT_PATCH);
4594 * These cases always need recursive; we do not drop caller-supplied
4595 * recursive bits for other formats here.
4597 if (options->output_format & (DIFF_FORMAT_PATCH |
4598 DIFF_FORMAT_NUMSTAT |
4599 DIFF_FORMAT_DIFFSTAT |
4600 DIFF_FORMAT_SHORTSTAT |
4601 DIFF_FORMAT_DIRSTAT |
4602 DIFF_FORMAT_SUMMARY |
4603 DIFF_FORMAT_CHECKDIFF))
4604 options->flags.recursive = 1;
4606 * Also pickaxe would not work very well if you do not say recursive
4608 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4609 options->flags.recursive = 1;
4611 * When patches are generated, submodules diffed against the work tree
4612 * must be checked for dirtiness too so it can be shown in the output
4614 if (options->output_format & DIFF_FORMAT_PATCH)
4615 options->flags.dirty_submodules = 1;
4617 if (options->detect_rename && options->rename_limit < 0)
4618 options->rename_limit = diff_rename_limit_default;
4619 if (hexsz < options->abbrev)
4620 options->abbrev = hexsz; /* full */
4623 * It does not make sense to show the first hit we happened
4624 * to have found. It does not make sense not to return with
4625 * exit code in such a case either.
4627 if (options->flags.quick) {
4628 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4629 options->flags.exit_with_status = 1;
4632 options->diff_path_counter = 0;
4634 if (options->flags.follow_renames && options->pathspec.nr != 1)
4635 die(_("--follow requires exactly one pathspec"));
4637 if (!options->use_color || external_diff())
4638 options->color_moved = 0;
4640 FREE_AND_NULL(options->parseopts);
4643 int parse_long_opt(const char *opt, const char **argv,
4644 const char **optarg)
4646 const char *arg = argv[0];
4647 if (!skip_prefix(arg, "--", &arg))
4648 return 0;
4649 if (!skip_prefix(arg, opt, &arg))
4650 return 0;
4651 if (*arg == '=') { /* stuck form: --option=value */
4652 *optarg = arg + 1;
4653 return 1;
4655 if (*arg != '\0')
4656 return 0;
4657 /* separate form: --option value */
4658 if (!argv[1])
4659 die("Option '--%s' requires a value", opt);
4660 *optarg = argv[1];
4661 return 2;
4664 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4666 struct diff_options *options = opt->value;
4667 int width = options->stat_width;
4668 int name_width = options->stat_name_width;
4669 int graph_width = options->stat_graph_width;
4670 int count = options->stat_count;
4671 char *end;
4673 BUG_ON_OPT_NEG(unset);
4675 if (!strcmp(opt->long_name, "stat")) {
4676 if (value) {
4677 width = strtoul(value, &end, 10);
4678 if (*end == ',')
4679 name_width = strtoul(end+1, &end, 10);
4680 if (*end == ',')
4681 count = strtoul(end+1, &end, 10);
4682 if (*end)
4683 return error(_("invalid --stat value: %s"), value);
4685 } else if (!strcmp(opt->long_name, "stat-width")) {
4686 width = strtoul(value, &end, 10);
4687 if (*end)
4688 return error(_("%s expects a numerical value"),
4689 opt->long_name);
4690 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4691 name_width = strtoul(value, &end, 10);
4692 if (*end)
4693 return error(_("%s expects a numerical value"),
4694 opt->long_name);
4695 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4696 graph_width = strtoul(value, &end, 10);
4697 if (*end)
4698 return error(_("%s expects a numerical value"),
4699 opt->long_name);
4700 } else if (!strcmp(opt->long_name, "stat-count")) {
4701 count = strtoul(value, &end, 10);
4702 if (*end)
4703 return error(_("%s expects a numerical value"),
4704 opt->long_name);
4705 } else
4706 BUG("%s should not get here", opt->long_name);
4708 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4709 options->stat_name_width = name_width;
4710 options->stat_graph_width = graph_width;
4711 options->stat_width = width;
4712 options->stat_count = count;
4713 return 0;
4716 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4718 struct strbuf errmsg = STRBUF_INIT;
4719 if (parse_dirstat_params(options, params, &errmsg))
4720 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4721 errmsg.buf);
4722 strbuf_release(&errmsg);
4724 * The caller knows a dirstat-related option is given from the command
4725 * line; allow it to say "return this_function();"
4727 options->output_format |= DIFF_FORMAT_DIRSTAT;
4728 return 1;
4731 static const char diff_status_letters[] = {
4732 DIFF_STATUS_ADDED,
4733 DIFF_STATUS_COPIED,
4734 DIFF_STATUS_DELETED,
4735 DIFF_STATUS_MODIFIED,
4736 DIFF_STATUS_RENAMED,
4737 DIFF_STATUS_TYPE_CHANGED,
4738 DIFF_STATUS_UNKNOWN,
4739 DIFF_STATUS_UNMERGED,
4740 DIFF_STATUS_FILTER_AON,
4741 DIFF_STATUS_FILTER_BROKEN,
4742 '\0',
4745 static unsigned int filter_bit['Z' + 1];
4747 static void prepare_filter_bits(void)
4749 int i;
4751 if (!filter_bit[DIFF_STATUS_ADDED]) {
4752 for (i = 0; diff_status_letters[i]; i++)
4753 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4757 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4759 return opt->filter & filter_bit[(int) status];
4762 unsigned diff_filter_bit(char status)
4764 prepare_filter_bits();
4765 return filter_bit[(int) status];
4768 static int diff_opt_diff_filter(const struct option *option,
4769 const char *optarg, int unset)
4771 struct diff_options *opt = option->value;
4772 int i, optch;
4774 BUG_ON_OPT_NEG(unset);
4775 prepare_filter_bits();
4778 * If there is a negation e.g. 'd' in the input, and we haven't
4779 * initialized the filter field with another --diff-filter, start
4780 * from full set of bits, except for AON.
4782 if (!opt->filter) {
4783 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4784 if (optch < 'a' || 'z' < optch)
4785 continue;
4786 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4787 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4788 break;
4792 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4793 unsigned int bit;
4794 int negate;
4796 if ('a' <= optch && optch <= 'z') {
4797 negate = 1;
4798 optch = toupper(optch);
4799 } else {
4800 negate = 0;
4803 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4804 if (!bit)
4805 return error(_("unknown change class '%c' in --diff-filter=%s"),
4806 optarg[i], optarg);
4807 if (negate)
4808 opt->filter &= ~bit;
4809 else
4810 opt->filter |= bit;
4812 return 0;
4815 static void enable_patch_output(int *fmt)
4817 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4818 *fmt |= DIFF_FORMAT_PATCH;
4821 static int diff_opt_ws_error_highlight(const struct option *option,
4822 const char *arg, int unset)
4824 struct diff_options *opt = option->value;
4825 int val = parse_ws_error_highlight(arg);
4827 BUG_ON_OPT_NEG(unset);
4828 if (val < 0)
4829 return error(_("unknown value after ws-error-highlight=%.*s"),
4830 -1 - val, arg);
4831 opt->ws_error_highlight = val;
4832 return 0;
4835 static int diff_opt_find_object(const struct option *option,
4836 const char *arg, int unset)
4838 struct diff_options *opt = option->value;
4839 struct object_id oid;
4841 BUG_ON_OPT_NEG(unset);
4842 if (get_oid(arg, &oid))
4843 return error(_("unable to resolve '%s'"), arg);
4845 if (!opt->objfind)
4846 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4848 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4849 opt->flags.recursive = 1;
4850 opt->flags.tree_in_recursive = 1;
4851 oidset_insert(opt->objfind, &oid);
4852 return 0;
4855 static int diff_opt_anchored(const struct option *opt,
4856 const char *arg, int unset)
4858 struct diff_options *options = opt->value;
4860 BUG_ON_OPT_NEG(unset);
4861 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4862 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4863 options->anchors_alloc);
4864 options->anchors[options->anchors_nr++] = xstrdup(arg);
4865 return 0;
4868 static int diff_opt_binary(const struct option *opt,
4869 const char *arg, int unset)
4871 struct diff_options *options = opt->value;
4873 BUG_ON_OPT_NEG(unset);
4874 BUG_ON_OPT_ARG(arg);
4875 enable_patch_output(&options->output_format);
4876 options->flags.binary = 1;
4877 return 0;
4880 static int diff_opt_break_rewrites(const struct option *opt,
4881 const char *arg, int unset)
4883 int *break_opt = opt->value;
4884 int opt1, opt2;
4886 BUG_ON_OPT_NEG(unset);
4887 if (!arg)
4888 arg = "";
4889 opt1 = parse_rename_score(&arg);
4890 if (*arg == 0)
4891 opt2 = 0;
4892 else if (*arg != '/')
4893 return error(_("%s expects <n>/<m> form"), opt->long_name);
4894 else {
4895 arg++;
4896 opt2 = parse_rename_score(&arg);
4898 if (*arg != 0)
4899 return error(_("%s expects <n>/<m> form"), opt->long_name);
4900 *break_opt = opt1 | (opt2 << 16);
4901 return 0;
4904 static int diff_opt_char(const struct option *opt,
4905 const char *arg, int unset)
4907 char *value = opt->value;
4909 BUG_ON_OPT_NEG(unset);
4910 if (arg[1])
4911 return error(_("%s expects a character, got '%s'"),
4912 opt->long_name, arg);
4913 *value = arg[0];
4914 return 0;
4917 static int diff_opt_color_moved(const struct option *opt,
4918 const char *arg, int unset)
4920 struct diff_options *options = opt->value;
4922 if (unset) {
4923 options->color_moved = COLOR_MOVED_NO;
4924 } else if (!arg) {
4925 if (diff_color_moved_default)
4926 options->color_moved = diff_color_moved_default;
4927 if (options->color_moved == COLOR_MOVED_NO)
4928 options->color_moved = COLOR_MOVED_DEFAULT;
4929 } else {
4930 int cm = parse_color_moved(arg);
4931 if (cm < 0)
4932 return error(_("bad --color-moved argument: %s"), arg);
4933 options->color_moved = cm;
4935 return 0;
4938 static int diff_opt_color_moved_ws(const struct option *opt,
4939 const char *arg, int unset)
4941 struct diff_options *options = opt->value;
4942 unsigned cm;
4944 if (unset) {
4945 options->color_moved_ws_handling = 0;
4946 return 0;
4949 cm = parse_color_moved_ws(arg);
4950 if (cm & COLOR_MOVED_WS_ERROR)
4951 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
4952 options->color_moved_ws_handling = cm;
4953 return 0;
4956 static int diff_opt_color_words(const struct option *opt,
4957 const char *arg, int unset)
4959 struct diff_options *options = opt->value;
4961 BUG_ON_OPT_NEG(unset);
4962 options->use_color = 1;
4963 options->word_diff = DIFF_WORDS_COLOR;
4964 options->word_regex = arg;
4965 return 0;
4968 static int diff_opt_compact_summary(const struct option *opt,
4969 const char *arg, int unset)
4971 struct diff_options *options = opt->value;
4973 BUG_ON_OPT_ARG(arg);
4974 if (unset) {
4975 options->flags.stat_with_summary = 0;
4976 } else {
4977 options->flags.stat_with_summary = 1;
4978 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4980 return 0;
4983 static int diff_opt_diff_algorithm(const struct option *opt,
4984 const char *arg, int unset)
4986 struct diff_options *options = opt->value;
4987 long value = parse_algorithm_value(arg);
4989 BUG_ON_OPT_NEG(unset);
4990 if (value < 0)
4991 return error(_("option diff-algorithm accepts \"myers\", "
4992 "\"minimal\", \"patience\" and \"histogram\""));
4994 /* clear out previous settings */
4995 DIFF_XDL_CLR(options, NEED_MINIMAL);
4996 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4997 options->xdl_opts |= value;
4998 return 0;
5001 static int diff_opt_dirstat(const struct option *opt,
5002 const char *arg, int unset)
5004 struct diff_options *options = opt->value;
5006 BUG_ON_OPT_NEG(unset);
5007 if (!strcmp(opt->long_name, "cumulative")) {
5008 if (arg)
5009 BUG("how come --cumulative take a value?");
5010 arg = "cumulative";
5011 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5012 parse_dirstat_opt(options, "files");
5013 parse_dirstat_opt(options, arg ? arg : "");
5014 return 0;
5017 static int diff_opt_find_copies(const struct option *opt,
5018 const char *arg, int unset)
5020 struct diff_options *options = opt->value;
5022 BUG_ON_OPT_NEG(unset);
5023 if (!arg)
5024 arg = "";
5025 options->rename_score = parse_rename_score(&arg);
5026 if (*arg != 0)
5027 return error(_("invalid argument to %s"), opt->long_name);
5029 if (options->detect_rename == DIFF_DETECT_COPY)
5030 options->flags.find_copies_harder = 1;
5031 else
5032 options->detect_rename = DIFF_DETECT_COPY;
5034 return 0;
5037 static int diff_opt_find_renames(const struct option *opt,
5038 const char *arg, int unset)
5040 struct diff_options *options = opt->value;
5042 BUG_ON_OPT_NEG(unset);
5043 if (!arg)
5044 arg = "";
5045 options->rename_score = parse_rename_score(&arg);
5046 if (*arg != 0)
5047 return error(_("invalid argument to %s"), opt->long_name);
5049 options->detect_rename = DIFF_DETECT_RENAME;
5050 return 0;
5053 static int diff_opt_follow(const struct option *opt,
5054 const char *arg, int unset)
5056 struct diff_options *options = opt->value;
5058 BUG_ON_OPT_ARG(arg);
5059 if (unset) {
5060 options->flags.follow_renames = 0;
5061 options->flags.default_follow_renames = 0;
5062 } else {
5063 options->flags.follow_renames = 1;
5065 return 0;
5068 static int diff_opt_ignore_submodules(const struct option *opt,
5069 const char *arg, int unset)
5071 struct diff_options *options = opt->value;
5073 BUG_ON_OPT_NEG(unset);
5074 if (!arg)
5075 arg = "all";
5076 options->flags.override_submodule_config = 1;
5077 handle_ignore_submodules_arg(options, arg);
5078 return 0;
5081 static int diff_opt_line_prefix(const struct option *opt,
5082 const char *optarg, int unset)
5084 struct diff_options *options = opt->value;
5086 BUG_ON_OPT_NEG(unset);
5087 options->line_prefix = optarg;
5088 options->line_prefix_length = strlen(options->line_prefix);
5089 graph_setup_line_prefix(options);
5090 return 0;
5093 static int diff_opt_no_prefix(const struct option *opt,
5094 const char *optarg, int unset)
5096 struct diff_options *options = opt->value;
5098 BUG_ON_OPT_NEG(unset);
5099 BUG_ON_OPT_ARG(optarg);
5100 options->a_prefix = "";
5101 options->b_prefix = "";
5102 return 0;
5105 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5106 const struct option *opt,
5107 const char *arg, int unset)
5109 struct diff_options *options = opt->value;
5110 char *path;
5112 BUG_ON_OPT_NEG(unset);
5113 path = prefix_filename(ctx->prefix, arg);
5114 options->file = xfopen(path, "w");
5115 options->close_file = 1;
5116 if (options->use_color != GIT_COLOR_ALWAYS)
5117 options->use_color = GIT_COLOR_NEVER;
5118 free(path);
5119 return 0;
5122 static int diff_opt_patience(const struct option *opt,
5123 const char *arg, int unset)
5125 struct diff_options *options = opt->value;
5126 int i;
5128 BUG_ON_OPT_NEG(unset);
5129 BUG_ON_OPT_ARG(arg);
5130 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5132 * Both --patience and --anchored use PATIENCE_DIFF
5133 * internally, so remove any anchors previously
5134 * specified.
5136 for (i = 0; i < options->anchors_nr; i++)
5137 free(options->anchors[i]);
5138 options->anchors_nr = 0;
5139 return 0;
5142 static int diff_opt_pickaxe_regex(const struct option *opt,
5143 const char *arg, int unset)
5145 struct diff_options *options = opt->value;
5147 BUG_ON_OPT_NEG(unset);
5148 options->pickaxe = arg;
5149 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5150 return 0;
5153 static int diff_opt_pickaxe_string(const struct option *opt,
5154 const char *arg, int unset)
5156 struct diff_options *options = opt->value;
5158 BUG_ON_OPT_NEG(unset);
5159 options->pickaxe = arg;
5160 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5161 return 0;
5164 static int diff_opt_relative(const struct option *opt,
5165 const char *arg, int unset)
5167 struct diff_options *options = opt->value;
5169 BUG_ON_OPT_NEG(unset);
5170 options->flags.relative_name = 1;
5171 if (arg)
5172 options->prefix = arg;
5173 return 0;
5176 static int diff_opt_submodule(const struct option *opt,
5177 const char *arg, int unset)
5179 struct diff_options *options = opt->value;
5181 BUG_ON_OPT_NEG(unset);
5182 if (!arg)
5183 arg = "log";
5184 if (parse_submodule_params(options, arg))
5185 return error(_("failed to parse --submodule option parameter: '%s'"),
5186 arg);
5187 return 0;
5190 static int diff_opt_textconv(const struct option *opt,
5191 const char *arg, int unset)
5193 struct diff_options *options = opt->value;
5195 BUG_ON_OPT_ARG(arg);
5196 if (unset) {
5197 options->flags.allow_textconv = 0;
5198 } else {
5199 options->flags.allow_textconv = 1;
5200 options->flags.textconv_set_via_cmdline = 1;
5202 return 0;
5205 static int diff_opt_unified(const struct option *opt,
5206 const char *arg, int unset)
5208 struct diff_options *options = opt->value;
5209 char *s;
5211 BUG_ON_OPT_NEG(unset);
5213 options->context = strtol(arg, &s, 10);
5214 if (*s)
5215 return error(_("%s expects a numerical value"), "--unified");
5216 enable_patch_output(&options->output_format);
5218 return 0;
5221 static int diff_opt_word_diff(const struct option *opt,
5222 const char *arg, int unset)
5224 struct diff_options *options = opt->value;
5226 BUG_ON_OPT_NEG(unset);
5227 if (arg) {
5228 if (!strcmp(arg, "plain"))
5229 options->word_diff = DIFF_WORDS_PLAIN;
5230 else if (!strcmp(arg, "color")) {
5231 options->use_color = 1;
5232 options->word_diff = DIFF_WORDS_COLOR;
5234 else if (!strcmp(arg, "porcelain"))
5235 options->word_diff = DIFF_WORDS_PORCELAIN;
5236 else if (!strcmp(arg, "none"))
5237 options->word_diff = DIFF_WORDS_NONE;
5238 else
5239 return error(_("bad --word-diff argument: %s"), arg);
5240 } else {
5241 if (options->word_diff == DIFF_WORDS_NONE)
5242 options->word_diff = DIFF_WORDS_PLAIN;
5244 return 0;
5247 static int diff_opt_word_diff_regex(const struct option *opt,
5248 const char *arg, int unset)
5250 struct diff_options *options = opt->value;
5252 BUG_ON_OPT_NEG(unset);
5253 if (options->word_diff == DIFF_WORDS_NONE)
5254 options->word_diff = DIFF_WORDS_PLAIN;
5255 options->word_regex = arg;
5256 return 0;
5259 static void prep_parse_options(struct diff_options *options)
5261 struct option parseopts[] = {
5262 OPT_GROUP(N_("Diff output format options")),
5263 OPT_BITOP('p', "patch", &options->output_format,
5264 N_("generate patch"),
5265 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5266 OPT_BIT_F('s', "no-patch", &options->output_format,
5267 N_("suppress diff output"),
5268 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5269 OPT_BITOP('u', NULL, &options->output_format,
5270 N_("generate patch"),
5271 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5272 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5273 N_("generate diffs with <n> lines context"),
5274 PARSE_OPT_NONEG, diff_opt_unified),
5275 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5276 N_("generate diffs with <n> lines context")),
5277 OPT_BIT_F(0, "raw", &options->output_format,
5278 N_("generate the diff in raw format"),
5279 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5280 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5281 N_("synonym for '-p --raw'"),
5282 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5283 DIFF_FORMAT_NO_OUTPUT),
5284 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5285 N_("synonym for '-p --stat'"),
5286 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5287 DIFF_FORMAT_NO_OUTPUT),
5288 OPT_BIT_F(0, "numstat", &options->output_format,
5289 N_("machine friendly --stat"),
5290 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5291 OPT_BIT_F(0, "shortstat", &options->output_format,
5292 N_("output only the last line of --stat"),
5293 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5294 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5295 N_("output the distribution of relative amount of changes for each sub-directory"),
5296 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5297 diff_opt_dirstat),
5298 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5299 N_("synonym for --dirstat=cumulative"),
5300 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5301 diff_opt_dirstat),
5302 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5303 N_("synonym for --dirstat=files,param1,param2..."),
5304 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5305 diff_opt_dirstat),
5306 OPT_BIT_F(0, "check", &options->output_format,
5307 N_("warn if changes introduce conflict markers or whitespace errors"),
5308 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5309 OPT_BIT_F(0, "summary", &options->output_format,
5310 N_("condensed summary such as creations, renames and mode changes"),
5311 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5312 OPT_BIT_F(0, "name-only", &options->output_format,
5313 N_("show only names of changed files"),
5314 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5315 OPT_BIT_F(0, "name-status", &options->output_format,
5316 N_("show only names and status of changed files"),
5317 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5318 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5319 N_("generate diffstat"),
5320 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5321 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5322 N_("generate diffstat with a given width"),
5323 PARSE_OPT_NONEG, diff_opt_stat),
5324 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5325 N_("generate diffstat with a given name width"),
5326 PARSE_OPT_NONEG, diff_opt_stat),
5327 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5328 N_("generate diffstat with a given graph width"),
5329 PARSE_OPT_NONEG, diff_opt_stat),
5330 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5331 N_("generate diffstat with limited lines"),
5332 PARSE_OPT_NONEG, diff_opt_stat),
5333 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5334 N_("generate compact summary in diffstat"),
5335 PARSE_OPT_NOARG, diff_opt_compact_summary),
5336 OPT_CALLBACK_F(0, "binary", options, NULL,
5337 N_("output a binary diff that can be applied"),
5338 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5339 OPT_BOOL(0, "full-index", &options->flags.full_index,
5340 N_("show full pre- and post-image object names on the \"index\" lines")),
5341 OPT_COLOR_FLAG(0, "color", &options->use_color,
5342 N_("show colored diff")),
5343 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5344 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5345 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
5346 OPT_SET_INT('z', NULL, &options->line_termination,
5347 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5349 OPT__ABBREV(&options->abbrev),
5350 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5351 N_("show the given source prefix instead of \"a/\""),
5352 PARSE_OPT_NONEG),
5353 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
5354 N_("show the given source prefix instead of \"b/\""),
5355 PARSE_OPT_NONEG),
5356 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5357 N_("prepend an additional prefix to every line of output"),
5358 PARSE_OPT_NONEG, diff_opt_line_prefix),
5359 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5360 N_("do not show any source or destination prefix"),
5361 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
5362 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5363 N_("show context between diff hunks up to the specified number of lines"),
5364 PARSE_OPT_NONEG),
5365 OPT_CALLBACK_F(0, "output-indicator-new",
5366 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5367 N_("<char>"),
5368 N_("specify the character to indicate a new line instead of '+'"),
5369 PARSE_OPT_NONEG, diff_opt_char),
5370 OPT_CALLBACK_F(0, "output-indicator-old",
5371 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5372 N_("<char>"),
5373 N_("specify the character to indicate an old line instead of '-'"),
5374 PARSE_OPT_NONEG, diff_opt_char),
5375 OPT_CALLBACK_F(0, "output-indicator-context",
5376 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5377 N_("<char>"),
5378 N_("specify the character to indicate a context instead of ' '"),
5379 PARSE_OPT_NONEG, diff_opt_char),
5381 OPT_GROUP(N_("Diff rename options")),
5382 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5383 N_("break complete rewrite changes into pairs of delete and create"),
5384 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5385 diff_opt_break_rewrites),
5386 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5387 N_("detect renames"),
5388 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5389 diff_opt_find_renames),
5390 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5391 N_("omit the preimage for deletes"),
5392 1, PARSE_OPT_NONEG),
5393 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5394 N_("detect copies"),
5395 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5396 diff_opt_find_copies),
5397 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5398 N_("use unmodified files as source to find copies")),
5399 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5400 N_("disable rename detection"),
5401 0, PARSE_OPT_NONEG),
5402 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5403 N_("use empty blobs as rename source")),
5404 OPT_CALLBACK_F(0, "follow", options, NULL,
5405 N_("continue listing the history of a file beyond renames"),
5406 PARSE_OPT_NOARG, diff_opt_follow),
5407 OPT_INTEGER('l', NULL, &options->rename_limit,
5408 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
5410 OPT_GROUP(N_("Diff algorithm options")),
5411 OPT_BIT(0, "minimal", &options->xdl_opts,
5412 N_("produce the smallest possible diff"),
5413 XDF_NEED_MINIMAL),
5414 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5415 N_("ignore whitespace when comparing lines"),
5416 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5417 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5418 N_("ignore changes in amount of whitespace"),
5419 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5420 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5421 N_("ignore changes in whitespace at EOL"),
5422 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5423 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5424 N_("ignore carrier-return at the end of line"),
5425 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5426 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5427 N_("ignore changes whose lines are all blank"),
5428 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5429 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5430 N_("heuristic to shift diff hunk boundaries for easy reading"),
5431 XDF_INDENT_HEURISTIC),
5432 OPT_CALLBACK_F(0, "patience", options, NULL,
5433 N_("generate diff using the \"patience diff\" algorithm"),
5434 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5435 diff_opt_patience),
5436 OPT_BITOP(0, "histogram", &options->xdl_opts,
5437 N_("generate diff using the \"histogram diff\" algorithm"),
5438 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5439 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5440 N_("choose a diff algorithm"),
5441 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5442 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5443 N_("generate diff using the \"anchored diff\" algorithm"),
5444 PARSE_OPT_NONEG, diff_opt_anchored),
5445 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5446 N_("show word diff, using <mode> to delimit changed words"),
5447 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5448 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5449 N_("use <regex> to decide what a word is"),
5450 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5451 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5452 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5453 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5454 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
5455 N_("move lines of code are colored differently"),
5456 PARSE_OPT_OPTARG, diff_opt_color_moved),
5457 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5458 N_("how white spaces are ignored in --color-moved"),
5459 0, diff_opt_color_moved_ws),
5461 OPT_GROUP(N_("Diff other options")),
5462 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5463 N_("when run from subdir, exclude changes outside and show relative paths"),
5464 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5465 diff_opt_relative),
5466 OPT_BOOL('a', "text", &options->flags.text,
5467 N_("treat all files as text")),
5468 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5469 N_("swap two inputs, reverse the diff")),
5470 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5471 N_("exit with 1 if there were differences, 0 otherwise")),
5472 OPT_BOOL(0, "quiet", &options->flags.quick,
5473 N_("disable all output of the program")),
5474 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5475 N_("allow an external diff helper to be executed")),
5476 OPT_CALLBACK_F(0, "textconv", options, NULL,
5477 N_("run external text conversion filters when comparing binary files"),
5478 PARSE_OPT_NOARG, diff_opt_textconv),
5479 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5480 N_("ignore changes to submodules in the diff generation"),
5481 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5482 diff_opt_ignore_submodules),
5483 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5484 N_("specify how differences in submodules are shown"),
5485 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5486 diff_opt_submodule),
5487 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5488 N_("hide 'git add -N' entries from the index"),
5489 1, PARSE_OPT_NONEG),
5490 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5491 N_("treat 'git add -N' entries as real in the index"),
5492 0, PARSE_OPT_NONEG),
5493 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5494 N_("look for differences that change the number of occurrences of the specified string"),
5495 0, diff_opt_pickaxe_string),
5496 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5497 N_("look for differences that change the number of occurrences of the specified regex"),
5498 0, diff_opt_pickaxe_regex),
5499 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5500 N_("show all changes in the changeset with -S or -G"),
5501 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5502 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5503 N_("treat <string> in -S as extended POSIX regular expression"),
5504 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
5505 OPT_FILENAME('O', NULL, &options->orderfile,
5506 N_("control the order in which files appear in the output")),
5507 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5508 N_("look for differences that change the number of occurrences of the specified object"),
5509 PARSE_OPT_NONEG, diff_opt_find_object),
5510 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5511 N_("select files by diff type"),
5512 PARSE_OPT_NONEG, diff_opt_diff_filter),
5513 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5514 N_("Output to a specific file"),
5515 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5517 OPT_END()
5520 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5521 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5524 int diff_opt_parse(struct diff_options *options,
5525 const char **av, int ac, const char *prefix)
5527 if (!prefix)
5528 prefix = "";
5530 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5531 PARSE_OPT_KEEP_DASHDASH |
5532 PARSE_OPT_KEEP_UNKNOWN |
5533 PARSE_OPT_NO_INTERNAL_HELP |
5534 PARSE_OPT_ONE_SHOT |
5535 PARSE_OPT_STOP_AT_NON_OPTION);
5537 return ac;
5540 int parse_rename_score(const char **cp_p)
5542 unsigned long num, scale;
5543 int ch, dot;
5544 const char *cp = *cp_p;
5546 num = 0;
5547 scale = 1;
5548 dot = 0;
5549 for (;;) {
5550 ch = *cp;
5551 if ( !dot && ch == '.' ) {
5552 scale = 1;
5553 dot = 1;
5554 } else if ( ch == '%' ) {
5555 scale = dot ? scale*100 : 100;
5556 cp++; /* % is always at the end */
5557 break;
5558 } else if ( ch >= '0' && ch <= '9' ) {
5559 if ( scale < 100000 ) {
5560 scale *= 10;
5561 num = (num*10) + (ch-'0');
5563 } else {
5564 break;
5566 cp++;
5568 *cp_p = cp;
5570 /* user says num divided by scale and we say internally that
5571 * is MAX_SCORE * num / scale.
5573 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5576 struct diff_queue_struct diff_queued_diff;
5578 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5580 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5581 queue->queue[queue->nr++] = dp;
5584 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5585 struct diff_filespec *one,
5586 struct diff_filespec *two)
5588 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5589 dp->one = one;
5590 dp->two = two;
5591 if (queue)
5592 diff_q(queue, dp);
5593 return dp;
5596 void diff_free_filepair(struct diff_filepair *p)
5598 free_filespec(p->one);
5599 free_filespec(p->two);
5600 free(p);
5603 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5605 int abblen;
5606 const char *abbrev;
5608 /* Do we want all 40 hex characters? */
5609 if (len == the_hash_algo->hexsz)
5610 return oid_to_hex(oid);
5612 /* An abbreviated value is fine, possibly followed by an ellipsis. */
5613 abbrev = diff_abbrev_oid(oid, len);
5615 if (!print_sha1_ellipsis())
5616 return abbrev;
5618 abblen = strlen(abbrev);
5621 * In well-behaved cases, where the abbreviated result is the
5622 * same as the requested length, append three dots after the
5623 * abbreviation (hence the whole logic is limited to the case
5624 * where abblen < 37); when the actual abbreviated result is a
5625 * bit longer than the requested length, we reduce the number
5626 * of dots so that they match the well-behaved ones. However,
5627 * if the actual abbreviation is longer than the requested
5628 * length by more than three, we give up on aligning, and add
5629 * three dots anyway, to indicate that the output is not the
5630 * full object name. Yes, this may be suboptimal, but this
5631 * appears only in "diff --raw --abbrev" output and it is not
5632 * worth the effort to change it now. Note that this would
5633 * likely to work fine when the automatic sizing of default
5634 * abbreviation length is used--we would be fed -1 in "len" in
5635 * that case, and will end up always appending three-dots, but
5636 * the automatic sizing is supposed to give abblen that ensures
5637 * uniqueness across all objects (statistically speaking).
5639 if (abblen < the_hash_algo->hexsz - 3) {
5640 static char hex[GIT_MAX_HEXSZ + 1];
5641 if (len < abblen && abblen <= len + 2)
5642 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5643 else
5644 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5645 return hex;
5648 return oid_to_hex(oid);
5651 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5653 int line_termination = opt->line_termination;
5654 int inter_name_termination = line_termination ? '\t' : '\0';
5656 fprintf(opt->file, "%s", diff_line_prefix(opt));
5657 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5658 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5659 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5660 fprintf(opt->file, "%s ",
5661 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5663 if (p->score) {
5664 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5665 inter_name_termination);
5666 } else {
5667 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5670 if (p->status == DIFF_STATUS_COPIED ||
5671 p->status == DIFF_STATUS_RENAMED) {
5672 const char *name_a, *name_b;
5673 name_a = p->one->path;
5674 name_b = p->two->path;
5675 strip_prefix(opt->prefix_length, &name_a, &name_b);
5676 write_name_quoted(name_a, opt->file, inter_name_termination);
5677 write_name_quoted(name_b, opt->file, line_termination);
5678 } else {
5679 const char *name_a, *name_b;
5680 name_a = p->one->mode ? p->one->path : p->two->path;
5681 name_b = NULL;
5682 strip_prefix(opt->prefix_length, &name_a, &name_b);
5683 write_name_quoted(name_a, opt->file, line_termination);
5687 int diff_unmodified_pair(struct diff_filepair *p)
5689 /* This function is written stricter than necessary to support
5690 * the currently implemented transformers, but the idea is to
5691 * let transformers to produce diff_filepairs any way they want,
5692 * and filter and clean them up here before producing the output.
5694 struct diff_filespec *one = p->one, *two = p->two;
5696 if (DIFF_PAIR_UNMERGED(p))
5697 return 0; /* unmerged is interesting */
5699 /* deletion, addition, mode or type change
5700 * and rename are all interesting.
5702 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5703 DIFF_PAIR_MODE_CHANGED(p) ||
5704 strcmp(one->path, two->path))
5705 return 0;
5707 /* both are valid and point at the same path. that is, we are
5708 * dealing with a change.
5710 if (one->oid_valid && two->oid_valid &&
5711 oideq(&one->oid, &two->oid) &&
5712 !one->dirty_submodule && !two->dirty_submodule)
5713 return 1; /* no change */
5714 if (!one->oid_valid && !two->oid_valid)
5715 return 1; /* both look at the same file on the filesystem. */
5716 return 0;
5719 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5721 if (diff_unmodified_pair(p))
5722 return;
5724 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5725 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5726 return; /* no tree diffs in patch format */
5728 run_diff(p, o);
5731 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5732 struct diffstat_t *diffstat)
5734 if (diff_unmodified_pair(p))
5735 return;
5737 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5738 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5739 return; /* no useful stat for tree diffs */
5741 run_diffstat(p, o, diffstat);
5744 static void diff_flush_checkdiff(struct diff_filepair *p,
5745 struct diff_options *o)
5747 if (diff_unmodified_pair(p))
5748 return;
5750 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5751 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5752 return; /* nothing to check in tree diffs */
5754 run_checkdiff(p, o);
5757 int diff_queue_is_empty(void)
5759 struct diff_queue_struct *q = &diff_queued_diff;
5760 int i;
5761 for (i = 0; i < q->nr; i++)
5762 if (!diff_unmodified_pair(q->queue[i]))
5763 return 0;
5764 return 1;
5767 #if DIFF_DEBUG
5768 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5770 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5771 x, one ? one : "",
5772 s->path,
5773 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5774 s->mode,
5775 s->oid_valid ? oid_to_hex(&s->oid) : "");
5776 fprintf(stderr, "queue[%d] %s size %lu\n",
5777 x, one ? one : "",
5778 s->size);
5781 void diff_debug_filepair(const struct diff_filepair *p, int i)
5783 diff_debug_filespec(p->one, i, "one");
5784 diff_debug_filespec(p->two, i, "two");
5785 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5786 p->score, p->status ? p->status : '?',
5787 p->one->rename_used, p->broken_pair);
5790 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5792 int i;
5793 if (msg)
5794 fprintf(stderr, "%s\n", msg);
5795 fprintf(stderr, "q->nr = %d\n", q->nr);
5796 for (i = 0; i < q->nr; i++) {
5797 struct diff_filepair *p = q->queue[i];
5798 diff_debug_filepair(p, i);
5801 #endif
5803 static void diff_resolve_rename_copy(void)
5805 int i;
5806 struct diff_filepair *p;
5807 struct diff_queue_struct *q = &diff_queued_diff;
5809 diff_debug_queue("resolve-rename-copy", q);
5811 for (i = 0; i < q->nr; i++) {
5812 p = q->queue[i];
5813 p->status = 0; /* undecided */
5814 if (DIFF_PAIR_UNMERGED(p))
5815 p->status = DIFF_STATUS_UNMERGED;
5816 else if (!DIFF_FILE_VALID(p->one))
5817 p->status = DIFF_STATUS_ADDED;
5818 else if (!DIFF_FILE_VALID(p->two))
5819 p->status = DIFF_STATUS_DELETED;
5820 else if (DIFF_PAIR_TYPE_CHANGED(p))
5821 p->status = DIFF_STATUS_TYPE_CHANGED;
5823 /* from this point on, we are dealing with a pair
5824 * whose both sides are valid and of the same type, i.e.
5825 * either in-place edit or rename/copy edit.
5827 else if (DIFF_PAIR_RENAME(p)) {
5829 * A rename might have re-connected a broken
5830 * pair up, causing the pathnames to be the
5831 * same again. If so, that's not a rename at
5832 * all, just a modification..
5834 * Otherwise, see if this source was used for
5835 * multiple renames, in which case we decrement
5836 * the count, and call it a copy.
5838 if (!strcmp(p->one->path, p->two->path))
5839 p->status = DIFF_STATUS_MODIFIED;
5840 else if (--p->one->rename_used > 0)
5841 p->status = DIFF_STATUS_COPIED;
5842 else
5843 p->status = DIFF_STATUS_RENAMED;
5845 else if (!oideq(&p->one->oid, &p->two->oid) ||
5846 p->one->mode != p->two->mode ||
5847 p->one->dirty_submodule ||
5848 p->two->dirty_submodule ||
5849 is_null_oid(&p->one->oid))
5850 p->status = DIFF_STATUS_MODIFIED;
5851 else {
5852 /* This is a "no-change" entry and should not
5853 * happen anymore, but prepare for broken callers.
5855 error("feeding unmodified %s to diffcore",
5856 p->one->path);
5857 p->status = DIFF_STATUS_UNKNOWN;
5860 diff_debug_queue("resolve-rename-copy done", q);
5863 static int check_pair_status(struct diff_filepair *p)
5865 switch (p->status) {
5866 case DIFF_STATUS_UNKNOWN:
5867 return 0;
5868 case 0:
5869 die("internal error in diff-resolve-rename-copy");
5870 default:
5871 return 1;
5875 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5877 int fmt = opt->output_format;
5879 if (fmt & DIFF_FORMAT_CHECKDIFF)
5880 diff_flush_checkdiff(p, opt);
5881 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5882 diff_flush_raw(p, opt);
5883 else if (fmt & DIFF_FORMAT_NAME) {
5884 const char *name_a, *name_b;
5885 name_a = p->two->path;
5886 name_b = NULL;
5887 strip_prefix(opt->prefix_length, &name_a, &name_b);
5888 fprintf(opt->file, "%s", diff_line_prefix(opt));
5889 write_name_quoted(name_a, opt->file, opt->line_termination);
5893 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5895 struct strbuf sb = STRBUF_INIT;
5896 if (fs->mode)
5897 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5898 else
5899 strbuf_addf(&sb, " %s ", newdelete);
5901 quote_c_style(fs->path, &sb, NULL, 0);
5902 strbuf_addch(&sb, '\n');
5903 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5904 sb.buf, sb.len, 0);
5905 strbuf_release(&sb);
5908 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5909 int show_name)
5911 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5912 struct strbuf sb = STRBUF_INIT;
5913 strbuf_addf(&sb, " mode change %06o => %06o",
5914 p->one->mode, p->two->mode);
5915 if (show_name) {
5916 strbuf_addch(&sb, ' ');
5917 quote_c_style(p->two->path, &sb, NULL, 0);
5919 strbuf_addch(&sb, '\n');
5920 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5921 sb.buf, sb.len, 0);
5922 strbuf_release(&sb);
5926 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5927 struct diff_filepair *p)
5929 struct strbuf sb = STRBUF_INIT;
5930 struct strbuf names = STRBUF_INIT;
5932 pprint_rename(&names, p->one->path, p->two->path);
5933 strbuf_addf(&sb, " %s %s (%d%%)\n",
5934 renamecopy, names.buf, similarity_index(p));
5935 strbuf_release(&names);
5936 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5937 sb.buf, sb.len, 0);
5938 show_mode_change(opt, p, 0);
5939 strbuf_release(&sb);
5942 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5944 switch(p->status) {
5945 case DIFF_STATUS_DELETED:
5946 show_file_mode_name(opt, "delete", p->one);
5947 break;
5948 case DIFF_STATUS_ADDED:
5949 show_file_mode_name(opt, "create", p->two);
5950 break;
5951 case DIFF_STATUS_COPIED:
5952 show_rename_copy(opt, "copy", p);
5953 break;
5954 case DIFF_STATUS_RENAMED:
5955 show_rename_copy(opt, "rename", p);
5956 break;
5957 default:
5958 if (p->score) {
5959 struct strbuf sb = STRBUF_INIT;
5960 strbuf_addstr(&sb, " rewrite ");
5961 quote_c_style(p->two->path, &sb, NULL, 0);
5962 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5963 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5964 sb.buf, sb.len, 0);
5965 strbuf_release(&sb);
5967 show_mode_change(opt, p, !p->score);
5968 break;
5972 struct patch_id_t {
5973 git_SHA_CTX *ctx;
5974 int patchlen;
5977 static int remove_space(char *line, int len)
5979 int i;
5980 char *dst = line;
5981 unsigned char c;
5983 for (i = 0; i < len; i++)
5984 if (!isspace((c = line[i])))
5985 *dst++ = c;
5987 return dst - line;
5990 static void patch_id_consume(void *priv, char *line, unsigned long len)
5992 struct patch_id_t *data = priv;
5993 int new_len;
5995 new_len = remove_space(line, len);
5997 git_SHA1_Update(data->ctx, line, new_len);
5998 data->patchlen += new_len;
6001 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
6003 git_SHA1_Update(ctx, str, strlen(str));
6006 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
6008 /* large enough for 2^32 in octal */
6009 char buf[12];
6010 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6011 git_SHA1_Update(ctx, buf, len);
6014 /* returns 0 upon success, and writes result into sha1 */
6015 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6017 struct diff_queue_struct *q = &diff_queued_diff;
6018 int i;
6019 git_SHA_CTX ctx;
6020 struct patch_id_t data;
6022 git_SHA1_Init(&ctx);
6023 memset(&data, 0, sizeof(struct patch_id_t));
6024 data.ctx = &ctx;
6026 for (i = 0; i < q->nr; i++) {
6027 xpparam_t xpp;
6028 xdemitconf_t xecfg;
6029 mmfile_t mf1, mf2;
6030 struct diff_filepair *p = q->queue[i];
6031 int len1, len2;
6033 memset(&xpp, 0, sizeof(xpp));
6034 memset(&xecfg, 0, sizeof(xecfg));
6035 if (p->status == 0)
6036 return error("internal diff status error");
6037 if (p->status == DIFF_STATUS_UNKNOWN)
6038 continue;
6039 if (diff_unmodified_pair(p))
6040 continue;
6041 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6042 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6043 continue;
6044 if (DIFF_PAIR_UNMERGED(p))
6045 continue;
6047 diff_fill_oid_info(p->one, options->repo->index);
6048 diff_fill_oid_info(p->two, options->repo->index);
6050 len1 = remove_space(p->one->path, strlen(p->one->path));
6051 len2 = remove_space(p->two->path, strlen(p->two->path));
6052 patch_id_add_string(&ctx, "diff--git");
6053 patch_id_add_string(&ctx, "a/");
6054 git_SHA1_Update(&ctx, p->one->path, len1);
6055 patch_id_add_string(&ctx, "b/");
6056 git_SHA1_Update(&ctx, p->two->path, len2);
6058 if (p->one->mode == 0) {
6059 patch_id_add_string(&ctx, "newfilemode");
6060 patch_id_add_mode(&ctx, p->two->mode);
6061 patch_id_add_string(&ctx, "---/dev/null");
6062 patch_id_add_string(&ctx, "+++b/");
6063 git_SHA1_Update(&ctx, p->two->path, len2);
6064 } else if (p->two->mode == 0) {
6065 patch_id_add_string(&ctx, "deletedfilemode");
6066 patch_id_add_mode(&ctx, p->one->mode);
6067 patch_id_add_string(&ctx, "---a/");
6068 git_SHA1_Update(&ctx, p->one->path, len1);
6069 patch_id_add_string(&ctx, "+++/dev/null");
6070 } else {
6071 patch_id_add_string(&ctx, "---a/");
6072 git_SHA1_Update(&ctx, p->one->path, len1);
6073 patch_id_add_string(&ctx, "+++b/");
6074 git_SHA1_Update(&ctx, p->two->path, len2);
6077 if (diff_header_only)
6078 continue;
6080 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6081 fill_mmfile(options->repo, &mf2, p->two) < 0)
6082 return error("unable to read files to diff");
6084 if (diff_filespec_is_binary(options->repo, p->one) ||
6085 diff_filespec_is_binary(options->repo, p->two)) {
6086 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
6087 GIT_SHA1_HEXSZ);
6088 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
6089 GIT_SHA1_HEXSZ);
6090 continue;
6093 xpp.flags = 0;
6094 xecfg.ctxlen = 3;
6095 xecfg.flags = 0;
6096 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
6097 patch_id_consume, &data, &xpp, &xecfg))
6098 return error("unable to generate patch-id diff for %s",
6099 p->one->path);
6102 git_SHA1_Final(oid->hash, &ctx);
6103 return 0;
6106 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6108 struct diff_queue_struct *q = &diff_queued_diff;
6109 int i;
6110 int result = diff_get_patch_id(options, oid, diff_header_only);
6112 for (i = 0; i < q->nr; i++)
6113 diff_free_filepair(q->queue[i]);
6115 free(q->queue);
6116 DIFF_QUEUE_CLEAR(q);
6118 return result;
6121 static int is_summary_empty(const struct diff_queue_struct *q)
6123 int i;
6125 for (i = 0; i < q->nr; i++) {
6126 const struct diff_filepair *p = q->queue[i];
6128 switch (p->status) {
6129 case DIFF_STATUS_DELETED:
6130 case DIFF_STATUS_ADDED:
6131 case DIFF_STATUS_COPIED:
6132 case DIFF_STATUS_RENAMED:
6133 return 0;
6134 default:
6135 if (p->score)
6136 return 0;
6137 if (p->one->mode && p->two->mode &&
6138 p->one->mode != p->two->mode)
6139 return 0;
6140 break;
6143 return 1;
6146 static const char rename_limit_warning[] =
6147 N_("inexact rename detection was skipped due to too many files.");
6149 static const char degrade_cc_to_c_warning[] =
6150 N_("only found copies from modified paths due to too many files.");
6152 static const char rename_limit_advice[] =
6153 N_("you may want to set your %s variable to at least "
6154 "%d and retry the command.");
6156 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6158 fflush(stdout);
6159 if (degraded_cc)
6160 warning(_(degrade_cc_to_c_warning));
6161 else if (needed)
6162 warning(_(rename_limit_warning));
6163 else
6164 return;
6165 if (0 < needed)
6166 warning(_(rename_limit_advice), varname, needed);
6169 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6171 int i;
6172 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6173 struct diff_queue_struct *q = &diff_queued_diff;
6175 if (WSEH_NEW & WS_RULE_MASK)
6176 BUG("WS rules bit mask overlaps with diff symbol flags");
6178 if (o->color_moved)
6179 o->emitted_symbols = &esm;
6181 for (i = 0; i < q->nr; i++) {
6182 struct diff_filepair *p = q->queue[i];
6183 if (check_pair_status(p))
6184 diff_flush_patch(p, o);
6187 if (o->emitted_symbols) {
6188 if (o->color_moved) {
6189 struct hashmap add_lines, del_lines;
6191 if (o->color_moved_ws_handling &
6192 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
6193 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
6195 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
6196 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
6198 add_lines_to_move_detection(o, &add_lines, &del_lines);
6199 mark_color_as_moved(o, &add_lines, &del_lines);
6200 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6201 dim_moved_lines(o);
6203 hashmap_free(&add_lines, 1);
6204 hashmap_free(&del_lines, 1);
6207 for (i = 0; i < esm.nr; i++)
6208 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6210 for (i = 0; i < esm.nr; i++)
6211 free((void *)esm.buf[i].line);
6212 esm.nr = 0;
6214 o->emitted_symbols = NULL;
6218 void diff_flush(struct diff_options *options)
6220 struct diff_queue_struct *q = &diff_queued_diff;
6221 int i, output_format = options->output_format;
6222 int separator = 0;
6223 int dirstat_by_line = 0;
6226 * Order: raw, stat, summary, patch
6227 * or: name/name-status/checkdiff (other bits clear)
6229 if (!q->nr)
6230 goto free_queue;
6232 if (output_format & (DIFF_FORMAT_RAW |
6233 DIFF_FORMAT_NAME |
6234 DIFF_FORMAT_NAME_STATUS |
6235 DIFF_FORMAT_CHECKDIFF)) {
6236 for (i = 0; i < q->nr; i++) {
6237 struct diff_filepair *p = q->queue[i];
6238 if (check_pair_status(p))
6239 flush_one_pair(p, options);
6241 separator++;
6244 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6245 dirstat_by_line = 1;
6247 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6248 dirstat_by_line) {
6249 struct diffstat_t diffstat;
6251 memset(&diffstat, 0, sizeof(struct diffstat_t));
6252 for (i = 0; i < q->nr; i++) {
6253 struct diff_filepair *p = q->queue[i];
6254 if (check_pair_status(p))
6255 diff_flush_stat(p, options, &diffstat);
6257 if (output_format & DIFF_FORMAT_NUMSTAT)
6258 show_numstat(&diffstat, options);
6259 if (output_format & DIFF_FORMAT_DIFFSTAT)
6260 show_stats(&diffstat, options);
6261 if (output_format & DIFF_FORMAT_SHORTSTAT)
6262 show_shortstats(&diffstat, options);
6263 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6264 show_dirstat_by_line(&diffstat, options);
6265 free_diffstat_info(&diffstat);
6266 separator++;
6268 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6269 show_dirstat(options);
6271 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6272 for (i = 0; i < q->nr; i++) {
6273 diff_summary(options, q->queue[i]);
6275 separator++;
6278 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6279 options->flags.exit_with_status &&
6280 options->flags.diff_from_contents) {
6282 * run diff_flush_patch for the exit status. setting
6283 * options->file to /dev/null should be safe, because we
6284 * aren't supposed to produce any output anyway.
6286 if (options->close_file)
6287 fclose(options->file);
6288 options->file = xfopen("/dev/null", "w");
6289 options->close_file = 1;
6290 options->color_moved = 0;
6291 for (i = 0; i < q->nr; i++) {
6292 struct diff_filepair *p = q->queue[i];
6293 if (check_pair_status(p))
6294 diff_flush_patch(p, options);
6295 if (options->found_changes)
6296 break;
6300 if (output_format & DIFF_FORMAT_PATCH) {
6301 if (separator) {
6302 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6303 if (options->stat_sep)
6304 /* attach patch instead of inline */
6305 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6306 NULL, 0, 0);
6309 diff_flush_patch_all_file_pairs(options);
6312 if (output_format & DIFF_FORMAT_CALLBACK)
6313 options->format_callback(q, options, options->format_callback_data);
6315 for (i = 0; i < q->nr; i++)
6316 diff_free_filepair(q->queue[i]);
6317 free_queue:
6318 free(q->queue);
6319 DIFF_QUEUE_CLEAR(q);
6320 if (options->close_file)
6321 fclose(options->file);
6324 * Report the content-level differences with HAS_CHANGES;
6325 * diff_addremove/diff_change does not set the bit when
6326 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6328 if (options->flags.diff_from_contents) {
6329 if (options->found_changes)
6330 options->flags.has_changes = 1;
6331 else
6332 options->flags.has_changes = 0;
6336 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6338 return (((p->status == DIFF_STATUS_MODIFIED) &&
6339 ((p->score &&
6340 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6341 (!p->score &&
6342 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6343 ((p->status != DIFF_STATUS_MODIFIED) &&
6344 filter_bit_tst(p->status, options)));
6347 static void diffcore_apply_filter(struct diff_options *options)
6349 int i;
6350 struct diff_queue_struct *q = &diff_queued_diff;
6351 struct diff_queue_struct outq;
6353 DIFF_QUEUE_CLEAR(&outq);
6355 if (!options->filter)
6356 return;
6358 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6359 int found;
6360 for (i = found = 0; !found && i < q->nr; i++) {
6361 if (match_filter(options, q->queue[i]))
6362 found++;
6364 if (found)
6365 return;
6367 /* otherwise we will clear the whole queue
6368 * by copying the empty outq at the end of this
6369 * function, but first clear the current entries
6370 * in the queue.
6372 for (i = 0; i < q->nr; i++)
6373 diff_free_filepair(q->queue[i]);
6375 else {
6376 /* Only the matching ones */
6377 for (i = 0; i < q->nr; i++) {
6378 struct diff_filepair *p = q->queue[i];
6379 if (match_filter(options, p))
6380 diff_q(&outq, p);
6381 else
6382 diff_free_filepair(p);
6385 free(q->queue);
6386 *q = outq;
6389 /* Check whether two filespecs with the same mode and size are identical */
6390 static int diff_filespec_is_identical(struct repository *r,
6391 struct diff_filespec *one,
6392 struct diff_filespec *two)
6394 if (S_ISGITLINK(one->mode))
6395 return 0;
6396 if (diff_populate_filespec(r, one, 0))
6397 return 0;
6398 if (diff_populate_filespec(r, two, 0))
6399 return 0;
6400 return !memcmp(one->data, two->data, one->size);
6403 static int diff_filespec_check_stat_unmatch(struct repository *r,
6404 struct diff_filepair *p)
6406 if (p->done_skip_stat_unmatch)
6407 return p->skip_stat_unmatch_result;
6409 p->done_skip_stat_unmatch = 1;
6410 p->skip_stat_unmatch_result = 0;
6412 * 1. Entries that come from stat info dirtiness
6413 * always have both sides (iow, not create/delete),
6414 * one side of the object name is unknown, with
6415 * the same mode and size. Keep the ones that
6416 * do not match these criteria. They have real
6417 * differences.
6419 * 2. At this point, the file is known to be modified,
6420 * with the same mode and size, and the object
6421 * name of one side is unknown. Need to inspect
6422 * the identical contents.
6424 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6425 !DIFF_FILE_VALID(p->two) ||
6426 (p->one->oid_valid && p->two->oid_valid) ||
6427 (p->one->mode != p->two->mode) ||
6428 diff_populate_filespec(r, p->one, CHECK_SIZE_ONLY) ||
6429 diff_populate_filespec(r, p->two, CHECK_SIZE_ONLY) ||
6430 (p->one->size != p->two->size) ||
6431 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6432 p->skip_stat_unmatch_result = 1;
6433 return p->skip_stat_unmatch_result;
6436 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6438 int i;
6439 struct diff_queue_struct *q = &diff_queued_diff;
6440 struct diff_queue_struct outq;
6441 DIFF_QUEUE_CLEAR(&outq);
6443 for (i = 0; i < q->nr; i++) {
6444 struct diff_filepair *p = q->queue[i];
6446 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6447 diff_q(&outq, p);
6448 else {
6450 * The caller can subtract 1 from skip_stat_unmatch
6451 * to determine how many paths were dirty only
6452 * due to stat info mismatch.
6454 if (!diffopt->flags.no_index)
6455 diffopt->skip_stat_unmatch++;
6456 diff_free_filepair(p);
6459 free(q->queue);
6460 *q = outq;
6463 static int diffnamecmp(const void *a_, const void *b_)
6465 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6466 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6467 const char *name_a, *name_b;
6469 name_a = a->one ? a->one->path : a->two->path;
6470 name_b = b->one ? b->one->path : b->two->path;
6471 return strcmp(name_a, name_b);
6474 void diffcore_fix_diff_index(void)
6476 struct diff_queue_struct *q = &diff_queued_diff;
6477 QSORT(q->queue, q->nr, diffnamecmp);
6480 void diffcore_std(struct diff_options *options)
6482 /* NOTE please keep the following in sync with diff_tree_combined() */
6483 if (options->skip_stat_unmatch)
6484 diffcore_skip_stat_unmatch(options);
6485 if (!options->found_follow) {
6486 /* See try_to_follow_renames() in tree-diff.c */
6487 if (options->break_opt != -1)
6488 diffcore_break(options->repo,
6489 options->break_opt);
6490 if (options->detect_rename)
6491 diffcore_rename(options);
6492 if (options->break_opt != -1)
6493 diffcore_merge_broken();
6495 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6496 diffcore_pickaxe(options);
6497 if (options->orderfile)
6498 diffcore_order(options->orderfile);
6499 if (!options->found_follow)
6500 /* See try_to_follow_renames() in tree-diff.c */
6501 diff_resolve_rename_copy();
6502 diffcore_apply_filter(options);
6504 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6505 options->flags.has_changes = 1;
6506 else
6507 options->flags.has_changes = 0;
6509 options->found_follow = 0;
6512 int diff_result_code(struct diff_options *opt, int status)
6514 int result = 0;
6516 diff_warn_rename_limit("diff.renameLimit",
6517 opt->needed_rename_limit,
6518 opt->degraded_cc_to_c);
6519 if (!opt->flags.exit_with_status &&
6520 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6521 return status;
6522 if (opt->flags.exit_with_status &&
6523 opt->flags.has_changes)
6524 result |= 01;
6525 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6526 opt->flags.check_failed)
6527 result |= 02;
6528 return result;
6531 int diff_can_quit_early(struct diff_options *opt)
6533 return (opt->flags.quick &&
6534 !opt->filter &&
6535 opt->flags.has_changes);
6539 * Shall changes to this submodule be ignored?
6541 * Submodule changes can be configured to be ignored separately for each path,
6542 * but that configuration can be overridden from the command line.
6544 static int is_submodule_ignored(const char *path, struct diff_options *options)
6546 int ignored = 0;
6547 struct diff_flags orig_flags = options->flags;
6548 if (!options->flags.override_submodule_config)
6549 set_diffopt_flags_from_submodule_config(options, path);
6550 if (options->flags.ignore_submodules)
6551 ignored = 1;
6552 options->flags = orig_flags;
6553 return ignored;
6556 void diff_addremove(struct diff_options *options,
6557 int addremove, unsigned mode,
6558 const struct object_id *oid,
6559 int oid_valid,
6560 const char *concatpath, unsigned dirty_submodule)
6562 struct diff_filespec *one, *two;
6564 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6565 return;
6567 /* This may look odd, but it is a preparation for
6568 * feeding "there are unchanged files which should
6569 * not produce diffs, but when you are doing copy
6570 * detection you would need them, so here they are"
6571 * entries to the diff-core. They will be prefixed
6572 * with something like '=' or '*' (I haven't decided
6573 * which but should not make any difference).
6574 * Feeding the same new and old to diff_change()
6575 * also has the same effect.
6576 * Before the final output happens, they are pruned after
6577 * merged into rename/copy pairs as appropriate.
6579 if (options->flags.reverse_diff)
6580 addremove = (addremove == '+' ? '-' :
6581 addremove == '-' ? '+' : addremove);
6583 if (options->prefix &&
6584 strncmp(concatpath, options->prefix, options->prefix_length))
6585 return;
6587 one = alloc_filespec(concatpath);
6588 two = alloc_filespec(concatpath);
6590 if (addremove != '+')
6591 fill_filespec(one, oid, oid_valid, mode);
6592 if (addremove != '-') {
6593 fill_filespec(two, oid, oid_valid, mode);
6594 two->dirty_submodule = dirty_submodule;
6597 diff_queue(&diff_queued_diff, one, two);
6598 if (!options->flags.diff_from_contents)
6599 options->flags.has_changes = 1;
6602 void diff_change(struct diff_options *options,
6603 unsigned old_mode, unsigned new_mode,
6604 const struct object_id *old_oid,
6605 const struct object_id *new_oid,
6606 int old_oid_valid, int new_oid_valid,
6607 const char *concatpath,
6608 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6610 struct diff_filespec *one, *two;
6611 struct diff_filepair *p;
6613 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6614 is_submodule_ignored(concatpath, options))
6615 return;
6617 if (options->flags.reverse_diff) {
6618 SWAP(old_mode, new_mode);
6619 SWAP(old_oid, new_oid);
6620 SWAP(old_oid_valid, new_oid_valid);
6621 SWAP(old_dirty_submodule, new_dirty_submodule);
6624 if (options->prefix &&
6625 strncmp(concatpath, options->prefix, options->prefix_length))
6626 return;
6628 one = alloc_filespec(concatpath);
6629 two = alloc_filespec(concatpath);
6630 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6631 fill_filespec(two, new_oid, new_oid_valid, new_mode);
6632 one->dirty_submodule = old_dirty_submodule;
6633 two->dirty_submodule = new_dirty_submodule;
6634 p = diff_queue(&diff_queued_diff, one, two);
6636 if (options->flags.diff_from_contents)
6637 return;
6639 if (options->flags.quick && options->skip_stat_unmatch &&
6640 !diff_filespec_check_stat_unmatch(options->repo, p))
6641 return;
6643 options->flags.has_changes = 1;
6646 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6648 struct diff_filepair *pair;
6649 struct diff_filespec *one, *two;
6651 if (options->prefix &&
6652 strncmp(path, options->prefix, options->prefix_length))
6653 return NULL;
6655 one = alloc_filespec(path);
6656 two = alloc_filespec(path);
6657 pair = diff_queue(&diff_queued_diff, one, two);
6658 pair->is_unmerged = 1;
6659 return pair;
6662 static char *run_textconv(struct repository *r,
6663 const char *pgm,
6664 struct diff_filespec *spec,
6665 size_t *outsize)
6667 struct diff_tempfile *temp;
6668 const char *argv[3];
6669 const char **arg = argv;
6670 struct child_process child = CHILD_PROCESS_INIT;
6671 struct strbuf buf = STRBUF_INIT;
6672 int err = 0;
6674 temp = prepare_temp_file(r, spec->path, spec);
6675 *arg++ = pgm;
6676 *arg++ = temp->name;
6677 *arg = NULL;
6679 child.use_shell = 1;
6680 child.argv = argv;
6681 child.out = -1;
6682 if (start_command(&child)) {
6683 remove_tempfile();
6684 return NULL;
6687 if (strbuf_read(&buf, child.out, 0) < 0)
6688 err = error("error reading from textconv command '%s'", pgm);
6689 close(child.out);
6691 if (finish_command(&child) || err) {
6692 strbuf_release(&buf);
6693 remove_tempfile();
6694 return NULL;
6696 remove_tempfile();
6698 return strbuf_detach(&buf, outsize);
6701 size_t fill_textconv(struct repository *r,
6702 struct userdiff_driver *driver,
6703 struct diff_filespec *df,
6704 char **outbuf)
6706 size_t size;
6708 if (!driver) {
6709 if (!DIFF_FILE_VALID(df)) {
6710 *outbuf = "";
6711 return 0;
6713 if (diff_populate_filespec(r, df, 0))
6714 die("unable to read files to diff");
6715 *outbuf = df->data;
6716 return df->size;
6719 if (!driver->textconv)
6720 BUG("fill_textconv called with non-textconv driver");
6722 if (driver->textconv_cache && df->oid_valid) {
6723 *outbuf = notes_cache_get(driver->textconv_cache,
6724 &df->oid,
6725 &size);
6726 if (*outbuf)
6727 return size;
6730 *outbuf = run_textconv(r, driver->textconv, df, &size);
6731 if (!*outbuf)
6732 die("unable to read files to diff");
6734 if (driver->textconv_cache && df->oid_valid) {
6735 /* ignore errors, as we might be in a readonly repository */
6736 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6737 size);
6739 * we could save up changes and flush them all at the end,
6740 * but we would need an extra call after all diffing is done.
6741 * Since generating a cache entry is the slow path anyway,
6742 * this extra overhead probably isn't a big deal.
6744 notes_cache_write(driver->textconv_cache);
6747 return size;
6750 int textconv_object(struct repository *r,
6751 const char *path,
6752 unsigned mode,
6753 const struct object_id *oid,
6754 int oid_valid,
6755 char **buf,
6756 unsigned long *buf_size)
6758 struct diff_filespec *df;
6759 struct userdiff_driver *textconv;
6761 df = alloc_filespec(path);
6762 fill_filespec(df, oid, oid_valid, mode);
6763 textconv = get_textconv(r, df);
6764 if (!textconv) {
6765 free_filespec(df);
6766 return 0;
6769 *buf_size = fill_textconv(r, textconv, df, buf);
6770 free_filespec(df);
6771 return 1;
6774 void setup_diff_pager(struct diff_options *opt)
6777 * If the user asked for our exit code, then either they want --quiet
6778 * or --exit-code. We should definitely not bother with a pager in the
6779 * former case, as we will generate no output. Since we still properly
6780 * report our exit code even when a pager is run, we _could_ run a
6781 * pager with --exit-code. But since we have not done so historically,
6782 * and because it is easy to find people oneline advising "git diff
6783 * --exit-code" in hooks and other scripts, we do not do so.
6785 if (!opt->flags.exit_with_status &&
6786 check_pager_config("diff") != 0)
6787 setup_pager();