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)
609 * This struct is used when we need to buffer the output of the diff output.
611 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
612 * into the pre/post image file. This pointer could be a union with the
613 * line pointer. By storing an offset into the file instead of the literal line,
614 * we can decrease the memory footprint for the buffered output. At first we
615 * may want to only have indirection for the content lines, but we could also
616 * enhance the state for emitting prefabricated lines, e.g. the similarity
617 * score line or hunk/file headers would only need to store a number or path
618 * and then the output can be constructed later on depending on state.
620 struct emitted_diff_symbol {
626 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
628 struct emitted_diff_symbols {
629 struct emitted_diff_symbol *buf;
632 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
634 static void append_emitted_diff_symbol(struct diff_options *o,
635 struct emitted_diff_symbol *e)
637 struct emitted_diff_symbol *f;
639 ALLOC_GROW(o->emitted_symbols->buf,
640 o->emitted_symbols->nr + 1,
641 o->emitted_symbols->alloc);
642 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
644 memcpy(f, e, sizeof(struct emitted_diff_symbol));
645 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
649 static void emit_line_ws_markup(struct diff_options *o,
650 const char *set, const char *reset,
651 const char *line, int len, char sign,
652 unsigned ws_rule, int blank_at_eof)
654 const char *ws = NULL;
656 if (o->ws_error_highlight & ws_rule) {
657 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
663 emit_line_0(o, set, reset, sign, line, len);
664 else if (blank_at_eof)
665 /* Blank line at EOF - paint '+' as well */
666 emit_line_0(o, ws, reset, sign, line, len);
668 /* Emit just the prefix, then the rest. */
669 emit_line_0(o, set, reset, sign, "", 0);
670 ws_check_emit(line, len, ws_rule,
671 o->file, set, reset, ws);
675 static void emit_diff_symbol_from_struct(struct diff_options *o,
676 struct emitted_diff_symbol *eds)
678 static const char *nneof = " No newline at end of file\n";
679 const char *context, *reset, *set, *meta, *fraginfo;
680 struct strbuf sb = STRBUF_INIT;
682 enum diff_symbol s = eds->s;
683 const char *line = eds->line;
685 unsigned flags = eds->flags;
688 case DIFF_SYMBOL_NO_LF_EOF:
689 context = diff_get_color_opt(o, DIFF_CONTEXT);
690 reset = diff_get_color_opt(o, DIFF_RESET);
692 emit_line_0(o, context, reset, '\\',
693 nneof, strlen(nneof));
695 case DIFF_SYMBOL_SUBMODULE_HEADER:
696 case DIFF_SYMBOL_SUBMODULE_ERROR:
697 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
698 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
699 case DIFF_SYMBOL_SUMMARY:
700 case DIFF_SYMBOL_STATS_LINE:
701 case DIFF_SYMBOL_BINARY_DIFF_BODY:
702 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
703 emit_line(o, "", "", line, len);
705 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
706 case DIFF_SYMBOL_CONTEXT_MARKER:
707 context = diff_get_color_opt(o, DIFF_CONTEXT);
708 reset = diff_get_color_opt(o, DIFF_RESET);
709 emit_line(o, context, reset, line, len);
711 case DIFF_SYMBOL_SEPARATOR:
712 fprintf(o->file, "%s%c",
714 o->line_termination);
716 case DIFF_SYMBOL_CONTEXT:
717 set = diff_get_color_opt(o, DIFF_CONTEXT);
718 reset = diff_get_color_opt(o, DIFF_RESET);
719 emit_line_ws_markup(o, set, reset, line, len, ' ',
720 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
722 case DIFF_SYMBOL_PLUS:
723 set = diff_get_color_opt(o, DIFF_FILE_NEW);
724 reset = diff_get_color_opt(o, DIFF_RESET);
725 emit_line_ws_markup(o, set, reset, line, len, '+',
726 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
727 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
729 case DIFF_SYMBOL_MINUS:
730 set = diff_get_color_opt(o, DIFF_FILE_OLD);
731 reset = diff_get_color_opt(o, DIFF_RESET);
732 emit_line_ws_markup(o, set, reset, line, len, '-',
733 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
735 case DIFF_SYMBOL_WORDS_PORCELAIN:
736 context = diff_get_color_opt(o, DIFF_CONTEXT);
737 reset = diff_get_color_opt(o, DIFF_RESET);
738 emit_line(o, context, reset, line, len);
739 fputs("~\n", o->file);
741 case DIFF_SYMBOL_WORDS:
742 context = diff_get_color_opt(o, DIFF_CONTEXT);
743 reset = diff_get_color_opt(o, DIFF_RESET);
745 * Skip the prefix character, if any. With
746 * diff_suppress_blank_empty, there may be
749 if (line[0] != '\n') {
753 emit_line(o, context, reset, line, len);
755 case DIFF_SYMBOL_FILEPAIR_PLUS:
756 meta = diff_get_color_opt(o, DIFF_METAINFO);
757 reset = diff_get_color_opt(o, DIFF_RESET);
758 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
760 strchr(line, ' ') ? "\t" : "");
762 case DIFF_SYMBOL_FILEPAIR_MINUS:
763 meta = diff_get_color_opt(o, DIFF_METAINFO);
764 reset = diff_get_color_opt(o, DIFF_RESET);
765 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
767 strchr(line, ' ') ? "\t" : "");
769 case DIFF_SYMBOL_BINARY_FILES:
770 case DIFF_SYMBOL_HEADER:
771 fprintf(o->file, "%s", line);
773 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
774 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
776 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
777 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
779 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
780 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
782 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
783 fputs(diff_line_prefix(o), o->file);
784 fputc('\n', o->file);
786 case DIFF_SYMBOL_REWRITE_DIFF:
787 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
788 reset = diff_get_color_opt(o, DIFF_RESET);
789 emit_line(o, fraginfo, reset, line, len);
791 case DIFF_SYMBOL_SUBMODULE_ADD:
792 set = diff_get_color_opt(o, DIFF_FILE_NEW);
793 reset = diff_get_color_opt(o, DIFF_RESET);
794 emit_line(o, set, reset, line, len);
796 case DIFF_SYMBOL_SUBMODULE_DEL:
797 set = diff_get_color_opt(o, DIFF_FILE_OLD);
798 reset = diff_get_color_opt(o, DIFF_RESET);
799 emit_line(o, set, reset, line, len);
801 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
802 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
803 diff_line_prefix(o), line);
805 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
806 fprintf(o->file, "%sSubmodule %s contains modified content\n",
807 diff_line_prefix(o), line);
809 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
810 emit_line(o, "", "", " 0 files changed\n",
811 strlen(" 0 files changed\n"));
813 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
814 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
816 case DIFF_SYMBOL_WORD_DIFF:
817 fprintf(o->file, "%.*s", len, line);
819 case DIFF_SYMBOL_STAT_SEP:
820 fputs(o->stat_sep, o->file);
823 die("BUG: unknown diff symbol");
828 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
829 const char *line, int len, unsigned flags)
831 struct emitted_diff_symbol e = {line, len, flags, s};
833 if (o->emitted_symbols)
834 append_emitted_diff_symbol(o, &e);
836 emit_diff_symbol_from_struct(o, &e);
839 void diff_emit_submodule_del(struct diff_options *o, const char *line)
841 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
844 void diff_emit_submodule_add(struct diff_options *o, const char *line)
846 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
849 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
851 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
852 path, strlen(path), 0);
855 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
857 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
858 path, strlen(path), 0);
861 void diff_emit_submodule_header(struct diff_options *o, const char *header)
863 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
864 header, strlen(header), 0);
867 void diff_emit_submodule_error(struct diff_options *o, const char *err)
869 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
872 void diff_emit_submodule_pipethrough(struct diff_options *o,
873 const char *line, int len)
875 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
878 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
880 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
881 ecbdata->blank_at_eof_in_preimage &&
882 ecbdata->blank_at_eof_in_postimage &&
883 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
884 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
886 return ws_blank_line(line, len, ecbdata->ws_rule);
889 static void emit_add_line(const char *reset,
890 struct emit_callback *ecbdata,
891 const char *line, int len)
893 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
894 if (new_blank_line_at_eof(ecbdata, line, len))
895 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
897 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
900 static void emit_del_line(const char *reset,
901 struct emit_callback *ecbdata,
902 const char *line, int len)
904 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
905 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
908 static void emit_context_line(const char *reset,
909 struct emit_callback *ecbdata,
910 const char *line, int len)
912 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
913 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
916 static void emit_hunk_header(struct emit_callback *ecbdata,
917 const char *line, int len)
919 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
920 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
921 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
922 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
923 static const char atat[2] = { '@', '@' };
925 struct strbuf msgbuf = STRBUF_INIT;
930 * As a hunk header must begin with "@@ -<old>, +<new> @@",
931 * it always is at least 10 bytes long.
934 memcmp(line, atat, 2) ||
935 !(ep = memmem(line + 2, len - 2, atat, 2))) {
936 emit_diff_symbol(ecbdata->opt,
937 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
940 ep += 2; /* skip over @@ */
942 /* The hunk header in fraginfo color */
943 strbuf_addstr(&msgbuf, frag);
944 strbuf_add(&msgbuf, line, ep - line);
945 strbuf_addstr(&msgbuf, reset);
951 if (line[len - i] == '\r' || line[len - i] == '\n')
954 /* blank before the func header */
955 for (cp = ep; ep - line < len; ep++)
956 if (*ep != ' ' && *ep != '\t')
959 strbuf_addstr(&msgbuf, context);
960 strbuf_add(&msgbuf, cp, ep - cp);
961 strbuf_addstr(&msgbuf, reset);
964 if (ep < line + len) {
965 strbuf_addstr(&msgbuf, func);
966 strbuf_add(&msgbuf, ep, line + len - ep);
967 strbuf_addstr(&msgbuf, reset);
970 strbuf_add(&msgbuf, line + len, org_len - len);
971 strbuf_complete_line(&msgbuf);
972 emit_diff_symbol(ecbdata->opt,
973 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
974 strbuf_release(&msgbuf);
977 static struct diff_tempfile *claim_diff_tempfile(void) {
979 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
980 if (!diff_temp[i].name)
981 return diff_temp + i;
982 die("BUG: diff is failing to clean up its tempfiles");
985 static void remove_tempfile(void)
988 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
989 if (is_tempfile_active(&diff_temp[i].tempfile))
990 delete_tempfile(&diff_temp[i].tempfile);
991 diff_temp[i].name = NULL;
995 static void add_line_count(struct strbuf *out, int count)
999 strbuf_addstr(out, "0,0");
1002 strbuf_addstr(out, "1");
1005 strbuf_addf(out, "1,%d", count);
1010 static void emit_rewrite_lines(struct emit_callback *ecb,
1011 int prefix, const char *data, int size)
1013 const char *endp = NULL;
1014 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1019 endp = memchr(data, '\n', size);
1020 len = endp ? (endp - data + 1) : size;
1021 if (prefix != '+') {
1022 ecb->lno_in_preimage++;
1023 emit_del_line(reset, ecb, data, len);
1025 ecb->lno_in_postimage++;
1026 emit_add_line(reset, ecb, data, len);
1032 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1035 static void emit_rewrite_diff(const char *name_a,
1037 struct diff_filespec *one,
1038 struct diff_filespec *two,
1039 struct userdiff_driver *textconv_one,
1040 struct userdiff_driver *textconv_two,
1041 struct diff_options *o)
1044 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1045 const char *a_prefix, *b_prefix;
1046 char *data_one, *data_two;
1047 size_t size_one, size_two;
1048 struct emit_callback ecbdata;
1049 struct strbuf out = STRBUF_INIT;
1051 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
1052 a_prefix = o->b_prefix;
1053 b_prefix = o->a_prefix;
1055 a_prefix = o->a_prefix;
1056 b_prefix = o->b_prefix;
1059 name_a += (*name_a == '/');
1060 name_b += (*name_b == '/');
1062 strbuf_reset(&a_name);
1063 strbuf_reset(&b_name);
1064 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1065 quote_two_c_style(&b_name, b_prefix, name_b, 0);
1067 size_one = fill_textconv(textconv_one, one, &data_one);
1068 size_two = fill_textconv(textconv_two, two, &data_two);
1070 memset(&ecbdata, 0, sizeof(ecbdata));
1071 ecbdata.color_diff = want_color(o->use_color);
1072 ecbdata.ws_rule = whitespace_rule(name_b);
1074 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1076 mf1.ptr = (char *)data_one;
1077 mf2.ptr = (char *)data_two;
1078 mf1.size = size_one;
1079 mf2.size = size_two;
1080 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1082 ecbdata.lno_in_preimage = 1;
1083 ecbdata.lno_in_postimage = 1;
1085 lc_a = count_lines(data_one, size_one);
1086 lc_b = count_lines(data_two, size_two);
1088 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1089 a_name.buf, a_name.len, 0);
1090 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1091 b_name.buf, b_name.len, 0);
1093 strbuf_addstr(&out, "@@ -");
1094 if (!o->irreversible_delete)
1095 add_line_count(&out, lc_a);
1097 strbuf_addstr(&out, "?,?");
1098 strbuf_addstr(&out, " +");
1099 add_line_count(&out, lc_b);
1100 strbuf_addstr(&out, " @@\n");
1101 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1102 strbuf_release(&out);
1104 if (lc_a && !o->irreversible_delete)
1105 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1107 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1109 free((char *)data_one);
1111 free((char *)data_two);
1114 struct diff_words_buffer {
1117 struct diff_words_orig {
1118 const char *begin, *end;
1120 int orig_nr, orig_alloc;
1123 static void diff_words_append(char *line, unsigned long len,
1124 struct diff_words_buffer *buffer)
1126 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1129 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1130 buffer->text.size += len;
1131 buffer->text.ptr[buffer->text.size] = '\0';
1134 struct diff_words_style_elem {
1137 const char *color; /* NULL; filled in by the setup code if
1138 * color is enabled */
1141 struct diff_words_style {
1142 enum diff_words_type type;
1143 struct diff_words_style_elem new, old, ctx;
1144 const char *newline;
1147 static struct diff_words_style diff_words_styles[] = {
1148 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1149 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1150 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1153 struct diff_words_data {
1154 struct diff_words_buffer minus, plus;
1155 const char *current_plus;
1157 struct diff_options *opt;
1158 regex_t *word_regex;
1159 enum diff_words_type type;
1160 struct diff_words_style *style;
1163 static int fn_out_diff_words_write_helper(struct diff_options *o,
1164 struct diff_words_style_elem *st_el,
1165 const char *newline,
1166 size_t count, const char *buf)
1169 struct strbuf sb = STRBUF_INIT;
1172 char *p = memchr(buf, '\n', count);
1174 strbuf_addstr(&sb, diff_line_prefix(o));
1177 const char *reset = st_el->color && *st_el->color ?
1178 GIT_COLOR_RESET : NULL;
1179 if (st_el->color && *st_el->color)
1180 strbuf_addstr(&sb, st_el->color);
1181 strbuf_addstr(&sb, st_el->prefix);
1182 strbuf_add(&sb, buf, p ? p - buf : count);
1183 strbuf_addstr(&sb, st_el->suffix);
1185 strbuf_addstr(&sb, reset);
1190 strbuf_addstr(&sb, newline);
1191 count -= p + 1 - buf;
1195 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1203 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1205 strbuf_release(&sb);
1210 * '--color-words' algorithm can be described as:
1212 * 1. collect the minus/plus lines of a diff hunk, divided into
1213 * minus-lines and plus-lines;
1215 * 2. break both minus-lines and plus-lines into words and
1216 * place them into two mmfile_t with one word for each line;
1218 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1220 * And for the common parts of the both file, we output the plus side text.
1221 * diff_words->current_plus is used to trace the current position of the plus file
1222 * which printed. diff_words->last_minus is used to trace the last minus word
1225 * For '--graph' to work with '--color-words', we need to output the graph prefix
1226 * on each line of color words output. Generally, there are two conditions on
1227 * which we should output the prefix.
1229 * 1. diff_words->last_minus == 0 &&
1230 * diff_words->current_plus == diff_words->plus.text.ptr
1232 * that is: the plus text must start as a new line, and if there is no minus
1233 * word printed, a graph prefix must be printed.
1235 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1236 * *(diff_words->current_plus - 1) == '\n'
1238 * that is: a graph prefix must be printed following a '\n'
1240 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1242 if ((diff_words->last_minus == 0 &&
1243 diff_words->current_plus == diff_words->plus.text.ptr) ||
1244 (diff_words->current_plus > diff_words->plus.text.ptr &&
1245 *(diff_words->current_plus - 1) == '\n')) {
1252 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
1254 struct diff_words_data *diff_words = priv;
1255 struct diff_words_style *style = diff_words->style;
1256 int minus_first, minus_len, plus_first, plus_len;
1257 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1258 struct diff_options *opt = diff_words->opt;
1259 const char *line_prefix;
1261 if (line[0] != '@' || parse_hunk_header(line, len,
1262 &minus_first, &minus_len, &plus_first, &plus_len))
1266 line_prefix = diff_line_prefix(opt);
1268 /* POSIX requires that first be decremented by one if len == 0... */
1270 minus_begin = diff_words->minus.orig[minus_first].begin;
1272 diff_words->minus.orig[minus_first + minus_len - 1].end;
1274 minus_begin = minus_end =
1275 diff_words->minus.orig[minus_first].end;
1278 plus_begin = diff_words->plus.orig[plus_first].begin;
1279 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1281 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1283 if (color_words_output_graph_prefix(diff_words)) {
1284 fputs(line_prefix, diff_words->opt->file);
1286 if (diff_words->current_plus != plus_begin) {
1287 fn_out_diff_words_write_helper(diff_words->opt,
1288 &style->ctx, style->newline,
1289 plus_begin - diff_words->current_plus,
1290 diff_words->current_plus);
1292 if (minus_begin != minus_end) {
1293 fn_out_diff_words_write_helper(diff_words->opt,
1294 &style->old, style->newline,
1295 minus_end - minus_begin, minus_begin);
1297 if (plus_begin != plus_end) {
1298 fn_out_diff_words_write_helper(diff_words->opt,
1299 &style->new, style->newline,
1300 plus_end - plus_begin, plus_begin);
1303 diff_words->current_plus = plus_end;
1304 diff_words->last_minus = minus_first;
1307 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1308 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1309 int *begin, int *end)
1311 if (word_regex && *begin < buffer->size) {
1312 regmatch_t match[1];
1313 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1314 buffer->size - *begin, 1, match, 0)) {
1315 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1316 '\n', match[0].rm_eo - match[0].rm_so);
1317 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1318 *begin += match[0].rm_so;
1319 return *begin >= *end;
1324 /* find the next word */
1325 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1327 if (*begin >= buffer->size)
1330 /* find the end of the word */
1332 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1339 * This function splits the words in buffer->text, stores the list with
1340 * newline separator into out, and saves the offsets of the original words
1343 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1344 regex_t *word_regex)
1352 /* fake an empty "0th" word */
1353 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1354 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1355 buffer->orig_nr = 1;
1357 for (i = 0; i < buffer->text.size; i++) {
1358 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1361 /* store original boundaries */
1362 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1363 buffer->orig_alloc);
1364 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1365 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1368 /* store one word */
1369 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1370 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1371 out->ptr[out->size + j - i] = '\n';
1372 out->size += j - i + 1;
1378 /* this executes the word diff on the accumulated buffers */
1379 static void diff_words_show(struct diff_words_data *diff_words)
1383 mmfile_t minus, plus;
1384 struct diff_words_style *style = diff_words->style;
1386 struct diff_options *opt = diff_words->opt;
1387 const char *line_prefix;
1390 line_prefix = diff_line_prefix(opt);
1392 /* special case: only removal */
1393 if (!diff_words->plus.text.size) {
1394 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1395 line_prefix, strlen(line_prefix), 0);
1396 fn_out_diff_words_write_helper(diff_words->opt,
1397 &style->old, style->newline,
1398 diff_words->minus.text.size,
1399 diff_words->minus.text.ptr);
1400 diff_words->minus.text.size = 0;
1404 diff_words->current_plus = diff_words->plus.text.ptr;
1405 diff_words->last_minus = 0;
1407 memset(&xpp, 0, sizeof(xpp));
1408 memset(&xecfg, 0, sizeof(xecfg));
1409 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1410 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1412 /* as only the hunk header will be parsed, we need a 0-context */
1414 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1416 die("unable to generate word diff");
1419 if (diff_words->current_plus != diff_words->plus.text.ptr +
1420 diff_words->plus.text.size) {
1421 if (color_words_output_graph_prefix(diff_words))
1422 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1423 line_prefix, strlen(line_prefix), 0);
1424 fn_out_diff_words_write_helper(diff_words->opt,
1425 &style->ctx, style->newline,
1426 diff_words->plus.text.ptr + diff_words->plus.text.size
1427 - diff_words->current_plus, diff_words->current_plus);
1429 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1432 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1433 static void diff_words_flush(struct emit_callback *ecbdata)
1435 struct diff_options *wo = ecbdata->diff_words->opt;
1437 if (ecbdata->diff_words->minus.text.size ||
1438 ecbdata->diff_words->plus.text.size)
1439 diff_words_show(ecbdata->diff_words);
1441 if (wo->emitted_symbols) {
1442 struct diff_options *o = ecbdata->opt;
1443 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1448 * Instead of appending each, concat all words to a line?
1450 for (i = 0; i < wol->nr; i++)
1451 append_emitted_diff_symbol(o, &wol->buf[i]);
1453 for (i = 0; i < wol->nr; i++)
1454 free((void *)wol->buf[i].line);
1460 static void diff_filespec_load_driver(struct diff_filespec *one)
1462 /* Use already-loaded driver */
1466 if (S_ISREG(one->mode))
1467 one->driver = userdiff_find_by_path(one->path);
1469 /* Fallback to default settings */
1471 one->driver = userdiff_find_by_name("default");
1474 static const char *userdiff_word_regex(struct diff_filespec *one)
1476 diff_filespec_load_driver(one);
1477 return one->driver->word_regex;
1480 static void init_diff_words_data(struct emit_callback *ecbdata,
1481 struct diff_options *orig_opts,
1482 struct diff_filespec *one,
1483 struct diff_filespec *two)
1486 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1487 memcpy(o, orig_opts, sizeof(struct diff_options));
1489 ecbdata->diff_words =
1490 xcalloc(1, sizeof(struct diff_words_data));
1491 ecbdata->diff_words->type = o->word_diff;
1492 ecbdata->diff_words->opt = o;
1494 if (orig_opts->emitted_symbols)
1495 o->emitted_symbols =
1496 xcalloc(1, sizeof(struct emitted_diff_symbols));
1499 o->word_regex = userdiff_word_regex(one);
1501 o->word_regex = userdiff_word_regex(two);
1503 o->word_regex = diff_word_regex_cfg;
1504 if (o->word_regex) {
1505 ecbdata->diff_words->word_regex = (regex_t *)
1506 xmalloc(sizeof(regex_t));
1507 if (regcomp(ecbdata->diff_words->word_regex,
1509 REG_EXTENDED | REG_NEWLINE))
1510 die ("Invalid regular expression: %s",
1513 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1514 if (o->word_diff == diff_words_styles[i].type) {
1515 ecbdata->diff_words->style =
1516 &diff_words_styles[i];
1520 if (want_color(o->use_color)) {
1521 struct diff_words_style *st = ecbdata->diff_words->style;
1522 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1523 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1524 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1528 static void free_diff_words_data(struct emit_callback *ecbdata)
1530 if (ecbdata->diff_words) {
1531 diff_words_flush(ecbdata);
1532 free (ecbdata->diff_words->opt->emitted_symbols);
1533 free (ecbdata->diff_words->opt);
1534 free (ecbdata->diff_words->minus.text.ptr);
1535 free (ecbdata->diff_words->minus.orig);
1536 free (ecbdata->diff_words->plus.text.ptr);
1537 free (ecbdata->diff_words->plus.orig);
1538 if (ecbdata->diff_words->word_regex) {
1539 regfree(ecbdata->diff_words->word_regex);
1540 free(ecbdata->diff_words->word_regex);
1542 FREE_AND_NULL(ecbdata->diff_words);
1546 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1548 if (want_color(diff_use_color))
1549 return diff_colors[ix];
1553 const char *diff_line_prefix(struct diff_options *opt)
1555 struct strbuf *msgbuf;
1556 if (!opt->output_prefix)
1559 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1563 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1566 unsigned long allot;
1570 return ecb->truncate(line, len);
1574 (void) utf8_width(&cp, &l);
1576 break; /* truncated in the middle? */
1581 static void find_lno(const char *line, struct emit_callback *ecbdata)
1584 ecbdata->lno_in_preimage = 0;
1585 ecbdata->lno_in_postimage = 0;
1586 p = strchr(line, '-');
1588 return; /* cannot happen */
1589 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1592 return; /* cannot happen */
1593 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1596 static void fn_out_consume(void *priv, char *line, unsigned long len)
1598 struct emit_callback *ecbdata = priv;
1599 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1600 struct diff_options *o = ecbdata->opt;
1602 o->found_changes = 1;
1604 if (ecbdata->header) {
1605 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
1606 ecbdata->header->buf, ecbdata->header->len, 0);
1607 strbuf_reset(ecbdata->header);
1608 ecbdata->header = NULL;
1611 if (ecbdata->label_path[0]) {
1612 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1613 ecbdata->label_path[0],
1614 strlen(ecbdata->label_path[0]), 0);
1615 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1616 ecbdata->label_path[1],
1617 strlen(ecbdata->label_path[1]), 0);
1618 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1621 if (diff_suppress_blank_empty
1622 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1627 if (line[0] == '@') {
1628 if (ecbdata->diff_words)
1629 diff_words_flush(ecbdata);
1630 len = sane_truncate_line(ecbdata, line, len);
1631 find_lno(line, ecbdata);
1632 emit_hunk_header(ecbdata, line, len);
1636 if (ecbdata->diff_words) {
1637 enum diff_symbol s =
1638 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
1639 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
1640 if (line[0] == '-') {
1641 diff_words_append(line, len,
1642 &ecbdata->diff_words->minus);
1644 } else if (line[0] == '+') {
1645 diff_words_append(line, len,
1646 &ecbdata->diff_words->plus);
1648 } else if (starts_with(line, "\\ ")) {
1650 * Eat the "no newline at eof" marker as if we
1651 * saw a "+" or "-" line with nothing on it,
1652 * and return without diff_words_flush() to
1653 * defer processing. If this is the end of
1654 * preimage, more "+" lines may come after it.
1658 diff_words_flush(ecbdata);
1659 emit_diff_symbol(o, s, line, len, 0);
1665 ecbdata->lno_in_postimage++;
1666 emit_add_line(reset, ecbdata, line + 1, len - 1);
1669 ecbdata->lno_in_preimage++;
1670 emit_del_line(reset, ecbdata, line + 1, len - 1);
1673 ecbdata->lno_in_postimage++;
1674 ecbdata->lno_in_preimage++;
1675 emit_context_line(reset, ecbdata, line + 1, len - 1);
1678 /* incomplete line at the end */
1679 ecbdata->lno_in_preimage++;
1680 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
1686 static char *pprint_rename(const char *a, const char *b)
1688 const char *old = a;
1689 const char *new = b;
1690 struct strbuf name = STRBUF_INIT;
1691 int pfx_length, sfx_length;
1692 int pfx_adjust_for_slash;
1693 int len_a = strlen(a);
1694 int len_b = strlen(b);
1695 int a_midlen, b_midlen;
1696 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1697 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1699 if (qlen_a || qlen_b) {
1700 quote_c_style(a, &name, NULL, 0);
1701 strbuf_addstr(&name, " => ");
1702 quote_c_style(b, &name, NULL, 0);
1703 return strbuf_detach(&name, NULL);
1706 /* Find common prefix */
1708 while (*old && *new && *old == *new) {
1710 pfx_length = old - a + 1;
1715 /* Find common suffix */
1720 * If there is a common prefix, it must end in a slash. In
1721 * that case we let this loop run 1 into the prefix to see the
1724 * If there is no common prefix, we cannot do this as it would
1725 * underrun the input strings.
1727 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1728 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1729 b + pfx_length - pfx_adjust_for_slash <= new &&
1732 sfx_length = len_a - (old - a);
1738 * pfx{mid-a => mid-b}sfx
1739 * {pfx-a => pfx-b}sfx
1740 * pfx{sfx-a => sfx-b}
1743 a_midlen = len_a - pfx_length - sfx_length;
1744 b_midlen = len_b - pfx_length - sfx_length;
1750 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1751 if (pfx_length + sfx_length) {
1752 strbuf_add(&name, a, pfx_length);
1753 strbuf_addch(&name, '{');
1755 strbuf_add(&name, a + pfx_length, a_midlen);
1756 strbuf_addstr(&name, " => ");
1757 strbuf_add(&name, b + pfx_length, b_midlen);
1758 if (pfx_length + sfx_length) {
1759 strbuf_addch(&name, '}');
1760 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1762 return strbuf_detach(&name, NULL);
1768 struct diffstat_file {
1772 unsigned is_unmerged:1;
1773 unsigned is_binary:1;
1774 unsigned is_renamed:1;
1775 unsigned is_interesting:1;
1776 uintmax_t added, deleted;
1780 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1784 struct diffstat_file *x;
1785 x = xcalloc(1, sizeof(*x));
1786 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1787 diffstat->files[diffstat->nr++] = x;
1789 x->from_name = xstrdup(name_a);
1790 x->name = xstrdup(name_b);
1794 x->from_name = NULL;
1795 x->name = xstrdup(name_a);
1800 static void diffstat_consume(void *priv, char *line, unsigned long len)
1802 struct diffstat_t *diffstat = priv;
1803 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1807 else if (line[0] == '-')
1811 const char mime_boundary_leader[] = "------------";
1813 static int scale_linear(int it, int width, int max_change)
1818 * make sure that at least one '-' or '+' is printed if
1819 * there is any change to this path. The easiest way is to
1820 * scale linearly as if the alloted width is one column shorter
1821 * than it is, and then add 1 to the result.
1823 return 1 + (it * (width - 1) / max_change);
1826 static void show_graph(struct strbuf *out, char ch, int cnt,
1827 const char *set, const char *reset)
1831 strbuf_addstr(out, set);
1832 strbuf_addchars(out, ch, cnt);
1833 strbuf_addstr(out, reset);
1836 static void fill_print_name(struct diffstat_file *file)
1840 if (file->print_name)
1843 if (!file->is_renamed) {
1844 struct strbuf buf = STRBUF_INIT;
1845 if (quote_c_style(file->name, &buf, NULL, 0)) {
1846 pname = strbuf_detach(&buf, NULL);
1849 strbuf_release(&buf);
1852 pname = pprint_rename(file->from_name, file->name);
1854 file->print_name = pname;
1857 static void print_stat_summary_inserts_deletes(struct diff_options *options,
1858 int files, int insertions, int deletions)
1860 struct strbuf sb = STRBUF_INIT;
1863 assert(insertions == 0 && deletions == 0);
1864 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
1870 (files == 1) ? " %d file changed" : " %d files changed",
1874 * For binary diff, the caller may want to print "x files
1875 * changed" with insertions == 0 && deletions == 0.
1877 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1878 * is probably less confusing (i.e skip over "2 files changed
1879 * but nothing about added/removed lines? Is this a bug in Git?").
1881 if (insertions || deletions == 0) {
1883 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1887 if (deletions || insertions == 0) {
1889 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1892 strbuf_addch(&sb, '\n');
1893 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
1895 strbuf_release(&sb);
1898 void print_stat_summary(FILE *fp, int files,
1899 int insertions, int deletions)
1901 struct diff_options o;
1902 memset(&o, 0, sizeof(o));
1905 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
1908 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1910 int i, len, add, del, adds = 0, dels = 0;
1911 uintmax_t max_change = 0, max_len = 0;
1912 int total_files = data->nr, count;
1913 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1914 const char *reset, *add_c, *del_c;
1915 int extra_shown = 0;
1916 const char *line_prefix = diff_line_prefix(options);
1917 struct strbuf out = STRBUF_INIT;
1922 count = options->stat_count ? options->stat_count : data->nr;
1924 reset = diff_get_color_opt(options, DIFF_RESET);
1925 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1926 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1929 * Find the longest filename and max number of changes
1931 for (i = 0; (i < count) && (i < data->nr); i++) {
1932 struct diffstat_file *file = data->files[i];
1933 uintmax_t change = file->added + file->deleted;
1935 if (!file->is_interesting && (change == 0)) {
1936 count++; /* not shown == room for one more */
1939 fill_print_name(file);
1940 len = strlen(file->print_name);
1944 if (file->is_unmerged) {
1945 /* "Unmerged" is 8 characters */
1946 bin_width = bin_width < 8 ? 8 : bin_width;
1949 if (file->is_binary) {
1950 /* "Bin XXX -> YYY bytes" */
1951 int w = 14 + decimal_width(file->added)
1952 + decimal_width(file->deleted);
1953 bin_width = bin_width < w ? w : bin_width;
1954 /* Display change counts aligned with "Bin" */
1959 if (max_change < change)
1960 max_change = change;
1962 count = i; /* where we can stop scanning in data->files[] */
1965 * We have width = stat_width or term_columns() columns total.
1966 * We want a maximum of min(max_len, stat_name_width) for the name part.
1967 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1968 * We also need 1 for " " and 4 + decimal_width(max_change)
1969 * for " | NNNN " and one the empty column at the end, altogether
1970 * 6 + decimal_width(max_change).
1972 * If there's not enough space, we will use the smaller of
1973 * stat_name_width (if set) and 5/8*width for the filename,
1974 * and the rest for constant elements + graph part, but no more
1975 * than stat_graph_width for the graph part.
1976 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1977 * for the standard terminal size).
1979 * In other words: stat_width limits the maximum width, and
1980 * stat_name_width fixes the maximum width of the filename,
1981 * and is also used to divide available columns if there
1984 * Binary files are displayed with "Bin XXX -> YYY bytes"
1985 * instead of the change count and graph. This part is treated
1986 * similarly to the graph part, except that it is not
1987 * "scaled". If total width is too small to accommodate the
1988 * guaranteed minimum width of the filename part and the
1989 * separators and this message, this message will "overflow"
1990 * making the line longer than the maximum width.
1993 if (options->stat_width == -1)
1994 width = term_columns() - strlen(line_prefix);
1996 width = options->stat_width ? options->stat_width : 80;
1997 number_width = decimal_width(max_change) > number_width ?
1998 decimal_width(max_change) : number_width;
2000 if (options->stat_graph_width == -1)
2001 options->stat_graph_width = diff_stat_graph_width;
2004 * Guarantee 3/8*16==6 for the graph part
2005 * and 5/8*16==10 for the filename part
2007 if (width < 16 + 6 + number_width)
2008 width = 16 + 6 + number_width;
2011 * First assign sizes that are wanted, ignoring available width.
2012 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2013 * starting from "XXX" should fit in graph_width.
2015 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2016 if (options->stat_graph_width &&
2017 options->stat_graph_width < graph_width)
2018 graph_width = options->stat_graph_width;
2020 name_width = (options->stat_name_width > 0 &&
2021 options->stat_name_width < max_len) ?
2022 options->stat_name_width : max_len;
2025 * Adjust adjustable widths not to exceed maximum width
2027 if (name_width + number_width + 6 + graph_width > width) {
2028 if (graph_width > width * 3/8 - number_width - 6) {
2029 graph_width = width * 3/8 - number_width - 6;
2030 if (graph_width < 6)
2034 if (options->stat_graph_width &&
2035 graph_width > options->stat_graph_width)
2036 graph_width = options->stat_graph_width;
2037 if (name_width > width - number_width - 6 - graph_width)
2038 name_width = width - number_width - 6 - graph_width;
2040 graph_width = width - number_width - 6 - name_width;
2044 * From here name_width is the width of the name area,
2045 * and graph_width is the width of the graph area.
2046 * max_change is used to scale graph properly.
2048 for (i = 0; i < count; i++) {
2049 const char *prefix = "";
2050 struct diffstat_file *file = data->files[i];
2051 char *name = file->print_name;
2052 uintmax_t added = file->added;
2053 uintmax_t deleted = file->deleted;
2056 if (!file->is_interesting && (added + deleted == 0))
2060 * "scale" the filename
2063 name_len = strlen(name);
2064 if (name_width < name_len) {
2068 name += name_len - len;
2069 slash = strchr(name, '/');
2074 if (file->is_binary) {
2075 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2076 strbuf_addf(&out, " %*s", number_width, "Bin");
2077 if (!added && !deleted) {
2078 strbuf_addch(&out, '\n');
2079 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2080 out.buf, out.len, 0);
2084 strbuf_addf(&out, " %s%"PRIuMAX"%s",
2085 del_c, deleted, reset);
2086 strbuf_addstr(&out, " -> ");
2087 strbuf_addf(&out, "%s%"PRIuMAX"%s",
2088 add_c, added, reset);
2089 strbuf_addstr(&out, " bytes\n");
2090 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2091 out.buf, out.len, 0);
2095 else if (file->is_unmerged) {
2096 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2097 strbuf_addstr(&out, " Unmerged\n");
2098 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2099 out.buf, out.len, 0);
2105 * scale the add/delete
2110 if (graph_width <= max_change) {
2111 int total = scale_linear(add + del, graph_width, max_change);
2112 if (total < 2 && add && del)
2113 /* width >= 2 due to the sanity check */
2116 add = scale_linear(add, graph_width, max_change);
2119 del = scale_linear(del, graph_width, max_change);
2123 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2124 strbuf_addf(&out, " %*"PRIuMAX"%s",
2125 number_width, added + deleted,
2126 added + deleted ? " " : "");
2127 show_graph(&out, '+', add, add_c, reset);
2128 show_graph(&out, '-', del, del_c, reset);
2129 strbuf_addch(&out, '\n');
2130 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2131 out.buf, out.len, 0);
2135 for (i = 0; i < data->nr; i++) {
2136 struct diffstat_file *file = data->files[i];
2137 uintmax_t added = file->added;
2138 uintmax_t deleted = file->deleted;
2140 if (file->is_unmerged ||
2141 (!file->is_interesting && (added + deleted == 0))) {
2146 if (!file->is_binary) {
2153 emit_diff_symbol(options,
2154 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2159 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2162 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2164 int i, adds = 0, dels = 0, total_files = data->nr;
2169 for (i = 0; i < data->nr; i++) {
2170 int added = data->files[i]->added;
2171 int deleted = data->files[i]->deleted;
2173 if (data->files[i]->is_unmerged ||
2174 (!data->files[i]->is_interesting && (added + deleted == 0))) {
2176 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2181 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2184 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2191 for (i = 0; i < data->nr; i++) {
2192 struct diffstat_file *file = data->files[i];
2194 fprintf(options->file, "%s", diff_line_prefix(options));
2196 if (file->is_binary)
2197 fprintf(options->file, "-\t-\t");
2199 fprintf(options->file,
2200 "%"PRIuMAX"\t%"PRIuMAX"\t",
2201 file->added, file->deleted);
2202 if (options->line_termination) {
2203 fill_print_name(file);
2204 if (!file->is_renamed)
2205 write_name_quoted(file->name, options->file,
2206 options->line_termination);
2208 fputs(file->print_name, options->file);
2209 putc(options->line_termination, options->file);
2212 if (file->is_renamed) {
2213 putc('\0', options->file);
2214 write_name_quoted(file->from_name, options->file, '\0');
2216 write_name_quoted(file->name, options->file, '\0');
2221 struct dirstat_file {
2223 unsigned long changed;
2226 struct dirstat_dir {
2227 struct dirstat_file *files;
2228 int alloc, nr, permille, cumulative;
2231 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2232 unsigned long changed, const char *base, int baselen)
2234 unsigned long this_dir = 0;
2235 unsigned int sources = 0;
2236 const char *line_prefix = diff_line_prefix(opt);
2239 struct dirstat_file *f = dir->files;
2240 int namelen = strlen(f->name);
2244 if (namelen < baselen)
2246 if (memcmp(f->name, base, baselen))
2248 slash = strchr(f->name + baselen, '/');
2250 int newbaselen = slash + 1 - f->name;
2251 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2263 * We don't report dirstat's for
2265 * - or cases where everything came from a single directory
2266 * under this directory (sources == 1).
2268 if (baselen && sources != 1) {
2270 int permille = this_dir * 1000 / changed;
2271 if (permille >= dir->permille) {
2272 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2273 permille / 10, permille % 10, baselen, base);
2274 if (!dir->cumulative)
2282 static int dirstat_compare(const void *_a, const void *_b)
2284 const struct dirstat_file *a = _a;
2285 const struct dirstat_file *b = _b;
2286 return strcmp(a->name, b->name);
2289 static void show_dirstat(struct diff_options *options)
2292 unsigned long changed;
2293 struct dirstat_dir dir;
2294 struct diff_queue_struct *q = &diff_queued_diff;
2299 dir.permille = options->dirstat_permille;
2300 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2303 for (i = 0; i < q->nr; i++) {
2304 struct diff_filepair *p = q->queue[i];
2306 unsigned long copied, added, damage;
2307 int content_changed;
2309 name = p->two->path ? p->two->path : p->one->path;
2311 if (p->one->oid_valid && p->two->oid_valid)
2312 content_changed = oidcmp(&p->one->oid, &p->two->oid);
2314 content_changed = 1;
2316 if (!content_changed) {
2318 * The SHA1 has not changed, so pre-/post-content is
2319 * identical. We can therefore skip looking at the
2320 * file contents altogether.
2326 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2328 * In --dirstat-by-file mode, we don't really need to
2329 * look at the actual file contents at all.
2330 * The fact that the SHA1 changed is enough for us to
2331 * add this file to the list of results
2332 * (with each file contributing equal damage).
2338 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2339 diff_populate_filespec(p->one, 0);
2340 diff_populate_filespec(p->two, 0);
2341 diffcore_count_changes(p->one, p->two, NULL, NULL,
2343 diff_free_filespec_data(p->one);
2344 diff_free_filespec_data(p->two);
2345 } else if (DIFF_FILE_VALID(p->one)) {
2346 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2348 diff_free_filespec_data(p->one);
2349 } else if (DIFF_FILE_VALID(p->two)) {
2350 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2352 added = p->two->size;
2353 diff_free_filespec_data(p->two);
2358 * Original minus copied is the removed material,
2359 * added is the new material. They are both damages
2360 * made to the preimage.
2361 * If the resulting damage is zero, we know that
2362 * diffcore_count_changes() considers the two entries to
2363 * be identical, but since content_changed is true, we
2364 * know that there must have been _some_ kind of change,
2365 * so we force all entries to have damage > 0.
2367 damage = (p->one->size - copied) + added;
2372 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2373 dir.files[dir.nr].name = name;
2374 dir.files[dir.nr].changed = damage;
2379 /* This can happen even with many files, if everything was renames */
2383 /* Show all directories with more than x% of the changes */
2384 QSORT(dir.files, dir.nr, dirstat_compare);
2385 gather_dirstat(options, &dir, changed, "", 0);
2388 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2391 unsigned long changed;
2392 struct dirstat_dir dir;
2400 dir.permille = options->dirstat_permille;
2401 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2404 for (i = 0; i < data->nr; i++) {
2405 struct diffstat_file *file = data->files[i];
2406 unsigned long damage = file->added + file->deleted;
2407 if (file->is_binary)
2409 * binary files counts bytes, not lines. Must find some
2410 * way to normalize binary bytes vs. textual lines.
2411 * The following heuristic assumes that there are 64
2413 * This is stupid and ugly, but very cheap...
2415 damage = (damage + 63) / 64;
2416 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2417 dir.files[dir.nr].name = file->name;
2418 dir.files[dir.nr].changed = damage;
2423 /* This can happen even with many files, if everything was renames */
2427 /* Show all directories with more than x% of the changes */
2428 QSORT(dir.files, dir.nr, dirstat_compare);
2429 gather_dirstat(options, &dir, changed, "", 0);
2432 static void free_diffstat_info(struct diffstat_t *diffstat)
2435 for (i = 0; i < diffstat->nr; i++) {
2436 struct diffstat_file *f = diffstat->files[i];
2437 if (f->name != f->print_name)
2438 free(f->print_name);
2443 free(diffstat->files);
2446 struct checkdiff_t {
2447 const char *filename;
2449 int conflict_marker_size;
2450 struct diff_options *o;
2455 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2460 if (len < marker_size + 1)
2462 firstchar = line[0];
2463 switch (firstchar) {
2464 case '=': case '>': case '<': case '|':
2469 for (cnt = 1; cnt < marker_size; cnt++)
2470 if (line[cnt] != firstchar)
2472 /* line[1] thru line[marker_size-1] are same as firstchar */
2473 if (len < marker_size + 1 || !isspace(line[marker_size]))
2478 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2480 struct checkdiff_t *data = priv;
2481 int marker_size = data->conflict_marker_size;
2482 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2483 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2484 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2486 const char *line_prefix;
2489 line_prefix = diff_line_prefix(data->o);
2491 if (line[0] == '+') {
2494 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2496 fprintf(data->o->file,
2497 "%s%s:%d: leftover conflict marker\n",
2498 line_prefix, data->filename, data->lineno);
2500 bad = ws_check(line + 1, len - 1, data->ws_rule);
2503 data->status |= bad;
2504 err = whitespace_error_string(bad);
2505 fprintf(data->o->file, "%s%s:%d: %s.\n",
2506 line_prefix, data->filename, data->lineno, err);
2508 emit_line(data->o, set, reset, line, 1);
2509 ws_check_emit(line + 1, len - 1, data->ws_rule,
2510 data->o->file, set, reset, ws);
2511 } else if (line[0] == ' ') {
2513 } else if (line[0] == '@') {
2514 char *plus = strchr(line, '+');
2516 data->lineno = strtol(plus, NULL, 10) - 1;
2518 die("invalid diff");
2522 static unsigned char *deflate_it(char *data,
2524 unsigned long *result_size)
2527 unsigned char *deflated;
2530 git_deflate_init(&stream, zlib_compression_level);
2531 bound = git_deflate_bound(&stream, size);
2532 deflated = xmalloc(bound);
2533 stream.next_out = deflated;
2534 stream.avail_out = bound;
2536 stream.next_in = (unsigned char *)data;
2537 stream.avail_in = size;
2538 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2540 git_deflate_end(&stream);
2541 *result_size = stream.total_out;
2545 static void emit_binary_diff_body(struct diff_options *o,
2546 mmfile_t *one, mmfile_t *two)
2552 unsigned long orig_size;
2553 unsigned long delta_size;
2554 unsigned long deflate_size;
2555 unsigned long data_size;
2557 /* We could do deflated delta, or we could do just deflated two,
2558 * whichever is smaller.
2561 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2562 if (one->size && two->size) {
2563 delta = diff_delta(one->ptr, one->size,
2564 two->ptr, two->size,
2565 &delta_size, deflate_size);
2567 void *to_free = delta;
2568 orig_size = delta_size;
2569 delta = deflate_it(delta, delta_size, &delta_size);
2574 if (delta && delta_size < deflate_size) {
2575 char *s = xstrfmt("%lu", orig_size);
2576 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2581 data_size = delta_size;
2583 char *s = xstrfmt("%lu", two->size);
2584 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2589 data_size = deflate_size;
2592 /* emit data encoded in base85 */
2596 int bytes = (52 < data_size) ? 52 : data_size;
2600 line[0] = bytes + 'A' - 1;
2602 line[0] = bytes - 26 + 'a' - 1;
2603 encode_85(line + 1, cp, bytes);
2604 cp = (char *) cp + bytes;
2610 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
2613 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
2617 static void emit_binary_diff(struct diff_options *o,
2618 mmfile_t *one, mmfile_t *two)
2620 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
2621 emit_binary_diff_body(o, one, two);
2622 emit_binary_diff_body(o, two, one);
2625 int diff_filespec_is_binary(struct diff_filespec *one)
2627 if (one->is_binary == -1) {
2628 diff_filespec_load_driver(one);
2629 if (one->driver->binary != -1)
2630 one->is_binary = one->driver->binary;
2632 if (!one->data && DIFF_FILE_VALID(one))
2633 diff_populate_filespec(one, CHECK_BINARY);
2634 if (one->is_binary == -1 && one->data)
2635 one->is_binary = buffer_is_binary(one->data,
2637 if (one->is_binary == -1)
2641 return one->is_binary;
2644 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2646 diff_filespec_load_driver(one);
2647 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2650 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2652 if (!options->a_prefix)
2653 options->a_prefix = a;
2654 if (!options->b_prefix)
2655 options->b_prefix = b;
2658 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2660 if (!DIFF_FILE_VALID(one))
2663 diff_filespec_load_driver(one);
2664 return userdiff_get_textconv(one->driver);
2667 static void builtin_diff(const char *name_a,
2669 struct diff_filespec *one,
2670 struct diff_filespec *two,
2671 const char *xfrm_msg,
2672 int must_show_header,
2673 struct diff_options *o,
2674 int complete_rewrite)
2678 char *a_one, *b_two;
2679 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2680 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2681 const char *a_prefix, *b_prefix;
2682 struct userdiff_driver *textconv_one = NULL;
2683 struct userdiff_driver *textconv_two = NULL;
2684 struct strbuf header = STRBUF_INIT;
2685 const char *line_prefix = diff_line_prefix(o);
2687 diff_set_mnemonic_prefix(o, "a/", "b/");
2688 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2689 a_prefix = o->b_prefix;
2690 b_prefix = o->a_prefix;
2692 a_prefix = o->a_prefix;
2693 b_prefix = o->b_prefix;
2696 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2697 (!one->mode || S_ISGITLINK(one->mode)) &&
2698 (!two->mode || S_ISGITLINK(two->mode))) {
2699 show_submodule_summary(o, one->path ? one->path : two->path,
2700 &one->oid, &two->oid,
2701 two->dirty_submodule);
2703 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2704 (!one->mode || S_ISGITLINK(one->mode)) &&
2705 (!two->mode || S_ISGITLINK(two->mode))) {
2706 show_submodule_inline_diff(o, one->path ? one->path : two->path,
2707 &one->oid, &two->oid,
2708 two->dirty_submodule);
2712 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2713 textconv_one = get_textconv(one);
2714 textconv_two = get_textconv(two);
2717 /* Never use a non-valid filename anywhere if at all possible */
2718 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2719 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2721 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2722 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2723 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2724 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2725 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2726 if (lbl[0][0] == '/') {
2728 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2730 strbuf_addstr(&header, xfrm_msg);
2731 must_show_header = 1;
2733 else if (lbl[1][0] == '/') {
2734 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2736 strbuf_addstr(&header, xfrm_msg);
2737 must_show_header = 1;
2740 if (one->mode != two->mode) {
2741 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2742 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2743 must_show_header = 1;
2746 strbuf_addstr(&header, xfrm_msg);
2749 * we do not run diff between different kind
2752 if ((one->mode ^ two->mode) & S_IFMT)
2753 goto free_ab_and_return;
2754 if (complete_rewrite &&
2755 (textconv_one || !diff_filespec_is_binary(one)) &&
2756 (textconv_two || !diff_filespec_is_binary(two))) {
2757 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2758 header.buf, header.len, 0);
2759 strbuf_reset(&header);
2760 emit_rewrite_diff(name_a, name_b, one, two,
2761 textconv_one, textconv_two, o);
2762 o->found_changes = 1;
2763 goto free_ab_and_return;
2767 if (o->irreversible_delete && lbl[1][0] == '/') {
2768 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
2770 strbuf_reset(&header);
2771 goto free_ab_and_return;
2772 } else if (!DIFF_OPT_TST(o, TEXT) &&
2773 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2774 (!textconv_two && diff_filespec_is_binary(two)) )) {
2775 struct strbuf sb = STRBUF_INIT;
2776 if (!one->data && !two->data &&
2777 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2778 !DIFF_OPT_TST(o, BINARY)) {
2779 if (!oidcmp(&one->oid, &two->oid)) {
2780 if (must_show_header)
2781 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2782 header.buf, header.len,
2784 goto free_ab_and_return;
2786 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2787 header.buf, header.len, 0);
2788 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
2789 diff_line_prefix(o), lbl[0], lbl[1]);
2790 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
2792 strbuf_release(&sb);
2793 goto free_ab_and_return;
2795 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2796 die("unable to read files to diff");
2797 /* Quite common confusing case */
2798 if (mf1.size == mf2.size &&
2799 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2800 if (must_show_header)
2801 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2802 header.buf, header.len, 0);
2803 goto free_ab_and_return;
2805 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
2806 strbuf_reset(&header);
2807 if (DIFF_OPT_TST(o, BINARY))
2808 emit_binary_diff(o, &mf1, &mf2);
2810 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
2811 diff_line_prefix(o), lbl[0], lbl[1]);
2812 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
2814 strbuf_release(&sb);
2816 o->found_changes = 1;
2818 /* Crazy xdl interfaces.. */
2819 const char *diffopts = getenv("GIT_DIFF_OPTS");
2823 struct emit_callback ecbdata;
2824 const struct userdiff_funcname *pe;
2826 if (must_show_header) {
2827 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2828 header.buf, header.len, 0);
2829 strbuf_reset(&header);
2832 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2833 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2835 pe = diff_funcname_pattern(one);
2837 pe = diff_funcname_pattern(two);
2839 memset(&xpp, 0, sizeof(xpp));
2840 memset(&xecfg, 0, sizeof(xecfg));
2841 memset(&ecbdata, 0, sizeof(ecbdata));
2842 ecbdata.label_path = lbl;
2843 ecbdata.color_diff = want_color(o->use_color);
2844 ecbdata.ws_rule = whitespace_rule(name_b);
2845 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2846 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2848 ecbdata.header = header.len ? &header : NULL;
2849 xpp.flags = o->xdl_opts;
2850 xecfg.ctxlen = o->context;
2851 xecfg.interhunkctxlen = o->interhunkcontext;
2852 xecfg.flags = XDL_EMIT_FUNCNAMES;
2853 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2854 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2856 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2859 else if (skip_prefix(diffopts, "--unified=", &v))
2860 xecfg.ctxlen = strtoul(v, NULL, 10);
2861 else if (skip_prefix(diffopts, "-u", &v))
2862 xecfg.ctxlen = strtoul(v, NULL, 10);
2864 init_diff_words_data(&ecbdata, o, one, two);
2865 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2867 die("unable to generate diff for %s", one->path);
2869 free_diff_words_data(&ecbdata);
2874 xdiff_clear_find_func(&xecfg);
2878 strbuf_release(&header);
2879 diff_free_filespec_data(one);
2880 diff_free_filespec_data(two);
2886 static void builtin_diffstat(const char *name_a, const char *name_b,
2887 struct diff_filespec *one,
2888 struct diff_filespec *two,
2889 struct diffstat_t *diffstat,
2890 struct diff_options *o,
2891 struct diff_filepair *p)
2894 struct diffstat_file *data;
2896 int complete_rewrite = 0;
2898 if (!DIFF_PAIR_UNMERGED(p)) {
2899 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2900 complete_rewrite = 1;
2903 data = diffstat_add(diffstat, name_a, name_b);
2904 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2907 data->is_unmerged = 1;
2911 same_contents = !oidcmp(&one->oid, &two->oid);
2913 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2914 data->is_binary = 1;
2915 if (same_contents) {
2919 data->added = diff_filespec_size(two);
2920 data->deleted = diff_filespec_size(one);
2924 else if (complete_rewrite) {
2925 diff_populate_filespec(one, 0);
2926 diff_populate_filespec(two, 0);
2927 data->deleted = count_lines(one->data, one->size);
2928 data->added = count_lines(two->data, two->size);
2931 else if (!same_contents) {
2932 /* Crazy xdl interfaces.. */
2936 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2937 die("unable to read files to diff");
2939 memset(&xpp, 0, sizeof(xpp));
2940 memset(&xecfg, 0, sizeof(xecfg));
2941 xpp.flags = o->xdl_opts;
2942 xecfg.ctxlen = o->context;
2943 xecfg.interhunkctxlen = o->interhunkcontext;
2944 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2946 die("unable to generate diffstat for %s", one->path);
2949 diff_free_filespec_data(one);
2950 diff_free_filespec_data(two);
2953 static void builtin_checkdiff(const char *name_a, const char *name_b,
2954 const char *attr_path,
2955 struct diff_filespec *one,
2956 struct diff_filespec *two,
2957 struct diff_options *o)
2960 struct checkdiff_t data;
2965 memset(&data, 0, sizeof(data));
2966 data.filename = name_b ? name_b : name_a;
2969 data.ws_rule = whitespace_rule(attr_path);
2970 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2972 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2973 die("unable to read files to diff");
2976 * All the other codepaths check both sides, but not checking
2977 * the "old" side here is deliberate. We are checking the newly
2978 * introduced changes, and as long as the "new" side is text, we
2979 * can and should check what it introduces.
2981 if (diff_filespec_is_binary(two))
2982 goto free_and_return;
2984 /* Crazy xdl interfaces.. */
2988 memset(&xpp, 0, sizeof(xpp));
2989 memset(&xecfg, 0, sizeof(xecfg));
2990 xecfg.ctxlen = 1; /* at least one context line */
2992 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2994 die("unable to generate checkdiff for %s", one->path);
2996 if (data.ws_rule & WS_BLANK_AT_EOF) {
2997 struct emit_callback ecbdata;
3000 ecbdata.ws_rule = data.ws_rule;
3001 check_blank_at_eof(&mf1, &mf2, &ecbdata);
3002 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3007 err = whitespace_error_string(WS_BLANK_AT_EOF);
3008 fprintf(o->file, "%s:%d: %s.\n",
3009 data.filename, blank_at_eof, err);
3010 data.status = 1; /* report errors */
3015 diff_free_filespec_data(one);
3016 diff_free_filespec_data(two);
3018 DIFF_OPT_SET(o, CHECK_FAILED);
3021 struct diff_filespec *alloc_filespec(const char *path)
3023 struct diff_filespec *spec;
3025 FLEXPTR_ALLOC_STR(spec, path, path);
3027 spec->is_binary = -1;
3031 void free_filespec(struct diff_filespec *spec)
3033 if (!--spec->count) {
3034 diff_free_filespec_data(spec);
3039 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3040 int oid_valid, unsigned short mode)
3043 spec->mode = canon_mode(mode);
3044 oidcpy(&spec->oid, oid);
3045 spec->oid_valid = oid_valid;
3050 * Given a name and sha1 pair, if the index tells us the file in
3051 * the work tree has that object contents, return true, so that
3052 * prepare_temp_file() does not have to inflate and extract.
3054 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
3056 const struct cache_entry *ce;
3061 * We do not read the cache ourselves here, because the
3062 * benchmark with my previous version that always reads cache
3063 * shows that it makes things worse for diff-tree comparing
3064 * two linux-2.6 kernel trees in an already checked out work
3065 * tree. This is because most diff-tree comparisons deal with
3066 * only a small number of files, while reading the cache is
3067 * expensive for a large project, and its cost outweighs the
3068 * savings we get by not inflating the object to a temporary
3069 * file. Practically, this code only helps when we are used
3070 * by diff-cache --cached, which does read the cache before
3076 /* We want to avoid the working directory if our caller
3077 * doesn't need the data in a normal file, this system
3078 * is rather slow with its stat/open/mmap/close syscalls,
3079 * and the object is contained in a pack file. The pack
3080 * is probably already open and will be faster to obtain
3081 * the data through than the working directory. Loose
3082 * objects however would tend to be slower as they need
3083 * to be individually opened and inflated.
3085 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
3089 * Similarly, if we'd have to convert the file contents anyway, that
3090 * makes the optimization not worthwhile.
3092 if (!want_file && would_convert_to_git(&the_index, name))
3096 pos = cache_name_pos(name, len);
3099 ce = active_cache[pos];
3102 * This is not the sha1 we are looking for, or
3103 * unreusable because it is not a regular file.
3105 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3109 * If ce is marked as "assume unchanged", there is no
3110 * guarantee that work tree matches what we are looking for.
3112 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3116 * If ce matches the file in the work tree, we can reuse it.
3118 if (ce_uptodate(ce) ||
3119 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3125 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3127 struct strbuf buf = STRBUF_INIT;
3130 /* Are we looking at the work tree? */
3131 if (s->dirty_submodule)
3134 strbuf_addf(&buf, "Subproject commit %s%s\n",
3135 oid_to_hex(&s->oid), dirty);
3139 strbuf_release(&buf);
3141 s->data = strbuf_detach(&buf, NULL);
3148 * While doing rename detection and pickaxe operation, we may need to
3149 * grab the data for the blob (or file) for our own in-core comparison.
3150 * diff_filespec has data and size fields for this purpose.
3152 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
3154 int size_only = flags & CHECK_SIZE_ONLY;
3157 * demote FAIL to WARN to allow inspecting the situation
3158 * instead of refusing.
3160 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
3164 if (!DIFF_FILE_VALID(s))
3165 die("internal error: asking to populate invalid file.");
3166 if (S_ISDIR(s->mode))
3172 if (size_only && 0 < s->size)
3175 if (S_ISGITLINK(s->mode))
3176 return diff_populate_gitlink(s, size_only);
3178 if (!s->oid_valid ||
3179 reuse_worktree_file(s->path, &s->oid, 0)) {
3180 struct strbuf buf = STRBUF_INIT;
3184 if (lstat(s->path, &st) < 0) {
3185 if (errno == ENOENT) {
3189 s->data = (char *)"";
3194 s->size = xsize_t(st.st_size);
3197 if (S_ISLNK(st.st_mode)) {
3198 struct strbuf sb = STRBUF_INIT;
3200 if (strbuf_readlink(&sb, s->path, s->size))
3203 s->data = strbuf_detach(&sb, NULL);
3209 * Even if the caller would be happy with getting
3210 * only the size, we cannot return early at this
3211 * point if the path requires us to run the content
3214 if (size_only && !would_convert_to_git(&the_index, s->path))
3218 * Note: this check uses xsize_t(st.st_size) that may
3219 * not be the true size of the blob after it goes
3220 * through convert_to_git(). This may not strictly be
3221 * correct, but the whole point of big_file_threshold
3222 * and is_binary check being that we want to avoid
3223 * opening the file and inspecting the contents, this
3226 if ((flags & CHECK_BINARY) &&
3227 s->size > big_file_threshold && s->is_binary == -1) {
3231 fd = open(s->path, O_RDONLY);
3234 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
3236 s->should_munmap = 1;
3239 * Convert from working tree format to canonical git format
3241 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
3243 munmap(s->data, s->size);
3244 s->should_munmap = 0;
3245 s->data = strbuf_detach(&buf, &size);
3251 enum object_type type;
3252 if (size_only || (flags & CHECK_BINARY)) {
3253 type = sha1_object_info(s->oid.hash, &s->size);
3255 die("unable to read %s",
3256 oid_to_hex(&s->oid));
3259 if (s->size > big_file_threshold && s->is_binary == -1) {
3264 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
3266 die("unable to read %s", oid_to_hex(&s->oid));
3272 void diff_free_filespec_blob(struct diff_filespec *s)
3276 else if (s->should_munmap)
3277 munmap(s->data, s->size);
3279 if (s->should_free || s->should_munmap) {
3280 s->should_free = s->should_munmap = 0;
3285 void diff_free_filespec_data(struct diff_filespec *s)
3287 diff_free_filespec_blob(s);
3288 FREE_AND_NULL(s->cnt_data);
3291 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
3294 const struct object_id *oid,
3298 struct strbuf buf = STRBUF_INIT;
3299 struct strbuf template = STRBUF_INIT;
3300 char *path_dup = xstrdup(path);
3301 const char *base = basename(path_dup);
3303 /* Generate "XXXXXX_basename.ext" */
3304 strbuf_addstr(&template, "XXXXXX_");
3305 strbuf_addstr(&template, base);
3307 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
3309 die_errno("unable to create temp-file");
3310 if (convert_to_working_tree(path,
3311 (const char *)blob, (size_t)size, &buf)) {
3315 if (write_in_full(fd, blob, size) != size)
3316 die_errno("unable to write temp-file");
3317 close_tempfile(&temp->tempfile);
3318 temp->name = get_tempfile_path(&temp->tempfile);
3319 oid_to_hex_r(temp->hex, oid);
3320 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
3321 strbuf_release(&buf);
3322 strbuf_release(&template);
3326 static struct diff_tempfile *prepare_temp_file(const char *name,
3327 struct diff_filespec *one)
3329 struct diff_tempfile *temp = claim_diff_tempfile();
3331 if (!DIFF_FILE_VALID(one)) {
3333 /* A '-' entry produces this for file-2, and
3334 * a '+' entry produces this for file-1.
3336 temp->name = "/dev/null";
3337 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3338 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3342 if (!S_ISGITLINK(one->mode) &&
3344 reuse_worktree_file(name, &one->oid, 1))) {
3346 if (lstat(name, &st) < 0) {
3347 if (errno == ENOENT)
3348 goto not_a_valid_file;
3349 die_errno("stat(%s)", name);
3351 if (S_ISLNK(st.st_mode)) {
3352 struct strbuf sb = STRBUF_INIT;
3353 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3354 die_errno("readlink(%s)", name);
3355 prep_temp_blob(name, temp, sb.buf, sb.len,
3357 &one->oid : &null_oid),
3359 one->mode : S_IFLNK));
3360 strbuf_release(&sb);
3363 /* we can borrow from the file in the work tree */
3365 if (!one->oid_valid)
3366 oid_to_hex_r(temp->hex, &null_oid);
3368 oid_to_hex_r(temp->hex, &one->oid);
3369 /* Even though we may sometimes borrow the
3370 * contents from the work tree, we always want
3371 * one->mode. mode is trustworthy even when
3372 * !(one->oid_valid), as long as
3373 * DIFF_FILE_VALID(one).
3375 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3380 if (diff_populate_filespec(one, 0))
3381 die("cannot read data blob for %s", one->path);
3382 prep_temp_blob(name, temp, one->data, one->size,
3383 &one->oid, one->mode);
3388 static void add_external_diff_name(struct argv_array *argv,
3390 struct diff_filespec *df)
3392 struct diff_tempfile *temp = prepare_temp_file(name, df);
3393 argv_array_push(argv, temp->name);
3394 argv_array_push(argv, temp->hex);
3395 argv_array_push(argv, temp->mode);
3398 /* An external diff command takes:
3400 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3401 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3404 static void run_external_diff(const char *pgm,
3407 struct diff_filespec *one,
3408 struct diff_filespec *two,
3409 const char *xfrm_msg,
3410 int complete_rewrite,
3411 struct diff_options *o)
3413 struct argv_array argv = ARGV_ARRAY_INIT;
3414 struct argv_array env = ARGV_ARRAY_INIT;
3415 struct diff_queue_struct *q = &diff_queued_diff;
3417 argv_array_push(&argv, pgm);
3418 argv_array_push(&argv, name);
3421 add_external_diff_name(&argv, name, one);
3423 add_external_diff_name(&argv, name, two);
3425 add_external_diff_name(&argv, other, two);
3426 argv_array_push(&argv, other);
3427 argv_array_push(&argv, xfrm_msg);
3431 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3432 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3434 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3435 die(_("external diff died, stopping at %s"), name);
3438 argv_array_clear(&argv);
3439 argv_array_clear(&env);
3442 static int similarity_index(struct diff_filepair *p)
3444 return p->score * 100 / MAX_SCORE;
3447 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3449 if (startup_info->have_repository)
3450 return find_unique_abbrev(oid->hash, abbrev);
3452 char *hex = oid_to_hex(oid);
3454 abbrev = FALLBACK_DEFAULT_ABBREV;
3455 if (abbrev > GIT_SHA1_HEXSZ)
3456 die("BUG: oid abbreviation out of range: %d", abbrev);
3463 static void fill_metainfo(struct strbuf *msg,
3466 struct diff_filespec *one,
3467 struct diff_filespec *two,
3468 struct diff_options *o,
3469 struct diff_filepair *p,
3470 int *must_show_header,
3473 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3474 const char *reset = diff_get_color(use_color, DIFF_RESET);
3475 const char *line_prefix = diff_line_prefix(o);
3477 *must_show_header = 1;
3478 strbuf_init(msg, PATH_MAX * 2 + 300);
3479 switch (p->status) {
3480 case DIFF_STATUS_COPIED:
3481 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3482 line_prefix, set, similarity_index(p));
3483 strbuf_addf(msg, "%s\n%s%scopy from ",
3484 reset, line_prefix, set);
3485 quote_c_style(name, msg, NULL, 0);
3486 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3487 quote_c_style(other, msg, NULL, 0);
3488 strbuf_addf(msg, "%s\n", reset);
3490 case DIFF_STATUS_RENAMED:
3491 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3492 line_prefix, set, similarity_index(p));
3493 strbuf_addf(msg, "%s\n%s%srename from ",
3494 reset, line_prefix, set);
3495 quote_c_style(name, msg, NULL, 0);
3496 strbuf_addf(msg, "%s\n%s%srename to ",
3497 reset, line_prefix, set);
3498 quote_c_style(other, msg, NULL, 0);
3499 strbuf_addf(msg, "%s\n", reset);
3501 case DIFF_STATUS_MODIFIED:
3503 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3505 set, similarity_index(p), reset);
3510 *must_show_header = 0;
3512 if (one && two && oidcmp(&one->oid, &two->oid)) {
3513 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3515 if (DIFF_OPT_TST(o, BINARY)) {
3517 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3518 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3521 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3522 diff_abbrev_oid(&one->oid, abbrev),
3523 diff_abbrev_oid(&two->oid, abbrev));
3524 if (one->mode == two->mode)
3525 strbuf_addf(msg, " %06o", one->mode);
3526 strbuf_addf(msg, "%s\n", reset);
3530 static void run_diff_cmd(const char *pgm,
3533 const char *attr_path,
3534 struct diff_filespec *one,
3535 struct diff_filespec *two,
3537 struct diff_options *o,
3538 struct diff_filepair *p)
3540 const char *xfrm_msg = NULL;
3541 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3542 int must_show_header = 0;
3545 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3546 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3547 if (drv && drv->external)
3548 pgm = drv->external;
3553 * don't use colors when the header is intended for an
3554 * external diff driver
3556 fill_metainfo(msg, name, other, one, two, o, p,
3558 want_color(o->use_color) && !pgm);
3559 xfrm_msg = msg->len ? msg->buf : NULL;
3563 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3564 complete_rewrite, o);
3568 builtin_diff(name, other ? other : name,
3569 one, two, xfrm_msg, must_show_header,
3570 o, complete_rewrite);
3572 fprintf(o->file, "* Unmerged path %s\n", name);
3575 static void diff_fill_oid_info(struct diff_filespec *one)
3577 if (DIFF_FILE_VALID(one)) {
3578 if (!one->oid_valid) {
3580 if (one->is_stdin) {
3584 if (lstat(one->path, &st) < 0)
3585 die_errno("stat '%s'", one->path);
3586 if (index_path(one->oid.hash, one->path, &st, 0))
3587 die("cannot hash %s", one->path);
3594 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3596 /* Strip the prefix but do not molest /dev/null and absolute paths */
3597 if (*namep && **namep != '/') {
3598 *namep += prefix_length;
3602 if (*otherp && **otherp != '/') {
3603 *otherp += prefix_length;
3604 if (**otherp == '/')
3609 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3611 const char *pgm = external_diff();
3613 struct diff_filespec *one = p->one;
3614 struct diff_filespec *two = p->two;
3617 const char *attr_path;
3620 other = (strcmp(name, two->path) ? two->path : NULL);
3622 if (o->prefix_length)
3623 strip_prefix(o->prefix_length, &name, &other);
3625 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3628 if (DIFF_PAIR_UNMERGED(p)) {
3629 run_diff_cmd(pgm, name, NULL, attr_path,
3630 NULL, NULL, NULL, o, p);
3634 diff_fill_oid_info(one);
3635 diff_fill_oid_info(two);
3638 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3639 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3641 * a filepair that changes between file and symlink
3642 * needs to be split into deletion and creation.
3644 struct diff_filespec *null = alloc_filespec(two->path);
3645 run_diff_cmd(NULL, name, other, attr_path,
3646 one, null, &msg, o, p);
3648 strbuf_release(&msg);
3650 null = alloc_filespec(one->path);
3651 run_diff_cmd(NULL, name, other, attr_path,
3652 null, two, &msg, o, p);
3656 run_diff_cmd(pgm, name, other, attr_path,
3657 one, two, &msg, o, p);
3659 strbuf_release(&msg);
3662 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3663 struct diffstat_t *diffstat)
3668 if (DIFF_PAIR_UNMERGED(p)) {
3670 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3674 name = p->one->path;
3675 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3677 if (o->prefix_length)
3678 strip_prefix(o->prefix_length, &name, &other);
3680 diff_fill_oid_info(p->one);
3681 diff_fill_oid_info(p->two);
3683 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3686 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3690 const char *attr_path;
3692 if (DIFF_PAIR_UNMERGED(p)) {
3697 name = p->one->path;
3698 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3699 attr_path = other ? other : name;
3701 if (o->prefix_length)
3702 strip_prefix(o->prefix_length, &name, &other);
3704 diff_fill_oid_info(p->one);
3705 diff_fill_oid_info(p->two);
3707 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3710 void diff_setup(struct diff_options *options)
3712 memcpy(options, &default_diff_options, sizeof(*options));
3714 options->file = stdout;
3716 options->abbrev = DEFAULT_ABBREV;
3717 options->line_termination = '\n';
3718 options->break_opt = -1;
3719 options->rename_limit = -1;
3720 options->dirstat_permille = diff_dirstat_permille_default;
3721 options->context = diff_context_default;
3722 options->interhunkcontext = diff_interhunk_context_default;
3723 options->ws_error_highlight = ws_error_highlight_default;
3724 DIFF_OPT_SET(options, RENAME_EMPTY);
3726 /* pathchange left =NULL by default */
3727 options->change = diff_change;
3728 options->add_remove = diff_addremove;
3729 options->use_color = diff_use_color_default;
3730 options->detect_rename = diff_detect_rename_default;
3731 options->xdl_opts |= diff_algorithm;
3732 if (diff_indent_heuristic)
3733 DIFF_XDL_SET(options, INDENT_HEURISTIC);
3735 options->orderfile = diff_order_file_cfg;
3737 if (diff_no_prefix) {
3738 options->a_prefix = options->b_prefix = "";
3739 } else if (!diff_mnemonic_prefix) {
3740 options->a_prefix = "a/";
3741 options->b_prefix = "b/";
3745 void diff_setup_done(struct diff_options *options)
3749 if (options->set_default)
3750 options->set_default(options);
3752 if (options->output_format & DIFF_FORMAT_NAME)
3754 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3756 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3758 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3761 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
3764 * Most of the time we can say "there are changes"
3765 * only by checking if there are changed paths, but
3766 * --ignore-whitespace* options force us to look
3770 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3771 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3772 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3773 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3775 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3777 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3778 options->detect_rename = DIFF_DETECT_COPY;
3780 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3781 options->prefix = NULL;
3782 if (options->prefix)
3783 options->prefix_length = strlen(options->prefix);
3785 options->prefix_length = 0;
3787 if (options->output_format & (DIFF_FORMAT_NAME |
3788 DIFF_FORMAT_NAME_STATUS |
3789 DIFF_FORMAT_CHECKDIFF |
3790 DIFF_FORMAT_NO_OUTPUT))
3791 options->output_format &= ~(DIFF_FORMAT_RAW |
3792 DIFF_FORMAT_NUMSTAT |
3793 DIFF_FORMAT_DIFFSTAT |
3794 DIFF_FORMAT_SHORTSTAT |
3795 DIFF_FORMAT_DIRSTAT |
3796 DIFF_FORMAT_SUMMARY |
3800 * These cases always need recursive; we do not drop caller-supplied
3801 * recursive bits for other formats here.
3803 if (options->output_format & (DIFF_FORMAT_PATCH |
3804 DIFF_FORMAT_NUMSTAT |
3805 DIFF_FORMAT_DIFFSTAT |
3806 DIFF_FORMAT_SHORTSTAT |
3807 DIFF_FORMAT_DIRSTAT |
3808 DIFF_FORMAT_SUMMARY |
3809 DIFF_FORMAT_CHECKDIFF))
3810 DIFF_OPT_SET(options, RECURSIVE);
3812 * Also pickaxe would not work very well if you do not say recursive
3814 if (options->pickaxe)
3815 DIFF_OPT_SET(options, RECURSIVE);
3817 * When patches are generated, submodules diffed against the work tree
3818 * must be checked for dirtiness too so it can be shown in the output
3820 if (options->output_format & DIFF_FORMAT_PATCH)
3821 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3823 if (options->detect_rename && options->rename_limit < 0)
3824 options->rename_limit = diff_rename_limit_default;
3825 if (options->setup & DIFF_SETUP_USE_CACHE) {
3827 /* read-cache does not die even when it fails
3828 * so it is safe for us to do this here. Also
3829 * it does not smudge active_cache or active_nr
3830 * when it fails, so we do not have to worry about
3831 * cleaning it up ourselves either.
3835 if (40 < options->abbrev)
3836 options->abbrev = 40; /* full */
3839 * It does not make sense to show the first hit we happened
3840 * to have found. It does not make sense not to return with
3841 * exit code in such a case either.
3843 if (DIFF_OPT_TST(options, QUICK)) {
3844 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3845 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3848 options->diff_path_counter = 0;
3850 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3851 die(_("--follow requires exactly one pathspec"));
3854 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3864 if (c == arg_short) {
3868 if (val && isdigit(c)) {
3870 int n = strtoul(arg, &end, 10);
3881 eq = strchrnul(arg, '=');
3883 if (!len || strncmp(arg, arg_long, len))
3888 if (!isdigit(*++eq))
3890 n = strtoul(eq, &end, 10);
3898 static int diff_scoreopt_parse(const char *opt);
3900 static inline int short_opt(char opt, const char **argv,
3901 const char **optarg)
3903 const char *arg = argv[0];
3904 if (arg[0] != '-' || arg[1] != opt)
3906 if (arg[2] != '\0') {
3911 die("Option '%c' requires a value", opt);
3916 int parse_long_opt(const char *opt, const char **argv,
3917 const char **optarg)
3919 const char *arg = argv[0];
3920 if (!skip_prefix(arg, "--", &arg))
3922 if (!skip_prefix(arg, opt, &arg))
3924 if (*arg == '=') { /* stuck form: --option=value */
3930 /* separate form: --option value */
3932 die("Option '--%s' requires a value", opt);
3937 static int stat_opt(struct diff_options *options, const char **av)
3939 const char *arg = av[0];
3941 int width = options->stat_width;
3942 int name_width = options->stat_name_width;
3943 int graph_width = options->stat_graph_width;
3944 int count = options->stat_count;
3947 if (!skip_prefix(arg, "--stat", &arg))
3948 die("BUG: stat option does not begin with --stat: %s", arg);
3953 if (skip_prefix(arg, "-width", &arg)) {
3955 width = strtoul(arg + 1, &end, 10);
3956 else if (!*arg && !av[1])
3957 die_want_option("--stat-width");
3959 width = strtoul(av[1], &end, 10);
3962 } else if (skip_prefix(arg, "-name-width", &arg)) {
3964 name_width = strtoul(arg + 1, &end, 10);
3965 else if (!*arg && !av[1])
3966 die_want_option("--stat-name-width");
3968 name_width = strtoul(av[1], &end, 10);
3971 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3973 graph_width = strtoul(arg + 1, &end, 10);
3974 else if (!*arg && !av[1])
3975 die_want_option("--stat-graph-width");
3977 graph_width = strtoul(av[1], &end, 10);
3980 } else if (skip_prefix(arg, "-count", &arg)) {
3982 count = strtoul(arg + 1, &end, 10);
3983 else if (!*arg && !av[1])
3984 die_want_option("--stat-count");
3986 count = strtoul(av[1], &end, 10);
3992 width = strtoul(arg+1, &end, 10);
3994 name_width = strtoul(end+1, &end, 10);
3996 count = strtoul(end+1, &end, 10);
3999 /* Important! This checks all the error cases! */
4002 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4003 options->stat_name_width = name_width;
4004 options->stat_graph_width = graph_width;
4005 options->stat_width = width;
4006 options->stat_count = count;
4010 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4012 struct strbuf errmsg = STRBUF_INIT;
4013 if (parse_dirstat_params(options, params, &errmsg))
4014 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4016 strbuf_release(&errmsg);
4018 * The caller knows a dirstat-related option is given from the command
4019 * line; allow it to say "return this_function();"
4021 options->output_format |= DIFF_FORMAT_DIRSTAT;
4025 static int parse_submodule_opt(struct diff_options *options, const char *value)
4027 if (parse_submodule_params(options, value))
4028 die(_("Failed to parse --submodule option parameter: '%s'"),
4033 static const char diff_status_letters[] = {
4036 DIFF_STATUS_DELETED,
4037 DIFF_STATUS_MODIFIED,
4038 DIFF_STATUS_RENAMED,
4039 DIFF_STATUS_TYPE_CHANGED,
4040 DIFF_STATUS_UNKNOWN,
4041 DIFF_STATUS_UNMERGED,
4042 DIFF_STATUS_FILTER_AON,
4043 DIFF_STATUS_FILTER_BROKEN,
4047 static unsigned int filter_bit['Z' + 1];
4049 static void prepare_filter_bits(void)
4053 if (!filter_bit[DIFF_STATUS_ADDED]) {
4054 for (i = 0; diff_status_letters[i]; i++)
4055 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4059 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4061 return opt->filter & filter_bit[(int) status];
4064 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4068 prepare_filter_bits();
4071 * If there is a negation e.g. 'd' in the input, and we haven't
4072 * initialized the filter field with another --diff-filter, start
4073 * from full set of bits, except for AON.
4076 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4077 if (optch < 'a' || 'z' < optch)
4079 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4080 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4085 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4089 if ('a' <= optch && optch <= 'z') {
4091 optch = toupper(optch);
4096 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4100 opt->filter &= ~bit;
4107 static void enable_patch_output(int *fmt) {
4108 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4109 *fmt |= DIFF_FORMAT_PATCH;
4112 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4114 int val = parse_ws_error_highlight(arg);
4117 error("unknown value after ws-error-highlight=%.*s",
4121 opt->ws_error_highlight = val;
4125 int diff_opt_parse(struct diff_options *options,
4126 const char **av, int ac, const char *prefix)
4128 const char *arg = av[0];
4135 /* Output format options */
4136 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
4137 || opt_arg(arg, 'U', "unified", &options->context))
4138 enable_patch_output(&options->output_format);
4139 else if (!strcmp(arg, "--raw"))
4140 options->output_format |= DIFF_FORMAT_RAW;
4141 else if (!strcmp(arg, "--patch-with-raw")) {
4142 enable_patch_output(&options->output_format);
4143 options->output_format |= DIFF_FORMAT_RAW;
4144 } else if (!strcmp(arg, "--numstat"))
4145 options->output_format |= DIFF_FORMAT_NUMSTAT;
4146 else if (!strcmp(arg, "--shortstat"))
4147 options->output_format |= DIFF_FORMAT_SHORTSTAT;
4148 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
4149 return parse_dirstat_opt(options, "");
4150 else if (skip_prefix(arg, "-X", &arg))
4151 return parse_dirstat_opt(options, arg);
4152 else if (skip_prefix(arg, "--dirstat=", &arg))
4153 return parse_dirstat_opt(options, arg);
4154 else if (!strcmp(arg, "--cumulative"))
4155 return parse_dirstat_opt(options, "cumulative");
4156 else if (!strcmp(arg, "--dirstat-by-file"))
4157 return parse_dirstat_opt(options, "files");
4158 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
4159 parse_dirstat_opt(options, "files");
4160 return parse_dirstat_opt(options, arg);
4162 else if (!strcmp(arg, "--check"))
4163 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4164 else if (!strcmp(arg, "--summary"))
4165 options->output_format |= DIFF_FORMAT_SUMMARY;
4166 else if (!strcmp(arg, "--patch-with-stat")) {
4167 enable_patch_output(&options->output_format);
4168 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4169 } else if (!strcmp(arg, "--name-only"))
4170 options->output_format |= DIFF_FORMAT_NAME;
4171 else if (!strcmp(arg, "--name-status"))
4172 options->output_format |= DIFF_FORMAT_NAME_STATUS;
4173 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
4174 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4175 else if (starts_with(arg, "--stat"))
4176 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4177 return stat_opt(options, av);
4179 /* renames options */
4180 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
4181 !strcmp(arg, "--break-rewrites")) {
4182 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
4183 return error("invalid argument to -B: %s", arg+2);
4185 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
4186 !strcmp(arg, "--find-renames")) {
4187 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4188 return error("invalid argument to -M: %s", arg+2);
4189 options->detect_rename = DIFF_DETECT_RENAME;
4191 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
4192 options->irreversible_delete = 1;
4194 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
4195 !strcmp(arg, "--find-copies")) {
4196 if (options->detect_rename == DIFF_DETECT_COPY)
4197 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4198 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
4199 return error("invalid argument to -C: %s", arg+2);
4200 options->detect_rename = DIFF_DETECT_COPY;
4202 else if (!strcmp(arg, "--no-renames"))
4203 options->detect_rename = 0;
4204 else if (!strcmp(arg, "--rename-empty"))
4205 DIFF_OPT_SET(options, RENAME_EMPTY);
4206 else if (!strcmp(arg, "--no-rename-empty"))
4207 DIFF_OPT_CLR(options, RENAME_EMPTY);
4208 else if (!strcmp(arg, "--relative"))
4209 DIFF_OPT_SET(options, RELATIVE_NAME);
4210 else if (skip_prefix(arg, "--relative=", &arg)) {
4211 DIFF_OPT_SET(options, RELATIVE_NAME);
4212 options->prefix = arg;
4216 else if (!strcmp(arg, "--minimal"))
4217 DIFF_XDL_SET(options, NEED_MINIMAL);
4218 else if (!strcmp(arg, "--no-minimal"))
4219 DIFF_XDL_CLR(options, NEED_MINIMAL);
4220 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
4221 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
4222 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
4223 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
4224 else if (!strcmp(arg, "--ignore-space-at-eol"))
4225 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
4226 else if (!strcmp(arg, "--ignore-blank-lines"))
4227 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
4228 else if (!strcmp(arg, "--indent-heuristic"))
4229 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4230 else if (!strcmp(arg, "--no-indent-heuristic"))
4231 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
4232 else if (!strcmp(arg, "--patience"))
4233 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4234 else if (!strcmp(arg, "--histogram"))
4235 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
4236 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
4237 long value = parse_algorithm_value(optarg);
4239 return error("option diff-algorithm accepts \"myers\", "
4240 "\"minimal\", \"patience\" and \"histogram\"");
4241 /* clear out previous settings */
4242 DIFF_XDL_CLR(options, NEED_MINIMAL);
4243 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
4244 options->xdl_opts |= value;
4249 else if (!strcmp(arg, "--binary")) {
4250 enable_patch_output(&options->output_format);
4251 DIFF_OPT_SET(options, BINARY);
4253 else if (!strcmp(arg, "--full-index"))
4254 DIFF_OPT_SET(options, FULL_INDEX);
4255 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
4256 DIFF_OPT_SET(options, TEXT);
4257 else if (!strcmp(arg, "-R"))
4258 DIFF_OPT_SET(options, REVERSE_DIFF);
4259 else if (!strcmp(arg, "--find-copies-harder"))
4260 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
4261 else if (!strcmp(arg, "--follow"))
4262 DIFF_OPT_SET(options, FOLLOW_RENAMES);
4263 else if (!strcmp(arg, "--no-follow")) {
4264 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
4265 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
4266 } else if (!strcmp(arg, "--color"))
4267 options->use_color = 1;
4268 else if (skip_prefix(arg, "--color=", &arg)) {
4269 int value = git_config_colorbool(NULL, arg);
4271 return error("option `color' expects \"always\", \"auto\", or \"never\"");
4272 options->use_color = value;
4274 else if (!strcmp(arg, "--no-color"))
4275 options->use_color = 0;
4276 else if (!strcmp(arg, "--color-words")) {
4277 options->use_color = 1;
4278 options->word_diff = DIFF_WORDS_COLOR;
4280 else if (skip_prefix(arg, "--color-words=", &arg)) {
4281 options->use_color = 1;
4282 options->word_diff = DIFF_WORDS_COLOR;
4283 options->word_regex = arg;
4285 else if (!strcmp(arg, "--word-diff")) {
4286 if (options->word_diff == DIFF_WORDS_NONE)
4287 options->word_diff = DIFF_WORDS_PLAIN;
4289 else if (skip_prefix(arg, "--word-diff=", &arg)) {
4290 if (!strcmp(arg, "plain"))
4291 options->word_diff = DIFF_WORDS_PLAIN;
4292 else if (!strcmp(arg, "color")) {
4293 options->use_color = 1;
4294 options->word_diff = DIFF_WORDS_COLOR;
4296 else if (!strcmp(arg, "porcelain"))
4297 options->word_diff = DIFF_WORDS_PORCELAIN;
4298 else if (!strcmp(arg, "none"))
4299 options->word_diff = DIFF_WORDS_NONE;
4301 die("bad --word-diff argument: %s", arg);
4303 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
4304 if (options->word_diff == DIFF_WORDS_NONE)
4305 options->word_diff = DIFF_WORDS_PLAIN;
4306 options->word_regex = optarg;
4309 else if (!strcmp(arg, "--exit-code"))
4310 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
4311 else if (!strcmp(arg, "--quiet"))
4312 DIFF_OPT_SET(options, QUICK);
4313 else if (!strcmp(arg, "--ext-diff"))
4314 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
4315 else if (!strcmp(arg, "--no-ext-diff"))
4316 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
4317 else if (!strcmp(arg, "--textconv"))
4318 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
4319 else if (!strcmp(arg, "--no-textconv"))
4320 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
4321 else if (!strcmp(arg, "--ignore-submodules")) {
4322 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4323 handle_ignore_submodules_arg(options, "all");
4324 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
4325 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
4326 handle_ignore_submodules_arg(options, arg);
4327 } else if (!strcmp(arg, "--submodule"))
4328 options->submodule_format = DIFF_SUBMODULE_LOG;
4329 else if (skip_prefix(arg, "--submodule=", &arg))
4330 return parse_submodule_opt(options, arg);
4331 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
4332 return parse_ws_error_highlight_opt(options, arg);
4333 else if (!strcmp(arg, "--ita-invisible-in-index"))
4334 options->ita_invisible_in_index = 1;
4335 else if (!strcmp(arg, "--ita-visible-in-index"))
4336 options->ita_invisible_in_index = 0;
4339 else if (!strcmp(arg, "-z"))
4340 options->line_termination = 0;
4341 else if ((argcount = short_opt('l', av, &optarg))) {
4342 options->rename_limit = strtoul(optarg, NULL, 10);
4345 else if ((argcount = short_opt('S', av, &optarg))) {
4346 options->pickaxe = optarg;
4347 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4349 } else if ((argcount = short_opt('G', av, &optarg))) {
4350 options->pickaxe = optarg;
4351 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4354 else if (!strcmp(arg, "--pickaxe-all"))
4355 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4356 else if (!strcmp(arg, "--pickaxe-regex"))
4357 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4358 else if ((argcount = short_opt('O', av, &optarg))) {
4359 options->orderfile = prefix_filename(prefix, optarg);
4362 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4363 int offending = parse_diff_filter_opt(optarg, options);
4365 die("unknown change class '%c' in --diff-filter=%s",
4369 else if (!strcmp(arg, "--no-abbrev"))
4370 options->abbrev = 0;
4371 else if (!strcmp(arg, "--abbrev"))
4372 options->abbrev = DEFAULT_ABBREV;
4373 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4374 options->abbrev = strtoul(arg, NULL, 10);
4375 if (options->abbrev < MINIMUM_ABBREV)
4376 options->abbrev = MINIMUM_ABBREV;
4377 else if (40 < options->abbrev)
4378 options->abbrev = 40;
4380 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4381 options->a_prefix = optarg;
4384 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4385 options->line_prefix = optarg;
4386 options->line_prefix_length = strlen(options->line_prefix);
4387 graph_setup_line_prefix(options);
4390 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4391 options->b_prefix = optarg;
4394 else if (!strcmp(arg, "--no-prefix"))
4395 options->a_prefix = options->b_prefix = "";
4396 else if (opt_arg(arg, '\0', "inter-hunk-context",
4397 &options->interhunkcontext))
4399 else if (!strcmp(arg, "-W"))
4400 DIFF_OPT_SET(options, FUNCCONTEXT);
4401 else if (!strcmp(arg, "--function-context"))
4402 DIFF_OPT_SET(options, FUNCCONTEXT);
4403 else if (!strcmp(arg, "--no-function-context"))
4404 DIFF_OPT_CLR(options, FUNCCONTEXT);
4405 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4406 char *path = prefix_filename(prefix, optarg);
4407 options->file = xfopen(path, "w");
4408 options->close_file = 1;
4409 if (options->use_color != GIT_COLOR_ALWAYS)
4410 options->use_color = GIT_COLOR_NEVER;
4418 int parse_rename_score(const char **cp_p)
4420 unsigned long num, scale;
4422 const char *cp = *cp_p;
4429 if ( !dot && ch == '.' ) {
4432 } else if ( ch == '%' ) {
4433 scale = dot ? scale*100 : 100;
4434 cp++; /* % is always at the end */
4436 } else if ( ch >= '0' && ch <= '9' ) {
4437 if ( scale < 100000 ) {
4439 num = (num*10) + (ch-'0');
4448 /* user says num divided by scale and we say internally that
4449 * is MAX_SCORE * num / scale.
4451 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4454 static int diff_scoreopt_parse(const char *opt)
4456 int opt1, opt2, cmd;
4462 /* convert the long-form arguments into short-form versions */
4463 if (skip_prefix(opt, "break-rewrites", &opt)) {
4464 if (*opt == 0 || *opt++ == '=')
4466 } else if (skip_prefix(opt, "find-copies", &opt)) {
4467 if (*opt == 0 || *opt++ == '=')
4469 } else if (skip_prefix(opt, "find-renames", &opt)) {
4470 if (*opt == 0 || *opt++ == '=')
4474 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4475 return -1; /* that is not a -M, -C, or -B option */
4477 opt1 = parse_rename_score(&opt);
4483 else if (*opt != '/')
4484 return -1; /* we expect -B80/99 or -B80 */
4487 opt2 = parse_rename_score(&opt);
4492 return opt1 | (opt2 << 16);
4495 struct diff_queue_struct diff_queued_diff;
4497 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4499 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4500 queue->queue[queue->nr++] = dp;
4503 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4504 struct diff_filespec *one,
4505 struct diff_filespec *two)
4507 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4515 void diff_free_filepair(struct diff_filepair *p)
4517 free_filespec(p->one);
4518 free_filespec(p->two);
4522 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4527 if (len == GIT_SHA1_HEXSZ)
4528 return oid_to_hex(oid);
4530 abbrev = diff_abbrev_oid(oid, len);
4531 abblen = strlen(abbrev);
4534 * In well-behaved cases, where the abbbreviated result is the
4535 * same as the requested length, append three dots after the
4536 * abbreviation (hence the whole logic is limited to the case
4537 * where abblen < 37); when the actual abbreviated result is a
4538 * bit longer than the requested length, we reduce the number
4539 * of dots so that they match the well-behaved ones. However,
4540 * if the actual abbreviation is longer than the requested
4541 * length by more than three, we give up on aligning, and add
4542 * three dots anyway, to indicate that the output is not the
4543 * full object name. Yes, this may be suboptimal, but this
4544 * appears only in "diff --raw --abbrev" output and it is not
4545 * worth the effort to change it now. Note that this would
4546 * likely to work fine when the automatic sizing of default
4547 * abbreviation length is used--we would be fed -1 in "len" in
4548 * that case, and will end up always appending three-dots, but
4549 * the automatic sizing is supposed to give abblen that ensures
4550 * uniqueness across all objects (statistically speaking).
4552 if (abblen < GIT_SHA1_HEXSZ - 3) {
4553 static char hex[GIT_MAX_HEXSZ + 1];
4554 if (len < abblen && abblen <= len + 2)
4555 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4557 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4561 return oid_to_hex(oid);
4564 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4566 int line_termination = opt->line_termination;
4567 int inter_name_termination = line_termination ? '\t' : '\0';
4569 fprintf(opt->file, "%s", diff_line_prefix(opt));
4570 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4571 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4572 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4573 fprintf(opt->file, "%s ",
4574 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4577 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4578 inter_name_termination);
4580 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4583 if (p->status == DIFF_STATUS_COPIED ||
4584 p->status == DIFF_STATUS_RENAMED) {
4585 const char *name_a, *name_b;
4586 name_a = p->one->path;
4587 name_b = p->two->path;
4588 strip_prefix(opt->prefix_length, &name_a, &name_b);
4589 write_name_quoted(name_a, opt->file, inter_name_termination);
4590 write_name_quoted(name_b, opt->file, line_termination);
4592 const char *name_a, *name_b;
4593 name_a = p->one->mode ? p->one->path : p->two->path;
4595 strip_prefix(opt->prefix_length, &name_a, &name_b);
4596 write_name_quoted(name_a, opt->file, line_termination);
4600 int diff_unmodified_pair(struct diff_filepair *p)
4602 /* This function is written stricter than necessary to support
4603 * the currently implemented transformers, but the idea is to
4604 * let transformers to produce diff_filepairs any way they want,
4605 * and filter and clean them up here before producing the output.
4607 struct diff_filespec *one = p->one, *two = p->two;
4609 if (DIFF_PAIR_UNMERGED(p))
4610 return 0; /* unmerged is interesting */
4612 /* deletion, addition, mode or type change
4613 * and rename are all interesting.
4615 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4616 DIFF_PAIR_MODE_CHANGED(p) ||
4617 strcmp(one->path, two->path))
4620 /* both are valid and point at the same path. that is, we are
4621 * dealing with a change.
4623 if (one->oid_valid && two->oid_valid &&
4624 !oidcmp(&one->oid, &two->oid) &&
4625 !one->dirty_submodule && !two->dirty_submodule)
4626 return 1; /* no change */
4627 if (!one->oid_valid && !two->oid_valid)
4628 return 1; /* both look at the same file on the filesystem. */
4632 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4634 if (diff_unmodified_pair(p))
4637 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4638 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4639 return; /* no tree diffs in patch format */
4644 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4645 struct diffstat_t *diffstat)
4647 if (diff_unmodified_pair(p))
4650 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4651 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4652 return; /* no useful stat for tree diffs */
4654 run_diffstat(p, o, diffstat);
4657 static void diff_flush_checkdiff(struct diff_filepair *p,
4658 struct diff_options *o)
4660 if (diff_unmodified_pair(p))
4663 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4664 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4665 return; /* nothing to check in tree diffs */
4667 run_checkdiff(p, o);
4670 int diff_queue_is_empty(void)
4672 struct diff_queue_struct *q = &diff_queued_diff;
4674 for (i = 0; i < q->nr; i++)
4675 if (!diff_unmodified_pair(q->queue[i]))
4681 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4683 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4686 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4688 s->oid_valid ? oid_to_hex(&s->oid) : "");
4689 fprintf(stderr, "queue[%d] %s size %lu\n",
4694 void diff_debug_filepair(const struct diff_filepair *p, int i)
4696 diff_debug_filespec(p->one, i, "one");
4697 diff_debug_filespec(p->two, i, "two");
4698 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4699 p->score, p->status ? p->status : '?',
4700 p->one->rename_used, p->broken_pair);
4703 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4707 fprintf(stderr, "%s\n", msg);
4708 fprintf(stderr, "q->nr = %d\n", q->nr);
4709 for (i = 0; i < q->nr; i++) {
4710 struct diff_filepair *p = q->queue[i];
4711 diff_debug_filepair(p, i);
4716 static void diff_resolve_rename_copy(void)
4719 struct diff_filepair *p;
4720 struct diff_queue_struct *q = &diff_queued_diff;
4722 diff_debug_queue("resolve-rename-copy", q);
4724 for (i = 0; i < q->nr; i++) {
4726 p->status = 0; /* undecided */
4727 if (DIFF_PAIR_UNMERGED(p))
4728 p->status = DIFF_STATUS_UNMERGED;
4729 else if (!DIFF_FILE_VALID(p->one))
4730 p->status = DIFF_STATUS_ADDED;
4731 else if (!DIFF_FILE_VALID(p->two))
4732 p->status = DIFF_STATUS_DELETED;
4733 else if (DIFF_PAIR_TYPE_CHANGED(p))
4734 p->status = DIFF_STATUS_TYPE_CHANGED;
4736 /* from this point on, we are dealing with a pair
4737 * whose both sides are valid and of the same type, i.e.
4738 * either in-place edit or rename/copy edit.
4740 else if (DIFF_PAIR_RENAME(p)) {
4742 * A rename might have re-connected a broken
4743 * pair up, causing the pathnames to be the
4744 * same again. If so, that's not a rename at
4745 * all, just a modification..
4747 * Otherwise, see if this source was used for
4748 * multiple renames, in which case we decrement
4749 * the count, and call it a copy.
4751 if (!strcmp(p->one->path, p->two->path))
4752 p->status = DIFF_STATUS_MODIFIED;
4753 else if (--p->one->rename_used > 0)
4754 p->status = DIFF_STATUS_COPIED;
4756 p->status = DIFF_STATUS_RENAMED;
4758 else if (oidcmp(&p->one->oid, &p->two->oid) ||
4759 p->one->mode != p->two->mode ||
4760 p->one->dirty_submodule ||
4761 p->two->dirty_submodule ||
4762 is_null_oid(&p->one->oid))
4763 p->status = DIFF_STATUS_MODIFIED;
4765 /* This is a "no-change" entry and should not
4766 * happen anymore, but prepare for broken callers.
4768 error("feeding unmodified %s to diffcore",
4770 p->status = DIFF_STATUS_UNKNOWN;
4773 diff_debug_queue("resolve-rename-copy done", q);
4776 static int check_pair_status(struct diff_filepair *p)
4778 switch (p->status) {
4779 case DIFF_STATUS_UNKNOWN:
4782 die("internal error in diff-resolve-rename-copy");
4788 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4790 int fmt = opt->output_format;
4792 if (fmt & DIFF_FORMAT_CHECKDIFF)
4793 diff_flush_checkdiff(p, opt);
4794 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4795 diff_flush_raw(p, opt);
4796 else if (fmt & DIFF_FORMAT_NAME) {
4797 const char *name_a, *name_b;
4798 name_a = p->two->path;
4800 strip_prefix(opt->prefix_length, &name_a, &name_b);
4801 fprintf(opt->file, "%s", diff_line_prefix(opt));
4802 write_name_quoted(name_a, opt->file, opt->line_termination);
4806 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
4808 struct strbuf sb = STRBUF_INIT;
4810 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
4812 strbuf_addf(&sb, " %s ", newdelete);
4814 quote_c_style(fs->path, &sb, NULL, 0);
4815 strbuf_addch(&sb, '\n');
4816 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4818 strbuf_release(&sb);
4821 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
4824 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4825 struct strbuf sb = STRBUF_INIT;
4826 strbuf_addf(&sb, " mode change %06o => %06o",
4827 p->one->mode, p->two->mode);
4829 strbuf_addch(&sb, ' ');
4830 quote_c_style(p->two->path, &sb, NULL, 0);
4832 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4834 strbuf_release(&sb);
4838 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
4839 struct diff_filepair *p)
4841 struct strbuf sb = STRBUF_INIT;
4842 char *names = pprint_rename(p->one->path, p->two->path);
4843 strbuf_addf(&sb, " %s %s (%d%%)\n",
4844 renamecopy, names, similarity_index(p));
4846 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4848 show_mode_change(opt, p, 0);
4851 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4854 case DIFF_STATUS_DELETED:
4855 show_file_mode_name(opt, "delete", p->one);
4857 case DIFF_STATUS_ADDED:
4858 show_file_mode_name(opt, "create", p->two);
4860 case DIFF_STATUS_COPIED:
4861 show_rename_copy(opt, "copy", p);
4863 case DIFF_STATUS_RENAMED:
4864 show_rename_copy(opt, "rename", p);
4868 struct strbuf sb = STRBUF_INIT;
4869 strbuf_addstr(&sb, " rewrite ");
4870 quote_c_style(p->two->path, &sb, NULL, 0);
4871 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
4872 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
4875 show_mode_change(opt, p, !p->score);
4885 static int remove_space(char *line, int len)
4891 for (i = 0; i < len; i++)
4892 if (!isspace((c = line[i])))
4898 static void patch_id_consume(void *priv, char *line, unsigned long len)
4900 struct patch_id_t *data = priv;
4903 /* Ignore line numbers when computing the SHA1 of the patch */
4904 if (starts_with(line, "@@ -"))
4907 new_len = remove_space(line, len);
4909 git_SHA1_Update(data->ctx, line, new_len);
4910 data->patchlen += new_len;
4913 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
4915 git_SHA1_Update(ctx, str, strlen(str));
4918 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
4920 /* large enough for 2^32 in octal */
4922 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
4923 git_SHA1_Update(ctx, buf, len);
4926 /* returns 0 upon success, and writes result into sha1 */
4927 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
4929 struct diff_queue_struct *q = &diff_queued_diff;
4932 struct patch_id_t data;
4934 git_SHA1_Init(&ctx);
4935 memset(&data, 0, sizeof(struct patch_id_t));
4938 for (i = 0; i < q->nr; i++) {
4942 struct diff_filepair *p = q->queue[i];
4945 memset(&xpp, 0, sizeof(xpp));
4946 memset(&xecfg, 0, sizeof(xecfg));
4948 return error("internal diff status error");
4949 if (p->status == DIFF_STATUS_UNKNOWN)
4951 if (diff_unmodified_pair(p))
4953 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4954 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4956 if (DIFF_PAIR_UNMERGED(p))
4959 diff_fill_oid_info(p->one);
4960 diff_fill_oid_info(p->two);
4962 len1 = remove_space(p->one->path, strlen(p->one->path));
4963 len2 = remove_space(p->two->path, strlen(p->two->path));
4964 patch_id_add_string(&ctx, "diff--git");
4965 patch_id_add_string(&ctx, "a/");
4966 git_SHA1_Update(&ctx, p->one->path, len1);
4967 patch_id_add_string(&ctx, "b/");
4968 git_SHA1_Update(&ctx, p->two->path, len2);
4970 if (p->one->mode == 0) {
4971 patch_id_add_string(&ctx, "newfilemode");
4972 patch_id_add_mode(&ctx, p->two->mode);
4973 patch_id_add_string(&ctx, "---/dev/null");
4974 patch_id_add_string(&ctx, "+++b/");
4975 git_SHA1_Update(&ctx, p->two->path, len2);
4976 } else if (p->two->mode == 0) {
4977 patch_id_add_string(&ctx, "deletedfilemode");
4978 patch_id_add_mode(&ctx, p->one->mode);
4979 patch_id_add_string(&ctx, "---a/");
4980 git_SHA1_Update(&ctx, p->one->path, len1);
4981 patch_id_add_string(&ctx, "+++/dev/null");
4983 patch_id_add_string(&ctx, "---a/");
4984 git_SHA1_Update(&ctx, p->one->path, len1);
4985 patch_id_add_string(&ctx, "+++b/");
4986 git_SHA1_Update(&ctx, p->two->path, len2);
4989 if (diff_header_only)
4992 if (fill_mmfile(&mf1, p->one) < 0 ||
4993 fill_mmfile(&mf2, p->two) < 0)
4994 return error("unable to read files to diff");
4996 if (diff_filespec_is_binary(p->one) ||
4997 diff_filespec_is_binary(p->two)) {
4998 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
5000 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
5008 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
5010 return error("unable to generate patch-id diff for %s",
5014 git_SHA1_Final(oid->hash, &ctx);
5018 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
5020 struct diff_queue_struct *q = &diff_queued_diff;
5022 int result = diff_get_patch_id(options, oid, diff_header_only);
5024 for (i = 0; i < q->nr; i++)
5025 diff_free_filepair(q->queue[i]);
5028 DIFF_QUEUE_CLEAR(q);
5033 static int is_summary_empty(const struct diff_queue_struct *q)
5037 for (i = 0; i < q->nr; i++) {
5038 const struct diff_filepair *p = q->queue[i];
5040 switch (p->status) {
5041 case DIFF_STATUS_DELETED:
5042 case DIFF_STATUS_ADDED:
5043 case DIFF_STATUS_COPIED:
5044 case DIFF_STATUS_RENAMED:
5049 if (p->one->mode && p->two->mode &&
5050 p->one->mode != p->two->mode)
5058 static const char rename_limit_warning[] =
5059 N_("inexact rename detection was skipped due to too many files.");
5061 static const char degrade_cc_to_c_warning[] =
5062 N_("only found copies from modified paths due to too many files.");
5064 static const char rename_limit_advice[] =
5065 N_("you may want to set your %s variable to at least "
5066 "%d and retry the command.");
5068 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
5071 warning(_(degrade_cc_to_c_warning));
5073 warning(_(rename_limit_warning));
5076 if (0 < needed && needed < 32767)
5077 warning(_(rename_limit_advice), varname, needed);
5080 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
5083 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
5084 struct diff_queue_struct *q = &diff_queued_diff;
5086 if (WSEH_NEW & WS_RULE_MASK)
5087 die("BUG: WS rules bit mask overlaps with diff symbol flags");
5090 * For testing purposes we want to make sure the diff machinery
5091 * works completely with the buffer. If there is anything emitted
5092 * outside the emit_string, then the order is screwed
5093 * up and the tests will fail.
5095 * TODO (later in this series):
5096 * We'll unset this pointer in a later patch.
5098 o->emitted_symbols = &esm;
5100 for (i = 0; i < q->nr; i++) {
5101 struct diff_filepair *p = q->queue[i];
5102 if (check_pair_status(p))
5103 diff_flush_patch(p, o);
5106 if (o->emitted_symbols) {
5107 for (i = 0; i < esm.nr; i++)
5108 emit_diff_symbol_from_struct(o, &esm.buf[i]);
5110 for (i = 0; i < esm.nr; i++)
5111 free((void *)esm.buf[i].line);
5116 void diff_flush(struct diff_options *options)
5118 struct diff_queue_struct *q = &diff_queued_diff;
5119 int i, output_format = options->output_format;
5121 int dirstat_by_line = 0;
5124 * Order: raw, stat, summary, patch
5125 * or: name/name-status/checkdiff (other bits clear)
5130 if (output_format & (DIFF_FORMAT_RAW |
5132 DIFF_FORMAT_NAME_STATUS |
5133 DIFF_FORMAT_CHECKDIFF)) {
5134 for (i = 0; i < q->nr; i++) {
5135 struct diff_filepair *p = q->queue[i];
5136 if (check_pair_status(p))
5137 flush_one_pair(p, options);
5142 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
5143 dirstat_by_line = 1;
5145 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
5147 struct diffstat_t diffstat;
5149 memset(&diffstat, 0, sizeof(struct diffstat_t));
5150 for (i = 0; i < q->nr; i++) {
5151 struct diff_filepair *p = q->queue[i];
5152 if (check_pair_status(p))
5153 diff_flush_stat(p, options, &diffstat);
5155 if (output_format & DIFF_FORMAT_NUMSTAT)
5156 show_numstat(&diffstat, options);
5157 if (output_format & DIFF_FORMAT_DIFFSTAT)
5158 show_stats(&diffstat, options);
5159 if (output_format & DIFF_FORMAT_SHORTSTAT)
5160 show_shortstats(&diffstat, options);
5161 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
5162 show_dirstat_by_line(&diffstat, options);
5163 free_diffstat_info(&diffstat);
5166 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
5167 show_dirstat(options);
5169 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
5170 for (i = 0; i < q->nr; i++) {
5171 diff_summary(options, q->queue[i]);
5176 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
5177 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
5178 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5180 * run diff_flush_patch for the exit status. setting
5181 * options->file to /dev/null should be safe, because we
5182 * aren't supposed to produce any output anyway.
5184 if (options->close_file)
5185 fclose(options->file);
5186 options->file = xfopen("/dev/null", "w");
5187 options->close_file = 1;
5188 for (i = 0; i < q->nr; i++) {
5189 struct diff_filepair *p = q->queue[i];
5190 if (check_pair_status(p))
5191 diff_flush_patch(p, options);
5192 if (options->found_changes)
5197 if (output_format & DIFF_FORMAT_PATCH) {
5199 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
5200 if (options->stat_sep)
5201 /* attach patch instead of inline */
5202 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
5206 diff_flush_patch_all_file_pairs(options);
5209 if (output_format & DIFF_FORMAT_CALLBACK)
5210 options->format_callback(q, options, options->format_callback_data);
5212 for (i = 0; i < q->nr; i++)
5213 diff_free_filepair(q->queue[i]);
5216 DIFF_QUEUE_CLEAR(q);
5217 if (options->close_file)
5218 fclose(options->file);
5221 * Report the content-level differences with HAS_CHANGES;
5222 * diff_addremove/diff_change does not set the bit when
5223 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
5225 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
5226 if (options->found_changes)
5227 DIFF_OPT_SET(options, HAS_CHANGES);
5229 DIFF_OPT_CLR(options, HAS_CHANGES);
5233 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
5235 return (((p->status == DIFF_STATUS_MODIFIED) &&
5237 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
5239 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
5240 ((p->status != DIFF_STATUS_MODIFIED) &&
5241 filter_bit_tst(p->status, options)));
5244 static void diffcore_apply_filter(struct diff_options *options)
5247 struct diff_queue_struct *q = &diff_queued_diff;
5248 struct diff_queue_struct outq;
5250 DIFF_QUEUE_CLEAR(&outq);
5252 if (!options->filter)
5255 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
5257 for (i = found = 0; !found && i < q->nr; i++) {
5258 if (match_filter(options, q->queue[i]))
5264 /* otherwise we will clear the whole queue
5265 * by copying the empty outq at the end of this
5266 * function, but first clear the current entries
5269 for (i = 0; i < q->nr; i++)
5270 diff_free_filepair(q->queue[i]);
5273 /* Only the matching ones */
5274 for (i = 0; i < q->nr; i++) {
5275 struct diff_filepair *p = q->queue[i];
5276 if (match_filter(options, p))
5279 diff_free_filepair(p);
5286 /* Check whether two filespecs with the same mode and size are identical */
5287 static int diff_filespec_is_identical(struct diff_filespec *one,
5288 struct diff_filespec *two)
5290 if (S_ISGITLINK(one->mode))
5292 if (diff_populate_filespec(one, 0))
5294 if (diff_populate_filespec(two, 0))
5296 return !memcmp(one->data, two->data, one->size);
5299 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
5301 if (p->done_skip_stat_unmatch)
5302 return p->skip_stat_unmatch_result;
5304 p->done_skip_stat_unmatch = 1;
5305 p->skip_stat_unmatch_result = 0;
5307 * 1. Entries that come from stat info dirtiness
5308 * always have both sides (iow, not create/delete),
5309 * one side of the object name is unknown, with
5310 * the same mode and size. Keep the ones that
5311 * do not match these criteria. They have real
5314 * 2. At this point, the file is known to be modified,
5315 * with the same mode and size, and the object
5316 * name of one side is unknown. Need to inspect
5317 * the identical contents.
5319 if (!DIFF_FILE_VALID(p->one) || /* (1) */
5320 !DIFF_FILE_VALID(p->two) ||
5321 (p->one->oid_valid && p->two->oid_valid) ||
5322 (p->one->mode != p->two->mode) ||
5323 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
5324 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
5325 (p->one->size != p->two->size) ||
5326 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
5327 p->skip_stat_unmatch_result = 1;
5328 return p->skip_stat_unmatch_result;
5331 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
5334 struct diff_queue_struct *q = &diff_queued_diff;
5335 struct diff_queue_struct outq;
5336 DIFF_QUEUE_CLEAR(&outq);
5338 for (i = 0; i < q->nr; i++) {
5339 struct diff_filepair *p = q->queue[i];
5341 if (diff_filespec_check_stat_unmatch(p))
5345 * The caller can subtract 1 from skip_stat_unmatch
5346 * to determine how many paths were dirty only
5347 * due to stat info mismatch.
5349 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
5350 diffopt->skip_stat_unmatch++;
5351 diff_free_filepair(p);
5358 static int diffnamecmp(const void *a_, const void *b_)
5360 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
5361 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
5362 const char *name_a, *name_b;
5364 name_a = a->one ? a->one->path : a->two->path;
5365 name_b = b->one ? b->one->path : b->two->path;
5366 return strcmp(name_a, name_b);
5369 void diffcore_fix_diff_index(struct diff_options *options)
5371 struct diff_queue_struct *q = &diff_queued_diff;
5372 QSORT(q->queue, q->nr, diffnamecmp);
5375 void diffcore_std(struct diff_options *options)
5377 /* NOTE please keep the following in sync with diff_tree_combined() */
5378 if (options->skip_stat_unmatch)
5379 diffcore_skip_stat_unmatch(options);
5380 if (!options->found_follow) {
5381 /* See try_to_follow_renames() in tree-diff.c */
5382 if (options->break_opt != -1)
5383 diffcore_break(options->break_opt);
5384 if (options->detect_rename)
5385 diffcore_rename(options);
5386 if (options->break_opt != -1)
5387 diffcore_merge_broken();
5389 if (options->pickaxe)
5390 diffcore_pickaxe(options);
5391 if (options->orderfile)
5392 diffcore_order(options->orderfile);
5393 if (!options->found_follow)
5394 /* See try_to_follow_renames() in tree-diff.c */
5395 diff_resolve_rename_copy();
5396 diffcore_apply_filter(options);
5398 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5399 DIFF_OPT_SET(options, HAS_CHANGES);
5401 DIFF_OPT_CLR(options, HAS_CHANGES);
5403 options->found_follow = 0;
5406 int diff_result_code(struct diff_options *opt, int status)
5410 diff_warn_rename_limit("diff.renameLimit",
5411 opt->needed_rename_limit,
5412 opt->degraded_cc_to_c);
5413 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5414 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5416 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5417 DIFF_OPT_TST(opt, HAS_CHANGES))
5419 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5420 DIFF_OPT_TST(opt, CHECK_FAILED))
5425 int diff_can_quit_early(struct diff_options *opt)
5427 return (DIFF_OPT_TST(opt, QUICK) &&
5429 DIFF_OPT_TST(opt, HAS_CHANGES));
5433 * Shall changes to this submodule be ignored?
5435 * Submodule changes can be configured to be ignored separately for each path,
5436 * but that configuration can be overridden from the command line.
5438 static int is_submodule_ignored(const char *path, struct diff_options *options)
5441 unsigned orig_flags = options->flags;
5442 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
5443 set_diffopt_flags_from_submodule_config(options, path);
5444 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
5446 options->flags = orig_flags;
5450 void diff_addremove(struct diff_options *options,
5451 int addremove, unsigned mode,
5452 const struct object_id *oid,
5454 const char *concatpath, unsigned dirty_submodule)
5456 struct diff_filespec *one, *two;
5458 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5461 /* This may look odd, but it is a preparation for
5462 * feeding "there are unchanged files which should
5463 * not produce diffs, but when you are doing copy
5464 * detection you would need them, so here they are"
5465 * entries to the diff-core. They will be prefixed
5466 * with something like '=' or '*' (I haven't decided
5467 * which but should not make any difference).
5468 * Feeding the same new and old to diff_change()
5469 * also has the same effect.
5470 * Before the final output happens, they are pruned after
5471 * merged into rename/copy pairs as appropriate.
5473 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5474 addremove = (addremove == '+' ? '-' :
5475 addremove == '-' ? '+' : addremove);
5477 if (options->prefix &&
5478 strncmp(concatpath, options->prefix, options->prefix_length))
5481 one = alloc_filespec(concatpath);
5482 two = alloc_filespec(concatpath);
5484 if (addremove != '+')
5485 fill_filespec(one, oid, oid_valid, mode);
5486 if (addremove != '-') {
5487 fill_filespec(two, oid, oid_valid, mode);
5488 two->dirty_submodule = dirty_submodule;
5491 diff_queue(&diff_queued_diff, one, two);
5492 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5493 DIFF_OPT_SET(options, HAS_CHANGES);
5496 void diff_change(struct diff_options *options,
5497 unsigned old_mode, unsigned new_mode,
5498 const struct object_id *old_oid,
5499 const struct object_id *new_oid,
5500 int old_oid_valid, int new_oid_valid,
5501 const char *concatpath,
5502 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5504 struct diff_filespec *one, *two;
5505 struct diff_filepair *p;
5507 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5508 is_submodule_ignored(concatpath, options))
5511 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5512 SWAP(old_mode, new_mode);
5513 SWAP(old_oid, new_oid);
5514 SWAP(old_oid_valid, new_oid_valid);
5515 SWAP(old_dirty_submodule, new_dirty_submodule);
5518 if (options->prefix &&
5519 strncmp(concatpath, options->prefix, options->prefix_length))
5522 one = alloc_filespec(concatpath);
5523 two = alloc_filespec(concatpath);
5524 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5525 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5526 one->dirty_submodule = old_dirty_submodule;
5527 two->dirty_submodule = new_dirty_submodule;
5528 p = diff_queue(&diff_queued_diff, one, two);
5530 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5533 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5534 !diff_filespec_check_stat_unmatch(p))
5537 DIFF_OPT_SET(options, HAS_CHANGES);
5540 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5542 struct diff_filepair *pair;
5543 struct diff_filespec *one, *two;
5545 if (options->prefix &&
5546 strncmp(path, options->prefix, options->prefix_length))
5549 one = alloc_filespec(path);
5550 two = alloc_filespec(path);
5551 pair = diff_queue(&diff_queued_diff, one, two);
5552 pair->is_unmerged = 1;
5556 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5559 struct diff_tempfile *temp;
5560 const char *argv[3];
5561 const char **arg = argv;
5562 struct child_process child = CHILD_PROCESS_INIT;
5563 struct strbuf buf = STRBUF_INIT;
5566 temp = prepare_temp_file(spec->path, spec);
5568 *arg++ = temp->name;
5571 child.use_shell = 1;
5574 if (start_command(&child)) {
5579 if (strbuf_read(&buf, child.out, 0) < 0)
5580 err = error("error reading from textconv command '%s'", pgm);
5583 if (finish_command(&child) || err) {
5584 strbuf_release(&buf);
5590 return strbuf_detach(&buf, outsize);
5593 size_t fill_textconv(struct userdiff_driver *driver,
5594 struct diff_filespec *df,
5600 if (!DIFF_FILE_VALID(df)) {
5604 if (diff_populate_filespec(df, 0))
5605 die("unable to read files to diff");
5610 if (!driver->textconv)
5611 die("BUG: fill_textconv called with non-textconv driver");
5613 if (driver->textconv_cache && df->oid_valid) {
5614 *outbuf = notes_cache_get(driver->textconv_cache,
5621 *outbuf = run_textconv(driver->textconv, df, &size);
5623 die("unable to read files to diff");
5625 if (driver->textconv_cache && df->oid_valid) {
5626 /* ignore errors, as we might be in a readonly repository */
5627 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
5630 * we could save up changes and flush them all at the end,
5631 * but we would need an extra call after all diffing is done.
5632 * Since generating a cache entry is the slow path anyway,
5633 * this extra overhead probably isn't a big deal.
5635 notes_cache_write(driver->textconv_cache);
5641 int textconv_object(const char *path,
5643 const struct object_id *oid,
5646 unsigned long *buf_size)
5648 struct diff_filespec *df;
5649 struct userdiff_driver *textconv;
5651 df = alloc_filespec(path);
5652 fill_filespec(df, oid, oid_valid, mode);
5653 textconv = get_textconv(df);
5659 *buf_size = fill_textconv(textconv, df, buf);
5664 void setup_diff_pager(struct diff_options *opt)
5667 * If the user asked for our exit code, then either they want --quiet
5668 * or --exit-code. We should definitely not bother with a pager in the
5669 * former case, as we will generate no output. Since we still properly
5670 * report our exit code even when a pager is run, we _could_ run a
5671 * pager with --exit-code. But since we have not done so historically,
5672 * and because it is easy to find people oneline advising "git diff
5673 * --exit-code" in hooks and other scripts, we do not do so.
5675 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5676 check_pager_config("diff") != 0)