2 * Copyright (C) 2005 Junio C Hamano
11 #include "xdiff-interface.h"
14 #include "run-command.h"
17 #include "submodule-config.h"
18 #include "submodule.h"
20 #include "string-list.h"
21 #include "argv-array.h"
24 #ifdef NO_FAST_WORKING_DIRECTORY
25 #define FAST_WORKING_DIRECTORY 0
27 #define FAST_WORKING_DIRECTORY 1
30 static int diff_detect_rename_default;
31 static int diff_indent_heuristic = 1;
32 static int diff_rename_limit_default = 400;
33 static int diff_suppress_blank_empty;
34 static int diff_use_color_default = -1;
35 static int diff_context_default = 3;
36 static int diff_interhunk_context_default;
37 static const char *diff_word_regex_cfg;
38 static const char *external_diff_cmd_cfg;
39 static const char *diff_order_file_cfg;
40 int diff_auto_refresh_index = 1;
41 static int diff_mnemonic_prefix;
42 static int diff_no_prefix;
43 static int diff_stat_graph_width;
44 static int diff_dirstat_permille_default = 30;
45 static struct diff_options default_diff_options;
46 static long diff_algorithm;
47 static unsigned ws_error_highlight_default = WSEH_NEW;
49 static char diff_colors[][COLOR_MAXLEN] = {
51 GIT_COLOR_NORMAL, /* CONTEXT */
52 GIT_COLOR_BOLD, /* METAINFO */
53 GIT_COLOR_CYAN, /* FRAGINFO */
54 GIT_COLOR_RED, /* OLD */
55 GIT_COLOR_GREEN, /* NEW */
56 GIT_COLOR_YELLOW, /* COMMIT */
57 GIT_COLOR_BG_RED, /* WHITESPACE */
58 GIT_COLOR_NORMAL, /* FUNCINFO */
61 static NORETURN void die_want_option(const char *option_name)
63 die(_("option '%s' requires a value"), option_name);
66 static int parse_diff_color_slot(const char *var)
68 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
70 if (!strcasecmp(var, "meta"))
72 if (!strcasecmp(var, "frag"))
74 if (!strcasecmp(var, "old"))
76 if (!strcasecmp(var, "new"))
78 if (!strcasecmp(var, "commit"))
80 if (!strcasecmp(var, "whitespace"))
81 return DIFF_WHITESPACE;
82 if (!strcasecmp(var, "func"))
87 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
88 struct strbuf *errmsg)
90 char *params_copy = xstrdup(params_string);
91 struct string_list params = STRING_LIST_INIT_NODUP;
96 string_list_split_in_place(¶ms, params_copy, ',', -1);
97 for (i = 0; i < params.nr; i++) {
98 const char *p = params.items[i].string;
99 if (!strcmp(p, "changes")) {
100 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
101 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
102 } else if (!strcmp(p, "lines")) {
103 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
104 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
105 } else if (!strcmp(p, "files")) {
106 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
107 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
108 } else if (!strcmp(p, "noncumulative")) {
109 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
110 } else if (!strcmp(p, "cumulative")) {
111 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
112 } else if (isdigit(*p)) {
114 int permille = strtoul(p, &end, 10) * 10;
115 if (*end == '.' && isdigit(*++end)) {
116 /* only use first digit */
117 permille += *end - '0';
118 /* .. and ignore any further digits */
119 while (isdigit(*++end))
123 options->dirstat_permille = permille;
125 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
130 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
135 string_list_clear(¶ms, 0);
140 static int parse_submodule_params(struct diff_options *options, const char *value)
142 if (!strcmp(value, "log"))
143 options->submodule_format = DIFF_SUBMODULE_LOG;
144 else if (!strcmp(value, "short"))
145 options->submodule_format = DIFF_SUBMODULE_SHORT;
146 else if (!strcmp(value, "diff"))
147 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
153 static int git_config_rename(const char *var, const char *value)
156 return DIFF_DETECT_RENAME;
157 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
158 return DIFF_DETECT_COPY;
159 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
162 long parse_algorithm_value(const char *value)
166 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
168 else if (!strcasecmp(value, "minimal"))
169 return XDF_NEED_MINIMAL;
170 else if (!strcasecmp(value, "patience"))
171 return XDF_PATIENCE_DIFF;
172 else if (!strcasecmp(value, "histogram"))
173 return XDF_HISTOGRAM_DIFF;
177 static int parse_one_token(const char **arg, const char *token)
180 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
187 static int parse_ws_error_highlight(const char *arg)
189 const char *orig_arg = arg;
193 if (parse_one_token(&arg, "none"))
195 else if (parse_one_token(&arg, "default"))
197 else if (parse_one_token(&arg, "all"))
198 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
199 else if (parse_one_token(&arg, "new"))
201 else if (parse_one_token(&arg, "old"))
203 else if (parse_one_token(&arg, "context"))
206 return -1 - (int)(arg - orig_arg);
215 * These are to give UI layer defaults.
216 * The core-level commands such as git-diff-files should
217 * never be affected by the setting of diff.renames
218 * the user happens to have in the configuration file.
220 void init_diff_ui_defaults(void)
222 diff_detect_rename_default = 1;
225 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
227 if (!strcmp(var, "diff.indentheuristic"))
228 diff_indent_heuristic = git_config_bool(var, value);
232 int git_diff_ui_config(const char *var, const char *value, void *cb)
234 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
235 diff_use_color_default = git_config_colorbool(var, value);
238 if (!strcmp(var, "diff.context")) {
239 diff_context_default = git_config_int(var, value);
240 if (diff_context_default < 0)
244 if (!strcmp(var, "diff.interhunkcontext")) {
245 diff_interhunk_context_default = git_config_int(var, value);
246 if (diff_interhunk_context_default < 0)
250 if (!strcmp(var, "diff.renames")) {
251 diff_detect_rename_default = git_config_rename(var, value);
254 if (!strcmp(var, "diff.autorefreshindex")) {
255 diff_auto_refresh_index = git_config_bool(var, value);
258 if (!strcmp(var, "diff.mnemonicprefix")) {
259 diff_mnemonic_prefix = git_config_bool(var, value);
262 if (!strcmp(var, "diff.noprefix")) {
263 diff_no_prefix = git_config_bool(var, value);
266 if (!strcmp(var, "diff.statgraphwidth")) {
267 diff_stat_graph_width = git_config_int(var, value);
270 if (!strcmp(var, "diff.external"))
271 return git_config_string(&external_diff_cmd_cfg, var, value);
272 if (!strcmp(var, "diff.wordregex"))
273 return git_config_string(&diff_word_regex_cfg, var, value);
274 if (!strcmp(var, "diff.orderfile"))
275 return git_config_pathname(&diff_order_file_cfg, var, value);
277 if (!strcmp(var, "diff.ignoresubmodules"))
278 handle_ignore_submodules_arg(&default_diff_options, value);
280 if (!strcmp(var, "diff.submodule")) {
281 if (parse_submodule_params(&default_diff_options, value))
282 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
287 if (!strcmp(var, "diff.algorithm")) {
288 diff_algorithm = parse_algorithm_value(value);
289 if (diff_algorithm < 0)
294 if (!strcmp(var, "diff.wserrorhighlight")) {
295 int val = parse_ws_error_highlight(value);
298 ws_error_highlight_default = val;
302 if (git_color_config(var, value, cb) < 0)
305 return git_diff_basic_config(var, value, cb);
308 int git_diff_basic_config(const char *var, const char *value, void *cb)
312 if (!strcmp(var, "diff.renamelimit")) {
313 diff_rename_limit_default = git_config_int(var, value);
317 if (userdiff_config(var, value) < 0)
320 if (skip_prefix(var, "diff.color.", &name) ||
321 skip_prefix(var, "color.diff.", &name)) {
322 int slot = parse_diff_color_slot(name);
326 return config_error_nonbool(var);
327 return color_parse(value, diff_colors[slot]);
330 /* like GNU diff's --suppress-blank-empty option */
331 if (!strcmp(var, "diff.suppressblankempty") ||
332 /* for backwards compatibility */
333 !strcmp(var, "diff.suppress-blank-empty")) {
334 diff_suppress_blank_empty = git_config_bool(var, value);
338 if (!strcmp(var, "diff.dirstat")) {
339 struct strbuf errmsg = STRBUF_INIT;
340 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
341 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
342 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
344 strbuf_release(&errmsg);
345 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
349 if (starts_with(var, "submodule."))
350 return parse_submodule_config_option(var, value);
352 if (git_diff_heuristic_config(var, value, cb) < 0)
355 return git_default_config(var, value, cb);
358 static char *quote_two(const char *one, const char *two)
360 int need_one = quote_c_style(one, NULL, NULL, 1);
361 int need_two = quote_c_style(two, NULL, NULL, 1);
362 struct strbuf res = STRBUF_INIT;
364 if (need_one + need_two) {
365 strbuf_addch(&res, '"');
366 quote_c_style(one, &res, NULL, 1);
367 quote_c_style(two, &res, NULL, 1);
368 strbuf_addch(&res, '"');
370 strbuf_addstr(&res, one);
371 strbuf_addstr(&res, two);
373 return strbuf_detach(&res, NULL);
376 static const char *external_diff(void)
378 static const char *external_diff_cmd = NULL;
379 static int done_preparing = 0;
382 return external_diff_cmd;
383 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
384 if (!external_diff_cmd)
385 external_diff_cmd = external_diff_cmd_cfg;
387 return external_diff_cmd;
391 * Keep track of files used for diffing. Sometimes such an entry
392 * refers to a temporary file, sometimes to an existing file, and
393 * sometimes to "/dev/null".
395 static struct diff_tempfile {
397 * filename external diff should read from, or NULL if this
398 * entry is currently not in use:
402 char hex[GIT_MAX_HEXSZ + 1];
406 * If this diff_tempfile instance refers to a temporary file,
407 * this tempfile object is used to manage its lifetime.
409 struct tempfile tempfile;
412 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
414 struct emit_callback {
417 int blank_at_eof_in_preimage;
418 int blank_at_eof_in_postimage;
420 int lno_in_postimage;
421 sane_truncate_fn truncate;
422 const char **label_path;
423 struct diff_words_data *diff_words;
424 struct diff_options *opt;
425 struct strbuf *header;
428 static int count_lines(const char *data, int size)
430 int count, ch, completely_empty = 1, nl_just_seen = 0;
437 completely_empty = 0;
441 completely_empty = 0;
444 if (completely_empty)
447 count++; /* no trailing newline */
451 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
453 if (!DIFF_FILE_VALID(one)) {
454 mf->ptr = (char *)""; /* does not matter */
458 else if (diff_populate_filespec(one, 0))
462 mf->size = one->size;
466 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
467 static unsigned long diff_filespec_size(struct diff_filespec *one)
469 if (!DIFF_FILE_VALID(one))
471 diff_populate_filespec(one, CHECK_SIZE_ONLY);
475 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
478 long size = mf->size;
483 ptr += size - 1; /* pointing at the very end */
485 ; /* incomplete line */
487 ptr--; /* skip the last LF */
488 while (mf->ptr < ptr) {
490 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
491 if (*prev_eol == '\n')
493 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
501 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
502 struct emit_callback *ecbdata)
505 unsigned ws_rule = ecbdata->ws_rule;
506 l1 = count_trailing_blank(mf1, ws_rule);
507 l2 = count_trailing_blank(mf2, ws_rule);
509 ecbdata->blank_at_eof_in_preimage = 0;
510 ecbdata->blank_at_eof_in_postimage = 0;
513 at = count_lines(mf1->ptr, mf1->size);
514 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
516 at = count_lines(mf2->ptr, mf2->size);
517 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
520 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
521 int first, const char *line, int len)
523 int has_trailing_newline, has_trailing_carriage_return;
525 FILE *file = o->file;
527 fputs(diff_line_prefix(o), file);
530 has_trailing_newline = (first == '\n');
531 has_trailing_carriage_return = (!has_trailing_newline &&
533 nofirst = has_trailing_newline || has_trailing_carriage_return;
535 has_trailing_newline = (len > 0 && line[len-1] == '\n');
536 if (has_trailing_newline)
538 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
539 if (has_trailing_carriage_return)
544 if (len || !nofirst) {
548 fwrite(line, len, 1, file);
551 if (has_trailing_carriage_return)
553 if (has_trailing_newline)
557 static void emit_line(struct diff_options *o, const char *set, const char *reset,
558 const char *line, int len)
560 emit_line_0(o, set, reset, line[0], line+1, len-1);
564 DIFF_SYMBOL_BINARY_DIFF_HEADER,
565 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
566 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
567 DIFF_SYMBOL_BINARY_DIFF_BODY,
568 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
569 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
570 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
571 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
572 DIFF_SYMBOL_STATS_LINE,
573 DIFF_SYMBOL_WORD_DIFF,
574 DIFF_SYMBOL_STAT_SEP,
576 DIFF_SYMBOL_SUBMODULE_ADD,
577 DIFF_SYMBOL_SUBMODULE_DEL,
578 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
579 DIFF_SYMBOL_SUBMODULE_MODIFIED,
580 DIFF_SYMBOL_SUBMODULE_HEADER,
581 DIFF_SYMBOL_SUBMODULE_ERROR,
582 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
583 DIFF_SYMBOL_REWRITE_DIFF,
584 DIFF_SYMBOL_BINARY_FILES,
586 DIFF_SYMBOL_FILEPAIR_PLUS,
587 DIFF_SYMBOL_FILEPAIR_MINUS,
588 DIFF_SYMBOL_WORDS_PORCELAIN,
591 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
594 DIFF_SYMBOL_NO_LF_EOF,
595 DIFF_SYMBOL_CONTEXT_FRAGINFO,
596 DIFF_SYMBOL_CONTEXT_MARKER,
597 DIFF_SYMBOL_SEPARATOR
600 * Flags for content lines:
601 * 0..12 are whitespace rules
602 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
603 * 16 is marking if the line is blank at EOF
605 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
606 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
608 static void emit_line_ws_markup(struct diff_options *o,
609 const char *set, const char *reset,
610 const char *line, int len, char sign,
611 unsigned ws_rule, int blank_at_eof)
613 const char *ws = NULL;
615 if (o->ws_error_highlight & ws_rule) {
616 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
622 emit_line_0(o, set, reset, sign, line, len);
623 else if (blank_at_eof)
624 /* Blank line at EOF - paint '+' as well */
625 emit_line_0(o, ws, reset, sign, line, len);
627 /* Emit just the prefix, then the rest. */
628 emit_line_0(o, set, reset, sign, "", 0);
629 ws_check_emit(line, len, ws_rule,
630 o->file, set, reset, ws);
634 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
635 const char *line, int len, unsigned flags)
637 static const char *nneof = " No newline at end of file\n";
638 const char *context, *reset, *set, *meta, *fraginfo;
639 struct strbuf sb = STRBUF_INIT;
641 case DIFF_SYMBOL_NO_LF_EOF:
642 context = diff_get_color_opt(o, DIFF_CONTEXT);
643 reset = diff_get_color_opt(o, DIFF_RESET);
645 emit_line_0(o, context, reset, '\\',
646 nneof, strlen(nneof));
648 case DIFF_SYMBOL_SUBMODULE_HEADER:
649 case DIFF_SYMBOL_SUBMODULE_ERROR:
650 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
651 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
652 case DIFF_SYMBOL_SUMMARY:
653 case DIFF_SYMBOL_STATS_LINE:
654 case DIFF_SYMBOL_BINARY_DIFF_BODY:
655 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
656 emit_line(o, "", "", line, len);
658 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
659 case DIFF_SYMBOL_CONTEXT_MARKER:
660 context = diff_get_color_opt(o, DIFF_CONTEXT);
661 reset = diff_get_color_opt(o, DIFF_RESET);
662 emit_line(o, context, reset, line, len);
664 case DIFF_SYMBOL_SEPARATOR:
665 fprintf(o->file, "%s%c",
667 o->line_termination);
669 case DIFF_SYMBOL_CONTEXT:
670 set = diff_get_color_opt(o, DIFF_CONTEXT);
671 reset = diff_get_color_opt(o, DIFF_RESET);
672 emit_line_ws_markup(o, set, reset, line, len, ' ',
673 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
675 case DIFF_SYMBOL_PLUS:
676 set = diff_get_color_opt(o, DIFF_FILE_NEW);
677 reset = diff_get_color_opt(o, DIFF_RESET);
678 emit_line_ws_markup(o, set, reset, line, len, '+',
679 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
680 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
682 case DIFF_SYMBOL_MINUS:
683 set = diff_get_color_opt(o, DIFF_FILE_OLD);
684 reset = diff_get_color_opt(o, DIFF_RESET);
685 emit_line_ws_markup(o, set, reset, line, len, '-',
686 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
688 case DIFF_SYMBOL_WORDS_PORCELAIN:
689 context = diff_get_color_opt(o, DIFF_CONTEXT);
690 reset = diff_get_color_opt(o, DIFF_RESET);
691 emit_line(o, context, reset, line, len);
692 fputs("~\n", o->file);
694 case DIFF_SYMBOL_WORDS:
695 context = diff_get_color_opt(o, DIFF_CONTEXT);
696 reset = diff_get_color_opt(o, DIFF_RESET);
698 * Skip the prefix character, if any. With
699 * diff_suppress_blank_empty, there may be
702 if (line[0] != '\n') {
706 emit_line(o, context, reset, line, len);
708 case DIFF_SYMBOL_FILEPAIR_PLUS:
709 meta = diff_get_color_opt(o, DIFF_METAINFO);
710 reset = diff_get_color_opt(o, DIFF_RESET);
711 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
713 strchr(line, ' ') ? "\t" : "");
715 case DIFF_SYMBOL_FILEPAIR_MINUS:
716 meta = diff_get_color_opt(o, DIFF_METAINFO);
717 reset = diff_get_color_opt(o, DIFF_RESET);
718 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
720 strchr(line, ' ') ? "\t" : "");
722 case DIFF_SYMBOL_BINARY_FILES:
723 case DIFF_SYMBOL_HEADER:
724 fprintf(o->file, "%s", line);
726 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
727 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
729 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
730 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
732 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
733 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
735 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
736 fputs(diff_line_prefix(o), o->file);
737 fputc('\n', o->file);
739 case DIFF_SYMBOL_REWRITE_DIFF:
740 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
741 reset = diff_get_color_opt(o, DIFF_RESET);
742 emit_line(o, fraginfo, reset, line, len);
744 case DIFF_SYMBOL_SUBMODULE_ADD:
745 set = diff_get_color_opt(o, DIFF_FILE_NEW);
746 reset = diff_get_color_opt(o, DIFF_RESET);
747 emit_line(o, set, reset, line, len);
749 case DIFF_SYMBOL_SUBMODULE_DEL:
750 set = diff_get_color_opt(o, DIFF_FILE_OLD);
751 reset = diff_get_color_opt(o, DIFF_RESET);
752 emit_line(o, set, reset, line, len);
754 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
755 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
756 diff_line_prefix(o), line);
758 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
759 fprintf(o->file, "%sSubmodule %s contains modified content\n",
760 diff_line_prefix(o), line);
762 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
763 emit_line(o, "", "", " 0 files changed\n",
764 strlen(" 0 files changed\n"));
766 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
767 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
769 case DIFF_SYMBOL_WORD_DIFF:
770 fprintf(o->file, "%.*s", len, line);
772 case DIFF_SYMBOL_STAT_SEP:
773 fputs(o->stat_sep, o->file);
776 die("BUG: unknown diff symbol");
781 void diff_emit_submodule_del(struct diff_options *o, const char *line)
783 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
786 void diff_emit_submodule_add(struct diff_options *o, const char *line)
788 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
791 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
793 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
794 path, strlen(path), 0);
797 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
799 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
800 path, strlen(path), 0);
803 void diff_emit_submodule_header(struct diff_options *o, const char *header)
805 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
806 header, strlen(header), 0);
809 void diff_emit_submodule_error(struct diff_options *o, const char *err)
811 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
814 void diff_emit_submodule_pipethrough(struct diff_options *o,
815 const char *line, int len)
817 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
820 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
822 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
823 ecbdata->blank_at_eof_in_preimage &&
824 ecbdata->blank_at_eof_in_postimage &&
825 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
826 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
828 return ws_blank_line(line, len, ecbdata->ws_rule);
831 static void emit_add_line(const char *reset,
832 struct emit_callback *ecbdata,
833 const char *line, int len)
835 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
836 if (new_blank_line_at_eof(ecbdata, line, len))
837 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
839 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
842 static void emit_del_line(const char *reset,
843 struct emit_callback *ecbdata,
844 const char *line, int len)
846 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
847 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
850 static void emit_context_line(const char *reset,
851 struct emit_callback *ecbdata,
852 const char *line, int len)
854 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
855 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
858 static void emit_hunk_header(struct emit_callback *ecbdata,
859 const char *line, int len)
861 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
862 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
863 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
864 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
865 static const char atat[2] = { '@', '@' };
867 struct strbuf msgbuf = STRBUF_INIT;
872 * As a hunk header must begin with "@@ -<old>, +<new> @@",
873 * it always is at least 10 bytes long.
876 memcmp(line, atat, 2) ||
877 !(ep = memmem(line + 2, len - 2, atat, 2))) {
878 emit_diff_symbol(ecbdata->opt,
879 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
882 ep += 2; /* skip over @@ */
884 /* The hunk header in fraginfo color */
885 strbuf_addstr(&msgbuf, frag);
886 strbuf_add(&msgbuf, line, ep - line);
887 strbuf_addstr(&msgbuf, reset);
893 if (line[len - i] == '\r' || line[len - i] == '\n')
896 /* blank before the func header */
897 for (cp = ep; ep - line < len; ep++)
898 if (*ep != ' ' && *ep != '\t')
901 strbuf_addstr(&msgbuf, context);
902 strbuf_add(&msgbuf, cp, ep - cp);
903 strbuf_addstr(&msgbuf, reset);
906 if (ep < line + len) {
907 strbuf_addstr(&msgbuf, func);
908 strbuf_add(&msgbuf, ep, line + len - ep);
909 strbuf_addstr(&msgbuf, reset);
912 strbuf_add(&msgbuf, line + len, org_len - len);
913 strbuf_complete_line(&msgbuf);
914 emit_diff_symbol(ecbdata->opt,
915 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
916 strbuf_release(&msgbuf);
919 static struct diff_tempfile *claim_diff_tempfile(void) {
921 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
922 if (!diff_temp[i].name)
923 return diff_temp + i;
924 die("BUG: diff is failing to clean up its tempfiles");
927 static void remove_tempfile(void)
930 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
931 if (is_tempfile_active(&diff_temp[i].tempfile))
932 delete_tempfile(&diff_temp[i].tempfile);
933 diff_temp[i].name = NULL;
937 static void add_line_count(struct strbuf *out, int count)
941 strbuf_addstr(out, "0,0");
944 strbuf_addstr(out, "1");
947 strbuf_addf(out, "1,%d", count);
952 static void emit_rewrite_lines(struct emit_callback *ecb,
953 int prefix, const char *data, int size)
955 const char *endp = NULL;
956 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
961 endp = memchr(data, '\n', size);
962 len = endp ? (endp - data + 1) : size;
964 ecb->lno_in_preimage++;
965 emit_del_line(reset, ecb, data, len);
967 ecb->lno_in_postimage++;
968 emit_add_line(reset, ecb, data, len);
974 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
977 static void emit_rewrite_diff(const char *name_a,
979 struct diff_filespec *one,
980 struct diff_filespec *two,
981 struct userdiff_driver *textconv_one,
982 struct userdiff_driver *textconv_two,
983 struct diff_options *o)
986 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
987 const char *a_prefix, *b_prefix;
988 char *data_one, *data_two;
989 size_t size_one, size_two;
990 struct emit_callback ecbdata;
991 struct strbuf out = STRBUF_INIT;
993 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
994 a_prefix = o->b_prefix;
995 b_prefix = o->a_prefix;
997 a_prefix = o->a_prefix;
998 b_prefix = o->b_prefix;
1001 name_a += (*name_a == '/');
1002 name_b += (*name_b == '/');
1004 strbuf_reset(&a_name);
1005 strbuf_reset(&b_name);
1006 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1007 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1009 size_one = fill_textconv(textconv_one, one, &data_one);
1010 size_two = fill_textconv(textconv_two, two, &data_two);
1012 memset(&ecbdata, 0, sizeof(ecbdata));
1013 ecbdata.color_diff = want_color(o->use_color);
1014 ecbdata.ws_rule = whitespace_rule(name_b);
1016 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1018 mf1.ptr = (char *)data_one;
1019 mf2.ptr = (char *)data_two;
1020 mf1.size = size_one;
1021 mf2.size = size_two;
1022 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1024 ecbdata.lno_in_preimage = 1;
1025 ecbdata.lno_in_postimage = 1;
1027 lc_a = count_lines(data_one, size_one);
1028 lc_b = count_lines(data_two, size_two);
1030 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1031 a_name.buf, a_name.len, 0);
1032 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1033 b_name.buf, b_name.len, 0);
1035 strbuf_addstr(&out, "@@ -");
1036 if (!o->irreversible_delete)
1037 add_line_count(&out, lc_a);
1039 strbuf_addstr(&out, "?,?");
1040 strbuf_addstr(&out, " +");
1041 add_line_count(&out, lc_b);
1042 strbuf_addstr(&out, " @@\n");
1043 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1044 strbuf_release(&out);
1046 if (lc_a && !o->irreversible_delete)
1047 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1049 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1051 free((char *)data_one);
1053 free((char *)data_two);
1056 struct diff_words_buffer {
1059 struct diff_words_orig {
1060 const char *begin, *end;
1062 int orig_nr, orig_alloc;
1065 static void diff_words_append(char *line, unsigned long len,
1066 struct diff_words_buffer *buffer)
1068 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1071 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1072 buffer->text.size += len;
1073 buffer->text.ptr[buffer->text.size] = '\0';
1076 struct diff_words_style_elem {
1079 const char *color; /* NULL; filled in by the setup code if
1080 * color is enabled */
1083 struct diff_words_style {
1084 enum diff_words_type type;
1085 struct diff_words_style_elem new, old, ctx;
1086 const char *newline;
1089 static struct diff_words_style diff_words_styles[] = {
1090 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1091 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1092 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1095 struct diff_words_data {
1096 struct diff_words_buffer minus, plus;
1097 const char *current_plus;
1099 struct diff_options *opt;
1100 regex_t *word_regex;
1101 enum diff_words_type type;
1102 struct diff_words_style *style;
1105 static int fn_out_diff_words_write_helper(struct diff_options *o,
1106 struct diff_words_style_elem *st_el,
1107 const char *newline,
1108 size_t count, const char *buf)
1111 struct strbuf sb = STRBUF_INIT;
1114 char *p = memchr(buf, '\n', count);
1116 strbuf_addstr(&sb, diff_line_prefix(o));
1119 const char *reset = st_el->color && *st_el->color ?
1120 GIT_COLOR_RESET : NULL;
1121 if (st_el->color && *st_el->color)
1122 strbuf_addstr(&sb, st_el->color);
1123 strbuf_addstr(&sb, st_el->prefix);
1124 strbuf_add(&sb, buf, p ? p - buf : count);
1125 strbuf_addstr(&sb, st_el->suffix);
1127 strbuf_addstr(&sb, reset);
1132 strbuf_addstr(&sb, newline);
1133 count -= p + 1 - buf;
1137 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1145 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1147 strbuf_release(&sb);
1152 * '--color-words' algorithm can be described as:
1154 * 1. collect the minus/plus lines of a diff hunk, divided into
1155 * minus-lines and plus-lines;
1157 * 2. break both minus-lines and plus-lines into words and
1158 * place them into two mmfile_t with one word for each line;
1160 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1162 * And for the common parts of the both file, we output the plus side text.
1163 * diff_words->current_plus is used to trace the current position of the plus file
1164 * which printed. diff_words->last_minus is used to trace the last minus word
1167 * For '--graph' to work with '--color-words', we need to output the graph prefix
1168 * on each line of color words output. Generally, there are two conditions on
1169 * which we should output the prefix.
1171 * 1. diff_words->last_minus == 0 &&
1172 * diff_words->current_plus == diff_words->plus.text.ptr
1174 * that is: the plus text must start as a new line, and if there is no minus
1175 * word printed, a graph prefix must be printed.
1177 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1178 * *(diff_words->current_plus - 1) == '\n'
1180 * that is: a graph prefix must be printed following a '\n'
1182 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1184 if ((diff_words->last_minus == 0 &&
1185 diff_words->current_plus == diff_words->plus.text.ptr) ||
1186 (diff_words->current_plus > diff_words->plus.text.ptr &&
1187 *(diff_words->current_plus - 1) == '\n')) {
1194 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1196 struct diff_words_data *diff_words = priv;
1197 struct diff_words_style *style = diff_words->style;
1198 int minus_first, minus_len, plus_first, plus_len;
1199 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1200 struct diff_options *opt = diff_words->opt;
1201 const char *line_prefix;
1203 if (line[0] != '@' || parse_hunk_header(line, len,
1204 &minus_first, &minus_len, &plus_first, &plus_len))
1208 line_prefix = diff_line_prefix(opt);
1210 /* POSIX requires that first be decremented by one if len == 0... */
1212 minus_begin = diff_words->minus.orig[minus_first].begin;
1214 diff_words->minus.orig[minus_first + minus_len - 1].end;
1216 minus_begin = minus_end =
1217 diff_words->minus.orig[minus_first].end;
1220 plus_begin = diff_words->plus.orig[plus_first].begin;
1221 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1223 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1225 if (color_words_output_graph_prefix(diff_words)) {
1226 fputs(line_prefix, diff_words->opt->file);
1228 if (diff_words->current_plus != plus_begin) {
1229 fn_out_diff_words_write_helper(diff_words->opt,
1230 &style->ctx, style->newline,
1231 plus_begin - diff_words->current_plus,
1232 diff_words->current_plus);
1234 if (minus_begin != minus_end) {
1235 fn_out_diff_words_write_helper(diff_words->opt,
1236 &style->old, style->newline,
1237 minus_end - minus_begin, minus_begin);
1239 if (plus_begin != plus_end) {
1240 fn_out_diff_words_write_helper(diff_words->opt,
1241 &style->new, style->newline,
1242 plus_end - plus_begin, plus_begin);
1245 diff_words->current_plus = plus_end;
1246 diff_words->last_minus = minus_first;
1249 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1250 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1251 int *begin, int *end)
1253 if (word_regex && *begin < buffer->size) {
1254 regmatch_t match[1];
1255 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1256 buffer->size - *begin, 1, match, 0)) {
1257 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1258 '\n', match[0].rm_eo - match[0].rm_so);
1259 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1260 *begin += match[0].rm_so;
1261 return *begin >= *end;
1266 /* find the next word */
1267 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1269 if (*begin >= buffer->size)
1272 /* find the end of the word */
1274 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1281 * This function splits the words in buffer->text, stores the list with
1282 * newline separator into out, and saves the offsets of the original words
1285 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1286 regex_t *word_regex)
1294 /* fake an empty "0th" word */
1295 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1296 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1297 buffer->orig_nr = 1;
1299 for (i = 0; i < buffer->text.size; i++) {
1300 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1303 /* store original boundaries */
1304 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1305 buffer->orig_alloc);
1306 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1307 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1310 /* store one word */
1311 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1312 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1313 out->ptr[out->size + j - i] = '\n';
1314 out->size += j - i + 1;
1320 /* this executes the word diff on the accumulated buffers */
1321 static void diff_words_show(struct diff_words_data *diff_words)
1325 mmfile_t minus, plus;
1326 struct diff_words_style *style = diff_words->style;
1328 struct diff_options *opt = diff_words->opt;
1329 const char *line_prefix;
1332 line_prefix = diff_line_prefix(opt);
1334 /* special case: only removal */
1335 if (!diff_words->plus.text.size) {
1336 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1337 line_prefix, strlen(line_prefix), 0);
1338 fn_out_diff_words_write_helper(diff_words->opt,
1339 &style->old, style->newline,
1340 diff_words->minus.text.size,
1341 diff_words->minus.text.ptr);
1342 diff_words->minus.text.size = 0;
1346 diff_words->current_plus = diff_words->plus.text.ptr;
1347 diff_words->last_minus = 0;
1349 memset(&xpp, 0, sizeof(xpp));
1350 memset(&xecfg, 0, sizeof(xecfg));
1351 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1352 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1354 /* as only the hunk header will be parsed, we need a 0-context */
1356 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1358 die("unable to generate word diff");
1361 if (diff_words->current_plus != diff_words->plus.text.ptr +
1362 diff_words->plus.text.size) {
1363 if (color_words_output_graph_prefix(diff_words))
1364 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1365 line_prefix, strlen(line_prefix), 0);
1366 fn_out_diff_words_write_helper(diff_words->opt,
1367 &style->ctx, style->newline,
1368 diff_words->plus.text.ptr + diff_words->plus.text.size
1369 - diff_words->current_plus, diff_words->current_plus);
1371 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1374 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1375 static void diff_words_flush(struct emit_callback *ecbdata)
1377 if (ecbdata->diff_words->minus.text.size ||
1378 ecbdata->diff_words->plus.text.size)
1379 diff_words_show(ecbdata->diff_words);
1382 static void diff_filespec_load_driver(struct diff_filespec *one)
1384 /* Use already-loaded driver */
1388 if (S_ISREG(one->mode))
1389 one->driver = userdiff_find_by_path(one->path);
1391 /* Fallback to default settings */
1393 one->driver = userdiff_find_by_name("default");
1396 static const char *userdiff_word_regex(struct diff_filespec *one)
1398 diff_filespec_load_driver(one);
1399 return one->driver->word_regex;
1402 static void init_diff_words_data(struct emit_callback *ecbdata,
1403 struct diff_options *orig_opts,
1404 struct diff_filespec *one,
1405 struct diff_filespec *two)
1408 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1409 memcpy(o, orig_opts, sizeof(struct diff_options));
1411 ecbdata->diff_words =
1412 xcalloc(1, sizeof(struct diff_words_data));
1413 ecbdata->diff_words->type = o->word_diff;
1414 ecbdata->diff_words->opt = o;
1416 o->word_regex = userdiff_word_regex(one);
1418 o->word_regex = userdiff_word_regex(two);
1420 o->word_regex = diff_word_regex_cfg;
1421 if (o->word_regex) {
1422 ecbdata->diff_words->word_regex = (regex_t *)
1423 xmalloc(sizeof(regex_t));
1424 if (regcomp(ecbdata->diff_words->word_regex,
1426 REG_EXTENDED | REG_NEWLINE))
1427 die ("Invalid regular expression: %s",
1430 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1431 if (o->word_diff == diff_words_styles[i].type) {
1432 ecbdata->diff_words->style =
1433 &diff_words_styles[i];
1437 if (want_color(o->use_color)) {
1438 struct diff_words_style *st = ecbdata->diff_words->style;
1439 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1440 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1441 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1445 static void free_diff_words_data(struct emit_callback *ecbdata)
1447 if (ecbdata->diff_words) {
1448 diff_words_flush(ecbdata);
1449 free (ecbdata->diff_words->opt);
1450 free (ecbdata->diff_words->minus.text.ptr);
1451 free (ecbdata->diff_words->minus.orig);
1452 free (ecbdata->diff_words->plus.text.ptr);
1453 free (ecbdata->diff_words->plus.orig);
1454 if (ecbdata->diff_words->word_regex) {
1455 regfree(ecbdata->diff_words->word_regex);
1456 free(ecbdata->diff_words->word_regex);
1458 FREE_AND_NULL(ecbdata->diff_words);
1462 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1464 if (want_color(diff_use_color))
1465 return diff_colors[ix];
1469 const char *diff_line_prefix(struct diff_options *opt)
1471 struct strbuf *msgbuf;
1472 if (!opt->output_prefix)
1475 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1479 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1482 unsigned long allot;
1486 return ecb->truncate(line, len);
1490 (void) utf8_width(&cp, &l);
1492 break; /* truncated in the middle? */
1497 static void find_lno(const char *line, struct emit_callback *ecbdata)
1500 ecbdata->lno_in_preimage = 0;
1501 ecbdata->lno_in_postimage = 0;
1502 p = strchr(line, '-');
1504 return; /* cannot happen */
1505 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1508 return; /* cannot happen */
1509 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1512 static void fn_out_consume(void *priv, char *line, unsigned long len)
1514 struct emit_callback *ecbdata = priv;
1515 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1516 struct diff_options *o = ecbdata->opt;
1518 o->found_changes = 1;
1520 if (ecbdata->header) {
1521 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1522 ecbdata->header->buf, ecbdata->header->len, 0);
1523 strbuf_reset(ecbdata->header);
1524 ecbdata->header = NULL;
1527 if (ecbdata->label_path[0]) {
1528 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1529 ecbdata->label_path[0],
1530 strlen(ecbdata->label_path[0]), 0);
1531 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1532 ecbdata->label_path[1],
1533 strlen(ecbdata->label_path[1]), 0);
1534 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1537 if (diff_suppress_blank_empty
1538 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1543 if (line[0] == '@') {
1544 if (ecbdata->diff_words)
1545 diff_words_flush(ecbdata);
1546 len = sane_truncate_line(ecbdata, line, len);
1547 find_lno(line, ecbdata);
1548 emit_hunk_header(ecbdata, line, len);
1552 if (ecbdata->diff_words) {
1553 enum diff_symbol s =
1554 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
1555 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
1556 if (line[0] == '-') {
1557 diff_words_append(line, len,
1558 &ecbdata->diff_words->minus);
1560 } else if (line[0] == '+') {
1561 diff_words_append(line, len,
1562 &ecbdata->diff_words->plus);
1564 } else if (starts_with(line, "\\ ")) {
1566 * Eat the "no newline at eof" marker as if we
1567 * saw a "+" or "-" line with nothing on it,
1568 * and return without diff_words_flush() to
1569 * defer processing. If this is the end of
1570 * preimage, more "+" lines may come after it.
1574 diff_words_flush(ecbdata);
1575 emit_diff_symbol(o, s, line, len, 0);
1581 ecbdata->lno_in_postimage++;
1582 emit_add_line(reset, ecbdata, line + 1, len - 1);
1585 ecbdata->lno_in_preimage++;
1586 emit_del_line(reset, ecbdata, line + 1, len - 1);
1589 ecbdata->lno_in_postimage++;
1590 ecbdata->lno_in_preimage++;
1591 emit_context_line(reset, ecbdata, line + 1, len - 1);
1594 /* incomplete line at the end */
1595 ecbdata->lno_in_preimage++;
1596 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1602 static char *pprint_rename(const char *a, const char *b)
1604 const char *old = a;
1605 const char *new = b;
1606 struct strbuf name = STRBUF_INIT;
1607 int pfx_length, sfx_length;
1608 int pfx_adjust_for_slash;
1609 int len_a = strlen(a);
1610 int len_b = strlen(b);
1611 int a_midlen, b_midlen;
1612 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1613 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1615 if (qlen_a || qlen_b) {
1616 quote_c_style(a, &name, NULL, 0);
1617 strbuf_addstr(&name, " => ");
1618 quote_c_style(b, &name, NULL, 0);
1619 return strbuf_detach(&name, NULL);
1622 /* Find common prefix */
1624 while (*old && *new && *old == *new) {
1626 pfx_length = old - a + 1;
1631 /* Find common suffix */
1636 * If there is a common prefix, it must end in a slash. In
1637 * that case we let this loop run 1 into the prefix to see the
1640 * If there is no common prefix, we cannot do this as it would
1641 * underrun the input strings.
1643 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1644 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1645 b + pfx_length - pfx_adjust_for_slash <= new &&
1648 sfx_length = len_a - (old - a);
1654 * pfx{mid-a => mid-b}sfx
1655 * {pfx-a => pfx-b}sfx
1656 * pfx{sfx-a => sfx-b}
1659 a_midlen = len_a - pfx_length - sfx_length;
1660 b_midlen = len_b - pfx_length - sfx_length;
1666 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1667 if (pfx_length + sfx_length) {
1668 strbuf_add(&name, a, pfx_length);
1669 strbuf_addch(&name, '{');
1671 strbuf_add(&name, a + pfx_length, a_midlen);
1672 strbuf_addstr(&name, " => ");
1673 strbuf_add(&name, b + pfx_length, b_midlen);
1674 if (pfx_length + sfx_length) {
1675 strbuf_addch(&name, '}');
1676 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1678 return strbuf_detach(&name, NULL);
1684 struct diffstat_file {
1688 unsigned is_unmerged:1;
1689 unsigned is_binary:1;
1690 unsigned is_renamed:1;
1691 unsigned is_interesting:1;
1692 uintmax_t added, deleted;
1696 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1700 struct diffstat_file *x;
1701 x = xcalloc(1, sizeof(*x));
1702 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1703 diffstat->files[diffstat->nr++] = x;
1705 x->from_name = xstrdup(name_a);
1706 x->name = xstrdup(name_b);
1710 x->from_name = NULL;
1711 x->name = xstrdup(name_a);
1716 static void diffstat_consume(void *priv, char *line, unsigned long len)
1718 struct diffstat_t *diffstat = priv;
1719 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1723 else if (line[0] == '-')
1727 const char mime_boundary_leader[] = "------------";
1729 static int scale_linear(int it, int width, int max_change)
1734 * make sure that at least one '-' or '+' is printed if
1735 * there is any change to this path. The easiest way is to
1736 * scale linearly as if the alloted width is one column shorter
1737 * than it is, and then add 1 to the result.
1739 return 1 + (it * (width - 1) / max_change);
1742 static void show_graph(struct strbuf *out, char ch, int cnt,
1743 const char *set, const char *reset)
1747 strbuf_addstr(out, set);
1748 strbuf_addchars(out, ch, cnt);
1749 strbuf_addstr(out, reset);
1752 static void fill_print_name(struct diffstat_file *file)
1756 if (file->print_name)
1759 if (!file->is_renamed) {
1760 struct strbuf buf = STRBUF_INIT;
1761 if (quote_c_style(file->name, &buf, NULL, 0)) {
1762 pname = strbuf_detach(&buf, NULL);
1765 strbuf_release(&buf);
1768 pname = pprint_rename(file->from_name, file->name);
1770 file->print_name = pname;
1773 static void print_stat_summary_inserts_deletes(struct diff_options *options,
1774 int files, int insertions, int deletions)
1776 struct strbuf sb = STRBUF_INIT;
1779 assert(insertions == 0 && deletions == 0);
1780 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
1786 (files == 1) ? " %d file changed" : " %d files changed",
1790 * For binary diff, the caller may want to print "x files
1791 * changed" with insertions == 0 && deletions == 0.
1793 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1794 * is probably less confusing (i.e skip over "2 files changed
1795 * but nothing about added/removed lines? Is this a bug in Git?").
1797 if (insertions || deletions == 0) {
1799 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1803 if (deletions || insertions == 0) {
1805 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1808 strbuf_addch(&sb, '\n');
1809 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
1811 strbuf_release(&sb);
1814 void print_stat_summary(FILE *fp, int files,
1815 int insertions, int deletions)
1817 struct diff_options o;
1818 memset(&o, 0, sizeof(o));
1821 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
1824 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1826 int i, len, add, del, adds = 0, dels = 0;
1827 uintmax_t max_change = 0, max_len = 0;
1828 int total_files = data->nr, count;
1829 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1830 const char *reset, *add_c, *del_c;
1831 int extra_shown = 0;
1832 const char *line_prefix = diff_line_prefix(options);
1833 struct strbuf out = STRBUF_INIT;
1838 count = options->stat_count ? options->stat_count : data->nr;
1840 reset = diff_get_color_opt(options, DIFF_RESET);
1841 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1842 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1845 * Find the longest filename and max number of changes
1847 for (i = 0; (i < count) && (i < data->nr); i++) {
1848 struct diffstat_file *file = data->files[i];
1849 uintmax_t change = file->added + file->deleted;
1851 if (!file->is_interesting && (change == 0)) {
1852 count++; /* not shown == room for one more */
1855 fill_print_name(file);
1856 len = strlen(file->print_name);
1860 if (file->is_unmerged) {
1861 /* "Unmerged" is 8 characters */
1862 bin_width = bin_width < 8 ? 8 : bin_width;
1865 if (file->is_binary) {
1866 /* "Bin XXX -> YYY bytes" */
1867 int w = 14 + decimal_width(file->added)
1868 + decimal_width(file->deleted);
1869 bin_width = bin_width < w ? w : bin_width;
1870 /* Display change counts aligned with "Bin" */
1875 if (max_change < change)
1876 max_change = change;
1878 count = i; /* where we can stop scanning in data->files[] */
1881 * We have width = stat_width or term_columns() columns total.
1882 * We want a maximum of min(max_len, stat_name_width) for the name part.
1883 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1884 * We also need 1 for " " and 4 + decimal_width(max_change)
1885 * for " | NNNN " and one the empty column at the end, altogether
1886 * 6 + decimal_width(max_change).
1888 * If there's not enough space, we will use the smaller of
1889 * stat_name_width (if set) and 5/8*width for the filename,
1890 * and the rest for constant elements + graph part, but no more
1891 * than stat_graph_width for the graph part.
1892 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1893 * for the standard terminal size).
1895 * In other words: stat_width limits the maximum width, and
1896 * stat_name_width fixes the maximum width of the filename,
1897 * and is also used to divide available columns if there
1900 * Binary files are displayed with "Bin XXX -> YYY bytes"
1901 * instead of the change count and graph. This part is treated
1902 * similarly to the graph part, except that it is not
1903 * "scaled". If total width is too small to accommodate the
1904 * guaranteed minimum width of the filename part and the
1905 * separators and this message, this message will "overflow"
1906 * making the line longer than the maximum width.
1909 if (options->stat_width == -1)
1910 width = term_columns() - strlen(line_prefix);
1912 width = options->stat_width ? options->stat_width : 80;
1913 number_width = decimal_width(max_change) > number_width ?
1914 decimal_width(max_change) : number_width;
1916 if (options->stat_graph_width == -1)
1917 options->stat_graph_width = diff_stat_graph_width;
1920 * Guarantee 3/8*16==6 for the graph part
1921 * and 5/8*16==10 for the filename part
1923 if (width < 16 + 6 + number_width)
1924 width = 16 + 6 + number_width;
1927 * First assign sizes that are wanted, ignoring available width.
1928 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1929 * starting from "XXX" should fit in graph_width.
1931 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1932 if (options->stat_graph_width &&
1933 options->stat_graph_width < graph_width)
1934 graph_width = options->stat_graph_width;
1936 name_width = (options->stat_name_width > 0 &&
1937 options->stat_name_width < max_len) ?
1938 options->stat_name_width : max_len;
1941 * Adjust adjustable widths not to exceed maximum width
1943 if (name_width + number_width + 6 + graph_width > width) {
1944 if (graph_width > width * 3/8 - number_width - 6) {
1945 graph_width = width * 3/8 - number_width - 6;
1946 if (graph_width < 6)
1950 if (options->stat_graph_width &&
1951 graph_width > options->stat_graph_width)
1952 graph_width = options->stat_graph_width;
1953 if (name_width > width - number_width - 6 - graph_width)
1954 name_width = width - number_width - 6 - graph_width;
1956 graph_width = width - number_width - 6 - name_width;
1960 * From here name_width is the width of the name area,
1961 * and graph_width is the width of the graph area.
1962 * max_change is used to scale graph properly.
1964 for (i = 0; i < count; i++) {
1965 const char *prefix = "";
1966 struct diffstat_file *file = data->files[i];
1967 char *name = file->print_name;
1968 uintmax_t added = file->added;
1969 uintmax_t deleted = file->deleted;
1972 if (!file->is_interesting && (added + deleted == 0))
1976 * "scale" the filename
1979 name_len = strlen(name);
1980 if (name_width < name_len) {
1984 name += name_len - len;
1985 slash = strchr(name, '/');
1990 if (file->is_binary) {
1991 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
1992 strbuf_addf(&out, " %*s", number_width, "Bin");
1993 if (!added && !deleted) {
1994 strbuf_addch(&out, '\n');
1995 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
1996 out.buf, out.len, 0);
2000 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2001 del_c, deleted, reset);
2002 strbuf_addstr(&out, " -> ");
2003 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2004 add_c, added, reset);
2005 strbuf_addstr(&out, " bytes\n");
2006 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2007 out.buf, out.len, 0);
2011 else if (file->is_unmerged) {
2012 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2013 strbuf_addstr(&out, " Unmerged\n");
2014 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2015 out.buf, out.len, 0);
2021 * scale the add/delete
2026 if (graph_width <= max_change) {
2027 int total = scale_linear(add + del, graph_width, max_change);
2028 if (total < 2 && add && del)
2029 /* width >= 2 due to the sanity check */
2032 add = scale_linear(add, graph_width, max_change);
2035 del = scale_linear(del, graph_width, max_change);
2039 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2040 strbuf_addf(&out, " %*"PRIuMAX"%s",
2041 number_width, added + deleted,
2042 added + deleted ? " " : "");
2043 show_graph(&out, '+', add, add_c, reset);
2044 show_graph(&out, '-', del, del_c, reset);
2045 strbuf_addch(&out, '\n');
2046 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2047 out.buf, out.len, 0);
2051 for (i = 0; i < data->nr; i++) {
2052 struct diffstat_file *file = data->files[i];
2053 uintmax_t added = file->added;
2054 uintmax_t deleted = file->deleted;
2056 if (file->is_unmerged ||
2057 (!file->is_interesting && (added + deleted == 0))) {
2062 if (!file->is_binary) {
2069 emit_diff_symbol(options,
2070 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2075 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2078 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2080 int i, adds = 0, dels = 0, total_files = data->nr;
2085 for (i = 0; i < data->nr; i++) {
2086 int added = data->files[i]->added;
2087 int deleted = data->files[i]->deleted;
2089 if (data->files[i]->is_unmerged ||
2090 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2092 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2097 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2100 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2107 for (i = 0; i < data->nr; i++) {
2108 struct diffstat_file *file = data->files[i];
2110 fprintf(options->file, "%s", diff_line_prefix(options));
2112 if (file->is_binary)
2113 fprintf(options->file, "-\t-\t");
2115 fprintf(options->file,
2116 "%"PRIuMAX"\t%"PRIuMAX"\t",
2117 file->added, file->deleted);
2118 if (options->line_termination) {
2119 fill_print_name(file);
2120 if (!file->is_renamed)
2121 write_name_quoted(file->name, options->file,
2122 options->line_termination);
2124 fputs(file->print_name, options->file);
2125 putc(options->line_termination, options->file);
2128 if (file->is_renamed) {
2129 putc('\0', options->file);
2130 write_name_quoted(file->from_name, options->file, '\0');
2132 write_name_quoted(file->name, options->file, '\0');
2137 struct dirstat_file {
2139 unsigned long changed;
2142 struct dirstat_dir {
2143 struct dirstat_file *files;
2144 int alloc, nr, permille, cumulative;
2147 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2148 unsigned long changed, const char *base, int baselen)
2150 unsigned long this_dir = 0;
2151 unsigned int sources = 0;
2152 const char *line_prefix = diff_line_prefix(opt);
2155 struct dirstat_file *f = dir->files;
2156 int namelen = strlen(f->name);
2160 if (namelen < baselen)
2162 if (memcmp(f->name, base, baselen))
2164 slash = strchr(f->name + baselen, '/');
2166 int newbaselen = slash + 1 - f->name;
2167 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2179 * We don't report dirstat's for
2181 * - or cases where everything came from a single directory
2182 * under this directory (sources == 1).
2184 if (baselen && sources != 1) {
2186 int permille = this_dir * 1000 / changed;
2187 if (permille >= dir->permille) {
2188 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2189 permille / 10, permille % 10, baselen, base);
2190 if (!dir->cumulative)
2198 static int dirstat_compare(const void *_a, const void *_b)
2200 const struct dirstat_file *a = _a;
2201 const struct dirstat_file *b = _b;
2202 return strcmp(a->name, b->name);
2205 static void show_dirstat(struct diff_options *options)
2208 unsigned long changed;
2209 struct dirstat_dir dir;
2210 struct diff_queue_struct *q = &diff_queued_diff;
2215 dir.permille = options->dirstat_permille;
2216 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2219 for (i = 0; i < q->nr; i++) {
2220 struct diff_filepair *p = q->queue[i];
2222 unsigned long copied, added, damage;
2223 int content_changed;
2225 name = p->two->path ? p->two->path : p->one->path;
2227 if (p->one->oid_valid && p->two->oid_valid)
2228 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2230 content_changed = 1;
2232 if (!content_changed) {
2234 * The SHA1 has not changed, so pre-/post-content is
2235 * identical. We can therefore skip looking at the
2236 * file contents altogether.
2242 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2244 * In --dirstat-by-file mode, we don't really need to
2245 * look at the actual file contents at all.
2246 * The fact that the SHA1 changed is enough for us to
2247 * add this file to the list of results
2248 * (with each file contributing equal damage).
2254 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2255 diff_populate_filespec(p->one, 0);
2256 diff_populate_filespec(p->two, 0);
2257 diffcore_count_changes(p->one, p->two, NULL, NULL,
2259 diff_free_filespec_data(p->one);
2260 diff_free_filespec_data(p->two);
2261 } else if (DIFF_FILE_VALID(p->one)) {
2262 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2264 diff_free_filespec_data(p->one);
2265 } else if (DIFF_FILE_VALID(p->two)) {
2266 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2268 added = p->two->size;
2269 diff_free_filespec_data(p->two);
2274 * Original minus copied is the removed material,
2275 * added is the new material. They are both damages
2276 * made to the preimage.
2277 * If the resulting damage is zero, we know that
2278 * diffcore_count_changes() considers the two entries to
2279 * be identical, but since content_changed is true, we
2280 * know that there must have been _some_ kind of change,
2281 * so we force all entries to have damage > 0.
2283 damage = (p->one->size - copied) + added;
2288 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2289 dir.files[dir.nr].name = name;
2290 dir.files[dir.nr].changed = damage;
2295 /* This can happen even with many files, if everything was renames */
2299 /* Show all directories with more than x% of the changes */
2300 QSORT(dir.files, dir.nr, dirstat_compare);
2301 gather_dirstat(options, &dir, changed, "", 0);
2304 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2307 unsigned long changed;
2308 struct dirstat_dir dir;
2316 dir.permille = options->dirstat_permille;
2317 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2320 for (i = 0; i < data->nr; i++) {
2321 struct diffstat_file *file = data->files[i];
2322 unsigned long damage = file->added + file->deleted;
2323 if (file->is_binary)
2325 * binary files counts bytes, not lines. Must find some
2326 * way to normalize binary bytes vs. textual lines.
2327 * The following heuristic assumes that there are 64
2329 * This is stupid and ugly, but very cheap...
2331 damage = (damage + 63) / 64;
2332 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2333 dir.files[dir.nr].name = file->name;
2334 dir.files[dir.nr].changed = damage;
2339 /* This can happen even with many files, if everything was renames */
2343 /* Show all directories with more than x% of the changes */
2344 QSORT(dir.files, dir.nr, dirstat_compare);
2345 gather_dirstat(options, &dir, changed, "", 0);
2348 static void free_diffstat_info(struct diffstat_t *diffstat)
2351 for (i = 0; i < diffstat->nr; i++) {
2352 struct diffstat_file *f = diffstat->files[i];
2353 if (f->name != f->print_name)
2354 free(f->print_name);
2359 free(diffstat->files);
2362 struct checkdiff_t {
2363 const char *filename;
2365 int conflict_marker_size;
2366 struct diff_options *o;
2371 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2376 if (len < marker_size + 1)
2378 firstchar = line[0];
2379 switch (firstchar) {
2380 case '=': case '>': case '<': case '|':
2385 for (cnt = 1; cnt < marker_size; cnt++)
2386 if (line[cnt] != firstchar)
2388 /* line[1] thru line[marker_size-1] are same as firstchar */
2389 if (len < marker_size + 1 || !isspace(line[marker_size]))
2394 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2396 struct checkdiff_t *data = priv;
2397 int marker_size = data->conflict_marker_size;
2398 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2399 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2400 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2402 const char *line_prefix;
2405 line_prefix = diff_line_prefix(data->o);
2407 if (line[0] == '+') {
2410 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2412 fprintf(data->o->file,
2413 "%s%s:%d: leftover conflict marker\n",
2414 line_prefix, data->filename, data->lineno);
2416 bad = ws_check(line + 1, len - 1, data->ws_rule);
2419 data->status |= bad;
2420 err = whitespace_error_string(bad);
2421 fprintf(data->o->file, "%s%s:%d: %s.\n",
2422 line_prefix, data->filename, data->lineno, err);
2424 emit_line(data->o, set, reset, line, 1);
2425 ws_check_emit(line + 1, len - 1, data->ws_rule,
2426 data->o->file, set, reset, ws);
2427 } else if (line[0] == ' ') {
2429 } else if (line[0] == '@') {
2430 char *plus = strchr(line, '+');
2432 data->lineno = strtol(plus, NULL, 10) - 1;
2434 die("invalid diff");
2438 static unsigned char *deflate_it(char *data,
2440 unsigned long *result_size)
2443 unsigned char *deflated;
2446 git_deflate_init(&stream, zlib_compression_level);
2447 bound = git_deflate_bound(&stream, size);
2448 deflated = xmalloc(bound);
2449 stream.next_out = deflated;
2450 stream.avail_out = bound;
2452 stream.next_in = (unsigned char *)data;
2453 stream.avail_in = size;
2454 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2456 git_deflate_end(&stream);
2457 *result_size = stream.total_out;
2461 static void emit_binary_diff_body(struct diff_options *o,
2462 mmfile_t *one, mmfile_t *two)
2468 unsigned long orig_size;
2469 unsigned long delta_size;
2470 unsigned long deflate_size;
2471 unsigned long data_size;
2473 /* We could do deflated delta, or we could do just deflated two,
2474 * whichever is smaller.
2477 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2478 if (one->size && two->size) {
2479 delta = diff_delta(one->ptr, one->size,
2480 two->ptr, two->size,
2481 &delta_size, deflate_size);
2483 void *to_free = delta;
2484 orig_size = delta_size;
2485 delta = deflate_it(delta, delta_size, &delta_size);
2490 if (delta && delta_size < deflate_size) {
2491 char *s = xstrfmt("%lu", orig_size);
2492 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2497 data_size = delta_size;
2499 char *s = xstrfmt("%lu", two->size);
2500 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2505 data_size = deflate_size;
2508 /* emit data encoded in base85 */
2512 int bytes = (52 < data_size) ? 52 : data_size;
2516 line[0] = bytes + 'A' - 1;
2518 line[0] = bytes - 26 + 'a' - 1;
2519 encode_85(line + 1, cp, bytes);
2520 cp = (char *) cp + bytes;
2526 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2529 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2533 static void emit_binary_diff(struct diff_options *o,
2534 mmfile_t *one, mmfile_t *two)
2536 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2537 emit_binary_diff_body(o, one, two);
2538 emit_binary_diff_body(o, two, one);
2541 int diff_filespec_is_binary(struct diff_filespec *one)
2543 if (one->is_binary == -1) {
2544 diff_filespec_load_driver(one);
2545 if (one->driver->binary != -1)
2546 one->is_binary = one->driver->binary;
2548 if (!one->data && DIFF_FILE_VALID(one))
2549 diff_populate_filespec(one, CHECK_BINARY);
2550 if (one->is_binary == -1 && one->data)
2551 one->is_binary = buffer_is_binary(one->data,
2553 if (one->is_binary == -1)
2557 return one->is_binary;
2560 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2562 diff_filespec_load_driver(one);
2563 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2566 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2568 if (!options->a_prefix)
2569 options->a_prefix = a;
2570 if (!options->b_prefix)
2571 options->b_prefix = b;
2574 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2576 if (!DIFF_FILE_VALID(one))
2579 diff_filespec_load_driver(one);
2580 return userdiff_get_textconv(one->driver);
2583 static void builtin_diff(const char *name_a,
2585 struct diff_filespec *one,
2586 struct diff_filespec *two,
2587 const char *xfrm_msg,
2588 int must_show_header,
2589 struct diff_options *o,
2590 int complete_rewrite)
2594 char *a_one, *b_two;
2595 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2596 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2597 const char *a_prefix, *b_prefix;
2598 struct userdiff_driver *textconv_one = NULL;
2599 struct userdiff_driver *textconv_two = NULL;
2600 struct strbuf header = STRBUF_INIT;
2601 const char *line_prefix = diff_line_prefix(o);
2603 diff_set_mnemonic_prefix(o, "a/", "b/");
2604 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2605 a_prefix = o->b_prefix;
2606 b_prefix = o->a_prefix;
2608 a_prefix = o->a_prefix;
2609 b_prefix = o->b_prefix;
2612 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2613 (!one->mode || S_ISGITLINK(one->mode)) &&
2614 (!two->mode || S_ISGITLINK(two->mode))) {
2615 show_submodule_summary(o, one->path ? one->path : two->path,
2616 &one->oid, &two->oid,
2617 two->dirty_submodule);
2619 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2620 (!one->mode || S_ISGITLINK(one->mode)) &&
2621 (!two->mode || S_ISGITLINK(two->mode))) {
2622 show_submodule_inline_diff(o, one->path ? one->path : two->path,
2623 &one->oid, &two->oid,
2624 two->dirty_submodule);
2628 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2629 textconv_one = get_textconv(one);
2630 textconv_two = get_textconv(two);
2633 /* Never use a non-valid filename anywhere if at all possible */
2634 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2635 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2637 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2638 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2639 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2640 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2641 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2642 if (lbl[0][0] == '/') {
2644 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2646 strbuf_addstr(&header, xfrm_msg);
2647 must_show_header = 1;
2649 else if (lbl[1][0] == '/') {
2650 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2652 strbuf_addstr(&header, xfrm_msg);
2653 must_show_header = 1;
2656 if (one->mode != two->mode) {
2657 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2658 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2659 must_show_header = 1;
2662 strbuf_addstr(&header, xfrm_msg);
2665 * we do not run diff between different kind
2668 if ((one->mode ^ two->mode) & S_IFMT)
2669 goto free_ab_and_return;
2670 if (complete_rewrite &&
2671 (textconv_one || !diff_filespec_is_binary(one)) &&
2672 (textconv_two || !diff_filespec_is_binary(two))) {
2673 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2674 header.buf, header.len, 0);
2675 strbuf_reset(&header);
2676 emit_rewrite_diff(name_a, name_b, one, two,
2677 textconv_one, textconv_two, o);
2678 o->found_changes = 1;
2679 goto free_ab_and_return;
2683 if (o->irreversible_delete && lbl[1][0] == '/') {
2684 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
2686 strbuf_reset(&header);
2687 goto free_ab_and_return;
2688 } else if (!DIFF_OPT_TST(o, TEXT) &&
2689 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2690 (!textconv_two && diff_filespec_is_binary(two)) )) {
2691 struct strbuf sb = STRBUF_INIT;
2692 if (!one->data && !two->data &&
2693 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2694 !DIFF_OPT_TST(o, BINARY)) {
2695 if (!oidcmp(&one->oid, &two->oid)) {
2696 if (must_show_header)
2697 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2698 header.buf, header.len,
2700 goto free_ab_and_return;
2702 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2703 header.buf, header.len, 0);
2704 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
2705 diff_line_prefix(o), lbl[0], lbl[1]);
2706 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
2708 strbuf_release(&sb);
2709 goto free_ab_and_return;
2711 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2712 die("unable to read files to diff");
2713 /* Quite common confusing case */
2714 if (mf1.size == mf2.size &&
2715 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2716 if (must_show_header)
2717 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2718 header.buf, header.len, 0);
2719 goto free_ab_and_return;
2721 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
2722 strbuf_reset(&header);
2723 if (DIFF_OPT_TST(o, BINARY))
2724 emit_binary_diff(o, &mf1, &mf2);
2726 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
2727 diff_line_prefix(o), lbl[0], lbl[1]);
2728 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
2730 strbuf_release(&sb);
2732 o->found_changes = 1;
2734 /* Crazy xdl interfaces.. */
2735 const char *diffopts = getenv("GIT_DIFF_OPTS");
2739 struct emit_callback ecbdata;
2740 const struct userdiff_funcname *pe;
2742 if (must_show_header) {
2743 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2744 header.buf, header.len, 0);
2745 strbuf_reset(&header);
2748 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2749 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2751 pe = diff_funcname_pattern(one);
2753 pe = diff_funcname_pattern(two);
2755 memset(&xpp, 0, sizeof(xpp));
2756 memset(&xecfg, 0, sizeof(xecfg));
2757 memset(&ecbdata, 0, sizeof(ecbdata));
2758 ecbdata.label_path = lbl;
2759 ecbdata.color_diff = want_color(o->use_color);
2760 ecbdata.ws_rule = whitespace_rule(name_b);
2761 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2762 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2764 ecbdata.header = header.len ? &header : NULL;
2765 xpp.flags = o->xdl_opts;
2766 xecfg.ctxlen = o->context;
2767 xecfg.interhunkctxlen = o->interhunkcontext;
2768 xecfg.flags = XDL_EMIT_FUNCNAMES;
2769 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2770 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2772 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2775 else if (skip_prefix(diffopts, "--unified=", &v))
2776 xecfg.ctxlen = strtoul(v, NULL, 10);
2777 else if (skip_prefix(diffopts, "-u", &v))
2778 xecfg.ctxlen = strtoul(v, NULL, 10);
2780 init_diff_words_data(&ecbdata, o, one, two);
2781 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2783 die("unable to generate diff for %s", one->path);
2785 free_diff_words_data(&ecbdata);
2790 xdiff_clear_find_func(&xecfg);
2794 strbuf_release(&header);
2795 diff_free_filespec_data(one);
2796 diff_free_filespec_data(two);
2802 static void builtin_diffstat(const char *name_a, const char *name_b,
2803 struct diff_filespec *one,
2804 struct diff_filespec *two,
2805 struct diffstat_t *diffstat,
2806 struct diff_options *o,
2807 struct diff_filepair *p)
2810 struct diffstat_file *data;
2812 int complete_rewrite = 0;
2814 if (!DIFF_PAIR_UNMERGED(p)) {
2815 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2816 complete_rewrite = 1;
2819 data = diffstat_add(diffstat, name_a, name_b);
2820 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2823 data->is_unmerged = 1;
2827 same_contents = !oidcmp(&one->oid, &two->oid);
2829 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2830 data->is_binary = 1;
2831 if (same_contents) {
2835 data->added = diff_filespec_size(two);
2836 data->deleted = diff_filespec_size(one);
2840 else if (complete_rewrite) {
2841 diff_populate_filespec(one, 0);
2842 diff_populate_filespec(two, 0);
2843 data->deleted = count_lines(one->data, one->size);
2844 data->added = count_lines(two->data, two->size);
2847 else if (!same_contents) {
2848 /* Crazy xdl interfaces.. */
2852 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2853 die("unable to read files to diff");
2855 memset(&xpp, 0, sizeof(xpp));
2856 memset(&xecfg, 0, sizeof(xecfg));
2857 xpp.flags = o->xdl_opts;
2858 xecfg.ctxlen = o->context;
2859 xecfg.interhunkctxlen = o->interhunkcontext;
2860 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2862 die("unable to generate diffstat for %s", one->path);
2865 diff_free_filespec_data(one);
2866 diff_free_filespec_data(two);
2869 static void builtin_checkdiff(const char *name_a, const char *name_b,
2870 const char *attr_path,
2871 struct diff_filespec *one,
2872 struct diff_filespec *two,
2873 struct diff_options *o)
2876 struct checkdiff_t data;
2881 memset(&data, 0, sizeof(data));
2882 data.filename = name_b ? name_b : name_a;
2885 data.ws_rule = whitespace_rule(attr_path);
2886 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2888 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2889 die("unable to read files to diff");
2892 * All the other codepaths check both sides, but not checking
2893 * the "old" side here is deliberate. We are checking the newly
2894 * introduced changes, and as long as the "new" side is text, we
2895 * can and should check what it introduces.
2897 if (diff_filespec_is_binary(two))
2898 goto free_and_return;
2900 /* Crazy xdl interfaces.. */
2904 memset(&xpp, 0, sizeof(xpp));
2905 memset(&xecfg, 0, sizeof(xecfg));
2906 xecfg.ctxlen = 1; /* at least one context line */
2908 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2910 die("unable to generate checkdiff for %s", one->path);
2912 if (data.ws_rule & WS_BLANK_AT_EOF) {
2913 struct emit_callback ecbdata;
2916 ecbdata.ws_rule = data.ws_rule;
2917 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2918 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2923 err = whitespace_error_string(WS_BLANK_AT_EOF);
2924 fprintf(o->file, "%s:%d: %s.\n",
2925 data.filename, blank_at_eof, err);
2926 data.status = 1; /* report errors */
2931 diff_free_filespec_data(one);
2932 diff_free_filespec_data(two);
2934 DIFF_OPT_SET(o, CHECK_FAILED);
2937 struct diff_filespec *alloc_filespec(const char *path)
2939 struct diff_filespec *spec;
2941 FLEXPTR_ALLOC_STR(spec, path, path);
2943 spec->is_binary = -1;
2947 void free_filespec(struct diff_filespec *spec)
2949 if (!--spec->count) {
2950 diff_free_filespec_data(spec);
2955 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
2956 int oid_valid, unsigned short mode)
2959 spec->mode = canon_mode(mode);
2960 oidcpy(&spec->oid, oid);
2961 spec->oid_valid = oid_valid;
2966 * Given a name and sha1 pair, if the index tells us the file in
2967 * the work tree has that object contents, return true, so that
2968 * prepare_temp_file() does not have to inflate and extract.
2970 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
2972 const struct cache_entry *ce;
2977 * We do not read the cache ourselves here, because the
2978 * benchmark with my previous version that always reads cache
2979 * shows that it makes things worse for diff-tree comparing
2980 * two linux-2.6 kernel trees in an already checked out work
2981 * tree. This is because most diff-tree comparisons deal with
2982 * only a small number of files, while reading the cache is
2983 * expensive for a large project, and its cost outweighs the
2984 * savings we get by not inflating the object to a temporary
2985 * file. Practically, this code only helps when we are used
2986 * by diff-cache --cached, which does read the cache before
2992 /* We want to avoid the working directory if our caller
2993 * doesn't need the data in a normal file, this system
2994 * is rather slow with its stat/open/mmap/close syscalls,
2995 * and the object is contained in a pack file. The pack
2996 * is probably already open and will be faster to obtain
2997 * the data through than the working directory. Loose
2998 * objects however would tend to be slower as they need
2999 * to be individually opened and inflated.
3001 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3005 * Similarly, if we'd have to convert the file contents anyway, that
3006 * makes the optimization not worthwhile.
3008 if (!want_file && would_convert_to_git(&the_index, name))
3012 pos = cache_name_pos(name, len);
3015 ce = active_cache[pos];
3018 * This is not the sha1 we are looking for, or
3019 * unreusable because it is not a regular file.
3021 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3025 * If ce is marked as "assume unchanged", there is no
3026 * guarantee that work tree matches what we are looking for.
3028 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3032 * If ce matches the file in the work tree, we can reuse it.
3034 if (ce_uptodate(ce) ||
3035 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3041 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3043 struct strbuf buf = STRBUF_INIT;
3046 /* Are we looking at the work tree? */
3047 if (s->dirty_submodule)
3050 strbuf_addf(&buf, "Subproject commit %s%s\n",
3051 oid_to_hex(&s->oid), dirty);
3055 strbuf_release(&buf);
3057 s->data = strbuf_detach(&buf, NULL);
3064 * While doing rename detection and pickaxe operation, we may need to
3065 * grab the data for the blob (or file) for our own in-core comparison.
3066 * diff_filespec has data and size fields for this purpose.
3068 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3070 int size_only = flags & CHECK_SIZE_ONLY;
3073 * demote FAIL to WARN to allow inspecting the situation
3074 * instead of refusing.
3076 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3080 if (!DIFF_FILE_VALID(s))
3081 die("internal error: asking to populate invalid file.");
3082 if (S_ISDIR(s->mode))
3088 if (size_only && 0 < s->size)
3091 if (S_ISGITLINK(s->mode))
3092 return diff_populate_gitlink(s, size_only);
3094 if (!s->oid_valid ||
3095 reuse_worktree_file(s->path, &s->oid, 0)) {
3096 struct strbuf buf = STRBUF_INIT;
3100 if (lstat(s->path, &st) < 0) {
3101 if (errno == ENOENT) {
3105 s->data = (char *)"";
3110 s->size = xsize_t(st.st_size);
3113 if (S_ISLNK(st.st_mode)) {
3114 struct strbuf sb = STRBUF_INIT;
3116 if (strbuf_readlink(&sb, s->path, s->size))
3119 s->data = strbuf_detach(&sb, NULL);
3125 * Even if the caller would be happy with getting
3126 * only the size, we cannot return early at this
3127 * point if the path requires us to run the content
3130 if (size_only && !would_convert_to_git(&the_index, s->path))
3134 * Note: this check uses xsize_t(st.st_size) that may
3135 * not be the true size of the blob after it goes
3136 * through convert_to_git(). This may not strictly be
3137 * correct, but the whole point of big_file_threshold
3138 * and is_binary check being that we want to avoid
3139 * opening the file and inspecting the contents, this
3142 if ((flags & CHECK_BINARY) &&
3143 s->size > big_file_threshold && s->is_binary == -1) {
3147 fd = open(s->path, O_RDONLY);
3150 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3152 s->should_munmap = 1;
3155 * Convert from working tree format to canonical git format
3157 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
3159 munmap(s->data, s->size);
3160 s->should_munmap = 0;
3161 s->data = strbuf_detach(&buf, &size);
3167 enum object_type type;
3168 if (size_only || (flags & CHECK_BINARY)) {
3169 type = sha1_object_info(s->oid.hash, &s->size);
3171 die("unable to read %s",
3172 oid_to_hex(&s->oid));
3175 if (s->size > big_file_threshold && s->is_binary == -1) {
3180 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
3182 die("unable to read %s", oid_to_hex(&s->oid));
3188 void diff_free_filespec_blob(struct diff_filespec *s)
3192 else if (s->should_munmap)
3193 munmap(s->data, s->size);
3195 if (s->should_free || s->should_munmap) {
3196 s->should_free = s->should_munmap = 0;
3201 void diff_free_filespec_data(struct diff_filespec *s)
3203 diff_free_filespec_blob(s);
3204 FREE_AND_NULL(s->cnt_data);
3207 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3210 const struct object_id *oid,
3214 struct strbuf buf = STRBUF_INIT;
3215 struct strbuf template = STRBUF_INIT;
3216 char *path_dup = xstrdup(path);
3217 const char *base = basename(path_dup);
3219 /* Generate "XXXXXX_basename.ext" */
3220 strbuf_addstr(&template, "XXXXXX_");
3221 strbuf_addstr(&template, base);
3223 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
3225 die_errno("unable to create temp-file");
3226 if (convert_to_working_tree(path,
3227 (const char *)blob, (size_t)size, &buf)) {
3231 if (write_in_full(fd, blob, size) != size)
3232 die_errno("unable to write temp-file");
3233 close_tempfile(&temp->tempfile);
3234 temp->name = get_tempfile_path(&temp->tempfile);
3235 oid_to_hex_r(temp->hex, oid);
3236 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3237 strbuf_release(&buf);
3238 strbuf_release(&template);
3242 static struct diff_tempfile *prepare_temp_file(const char *name,
3243 struct diff_filespec *one)
3245 struct diff_tempfile *temp = claim_diff_tempfile();
3247 if (!DIFF_FILE_VALID(one)) {
3249 /* A '-' entry produces this for file-2, and
3250 * a '+' entry produces this for file-1.
3252 temp->name = "/dev/null";
3253 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3254 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3258 if (!S_ISGITLINK(one->mode) &&
3260 reuse_worktree_file(name, &one->oid, 1))) {
3262 if (lstat(name, &st) < 0) {
3263 if (errno == ENOENT)
3264 goto not_a_valid_file;
3265 die_errno("stat(%s)", name);
3267 if (S_ISLNK(st.st_mode)) {
3268 struct strbuf sb = STRBUF_INIT;
3269 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3270 die_errno("readlink(%s)", name);
3271 prep_temp_blob(name, temp, sb.buf, sb.len,
3273 &one->oid : &null_oid),
3275 one->mode : S_IFLNK));
3276 strbuf_release(&sb);
3279 /* we can borrow from the file in the work tree */
3281 if (!one->oid_valid)
3282 oid_to_hex_r(temp->hex, &null_oid);
3284 oid_to_hex_r(temp->hex, &one->oid);
3285 /* Even though we may sometimes borrow the
3286 * contents from the work tree, we always want
3287 * one->mode. mode is trustworthy even when
3288 * !(one->oid_valid), as long as
3289 * DIFF_FILE_VALID(one).
3291 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3296 if (diff_populate_filespec(one, 0))
3297 die("cannot read data blob for %s", one->path);
3298 prep_temp_blob(name, temp, one->data, one->size,
3299 &one->oid, one->mode);
3304 static void add_external_diff_name(struct argv_array *argv,
3306 struct diff_filespec *df)
3308 struct diff_tempfile *temp = prepare_temp_file(name, df);
3309 argv_array_push(argv, temp->name);
3310 argv_array_push(argv, temp->hex);
3311 argv_array_push(argv, temp->mode);
3314 /* An external diff command takes:
3316 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3317 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3320 static void run_external_diff(const char *pgm,
3323 struct diff_filespec *one,
3324 struct diff_filespec *two,
3325 const char *xfrm_msg,
3326 int complete_rewrite,
3327 struct diff_options *o)
3329 struct argv_array argv = ARGV_ARRAY_INIT;
3330 struct argv_array env = ARGV_ARRAY_INIT;
3331 struct diff_queue_struct *q = &diff_queued_diff;
3333 argv_array_push(&argv, pgm);
3334 argv_array_push(&argv, name);
3337 add_external_diff_name(&argv, name, one);
3339 add_external_diff_name(&argv, name, two);
3341 add_external_diff_name(&argv, other, two);
3342 argv_array_push(&argv, other);
3343 argv_array_push(&argv, xfrm_msg);
3347 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3348 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3350 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3351 die(_("external diff died, stopping at %s"), name);
3354 argv_array_clear(&argv);
3355 argv_array_clear(&env);
3358 static int similarity_index(struct diff_filepair *p)
3360 return p->score * 100 / MAX_SCORE;
3363 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3365 if (startup_info->have_repository)
3366 return find_unique_abbrev(oid->hash, abbrev);
3368 char *hex = oid_to_hex(oid);
3370 abbrev = FALLBACK_DEFAULT_ABBREV;
3371 if (abbrev > GIT_SHA1_HEXSZ)
3372 die("BUG: oid abbreviation out of range: %d", abbrev);
3379 static void fill_metainfo(struct strbuf *msg,
3382 struct diff_filespec *one,
3383 struct diff_filespec *two,
3384 struct diff_options *o,
3385 struct diff_filepair *p,
3386 int *must_show_header,
3389 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3390 const char *reset = diff_get_color(use_color, DIFF_RESET);
3391 const char *line_prefix = diff_line_prefix(o);
3393 *must_show_header = 1;
3394 strbuf_init(msg, PATH_MAX * 2 + 300);
3395 switch (p->status) {
3396 case DIFF_STATUS_COPIED:
3397 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3398 line_prefix, set, similarity_index(p));
3399 strbuf_addf(msg, "%s\n%s%scopy from ",
3400 reset, line_prefix, set);
3401 quote_c_style(name, msg, NULL, 0);
3402 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3403 quote_c_style(other, msg, NULL, 0);
3404 strbuf_addf(msg, "%s\n", reset);
3406 case DIFF_STATUS_RENAMED:
3407 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3408 line_prefix, set, similarity_index(p));
3409 strbuf_addf(msg, "%s\n%s%srename from ",
3410 reset, line_prefix, set);
3411 quote_c_style(name, msg, NULL, 0);
3412 strbuf_addf(msg, "%s\n%s%srename to ",
3413 reset, line_prefix, set);
3414 quote_c_style(other, msg, NULL, 0);
3415 strbuf_addf(msg, "%s\n", reset);
3417 case DIFF_STATUS_MODIFIED:
3419 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3421 set, similarity_index(p), reset);
3426 *must_show_header = 0;
3428 if (one && two && oidcmp(&one->oid, &two->oid)) {
3429 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3431 if (DIFF_OPT_TST(o, BINARY)) {
3433 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3434 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3437 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3438 diff_abbrev_oid(&one->oid, abbrev),
3439 diff_abbrev_oid(&two->oid, abbrev));
3440 if (one->mode == two->mode)
3441 strbuf_addf(msg, " %06o", one->mode);
3442 strbuf_addf(msg, "%s\n", reset);
3446 static void run_diff_cmd(const char *pgm,
3449 const char *attr_path,
3450 struct diff_filespec *one,
3451 struct diff_filespec *two,
3453 struct diff_options *o,
3454 struct diff_filepair *p)
3456 const char *xfrm_msg = NULL;
3457 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3458 int must_show_header = 0;
3461 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3462 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3463 if (drv && drv->external)
3464 pgm = drv->external;
3469 * don't use colors when the header is intended for an
3470 * external diff driver
3472 fill_metainfo(msg, name, other, one, two, o, p,
3474 want_color(o->use_color) && !pgm);
3475 xfrm_msg = msg->len ? msg->buf : NULL;
3479 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3480 complete_rewrite, o);
3484 builtin_diff(name, other ? other : name,
3485 one, two, xfrm_msg, must_show_header,
3486 o, complete_rewrite);
3488 fprintf(o->file, "* Unmerged path %s\n", name);
3491 static void diff_fill_oid_info(struct diff_filespec *one)
3493 if (DIFF_FILE_VALID(one)) {
3494 if (!one->oid_valid) {
3496 if (one->is_stdin) {
3500 if (lstat(one->path, &st) < 0)
3501 die_errno("stat '%s'", one->path);
3502 if (index_path(one->oid.hash, one->path, &st, 0))
3503 die("cannot hash %s", one->path);
3510 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3512 /* Strip the prefix but do not molest /dev/null and absolute paths */
3513 if (*namep && **namep != '/') {
3514 *namep += prefix_length;
3518 if (*otherp && **otherp != '/') {
3519 *otherp += prefix_length;
3520 if (**otherp == '/')
3525 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3527 const char *pgm = external_diff();
3529 struct diff_filespec *one = p->one;
3530 struct diff_filespec *two = p->two;
3533 const char *attr_path;
3536 other = (strcmp(name, two->path) ? two->path : NULL);
3538 if (o->prefix_length)
3539 strip_prefix(o->prefix_length, &name, &other);
3541 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3544 if (DIFF_PAIR_UNMERGED(p)) {
3545 run_diff_cmd(pgm, name, NULL, attr_path,
3546 NULL, NULL, NULL, o, p);
3550 diff_fill_oid_info(one);
3551 diff_fill_oid_info(two);
3554 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3555 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3557 * a filepair that changes between file and symlink
3558 * needs to be split into deletion and creation.
3560 struct diff_filespec *null = alloc_filespec(two->path);
3561 run_diff_cmd(NULL, name, other, attr_path,
3562 one, null, &msg, o, p);
3564 strbuf_release(&msg);
3566 null = alloc_filespec(one->path);
3567 run_diff_cmd(NULL, name, other, attr_path,
3568 null, two, &msg, o, p);
3572 run_diff_cmd(pgm, name, other, attr_path,
3573 one, two, &msg, o, p);
3575 strbuf_release(&msg);
3578 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3579 struct diffstat_t *diffstat)
3584 if (DIFF_PAIR_UNMERGED(p)) {
3586 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3590 name = p->one->path;
3591 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3593 if (o->prefix_length)
3594 strip_prefix(o->prefix_length, &name, &other);
3596 diff_fill_oid_info(p->one);
3597 diff_fill_oid_info(p->two);
3599 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3602 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3606 const char *attr_path;
3608 if (DIFF_PAIR_UNMERGED(p)) {
3613 name = p->one->path;
3614 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3615 attr_path = other ? other : name;
3617 if (o->prefix_length)
3618 strip_prefix(o->prefix_length, &name, &other);
3620 diff_fill_oid_info(p->one);
3621 diff_fill_oid_info(p->two);
3623 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3626 void diff_setup(struct diff_options *options)
3628 memcpy(options, &default_diff_options, sizeof(*options));
3630 options->file = stdout;
3632 options->abbrev = DEFAULT_ABBREV;
3633 options->line_termination = '\n';
3634 options->break_opt = -1;
3635 options->rename_limit = -1;
3636 options->dirstat_permille = diff_dirstat_permille_default;
3637 options->context = diff_context_default;
3638 options->interhunkcontext = diff_interhunk_context_default;
3639 options->ws_error_highlight = ws_error_highlight_default;
3640 DIFF_OPT_SET(options, RENAME_EMPTY);
3642 /* pathchange left =NULL by default */
3643 options->change = diff_change;
3644 options->add_remove = diff_addremove;
3645 options->use_color = diff_use_color_default;
3646 options->detect_rename = diff_detect_rename_default;
3647 options->xdl_opts |= diff_algorithm;
3648 if (diff_indent_heuristic)
3649 DIFF_XDL_SET(options, INDENT_HEURISTIC);
3651 options->orderfile = diff_order_file_cfg;
3653 if (diff_no_prefix) {
3654 options->a_prefix = options->b_prefix = "";
3655 } else if (!diff_mnemonic_prefix) {
3656 options->a_prefix = "a/";
3657 options->b_prefix = "b/";
3661 void diff_setup_done(struct diff_options *options)
3665 if (options->set_default)
3666 options->set_default(options);
3668 if (options->output_format & DIFF_FORMAT_NAME)
3670 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3672 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3674 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3677 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
3680 * Most of the time we can say "there are changes"
3681 * only by checking if there are changed paths, but
3682 * --ignore-whitespace* options force us to look
3686 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3687 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3688 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3689 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3691 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3693 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3694 options->detect_rename = DIFF_DETECT_COPY;
3696 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3697 options->prefix = NULL;
3698 if (options->prefix)
3699 options->prefix_length = strlen(options->prefix);
3701 options->prefix_length = 0;
3703 if (options->output_format & (DIFF_FORMAT_NAME |
3704 DIFF_FORMAT_NAME_STATUS |
3705 DIFF_FORMAT_CHECKDIFF |
3706 DIFF_FORMAT_NO_OUTPUT))
3707 options->output_format &= ~(DIFF_FORMAT_RAW |
3708 DIFF_FORMAT_NUMSTAT |
3709 DIFF_FORMAT_DIFFSTAT |
3710 DIFF_FORMAT_SHORTSTAT |
3711 DIFF_FORMAT_DIRSTAT |
3712 DIFF_FORMAT_SUMMARY |
3716 * These cases always need recursive; we do not drop caller-supplied
3717 * recursive bits for other formats here.
3719 if (options->output_format & (DIFF_FORMAT_PATCH |
3720 DIFF_FORMAT_NUMSTAT |
3721 DIFF_FORMAT_DIFFSTAT |
3722 DIFF_FORMAT_SHORTSTAT |
3723 DIFF_FORMAT_DIRSTAT |
3724 DIFF_FORMAT_SUMMARY |
3725 DIFF_FORMAT_CHECKDIFF))
3726 DIFF_OPT_SET(options, RECURSIVE);
3728 * Also pickaxe would not work very well if you do not say recursive
3730 if (options->pickaxe)
3731 DIFF_OPT_SET(options, RECURSIVE);
3733 * When patches are generated, submodules diffed against the work tree
3734 * must be checked for dirtiness too so it can be shown in the output
3736 if (options->output_format & DIFF_FORMAT_PATCH)
3737 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3739 if (options->detect_rename && options->rename_limit < 0)
3740 options->rename_limit = diff_rename_limit_default;
3741 if (options->setup & DIFF_SETUP_USE_CACHE) {
3743 /* read-cache does not die even when it fails
3744 * so it is safe for us to do this here. Also
3745 * it does not smudge active_cache or active_nr
3746 * when it fails, so we do not have to worry about
3747 * cleaning it up ourselves either.
3751 if (40 < options->abbrev)
3752 options->abbrev = 40; /* full */
3755 * It does not make sense to show the first hit we happened
3756 * to have found. It does not make sense not to return with
3757 * exit code in such a case either.
3759 if (DIFF_OPT_TST(options, QUICK)) {
3760 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3761 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3764 options->diff_path_counter = 0;
3766 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3767 die(_("--follow requires exactly one pathspec"));
3770 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3780 if (c == arg_short) {
3784 if (val && isdigit(c)) {
3786 int n = strtoul(arg, &end, 10);
3797 eq = strchrnul(arg, '=');
3799 if (!len || strncmp(arg, arg_long, len))
3804 if (!isdigit(*++eq))
3806 n = strtoul(eq, &end, 10);
3814 static int diff_scoreopt_parse(const char *opt);
3816 static inline int short_opt(char opt, const char **argv,
3817 const char **optarg)
3819 const char *arg = argv[0];
3820 if (arg[0] != '-' || arg[1] != opt)
3822 if (arg[2] != '\0') {
3827 die("Option '%c' requires a value", opt);
3832 int parse_long_opt(const char *opt, const char **argv,
3833 const char **optarg)
3835 const char *arg = argv[0];
3836 if (!skip_prefix(arg, "--", &arg))
3838 if (!skip_prefix(arg, opt, &arg))
3840 if (*arg == '=') { /* stuck form: --option=value */
3846 /* separate form: --option value */
3848 die("Option '--%s' requires a value", opt);
3853 static int stat_opt(struct diff_options *options, const char **av)
3855 const char *arg = av[0];
3857 int width = options->stat_width;
3858 int name_width = options->stat_name_width;
3859 int graph_width = options->stat_graph_width;
3860 int count = options->stat_count;
3863 if (!skip_prefix(arg, "--stat", &arg))
3864 die("BUG: stat option does not begin with --stat: %s", arg);
3869 if (skip_prefix(arg, "-width", &arg)) {
3871 width = strtoul(arg + 1, &end, 10);
3872 else if (!*arg && !av[1])
3873 die_want_option("--stat-width");
3875 width = strtoul(av[1], &end, 10);
3878 } else if (skip_prefix(arg, "-name-width", &arg)) {
3880 name_width = strtoul(arg + 1, &end, 10);
3881 else if (!*arg && !av[1])
3882 die_want_option("--stat-name-width");
3884 name_width = strtoul(av[1], &end, 10);
3887 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3889 graph_width = strtoul(arg + 1, &end, 10);
3890 else if (!*arg && !av[1])
3891 die_want_option("--stat-graph-width");
3893 graph_width = strtoul(av[1], &end, 10);
3896 } else if (skip_prefix(arg, "-count", &arg)) {
3898 count = strtoul(arg + 1, &end, 10);
3899 else if (!*arg && !av[1])
3900 die_want_option("--stat-count");
3902 count = strtoul(av[1], &end, 10);
3908 width = strtoul(arg+1, &end, 10);
3910 name_width = strtoul(end+1, &end, 10);
3912 count = strtoul(end+1, &end, 10);
3915 /* Important! This checks all the error cases! */
3918 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3919 options->stat_name_width = name_width;
3920 options->stat_graph_width = graph_width;
3921 options->stat_width = width;
3922 options->stat_count = count;
3926 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3928 struct strbuf errmsg = STRBUF_INIT;
3929 if (parse_dirstat_params(options, params, &errmsg))
3930 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3932 strbuf_release(&errmsg);
3934 * The caller knows a dirstat-related option is given from the command
3935 * line; allow it to say "return this_function();"
3937 options->output_format |= DIFF_FORMAT_DIRSTAT;
3941 static int parse_submodule_opt(struct diff_options *options, const char *value)
3943 if (parse_submodule_params(options, value))
3944 die(_("Failed to parse --submodule option parameter: '%s'"),
3949 static const char diff_status_letters[] = {
3952 DIFF_STATUS_DELETED,
3953 DIFF_STATUS_MODIFIED,
3954 DIFF_STATUS_RENAMED,
3955 DIFF_STATUS_TYPE_CHANGED,
3956 DIFF_STATUS_UNKNOWN,
3957 DIFF_STATUS_UNMERGED,
3958 DIFF_STATUS_FILTER_AON,
3959 DIFF_STATUS_FILTER_BROKEN,
3963 static unsigned int filter_bit['Z' + 1];
3965 static void prepare_filter_bits(void)
3969 if (!filter_bit[DIFF_STATUS_ADDED]) {
3970 for (i = 0; diff_status_letters[i]; i++)
3971 filter_bit[(int) diff_status_letters[i]] = (1 << i);
3975 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
3977 return opt->filter & filter_bit[(int) status];
3980 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
3984 prepare_filter_bits();
3987 * If there is a negation e.g. 'd' in the input, and we haven't
3988 * initialized the filter field with another --diff-filter, start
3989 * from full set of bits, except for AON.
3992 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3993 if (optch < 'a' || 'z' < optch)
3995 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
3996 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4001 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4005 if ('a' <= optch && optch <= 'z') {
4007 optch = toupper(optch);
4012 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4016 opt->filter &= ~bit;
4023 static void enable_patch_output(int *fmt) {
4024 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4025 *fmt |= DIFF_FORMAT_PATCH;
4028 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4030 int val = parse_ws_error_highlight(arg);
4033 error("unknown value after ws-error-highlight=%.*s",
4037 opt->ws_error_highlight = val;
4041 int diff_opt_parse(struct diff_options *options,
4042 const char **av, int ac, const char *prefix)
4044 const char *arg = av[0];
4051 /* Output format options */
4052 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4053 || opt_arg(arg, 'U', "unified", &options->context))
4054 enable_patch_output(&options->output_format);
4055 else if (!strcmp(arg, "--raw"))
4056 options->output_format |= DIFF_FORMAT_RAW;
4057 else if (!strcmp(arg, "--patch-with-raw")) {
4058 enable_patch_output(&options->output_format);
4059 options->output_format |= DIFF_FORMAT_RAW;
4060 } else if (!strcmp(arg, "--numstat"))
4061 options->output_format |= DIFF_FORMAT_NUMSTAT;
4062 else if (!strcmp(arg, "--shortstat"))
4063 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4064 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
4065 return parse_dirstat_opt(options, "");
4066 else if (skip_prefix(arg, "-X", &arg))
4067 return parse_dirstat_opt(options, arg);
4068 else if (skip_prefix(arg, "--dirstat=", &arg))
4069 return parse_dirstat_opt(options, arg);
4070 else if (!strcmp(arg, "--cumulative"))
4071 return parse_dirstat_opt(options, "cumulative");
4072 else if (!strcmp(arg, "--dirstat-by-file"))
4073 return parse_dirstat_opt(options, "files");
4074 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
4075 parse_dirstat_opt(options, "files");
4076 return parse_dirstat_opt(options, arg);
4078 else if (!strcmp(arg, "--check"))
4079 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4080 else if (!strcmp(arg, "--summary"))
4081 options->output_format |= DIFF_FORMAT_SUMMARY;
4082 else if (!strcmp(arg, "--patch-with-stat")) {
4083 enable_patch_output(&options->output_format);
4084 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4085 } else if (!strcmp(arg, "--name-only"))
4086 options->output_format |= DIFF_FORMAT_NAME;
4087 else if (!strcmp(arg, "--name-status"))
4088 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4089 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4090 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4091 else if (starts_with(arg, "--stat"))
4092 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4093 return stat_opt(options, av);
4095 /* renames options */
4096 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
4097 !strcmp(arg, "--break-rewrites")) {
4098 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4099 return error("invalid argument to -B: %s", arg+2);
4101 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
4102 !strcmp(arg, "--find-renames")) {
4103 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4104 return error("invalid argument to -M: %s", arg+2);
4105 options->detect_rename = DIFF_DETECT_RENAME;
4107 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4108 options->irreversible_delete = 1;
4110 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
4111 !strcmp(arg, "--find-copies")) {
4112 if (options->detect_rename == DIFF_DETECT_COPY)
4113 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4114 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4115 return error("invalid argument to -C: %s", arg+2);
4116 options->detect_rename = DIFF_DETECT_COPY;
4118 else if (!strcmp(arg, "--no-renames"))
4119 options->detect_rename = 0;
4120 else if (!strcmp(arg, "--rename-empty"))
4121 DIFF_OPT_SET(options, RENAME_EMPTY);
4122 else if (!strcmp(arg, "--no-rename-empty"))
4123 DIFF_OPT_CLR(options, RENAME_EMPTY);
4124 else if (!strcmp(arg, "--relative"))
4125 DIFF_OPT_SET(options, RELATIVE_NAME);
4126 else if (skip_prefix(arg, "--relative=", &arg)) {
4127 DIFF_OPT_SET(options, RELATIVE_NAME);
4128 options->prefix = arg;
4132 else if (!strcmp(arg, "--minimal"))
4133 DIFF_XDL_SET(options, NEED_MINIMAL);
4134 else if (!strcmp(arg, "--no-minimal"))
4135 DIFF_XDL_CLR(options, NEED_MINIMAL);
4136 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4137 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4138 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4139 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4140 else if (!strcmp(arg, "--ignore-space-at-eol"))
4141 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4142 else if (!strcmp(arg, "--ignore-blank-lines"))
4143 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4144 else if (!strcmp(arg, "--indent-heuristic"))
4145 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4146 else if (!strcmp(arg, "--no-indent-heuristic"))
4147 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4148 else if (!strcmp(arg, "--patience"))
4149 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4150 else if (!strcmp(arg, "--histogram"))
4151 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4152 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4153 long value = parse_algorithm_value(optarg);
4155 return error("option diff-algorithm accepts \"myers\", "
4156 "\"minimal\", \"patience\" and \"histogram\"");
4157 /* clear out previous settings */
4158 DIFF_XDL_CLR(options, NEED_MINIMAL);
4159 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4160 options->xdl_opts |= value;
4165 else if (!strcmp(arg, "--binary")) {
4166 enable_patch_output(&options->output_format);
4167 DIFF_OPT_SET(options, BINARY);
4169 else if (!strcmp(arg, "--full-index"))
4170 DIFF_OPT_SET(options, FULL_INDEX);
4171 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4172 DIFF_OPT_SET(options, TEXT);
4173 else if (!strcmp(arg, "-R"))
4174 DIFF_OPT_SET(options, REVERSE_DIFF);
4175 else if (!strcmp(arg, "--find-copies-harder"))
4176 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4177 else if (!strcmp(arg, "--follow"))
4178 DIFF_OPT_SET(options, FOLLOW_RENAMES);
4179 else if (!strcmp(arg, "--no-follow")) {
4180 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
4181 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
4182 } else if (!strcmp(arg, "--color"))
4183 options->use_color = 1;
4184 else if (skip_prefix(arg, "--color=", &arg)) {
4185 int value = git_config_colorbool(NULL, arg);
4187 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4188 options->use_color = value;
4190 else if (!strcmp(arg, "--no-color"))
4191 options->use_color = 0;
4192 else if (!strcmp(arg, "--color-words")) {
4193 options->use_color = 1;
4194 options->word_diff = DIFF_WORDS_COLOR;
4196 else if (skip_prefix(arg, "--color-words=", &arg)) {
4197 options->use_color = 1;
4198 options->word_diff = DIFF_WORDS_COLOR;
4199 options->word_regex = arg;
4201 else if (!strcmp(arg, "--word-diff")) {
4202 if (options->word_diff == DIFF_WORDS_NONE)
4203 options->word_diff = DIFF_WORDS_PLAIN;
4205 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4206 if (!strcmp(arg, "plain"))
4207 options->word_diff = DIFF_WORDS_PLAIN;
4208 else if (!strcmp(arg, "color")) {
4209 options->use_color = 1;
4210 options->word_diff = DIFF_WORDS_COLOR;
4212 else if (!strcmp(arg, "porcelain"))
4213 options->word_diff = DIFF_WORDS_PORCELAIN;
4214 else if (!strcmp(arg, "none"))
4215 options->word_diff = DIFF_WORDS_NONE;
4217 die("bad --word-diff argument: %s", arg);
4219 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4220 if (options->word_diff == DIFF_WORDS_NONE)
4221 options->word_diff = DIFF_WORDS_PLAIN;
4222 options->word_regex = optarg;
4225 else if (!strcmp(arg, "--exit-code"))
4226 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4227 else if (!strcmp(arg, "--quiet"))
4228 DIFF_OPT_SET(options, QUICK);
4229 else if (!strcmp(arg, "--ext-diff"))
4230 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
4231 else if (!strcmp(arg, "--no-ext-diff"))
4232 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
4233 else if (!strcmp(arg, "--textconv"))
4234 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
4235 else if (!strcmp(arg, "--no-textconv"))
4236 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
4237 else if (!strcmp(arg, "--ignore-submodules")) {
4238 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4239 handle_ignore_submodules_arg(options, "all");
4240 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
4241 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4242 handle_ignore_submodules_arg(options, arg);
4243 } else if (!strcmp(arg, "--submodule"))
4244 options->submodule_format = DIFF_SUBMODULE_LOG;
4245 else if (skip_prefix(arg, "--submodule=", &arg))
4246 return parse_submodule_opt(options, arg);
4247 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4248 return parse_ws_error_highlight_opt(options, arg);
4249 else if (!strcmp(arg, "--ita-invisible-in-index"))
4250 options->ita_invisible_in_index = 1;
4251 else if (!strcmp(arg, "--ita-visible-in-index"))
4252 options->ita_invisible_in_index = 0;
4255 else if (!strcmp(arg, "-z"))
4256 options->line_termination = 0;
4257 else if ((argcount = short_opt('l', av, &optarg))) {
4258 options->rename_limit = strtoul(optarg, NULL, 10);
4261 else if ((argcount = short_opt('S', av, &optarg))) {
4262 options->pickaxe = optarg;
4263 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4265 } else if ((argcount = short_opt('G', av, &optarg))) {
4266 options->pickaxe = optarg;
4267 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4270 else if (!strcmp(arg, "--pickaxe-all"))
4271 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4272 else if (!strcmp(arg, "--pickaxe-regex"))
4273 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4274 else if ((argcount = short_opt('O', av, &optarg))) {
4275 options->orderfile = prefix_filename(prefix, optarg);
4278 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4279 int offending = parse_diff_filter_opt(optarg, options);
4281 die("unknown change class '%c' in --diff-filter=%s",
4285 else if (!strcmp(arg, "--no-abbrev"))
4286 options->abbrev = 0;
4287 else if (!strcmp(arg, "--abbrev"))
4288 options->abbrev = DEFAULT_ABBREV;
4289 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4290 options->abbrev = strtoul(arg, NULL, 10);
4291 if (options->abbrev < MINIMUM_ABBREV)
4292 options->abbrev = MINIMUM_ABBREV;
4293 else if (40 < options->abbrev)
4294 options->abbrev = 40;
4296 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4297 options->a_prefix = optarg;
4300 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4301 options->line_prefix = optarg;
4302 options->line_prefix_length = strlen(options->line_prefix);
4303 graph_setup_line_prefix(options);
4306 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4307 options->b_prefix = optarg;
4310 else if (!strcmp(arg, "--no-prefix"))
4311 options->a_prefix = options->b_prefix = "";
4312 else if (opt_arg(arg, '\0', "inter-hunk-context",
4313 &options->interhunkcontext))
4315 else if (!strcmp(arg, "-W"))
4316 DIFF_OPT_SET(options, FUNCCONTEXT);
4317 else if (!strcmp(arg, "--function-context"))
4318 DIFF_OPT_SET(options, FUNCCONTEXT);
4319 else if (!strcmp(arg, "--no-function-context"))
4320 DIFF_OPT_CLR(options, FUNCCONTEXT);
4321 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4322 char *path = prefix_filename(prefix, optarg);
4323 options->file = xfopen(path, "w");
4324 options->close_file = 1;
4325 if (options->use_color != GIT_COLOR_ALWAYS)
4326 options->use_color = GIT_COLOR_NEVER;
4334 int parse_rename_score(const char **cp_p)
4336 unsigned long num, scale;
4338 const char *cp = *cp_p;
4345 if ( !dot && ch == '.' ) {
4348 } else if ( ch == '%' ) {
4349 scale = dot ? scale*100 : 100;
4350 cp++; /* % is always at the end */
4352 } else if ( ch >= '0' && ch <= '9' ) {
4353 if ( scale < 100000 ) {
4355 num = (num*10) + (ch-'0');
4364 /* user says num divided by scale and we say internally that
4365 * is MAX_SCORE * num / scale.
4367 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4370 static int diff_scoreopt_parse(const char *opt)
4372 int opt1, opt2, cmd;
4378 /* convert the long-form arguments into short-form versions */
4379 if (skip_prefix(opt, "break-rewrites", &opt)) {
4380 if (*opt == 0 || *opt++ == '=')
4382 } else if (skip_prefix(opt, "find-copies", &opt)) {
4383 if (*opt == 0 || *opt++ == '=')
4385 } else if (skip_prefix(opt, "find-renames", &opt)) {
4386 if (*opt == 0 || *opt++ == '=')
4390 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4391 return -1; /* that is not a -M, -C, or -B option */
4393 opt1 = parse_rename_score(&opt);
4399 else if (*opt != '/')
4400 return -1; /* we expect -B80/99 or -B80 */
4403 opt2 = parse_rename_score(&opt);
4408 return opt1 | (opt2 << 16);
4411 struct diff_queue_struct diff_queued_diff;
4413 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4415 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4416 queue->queue[queue->nr++] = dp;
4419 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4420 struct diff_filespec *one,
4421 struct diff_filespec *two)
4423 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4431 void diff_free_filepair(struct diff_filepair *p)
4433 free_filespec(p->one);
4434 free_filespec(p->two);
4438 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4443 if (len == GIT_SHA1_HEXSZ)
4444 return oid_to_hex(oid);
4446 abbrev = diff_abbrev_oid(oid, len);
4447 abblen = strlen(abbrev);
4450 * In well-behaved cases, where the abbbreviated result is the
4451 * same as the requested length, append three dots after the
4452 * abbreviation (hence the whole logic is limited to the case
4453 * where abblen < 37); when the actual abbreviated result is a
4454 * bit longer than the requested length, we reduce the number
4455 * of dots so that they match the well-behaved ones. However,
4456 * if the actual abbreviation is longer than the requested
4457 * length by more than three, we give up on aligning, and add
4458 * three dots anyway, to indicate that the output is not the
4459 * full object name. Yes, this may be suboptimal, but this
4460 * appears only in "diff --raw --abbrev" output and it is not
4461 * worth the effort to change it now. Note that this would
4462 * likely to work fine when the automatic sizing of default
4463 * abbreviation length is used--we would be fed -1 in "len" in
4464 * that case, and will end up always appending three-dots, but
4465 * the automatic sizing is supposed to give abblen that ensures
4466 * uniqueness across all objects (statistically speaking).
4468 if (abblen < GIT_SHA1_HEXSZ - 3) {
4469 static char hex[GIT_MAX_HEXSZ + 1];
4470 if (len < abblen && abblen <= len + 2)
4471 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4473 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4477 return oid_to_hex(oid);
4480 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4482 int line_termination = opt->line_termination;
4483 int inter_name_termination = line_termination ? '\t' : '\0';
4485 fprintf(opt->file, "%s", diff_line_prefix(opt));
4486 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4487 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4488 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4489 fprintf(opt->file, "%s ",
4490 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4493 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4494 inter_name_termination);
4496 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4499 if (p->status == DIFF_STATUS_COPIED ||
4500 p->status == DIFF_STATUS_RENAMED) {
4501 const char *name_a, *name_b;
4502 name_a = p->one->path;
4503 name_b = p->two->path;
4504 strip_prefix(opt->prefix_length, &name_a, &name_b);
4505 write_name_quoted(name_a, opt->file, inter_name_termination);
4506 write_name_quoted(name_b, opt->file, line_termination);
4508 const char *name_a, *name_b;
4509 name_a = p->one->mode ? p->one->path : p->two->path;
4511 strip_prefix(opt->prefix_length, &name_a, &name_b);
4512 write_name_quoted(name_a, opt->file, line_termination);
4516 int diff_unmodified_pair(struct diff_filepair *p)
4518 /* This function is written stricter than necessary to support
4519 * the currently implemented transformers, but the idea is to
4520 * let transformers to produce diff_filepairs any way they want,
4521 * and filter and clean them up here before producing the output.
4523 struct diff_filespec *one = p->one, *two = p->two;
4525 if (DIFF_PAIR_UNMERGED(p))
4526 return 0; /* unmerged is interesting */
4528 /* deletion, addition, mode or type change
4529 * and rename are all interesting.
4531 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4532 DIFF_PAIR_MODE_CHANGED(p) ||
4533 strcmp(one->path, two->path))
4536 /* both are valid and point at the same path. that is, we are
4537 * dealing with a change.
4539 if (one->oid_valid && two->oid_valid &&
4540 !oidcmp(&one->oid, &two->oid) &&
4541 !one->dirty_submodule && !two->dirty_submodule)
4542 return 1; /* no change */
4543 if (!one->oid_valid && !two->oid_valid)
4544 return 1; /* both look at the same file on the filesystem. */
4548 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4550 if (diff_unmodified_pair(p))
4553 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4554 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4555 return; /* no tree diffs in patch format */
4560 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4561 struct diffstat_t *diffstat)
4563 if (diff_unmodified_pair(p))
4566 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4567 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4568 return; /* no useful stat for tree diffs */
4570 run_diffstat(p, o, diffstat);
4573 static void diff_flush_checkdiff(struct diff_filepair *p,
4574 struct diff_options *o)
4576 if (diff_unmodified_pair(p))
4579 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4580 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4581 return; /* nothing to check in tree diffs */
4583 run_checkdiff(p, o);
4586 int diff_queue_is_empty(void)
4588 struct diff_queue_struct *q = &diff_queued_diff;
4590 for (i = 0; i < q->nr; i++)
4591 if (!diff_unmodified_pair(q->queue[i]))
4597 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4599 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4602 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4604 s->oid_valid ? oid_to_hex(&s->oid) : "");
4605 fprintf(stderr, "queue[%d] %s size %lu\n",
4610 void diff_debug_filepair(const struct diff_filepair *p, int i)
4612 diff_debug_filespec(p->one, i, "one");
4613 diff_debug_filespec(p->two, i, "two");
4614 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4615 p->score, p->status ? p->status : '?',
4616 p->one->rename_used, p->broken_pair);
4619 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4623 fprintf(stderr, "%s\n", msg);
4624 fprintf(stderr, "q->nr = %d\n", q->nr);
4625 for (i = 0; i < q->nr; i++) {
4626 struct diff_filepair *p = q->queue[i];
4627 diff_debug_filepair(p, i);
4632 static void diff_resolve_rename_copy(void)
4635 struct diff_filepair *p;
4636 struct diff_queue_struct *q = &diff_queued_diff;
4638 diff_debug_queue("resolve-rename-copy", q);
4640 for (i = 0; i < q->nr; i++) {
4642 p->status = 0; /* undecided */
4643 if (DIFF_PAIR_UNMERGED(p))
4644 p->status = DIFF_STATUS_UNMERGED;
4645 else if (!DIFF_FILE_VALID(p->one))
4646 p->status = DIFF_STATUS_ADDED;
4647 else if (!DIFF_FILE_VALID(p->two))
4648 p->status = DIFF_STATUS_DELETED;
4649 else if (DIFF_PAIR_TYPE_CHANGED(p))
4650 p->status = DIFF_STATUS_TYPE_CHANGED;
4652 /* from this point on, we are dealing with a pair
4653 * whose both sides are valid and of the same type, i.e.
4654 * either in-place edit or rename/copy edit.
4656 else if (DIFF_PAIR_RENAME(p)) {
4658 * A rename might have re-connected a broken
4659 * pair up, causing the pathnames to be the
4660 * same again. If so, that's not a rename at
4661 * all, just a modification..
4663 * Otherwise, see if this source was used for
4664 * multiple renames, in which case we decrement
4665 * the count, and call it a copy.
4667 if (!strcmp(p->one->path, p->two->path))
4668 p->status = DIFF_STATUS_MODIFIED;
4669 else if (--p->one->rename_used > 0)
4670 p->status = DIFF_STATUS_COPIED;
4672 p->status = DIFF_STATUS_RENAMED;
4674 else if (oidcmp(&p->one->oid, &p->two->oid) ||
4675 p->one->mode != p->two->mode ||
4676 p->one->dirty_submodule ||
4677 p->two->dirty_submodule ||
4678 is_null_oid(&p->one->oid))
4679 p->status = DIFF_STATUS_MODIFIED;
4681 /* This is a "no-change" entry and should not
4682 * happen anymore, but prepare for broken callers.
4684 error("feeding unmodified %s to diffcore",
4686 p->status = DIFF_STATUS_UNKNOWN;
4689 diff_debug_queue("resolve-rename-copy done", q);
4692 static int check_pair_status(struct diff_filepair *p)
4694 switch (p->status) {
4695 case DIFF_STATUS_UNKNOWN:
4698 die("internal error in diff-resolve-rename-copy");
4704 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4706 int fmt = opt->output_format;
4708 if (fmt & DIFF_FORMAT_CHECKDIFF)
4709 diff_flush_checkdiff(p, opt);
4710 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4711 diff_flush_raw(p, opt);
4712 else if (fmt & DIFF_FORMAT_NAME) {
4713 const char *name_a, *name_b;
4714 name_a = p->two->path;
4716 strip_prefix(opt->prefix_length, &name_a, &name_b);
4717 fprintf(opt->file, "%s", diff_line_prefix(opt));
4718 write_name_quoted(name_a, opt->file, opt->line_termination);
4722 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
4724 struct strbuf sb = STRBUF_INIT;
4726 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
4728 strbuf_addf(&sb, " %s ", newdelete);
4730 quote_c_style(fs->path, &sb, NULL, 0);
4731 strbuf_addch(&sb, '\n');
4732 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4734 strbuf_release(&sb);
4737 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
4740 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4741 struct strbuf sb = STRBUF_INIT;
4742 strbuf_addf(&sb, " mode change %06o => %06o",
4743 p->one->mode, p->two->mode);
4745 strbuf_addch(&sb, ' ');
4746 quote_c_style(p->two->path, &sb, NULL, 0);
4748 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4750 strbuf_release(&sb);
4754 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
4755 struct diff_filepair *p)
4757 struct strbuf sb = STRBUF_INIT;
4758 char *names = pprint_rename(p->one->path, p->two->path);
4759 strbuf_addf(&sb, " %s %s (%d%%)\n",
4760 renamecopy, names, similarity_index(p));
4762 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4764 show_mode_change(opt, p, 0);
4767 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4770 case DIFF_STATUS_DELETED:
4771 show_file_mode_name(opt, "delete", p->one);
4773 case DIFF_STATUS_ADDED:
4774 show_file_mode_name(opt, "create", p->two);
4776 case DIFF_STATUS_COPIED:
4777 show_rename_copy(opt, "copy", p);
4779 case DIFF_STATUS_RENAMED:
4780 show_rename_copy(opt, "rename", p);
4784 struct strbuf sb = STRBUF_INIT;
4785 strbuf_addstr(&sb, " rewrite ");
4786 quote_c_style(p->two->path, &sb, NULL, 0);
4787 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
4788 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4791 show_mode_change(opt, p, !p->score);
4801 static int remove_space(char *line, int len)
4807 for (i = 0; i < len; i++)
4808 if (!isspace((c = line[i])))
4814 static void patch_id_consume(void *priv, char *line, unsigned long len)
4816 struct patch_id_t *data = priv;
4819 /* Ignore line numbers when computing the SHA1 of the patch */
4820 if (starts_with(line, "@@ -"))
4823 new_len = remove_space(line, len);
4825 git_SHA1_Update(data->ctx, line, new_len);
4826 data->patchlen += new_len;
4829 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
4831 git_SHA1_Update(ctx, str, strlen(str));
4834 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
4836 /* large enough for 2^32 in octal */
4838 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
4839 git_SHA1_Update(ctx, buf, len);
4842 /* returns 0 upon success, and writes result into sha1 */
4843 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
4845 struct diff_queue_struct *q = &diff_queued_diff;
4848 struct patch_id_t data;
4850 git_SHA1_Init(&ctx);
4851 memset(&data, 0, sizeof(struct patch_id_t));
4854 for (i = 0; i < q->nr; i++) {
4858 struct diff_filepair *p = q->queue[i];
4861 memset(&xpp, 0, sizeof(xpp));
4862 memset(&xecfg, 0, sizeof(xecfg));
4864 return error("internal diff status error");
4865 if (p->status == DIFF_STATUS_UNKNOWN)
4867 if (diff_unmodified_pair(p))
4869 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4870 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4872 if (DIFF_PAIR_UNMERGED(p))
4875 diff_fill_oid_info(p->one);
4876 diff_fill_oid_info(p->two);
4878 len1 = remove_space(p->one->path, strlen(p->one->path));
4879 len2 = remove_space(p->two->path, strlen(p->two->path));
4880 patch_id_add_string(&ctx, "diff--git");
4881 patch_id_add_string(&ctx, "a/");
4882 git_SHA1_Update(&ctx, p->one->path, len1);
4883 patch_id_add_string(&ctx, "b/");
4884 git_SHA1_Update(&ctx, p->two->path, len2);
4886 if (p->one->mode == 0) {
4887 patch_id_add_string(&ctx, "newfilemode");
4888 patch_id_add_mode(&ctx, p->two->mode);
4889 patch_id_add_string(&ctx, "---/dev/null");
4890 patch_id_add_string(&ctx, "+++b/");
4891 git_SHA1_Update(&ctx, p->two->path, len2);
4892 } else if (p->two->mode == 0) {
4893 patch_id_add_string(&ctx, "deletedfilemode");
4894 patch_id_add_mode(&ctx, p->one->mode);
4895 patch_id_add_string(&ctx, "---a/");
4896 git_SHA1_Update(&ctx, p->one->path, len1);
4897 patch_id_add_string(&ctx, "+++/dev/null");
4899 patch_id_add_string(&ctx, "---a/");
4900 git_SHA1_Update(&ctx, p->one->path, len1);
4901 patch_id_add_string(&ctx, "+++b/");
4902 git_SHA1_Update(&ctx, p->two->path, len2);
4905 if (diff_header_only)
4908 if (fill_mmfile(&mf1, p->one) < 0 ||
4909 fill_mmfile(&mf2, p->two) < 0)
4910 return error("unable to read files to diff");
4912 if (diff_filespec_is_binary(p->one) ||
4913 diff_filespec_is_binary(p->two)) {
4914 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
4916 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
4924 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4926 return error("unable to generate patch-id diff for %s",
4930 git_SHA1_Final(oid->hash, &ctx);
4934 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
4936 struct diff_queue_struct *q = &diff_queued_diff;
4938 int result = diff_get_patch_id(options, oid, diff_header_only);
4940 for (i = 0; i < q->nr; i++)
4941 diff_free_filepair(q->queue[i]);
4944 DIFF_QUEUE_CLEAR(q);
4949 static int is_summary_empty(const struct diff_queue_struct *q)
4953 for (i = 0; i < q->nr; i++) {
4954 const struct diff_filepair *p = q->queue[i];
4956 switch (p->status) {
4957 case DIFF_STATUS_DELETED:
4958 case DIFF_STATUS_ADDED:
4959 case DIFF_STATUS_COPIED:
4960 case DIFF_STATUS_RENAMED:
4965 if (p->one->mode && p->two->mode &&
4966 p->one->mode != p->two->mode)
4974 static const char rename_limit_warning[] =
4975 N_("inexact rename detection was skipped due to too many files.");
4977 static const char degrade_cc_to_c_warning[] =
4978 N_("only found copies from modified paths due to too many files.");
4980 static const char rename_limit_advice[] =
4981 N_("you may want to set your %s variable to at least "
4982 "%d and retry the command.");
4984 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4987 warning(_(degrade_cc_to_c_warning));
4989 warning(_(rename_limit_warning));
4992 if (0 < needed && needed < 32767)
4993 warning(_(rename_limit_advice), varname, needed);
4996 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
4999 struct diff_queue_struct *q = &diff_queued_diff;
5001 if (WSEH_NEW & WS_RULE_MASK)
5002 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5004 for (i = 0; i < q->nr; i++) {
5005 struct diff_filepair *p = q->queue[i];
5006 if (check_pair_status(p))
5007 diff_flush_patch(p, o);
5011 void diff_flush(struct diff_options *options)
5013 struct diff_queue_struct *q = &diff_queued_diff;
5014 int i, output_format = options->output_format;
5016 int dirstat_by_line = 0;
5019 * Order: raw, stat, summary, patch
5020 * or: name/name-status/checkdiff (other bits clear)
5025 if (output_format & (DIFF_FORMAT_RAW |
5027 DIFF_FORMAT_NAME_STATUS |
5028 DIFF_FORMAT_CHECKDIFF)) {
5029 for (i = 0; i < q->nr; i++) {
5030 struct diff_filepair *p = q->queue[i];
5031 if (check_pair_status(p))
5032 flush_one_pair(p, options);
5037 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
5038 dirstat_by_line = 1;
5040 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5042 struct diffstat_t diffstat;
5044 memset(&diffstat, 0, sizeof(struct diffstat_t));
5045 for (i = 0; i < q->nr; i++) {
5046 struct diff_filepair *p = q->queue[i];
5047 if (check_pair_status(p))
5048 diff_flush_stat(p, options, &diffstat);
5050 if (output_format & DIFF_FORMAT_NUMSTAT)
5051 show_numstat(&diffstat, options);
5052 if (output_format & DIFF_FORMAT_DIFFSTAT)
5053 show_stats(&diffstat, options);
5054 if (output_format & DIFF_FORMAT_SHORTSTAT)
5055 show_shortstats(&diffstat, options);
5056 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5057 show_dirstat_by_line(&diffstat, options);
5058 free_diffstat_info(&diffstat);
5061 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5062 show_dirstat(options);
5064 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5065 for (i = 0; i < q->nr; i++) {
5066 diff_summary(options, q->queue[i]);
5071 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5072 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
5073 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5075 * run diff_flush_patch for the exit status. setting
5076 * options->file to /dev/null should be safe, because we
5077 * aren't supposed to produce any output anyway.
5079 if (options->close_file)
5080 fclose(options->file);
5081 options->file = xfopen("/dev/null", "w");
5082 options->close_file = 1;
5083 for (i = 0; i < q->nr; i++) {
5084 struct diff_filepair *p = q->queue[i];
5085 if (check_pair_status(p))
5086 diff_flush_patch(p, options);
5087 if (options->found_changes)
5092 if (output_format & DIFF_FORMAT_PATCH) {
5094 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5095 if (options->stat_sep)
5096 /* attach patch instead of inline */
5097 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5101 diff_flush_patch_all_file_pairs(options);
5104 if (output_format & DIFF_FORMAT_CALLBACK)
5105 options->format_callback(q, options, options->format_callback_data);
5107 for (i = 0; i < q->nr; i++)
5108 diff_free_filepair(q->queue[i]);
5111 DIFF_QUEUE_CLEAR(q);
5112 if (options->close_file)
5113 fclose(options->file);
5116 * Report the content-level differences with HAS_CHANGES;
5117 * diff_addremove/diff_change does not set the bit when
5118 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5120 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5121 if (options->found_changes)
5122 DIFF_OPT_SET(options, HAS_CHANGES);
5124 DIFF_OPT_CLR(options, HAS_CHANGES);
5128 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5130 return (((p->status == DIFF_STATUS_MODIFIED) &&
5132 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5134 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5135 ((p->status != DIFF_STATUS_MODIFIED) &&
5136 filter_bit_tst(p->status, options)));
5139 static void diffcore_apply_filter(struct diff_options *options)
5142 struct diff_queue_struct *q = &diff_queued_diff;
5143 struct diff_queue_struct outq;
5145 DIFF_QUEUE_CLEAR(&outq);
5147 if (!options->filter)
5150 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5152 for (i = found = 0; !found && i < q->nr; i++) {
5153 if (match_filter(options, q->queue[i]))
5159 /* otherwise we will clear the whole queue
5160 * by copying the empty outq at the end of this
5161 * function, but first clear the current entries
5164 for (i = 0; i < q->nr; i++)
5165 diff_free_filepair(q->queue[i]);
5168 /* Only the matching ones */
5169 for (i = 0; i < q->nr; i++) {
5170 struct diff_filepair *p = q->queue[i];
5171 if (match_filter(options, p))
5174 diff_free_filepair(p);
5181 /* Check whether two filespecs with the same mode and size are identical */
5182 static int diff_filespec_is_identical(struct diff_filespec *one,
5183 struct diff_filespec *two)
5185 if (S_ISGITLINK(one->mode))
5187 if (diff_populate_filespec(one, 0))
5189 if (diff_populate_filespec(two, 0))
5191 return !memcmp(one->data, two->data, one->size);
5194 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5196 if (p->done_skip_stat_unmatch)
5197 return p->skip_stat_unmatch_result;
5199 p->done_skip_stat_unmatch = 1;
5200 p->skip_stat_unmatch_result = 0;
5202 * 1. Entries that come from stat info dirtiness
5203 * always have both sides (iow, not create/delete),
5204 * one side of the object name is unknown, with
5205 * the same mode and size. Keep the ones that
5206 * do not match these criteria. They have real
5209 * 2. At this point, the file is known to be modified,
5210 * with the same mode and size, and the object
5211 * name of one side is unknown. Need to inspect
5212 * the identical contents.
5214 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5215 !DIFF_FILE_VALID(p->two) ||
5216 (p->one->oid_valid && p->two->oid_valid) ||
5217 (p->one->mode != p->two->mode) ||
5218 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5219 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5220 (p->one->size != p->two->size) ||
5221 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5222 p->skip_stat_unmatch_result = 1;
5223 return p->skip_stat_unmatch_result;
5226 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5229 struct diff_queue_struct *q = &diff_queued_diff;
5230 struct diff_queue_struct outq;
5231 DIFF_QUEUE_CLEAR(&outq);
5233 for (i = 0; i < q->nr; i++) {
5234 struct diff_filepair *p = q->queue[i];
5236 if (diff_filespec_check_stat_unmatch(p))
5240 * The caller can subtract 1 from skip_stat_unmatch
5241 * to determine how many paths were dirty only
5242 * due to stat info mismatch.
5244 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
5245 diffopt->skip_stat_unmatch++;
5246 diff_free_filepair(p);
5253 static int diffnamecmp(const void *a_, const void *b_)
5255 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5256 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5257 const char *name_a, *name_b;
5259 name_a = a->one ? a->one->path : a->two->path;
5260 name_b = b->one ? b->one->path : b->two->path;
5261 return strcmp(name_a, name_b);
5264 void diffcore_fix_diff_index(struct diff_options *options)
5266 struct diff_queue_struct *q = &diff_queued_diff;
5267 QSORT(q->queue, q->nr, diffnamecmp);
5270 void diffcore_std(struct diff_options *options)
5272 /* NOTE please keep the following in sync with diff_tree_combined() */
5273 if (options->skip_stat_unmatch)
5274 diffcore_skip_stat_unmatch(options);
5275 if (!options->found_follow) {
5276 /* See try_to_follow_renames() in tree-diff.c */
5277 if (options->break_opt != -1)
5278 diffcore_break(options->break_opt);
5279 if (options->detect_rename)
5280 diffcore_rename(options);
5281 if (options->break_opt != -1)
5282 diffcore_merge_broken();
5284 if (options->pickaxe)
5285 diffcore_pickaxe(options);
5286 if (options->orderfile)
5287 diffcore_order(options->orderfile);
5288 if (!options->found_follow)
5289 /* See try_to_follow_renames() in tree-diff.c */
5290 diff_resolve_rename_copy();
5291 diffcore_apply_filter(options);
5293 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5294 DIFF_OPT_SET(options, HAS_CHANGES);
5296 DIFF_OPT_CLR(options, HAS_CHANGES);
5298 options->found_follow = 0;
5301 int diff_result_code(struct diff_options *opt, int status)
5305 diff_warn_rename_limit("diff.renameLimit",
5306 opt->needed_rename_limit,
5307 opt->degraded_cc_to_c);
5308 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5309 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5311 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5312 DIFF_OPT_TST(opt, HAS_CHANGES))
5314 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5315 DIFF_OPT_TST(opt, CHECK_FAILED))
5320 int diff_can_quit_early(struct diff_options *opt)
5322 return (DIFF_OPT_TST(opt, QUICK) &&
5324 DIFF_OPT_TST(opt, HAS_CHANGES));
5328 * Shall changes to this submodule be ignored?
5330 * Submodule changes can be configured to be ignored separately for each path,
5331 * but that configuration can be overridden from the command line.
5333 static int is_submodule_ignored(const char *path, struct diff_options *options)
5336 unsigned orig_flags = options->flags;
5337 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
5338 set_diffopt_flags_from_submodule_config(options, path);
5339 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
5341 options->flags = orig_flags;
5345 void diff_addremove(struct diff_options *options,
5346 int addremove, unsigned mode,
5347 const struct object_id *oid,
5349 const char *concatpath, unsigned dirty_submodule)
5351 struct diff_filespec *one, *two;
5353 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5356 /* This may look odd, but it is a preparation for
5357 * feeding "there are unchanged files which should
5358 * not produce diffs, but when you are doing copy
5359 * detection you would need them, so here they are"
5360 * entries to the diff-core. They will be prefixed
5361 * with something like '=' or '*' (I haven't decided
5362 * which but should not make any difference).
5363 * Feeding the same new and old to diff_change()
5364 * also has the same effect.
5365 * Before the final output happens, they are pruned after
5366 * merged into rename/copy pairs as appropriate.
5368 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5369 addremove = (addremove == '+' ? '-' :
5370 addremove == '-' ? '+' : addremove);
5372 if (options->prefix &&
5373 strncmp(concatpath, options->prefix, options->prefix_length))
5376 one = alloc_filespec(concatpath);
5377 two = alloc_filespec(concatpath);
5379 if (addremove != '+')
5380 fill_filespec(one, oid, oid_valid, mode);
5381 if (addremove != '-') {
5382 fill_filespec(two, oid, oid_valid, mode);
5383 two->dirty_submodule = dirty_submodule;
5386 diff_queue(&diff_queued_diff, one, two);
5387 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5388 DIFF_OPT_SET(options, HAS_CHANGES);
5391 void diff_change(struct diff_options *options,
5392 unsigned old_mode, unsigned new_mode,
5393 const struct object_id *old_oid,
5394 const struct object_id *new_oid,
5395 int old_oid_valid, int new_oid_valid,
5396 const char *concatpath,
5397 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5399 struct diff_filespec *one, *two;
5400 struct diff_filepair *p;
5402 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5403 is_submodule_ignored(concatpath, options))
5406 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5407 SWAP(old_mode, new_mode);
5408 SWAP(old_oid, new_oid);
5409 SWAP(old_oid_valid, new_oid_valid);
5410 SWAP(old_dirty_submodule, new_dirty_submodule);
5413 if (options->prefix &&
5414 strncmp(concatpath, options->prefix, options->prefix_length))
5417 one = alloc_filespec(concatpath);
5418 two = alloc_filespec(concatpath);
5419 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5420 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5421 one->dirty_submodule = old_dirty_submodule;
5422 two->dirty_submodule = new_dirty_submodule;
5423 p = diff_queue(&diff_queued_diff, one, two);
5425 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5428 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5429 !diff_filespec_check_stat_unmatch(p))
5432 DIFF_OPT_SET(options, HAS_CHANGES);
5435 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5437 struct diff_filepair *pair;
5438 struct diff_filespec *one, *two;
5440 if (options->prefix &&
5441 strncmp(path, options->prefix, options->prefix_length))
5444 one = alloc_filespec(path);
5445 two = alloc_filespec(path);
5446 pair = diff_queue(&diff_queued_diff, one, two);
5447 pair->is_unmerged = 1;
5451 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5454 struct diff_tempfile *temp;
5455 const char *argv[3];
5456 const char **arg = argv;
5457 struct child_process child = CHILD_PROCESS_INIT;
5458 struct strbuf buf = STRBUF_INIT;
5461 temp = prepare_temp_file(spec->path, spec);
5463 *arg++ = temp->name;
5466 child.use_shell = 1;
5469 if (start_command(&child)) {
5474 if (strbuf_read(&buf, child.out, 0) < 0)
5475 err = error("error reading from textconv command '%s'", pgm);
5478 if (finish_command(&child) || err) {
5479 strbuf_release(&buf);
5485 return strbuf_detach(&buf, outsize);
5488 size_t fill_textconv(struct userdiff_driver *driver,
5489 struct diff_filespec *df,
5495 if (!DIFF_FILE_VALID(df)) {
5499 if (diff_populate_filespec(df, 0))
5500 die("unable to read files to diff");
5505 if (!driver->textconv)
5506 die("BUG: fill_textconv called with non-textconv driver");
5508 if (driver->textconv_cache && df->oid_valid) {
5509 *outbuf = notes_cache_get(driver->textconv_cache,
5516 *outbuf = run_textconv(driver->textconv, df, &size);
5518 die("unable to read files to diff");
5520 if (driver->textconv_cache && df->oid_valid) {
5521 /* ignore errors, as we might be in a readonly repository */
5522 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
5525 * we could save up changes and flush them all at the end,
5526 * but we would need an extra call after all diffing is done.
5527 * Since generating a cache entry is the slow path anyway,
5528 * this extra overhead probably isn't a big deal.
5530 notes_cache_write(driver->textconv_cache);
5536 int textconv_object(const char *path,
5538 const struct object_id *oid,
5541 unsigned long *buf_size)
5543 struct diff_filespec *df;
5544 struct userdiff_driver *textconv;
5546 df = alloc_filespec(path);
5547 fill_filespec(df, oid, oid_valid, mode);
5548 textconv = get_textconv(df);
5554 *buf_size = fill_textconv(textconv, df, buf);
5559 void setup_diff_pager(struct diff_options *opt)
5562 * If the user asked for our exit code, then either they want --quiet
5563 * or --exit-code. We should definitely not bother with a pager in the
5564 * former case, as we will generate no output. Since we still properly
5565 * report our exit code even when a pager is run, we _could_ run a
5566 * pager with --exit-code. But since we have not done so historically,
5567 * and because it is easy to find people oneline advising "git diff
5568 * --exit-code" in hooks and other scripts, we do not do so.
5570 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5571 check_pager_config("diff") != 0)