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 return git_diff_basic_config(var, value, cb);
305 int git_diff_basic_config(const char *var, const char *value, void *cb)
309 if (!strcmp(var, "diff.renamelimit")) {
310 diff_rename_limit_default = git_config_int(var, value);
314 if (userdiff_config(var, value) < 0)
317 if (skip_prefix(var, "diff.color.", &name) ||
318 skip_prefix(var, "color.diff.", &name)) {
319 int slot = parse_diff_color_slot(name);
323 return config_error_nonbool(var);
324 return color_parse(value, diff_colors[slot]);
327 /* like GNU diff's --suppress-blank-empty option */
328 if (!strcmp(var, "diff.suppressblankempty") ||
329 /* for backwards compatibility */
330 !strcmp(var, "diff.suppress-blank-empty")) {
331 diff_suppress_blank_empty = git_config_bool(var, value);
335 if (!strcmp(var, "diff.dirstat")) {
336 struct strbuf errmsg = STRBUF_INIT;
337 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
338 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
339 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
341 strbuf_release(&errmsg);
342 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
346 if (starts_with(var, "submodule."))
347 return parse_submodule_config_option(var, value);
349 if (git_diff_heuristic_config(var, value, cb) < 0)
352 return git_default_config(var, value, cb);
355 static char *quote_two(const char *one, const char *two)
357 int need_one = quote_c_style(one, NULL, NULL, 1);
358 int need_two = quote_c_style(two, NULL, NULL, 1);
359 struct strbuf res = STRBUF_INIT;
361 if (need_one + need_two) {
362 strbuf_addch(&res, '"');
363 quote_c_style(one, &res, NULL, 1);
364 quote_c_style(two, &res, NULL, 1);
365 strbuf_addch(&res, '"');
367 strbuf_addstr(&res, one);
368 strbuf_addstr(&res, two);
370 return strbuf_detach(&res, NULL);
373 static const char *external_diff(void)
375 static const char *external_diff_cmd = NULL;
376 static int done_preparing = 0;
379 return external_diff_cmd;
380 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
381 if (!external_diff_cmd)
382 external_diff_cmd = external_diff_cmd_cfg;
384 return external_diff_cmd;
388 * Keep track of files used for diffing. Sometimes such an entry
389 * refers to a temporary file, sometimes to an existing file, and
390 * sometimes to "/dev/null".
392 static struct diff_tempfile {
394 * filename external diff should read from, or NULL if this
395 * entry is currently not in use:
399 char hex[GIT_MAX_HEXSZ + 1];
403 * If this diff_tempfile instance refers to a temporary file,
404 * this tempfile object is used to manage its lifetime.
406 struct tempfile tempfile;
409 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
411 struct emit_callback {
414 int blank_at_eof_in_preimage;
415 int blank_at_eof_in_postimage;
417 int lno_in_postimage;
418 sane_truncate_fn truncate;
419 const char **label_path;
420 struct diff_words_data *diff_words;
421 struct diff_options *opt;
422 struct strbuf *header;
425 static int count_lines(const char *data, int size)
427 int count, ch, completely_empty = 1, nl_just_seen = 0;
434 completely_empty = 0;
438 completely_empty = 0;
441 if (completely_empty)
444 count++; /* no trailing newline */
448 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
450 if (!DIFF_FILE_VALID(one)) {
451 mf->ptr = (char *)""; /* does not matter */
455 else if (diff_populate_filespec(one, 0))
459 mf->size = one->size;
463 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
464 static unsigned long diff_filespec_size(struct diff_filespec *one)
466 if (!DIFF_FILE_VALID(one))
468 diff_populate_filespec(one, CHECK_SIZE_ONLY);
472 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
475 long size = mf->size;
480 ptr += size - 1; /* pointing at the very end */
482 ; /* incomplete line */
484 ptr--; /* skip the last LF */
485 while (mf->ptr < ptr) {
487 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
488 if (*prev_eol == '\n')
490 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
498 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
499 struct emit_callback *ecbdata)
502 unsigned ws_rule = ecbdata->ws_rule;
503 l1 = count_trailing_blank(mf1, ws_rule);
504 l2 = count_trailing_blank(mf2, ws_rule);
506 ecbdata->blank_at_eof_in_preimage = 0;
507 ecbdata->blank_at_eof_in_postimage = 0;
510 at = count_lines(mf1->ptr, mf1->size);
511 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
513 at = count_lines(mf2->ptr, mf2->size);
514 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
517 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
518 int first, const char *line, int len)
520 int has_trailing_newline, has_trailing_carriage_return;
522 FILE *file = o->file;
524 fputs(diff_line_prefix(o), file);
527 has_trailing_newline = (first == '\n');
528 has_trailing_carriage_return = (!has_trailing_newline &&
530 nofirst = has_trailing_newline || has_trailing_carriage_return;
532 has_trailing_newline = (len > 0 && line[len-1] == '\n');
533 if (has_trailing_newline)
535 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
536 if (has_trailing_carriage_return)
541 if (len || !nofirst) {
545 fwrite(line, len, 1, file);
548 if (has_trailing_carriage_return)
550 if (has_trailing_newline)
554 static void emit_line(struct diff_options *o, const char *set, const char *reset,
555 const char *line, int len)
557 emit_line_0(o, set, reset, line[0], line+1, len-1);
560 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
562 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
563 ecbdata->blank_at_eof_in_preimage &&
564 ecbdata->blank_at_eof_in_postimage &&
565 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
566 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
568 return ws_blank_line(line, len, ecbdata->ws_rule);
571 static void emit_line_checked(const char *reset,
572 struct emit_callback *ecbdata,
573 const char *line, int len,
574 enum color_diff color,
575 unsigned ws_error_highlight,
578 const char *set = diff_get_color(ecbdata->color_diff, color);
579 const char *ws = NULL;
581 if (ecbdata->opt->ws_error_highlight & ws_error_highlight) {
582 ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
588 emit_line_0(ecbdata->opt, set, reset, sign, line, len);
589 else if (sign == '+' && new_blank_line_at_eof(ecbdata, line, len))
590 /* Blank line at EOF - paint '+' as well */
591 emit_line_0(ecbdata->opt, ws, reset, sign, line, len);
593 /* Emit just the prefix, then the rest. */
594 emit_line_0(ecbdata->opt, set, reset, sign, "", 0);
595 ws_check_emit(line, len, ecbdata->ws_rule,
596 ecbdata->opt->file, set, reset, ws);
600 static void emit_add_line(const char *reset,
601 struct emit_callback *ecbdata,
602 const char *line, int len)
604 emit_line_checked(reset, ecbdata, line, len,
605 DIFF_FILE_NEW, WSEH_NEW, '+');
608 static void emit_del_line(const char *reset,
609 struct emit_callback *ecbdata,
610 const char *line, int len)
612 emit_line_checked(reset, ecbdata, line, len,
613 DIFF_FILE_OLD, WSEH_OLD, '-');
616 static void emit_context_line(const char *reset,
617 struct emit_callback *ecbdata,
618 const char *line, int len)
620 emit_line_checked(reset, ecbdata, line, len,
621 DIFF_CONTEXT, WSEH_CONTEXT, ' ');
624 static void emit_hunk_header(struct emit_callback *ecbdata,
625 const char *line, int len)
627 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
628 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
629 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
630 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
631 static const char atat[2] = { '@', '@' };
633 struct strbuf msgbuf = STRBUF_INIT;
638 * As a hunk header must begin with "@@ -<old>, +<new> @@",
639 * it always is at least 10 bytes long.
642 memcmp(line, atat, 2) ||
643 !(ep = memmem(line + 2, len - 2, atat, 2))) {
644 emit_line(ecbdata->opt, context, reset, line, len);
647 ep += 2; /* skip over @@ */
649 /* The hunk header in fraginfo color */
650 strbuf_addstr(&msgbuf, frag);
651 strbuf_add(&msgbuf, line, ep - line);
652 strbuf_addstr(&msgbuf, reset);
658 if (line[len - i] == '\r' || line[len - i] == '\n')
661 /* blank before the func header */
662 for (cp = ep; ep - line < len; ep++)
663 if (*ep != ' ' && *ep != '\t')
666 strbuf_addstr(&msgbuf, context);
667 strbuf_add(&msgbuf, cp, ep - cp);
668 strbuf_addstr(&msgbuf, reset);
671 if (ep < line + len) {
672 strbuf_addstr(&msgbuf, func);
673 strbuf_add(&msgbuf, ep, line + len - ep);
674 strbuf_addstr(&msgbuf, reset);
677 strbuf_add(&msgbuf, line + len, org_len - len);
678 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
679 strbuf_release(&msgbuf);
682 static struct diff_tempfile *claim_diff_tempfile(void) {
684 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
685 if (!diff_temp[i].name)
686 return diff_temp + i;
687 die("BUG: diff is failing to clean up its tempfiles");
690 static void remove_tempfile(void)
693 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
694 if (is_tempfile_active(&diff_temp[i].tempfile))
695 delete_tempfile(&diff_temp[i].tempfile);
696 diff_temp[i].name = NULL;
700 static void print_line_count(FILE *file, int count)
704 fprintf(file, "0,0");
710 fprintf(file, "1,%d", count);
715 static void emit_rewrite_lines(struct emit_callback *ecb,
716 int prefix, const char *data, int size)
718 const char *endp = NULL;
719 static const char *nneof = " No newline at end of file\n";
720 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
725 endp = memchr(data, '\n', size);
726 len = endp ? (endp - data + 1) : size;
728 ecb->lno_in_preimage++;
729 emit_del_line(reset, ecb, data, len);
731 ecb->lno_in_postimage++;
732 emit_add_line(reset, ecb, data, len);
738 const char *context = diff_get_color(ecb->color_diff,
740 putc('\n', ecb->opt->file);
741 emit_line_0(ecb->opt, context, reset, '\\',
742 nneof, strlen(nneof));
746 static void emit_rewrite_diff(const char *name_a,
748 struct diff_filespec *one,
749 struct diff_filespec *two,
750 struct userdiff_driver *textconv_one,
751 struct userdiff_driver *textconv_two,
752 struct diff_options *o)
755 const char *name_a_tab, *name_b_tab;
756 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
757 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
758 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
759 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
760 const char *a_prefix, *b_prefix;
761 char *data_one, *data_two;
762 size_t size_one, size_two;
763 struct emit_callback ecbdata;
764 const char *line_prefix = diff_line_prefix(o);
766 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
767 a_prefix = o->b_prefix;
768 b_prefix = o->a_prefix;
770 a_prefix = o->a_prefix;
771 b_prefix = o->b_prefix;
774 name_a += (*name_a == '/');
775 name_b += (*name_b == '/');
776 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
777 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
779 strbuf_reset(&a_name);
780 strbuf_reset(&b_name);
781 quote_two_c_style(&a_name, a_prefix, name_a, 0);
782 quote_two_c_style(&b_name, b_prefix, name_b, 0);
784 size_one = fill_textconv(textconv_one, one, &data_one);
785 size_two = fill_textconv(textconv_two, two, &data_two);
787 memset(&ecbdata, 0, sizeof(ecbdata));
788 ecbdata.color_diff = want_color(o->use_color);
789 ecbdata.ws_rule = whitespace_rule(name_b);
791 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
793 mf1.ptr = (char *)data_one;
794 mf2.ptr = (char *)data_two;
797 check_blank_at_eof(&mf1, &mf2, &ecbdata);
799 ecbdata.lno_in_preimage = 1;
800 ecbdata.lno_in_postimage = 1;
802 lc_a = count_lines(data_one, size_one);
803 lc_b = count_lines(data_two, size_two);
805 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
806 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
807 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
808 line_prefix, fraginfo);
809 if (!o->irreversible_delete)
810 print_line_count(o->file, lc_a);
812 fprintf(o->file, "?,?");
813 fprintf(o->file, " +");
814 print_line_count(o->file, lc_b);
815 fprintf(o->file, " @@%s\n", reset);
816 if (lc_a && !o->irreversible_delete)
817 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
819 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
821 free((char *)data_one);
823 free((char *)data_two);
826 struct diff_words_buffer {
829 struct diff_words_orig {
830 const char *begin, *end;
832 int orig_nr, orig_alloc;
835 static void diff_words_append(char *line, unsigned long len,
836 struct diff_words_buffer *buffer)
838 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
841 memcpy(buffer->text.ptr + buffer->text.size, line, len);
842 buffer->text.size += len;
843 buffer->text.ptr[buffer->text.size] = '\0';
846 struct diff_words_style_elem {
849 const char *color; /* NULL; filled in by the setup code if
850 * color is enabled */
853 struct diff_words_style {
854 enum diff_words_type type;
855 struct diff_words_style_elem new, old, ctx;
859 static struct diff_words_style diff_words_styles[] = {
860 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
861 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
862 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
865 struct diff_words_data {
866 struct diff_words_buffer minus, plus;
867 const char *current_plus;
869 struct diff_options *opt;
871 enum diff_words_type type;
872 struct diff_words_style *style;
875 static int fn_out_diff_words_write_helper(FILE *fp,
876 struct diff_words_style_elem *st_el,
878 size_t count, const char *buf,
879 const char *line_prefix)
884 char *p = memchr(buf, '\n', count);
886 fputs(line_prefix, fp);
888 if (st_el->color && fputs(st_el->color, fp) < 0)
890 if (fputs(st_el->prefix, fp) < 0 ||
891 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
892 fputs(st_el->suffix, fp) < 0)
894 if (st_el->color && *st_el->color
895 && fputs(GIT_COLOR_RESET, fp) < 0)
900 if (fputs(newline, fp) < 0)
902 count -= p + 1 - buf;
910 * '--color-words' algorithm can be described as:
912 * 1. collect the minus/plus lines of a diff hunk, divided into
913 * minus-lines and plus-lines;
915 * 2. break both minus-lines and plus-lines into words and
916 * place them into two mmfile_t with one word for each line;
918 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
920 * And for the common parts of the both file, we output the plus side text.
921 * diff_words->current_plus is used to trace the current position of the plus file
922 * which printed. diff_words->last_minus is used to trace the last minus word
925 * For '--graph' to work with '--color-words', we need to output the graph prefix
926 * on each line of color words output. Generally, there are two conditions on
927 * which we should output the prefix.
929 * 1. diff_words->last_minus == 0 &&
930 * diff_words->current_plus == diff_words->plus.text.ptr
932 * that is: the plus text must start as a new line, and if there is no minus
933 * word printed, a graph prefix must be printed.
935 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
936 * *(diff_words->current_plus - 1) == '\n'
938 * that is: a graph prefix must be printed following a '\n'
940 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
942 if ((diff_words->last_minus == 0 &&
943 diff_words->current_plus == diff_words->plus.text.ptr) ||
944 (diff_words->current_plus > diff_words->plus.text.ptr &&
945 *(diff_words->current_plus - 1) == '\n')) {
952 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
954 struct diff_words_data *diff_words = priv;
955 struct diff_words_style *style = diff_words->style;
956 int minus_first, minus_len, plus_first, plus_len;
957 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
958 struct diff_options *opt = diff_words->opt;
959 const char *line_prefix;
961 if (line[0] != '@' || parse_hunk_header(line, len,
962 &minus_first, &minus_len, &plus_first, &plus_len))
966 line_prefix = diff_line_prefix(opt);
968 /* POSIX requires that first be decremented by one if len == 0... */
970 minus_begin = diff_words->minus.orig[minus_first].begin;
972 diff_words->minus.orig[minus_first + minus_len - 1].end;
974 minus_begin = minus_end =
975 diff_words->minus.orig[minus_first].end;
978 plus_begin = diff_words->plus.orig[plus_first].begin;
979 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
981 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
983 if (color_words_output_graph_prefix(diff_words)) {
984 fputs(line_prefix, diff_words->opt->file);
986 if (diff_words->current_plus != plus_begin) {
987 fn_out_diff_words_write_helper(diff_words->opt->file,
988 &style->ctx, style->newline,
989 plus_begin - diff_words->current_plus,
990 diff_words->current_plus, line_prefix);
991 if (*(plus_begin - 1) == '\n')
992 fputs(line_prefix, diff_words->opt->file);
994 if (minus_begin != minus_end) {
995 fn_out_diff_words_write_helper(diff_words->opt->file,
996 &style->old, style->newline,
997 minus_end - minus_begin, minus_begin,
1000 if (plus_begin != plus_end) {
1001 fn_out_diff_words_write_helper(diff_words->opt->file,
1002 &style->new, style->newline,
1003 plus_end - plus_begin, plus_begin,
1007 diff_words->current_plus = plus_end;
1008 diff_words->last_minus = minus_first;
1011 /* This function starts looking at *begin, and returns 0 iff a word was found. */
1012 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1013 int *begin, int *end)
1015 if (word_regex && *begin < buffer->size) {
1016 regmatch_t match[1];
1017 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1018 buffer->size - *begin, 1, match, 0)) {
1019 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1020 '\n', match[0].rm_eo - match[0].rm_so);
1021 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1022 *begin += match[0].rm_so;
1023 return *begin >= *end;
1028 /* find the next word */
1029 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1031 if (*begin >= buffer->size)
1034 /* find the end of the word */
1036 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1043 * This function splits the words in buffer->text, stores the list with
1044 * newline separator into out, and saves the offsets of the original words
1047 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1048 regex_t *word_regex)
1056 /* fake an empty "0th" word */
1057 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1058 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1059 buffer->orig_nr = 1;
1061 for (i = 0; i < buffer->text.size; i++) {
1062 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1065 /* store original boundaries */
1066 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1067 buffer->orig_alloc);
1068 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1069 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1072 /* store one word */
1073 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1074 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1075 out->ptr[out->size + j - i] = '\n';
1076 out->size += j - i + 1;
1082 /* this executes the word diff on the accumulated buffers */
1083 static void diff_words_show(struct diff_words_data *diff_words)
1087 mmfile_t minus, plus;
1088 struct diff_words_style *style = diff_words->style;
1090 struct diff_options *opt = diff_words->opt;
1091 const char *line_prefix;
1094 line_prefix = diff_line_prefix(opt);
1096 /* special case: only removal */
1097 if (!diff_words->plus.text.size) {
1098 fputs(line_prefix, diff_words->opt->file);
1099 fn_out_diff_words_write_helper(diff_words->opt->file,
1100 &style->old, style->newline,
1101 diff_words->minus.text.size,
1102 diff_words->minus.text.ptr, line_prefix);
1103 diff_words->minus.text.size = 0;
1107 diff_words->current_plus = diff_words->plus.text.ptr;
1108 diff_words->last_minus = 0;
1110 memset(&xpp, 0, sizeof(xpp));
1111 memset(&xecfg, 0, sizeof(xecfg));
1112 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1113 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1115 /* as only the hunk header will be parsed, we need a 0-context */
1117 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1119 die("unable to generate word diff");
1122 if (diff_words->current_plus != diff_words->plus.text.ptr +
1123 diff_words->plus.text.size) {
1124 if (color_words_output_graph_prefix(diff_words))
1125 fputs(line_prefix, diff_words->opt->file);
1126 fn_out_diff_words_write_helper(diff_words->opt->file,
1127 &style->ctx, style->newline,
1128 diff_words->plus.text.ptr + diff_words->plus.text.size
1129 - diff_words->current_plus, diff_words->current_plus,
1132 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1135 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1136 static void diff_words_flush(struct emit_callback *ecbdata)
1138 if (ecbdata->diff_words->minus.text.size ||
1139 ecbdata->diff_words->plus.text.size)
1140 diff_words_show(ecbdata->diff_words);
1143 static void diff_filespec_load_driver(struct diff_filespec *one)
1145 /* Use already-loaded driver */
1149 if (S_ISREG(one->mode))
1150 one->driver = userdiff_find_by_path(one->path);
1152 /* Fallback to default settings */
1154 one->driver = userdiff_find_by_name("default");
1157 static const char *userdiff_word_regex(struct diff_filespec *one)
1159 diff_filespec_load_driver(one);
1160 return one->driver->word_regex;
1163 static void init_diff_words_data(struct emit_callback *ecbdata,
1164 struct diff_options *orig_opts,
1165 struct diff_filespec *one,
1166 struct diff_filespec *two)
1169 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1170 memcpy(o, orig_opts, sizeof(struct diff_options));
1172 ecbdata->diff_words =
1173 xcalloc(1, sizeof(struct diff_words_data));
1174 ecbdata->diff_words->type = o->word_diff;
1175 ecbdata->diff_words->opt = o;
1177 o->word_regex = userdiff_word_regex(one);
1179 o->word_regex = userdiff_word_regex(two);
1181 o->word_regex = diff_word_regex_cfg;
1182 if (o->word_regex) {
1183 ecbdata->diff_words->word_regex = (regex_t *)
1184 xmalloc(sizeof(regex_t));
1185 if (regcomp(ecbdata->diff_words->word_regex,
1187 REG_EXTENDED | REG_NEWLINE))
1188 die ("Invalid regular expression: %s",
1191 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1192 if (o->word_diff == diff_words_styles[i].type) {
1193 ecbdata->diff_words->style =
1194 &diff_words_styles[i];
1198 if (want_color(o->use_color)) {
1199 struct diff_words_style *st = ecbdata->diff_words->style;
1200 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1201 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1202 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1206 static void free_diff_words_data(struct emit_callback *ecbdata)
1208 if (ecbdata->diff_words) {
1209 diff_words_flush(ecbdata);
1210 free (ecbdata->diff_words->opt);
1211 free (ecbdata->diff_words->minus.text.ptr);
1212 free (ecbdata->diff_words->minus.orig);
1213 free (ecbdata->diff_words->plus.text.ptr);
1214 free (ecbdata->diff_words->plus.orig);
1215 if (ecbdata->diff_words->word_regex) {
1216 regfree(ecbdata->diff_words->word_regex);
1217 free(ecbdata->diff_words->word_regex);
1219 FREE_AND_NULL(ecbdata->diff_words);
1223 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1225 if (want_color(diff_use_color))
1226 return diff_colors[ix];
1230 const char *diff_line_prefix(struct diff_options *opt)
1232 struct strbuf *msgbuf;
1233 if (!opt->output_prefix)
1236 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1240 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1243 unsigned long allot;
1247 return ecb->truncate(line, len);
1251 (void) utf8_width(&cp, &l);
1253 break; /* truncated in the middle? */
1258 static void find_lno(const char *line, struct emit_callback *ecbdata)
1261 ecbdata->lno_in_preimage = 0;
1262 ecbdata->lno_in_postimage = 0;
1263 p = strchr(line, '-');
1265 return; /* cannot happen */
1266 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1269 return; /* cannot happen */
1270 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1273 static void fn_out_consume(void *priv, char *line, unsigned long len)
1275 struct emit_callback *ecbdata = priv;
1276 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1277 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1278 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1279 struct diff_options *o = ecbdata->opt;
1280 const char *line_prefix = diff_line_prefix(o);
1282 o->found_changes = 1;
1284 if (ecbdata->header) {
1285 fprintf(o->file, "%s", ecbdata->header->buf);
1286 strbuf_reset(ecbdata->header);
1287 ecbdata->header = NULL;
1290 if (ecbdata->label_path[0]) {
1291 const char *name_a_tab, *name_b_tab;
1293 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1294 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1296 fprintf(o->file, "%s%s--- %s%s%s\n",
1297 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1298 fprintf(o->file, "%s%s+++ %s%s%s\n",
1299 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1300 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1303 if (diff_suppress_blank_empty
1304 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1309 if (line[0] == '@') {
1310 if (ecbdata->diff_words)
1311 diff_words_flush(ecbdata);
1312 len = sane_truncate_line(ecbdata, line, len);
1313 find_lno(line, ecbdata);
1314 emit_hunk_header(ecbdata, line, len);
1315 if (line[len-1] != '\n')
1316 putc('\n', o->file);
1320 if (ecbdata->diff_words) {
1321 if (line[0] == '-') {
1322 diff_words_append(line, len,
1323 &ecbdata->diff_words->minus);
1325 } else if (line[0] == '+') {
1326 diff_words_append(line, len,
1327 &ecbdata->diff_words->plus);
1329 } else if (starts_with(line, "\\ ")) {
1331 * Eat the "no newline at eof" marker as if we
1332 * saw a "+" or "-" line with nothing on it,
1333 * and return without diff_words_flush() to
1334 * defer processing. If this is the end of
1335 * preimage, more "+" lines may come after it.
1339 diff_words_flush(ecbdata);
1340 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1341 emit_line(o, context, reset, line, len);
1342 fputs("~\n", o->file);
1345 * Skip the prefix character, if any. With
1346 * diff_suppress_blank_empty, there may be
1349 if (line[0] != '\n') {
1353 emit_line(o, context, reset, line, len);
1360 ecbdata->lno_in_postimage++;
1361 emit_add_line(reset, ecbdata, line + 1, len - 1);
1364 ecbdata->lno_in_preimage++;
1365 emit_del_line(reset, ecbdata, line + 1, len - 1);
1368 ecbdata->lno_in_postimage++;
1369 ecbdata->lno_in_preimage++;
1370 emit_context_line(reset, ecbdata, line + 1, len - 1);
1373 /* incomplete line at the end */
1374 ecbdata->lno_in_preimage++;
1375 emit_line(o, diff_get_color(ecbdata->color_diff, DIFF_CONTEXT),
1381 static char *pprint_rename(const char *a, const char *b)
1383 const char *old = a;
1384 const char *new = b;
1385 struct strbuf name = STRBUF_INIT;
1386 int pfx_length, sfx_length;
1387 int pfx_adjust_for_slash;
1388 int len_a = strlen(a);
1389 int len_b = strlen(b);
1390 int a_midlen, b_midlen;
1391 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1392 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1394 if (qlen_a || qlen_b) {
1395 quote_c_style(a, &name, NULL, 0);
1396 strbuf_addstr(&name, " => ");
1397 quote_c_style(b, &name, NULL, 0);
1398 return strbuf_detach(&name, NULL);
1401 /* Find common prefix */
1403 while (*old && *new && *old == *new) {
1405 pfx_length = old - a + 1;
1410 /* Find common suffix */
1415 * If there is a common prefix, it must end in a slash. In
1416 * that case we let this loop run 1 into the prefix to see the
1419 * If there is no common prefix, we cannot do this as it would
1420 * underrun the input strings.
1422 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1423 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1424 b + pfx_length - pfx_adjust_for_slash <= new &&
1427 sfx_length = len_a - (old - a);
1433 * pfx{mid-a => mid-b}sfx
1434 * {pfx-a => pfx-b}sfx
1435 * pfx{sfx-a => sfx-b}
1438 a_midlen = len_a - pfx_length - sfx_length;
1439 b_midlen = len_b - pfx_length - sfx_length;
1445 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1446 if (pfx_length + sfx_length) {
1447 strbuf_add(&name, a, pfx_length);
1448 strbuf_addch(&name, '{');
1450 strbuf_add(&name, a + pfx_length, a_midlen);
1451 strbuf_addstr(&name, " => ");
1452 strbuf_add(&name, b + pfx_length, b_midlen);
1453 if (pfx_length + sfx_length) {
1454 strbuf_addch(&name, '}');
1455 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1457 return strbuf_detach(&name, NULL);
1463 struct diffstat_file {
1467 unsigned is_unmerged:1;
1468 unsigned is_binary:1;
1469 unsigned is_renamed:1;
1470 unsigned is_interesting:1;
1471 uintmax_t added, deleted;
1475 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1479 struct diffstat_file *x;
1480 x = xcalloc(1, sizeof(*x));
1481 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1482 diffstat->files[diffstat->nr++] = x;
1484 x->from_name = xstrdup(name_a);
1485 x->name = xstrdup(name_b);
1489 x->from_name = NULL;
1490 x->name = xstrdup(name_a);
1495 static void diffstat_consume(void *priv, char *line, unsigned long len)
1497 struct diffstat_t *diffstat = priv;
1498 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1502 else if (line[0] == '-')
1506 const char mime_boundary_leader[] = "------------";
1508 static int scale_linear(int it, int width, int max_change)
1513 * make sure that at least one '-' or '+' is printed if
1514 * there is any change to this path. The easiest way is to
1515 * scale linearly as if the alloted width is one column shorter
1516 * than it is, and then add 1 to the result.
1518 return 1 + (it * (width - 1) / max_change);
1521 static void show_name(FILE *file,
1522 const char *prefix, const char *name, int len)
1524 fprintf(file, " %s%-*s |", prefix, len, name);
1527 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1531 fprintf(file, "%s", set);
1534 fprintf(file, "%s", reset);
1537 static void fill_print_name(struct diffstat_file *file)
1541 if (file->print_name)
1544 if (!file->is_renamed) {
1545 struct strbuf buf = STRBUF_INIT;
1546 if (quote_c_style(file->name, &buf, NULL, 0)) {
1547 pname = strbuf_detach(&buf, NULL);
1550 strbuf_release(&buf);
1553 pname = pprint_rename(file->from_name, file->name);
1555 file->print_name = pname;
1558 int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1560 struct strbuf sb = STRBUF_INIT;
1564 assert(insertions == 0 && deletions == 0);
1565 return fprintf(fp, "%s\n", " 0 files changed");
1569 (files == 1) ? " %d file changed" : " %d files changed",
1573 * For binary diff, the caller may want to print "x files
1574 * changed" with insertions == 0 && deletions == 0.
1576 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1577 * is probably less confusing (i.e skip over "2 files changed
1578 * but nothing about added/removed lines? Is this a bug in Git?").
1580 if (insertions || deletions == 0) {
1582 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1586 if (deletions || insertions == 0) {
1588 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1591 strbuf_addch(&sb, '\n');
1592 ret = fputs(sb.buf, fp);
1593 strbuf_release(&sb);
1597 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1599 int i, len, add, del, adds = 0, dels = 0;
1600 uintmax_t max_change = 0, max_len = 0;
1601 int total_files = data->nr, count;
1602 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1603 const char *reset, *add_c, *del_c;
1604 const char *line_prefix = "";
1605 int extra_shown = 0;
1610 line_prefix = diff_line_prefix(options);
1611 count = options->stat_count ? options->stat_count : data->nr;
1613 reset = diff_get_color_opt(options, DIFF_RESET);
1614 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1615 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1618 * Find the longest filename and max number of changes
1620 for (i = 0; (i < count) && (i < data->nr); i++) {
1621 struct diffstat_file *file = data->files[i];
1622 uintmax_t change = file->added + file->deleted;
1624 if (!file->is_interesting && (change == 0)) {
1625 count++; /* not shown == room for one more */
1628 fill_print_name(file);
1629 len = strlen(file->print_name);
1633 if (file->is_unmerged) {
1634 /* "Unmerged" is 8 characters */
1635 bin_width = bin_width < 8 ? 8 : bin_width;
1638 if (file->is_binary) {
1639 /* "Bin XXX -> YYY bytes" */
1640 int w = 14 + decimal_width(file->added)
1641 + decimal_width(file->deleted);
1642 bin_width = bin_width < w ? w : bin_width;
1643 /* Display change counts aligned with "Bin" */
1648 if (max_change < change)
1649 max_change = change;
1651 count = i; /* where we can stop scanning in data->files[] */
1654 * We have width = stat_width or term_columns() columns total.
1655 * We want a maximum of min(max_len, stat_name_width) for the name part.
1656 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1657 * We also need 1 for " " and 4 + decimal_width(max_change)
1658 * for " | NNNN " and one the empty column at the end, altogether
1659 * 6 + decimal_width(max_change).
1661 * If there's not enough space, we will use the smaller of
1662 * stat_name_width (if set) and 5/8*width for the filename,
1663 * and the rest for constant elements + graph part, but no more
1664 * than stat_graph_width for the graph part.
1665 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1666 * for the standard terminal size).
1668 * In other words: stat_width limits the maximum width, and
1669 * stat_name_width fixes the maximum width of the filename,
1670 * and is also used to divide available columns if there
1673 * Binary files are displayed with "Bin XXX -> YYY bytes"
1674 * instead of the change count and graph. This part is treated
1675 * similarly to the graph part, except that it is not
1676 * "scaled". If total width is too small to accommodate the
1677 * guaranteed minimum width of the filename part and the
1678 * separators and this message, this message will "overflow"
1679 * making the line longer than the maximum width.
1682 if (options->stat_width == -1)
1683 width = term_columns() - strlen(line_prefix);
1685 width = options->stat_width ? options->stat_width : 80;
1686 number_width = decimal_width(max_change) > number_width ?
1687 decimal_width(max_change) : number_width;
1689 if (options->stat_graph_width == -1)
1690 options->stat_graph_width = diff_stat_graph_width;
1693 * Guarantee 3/8*16==6 for the graph part
1694 * and 5/8*16==10 for the filename part
1696 if (width < 16 + 6 + number_width)
1697 width = 16 + 6 + number_width;
1700 * First assign sizes that are wanted, ignoring available width.
1701 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1702 * starting from "XXX" should fit in graph_width.
1704 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1705 if (options->stat_graph_width &&
1706 options->stat_graph_width < graph_width)
1707 graph_width = options->stat_graph_width;
1709 name_width = (options->stat_name_width > 0 &&
1710 options->stat_name_width < max_len) ?
1711 options->stat_name_width : max_len;
1714 * Adjust adjustable widths not to exceed maximum width
1716 if (name_width + number_width + 6 + graph_width > width) {
1717 if (graph_width > width * 3/8 - number_width - 6) {
1718 graph_width = width * 3/8 - number_width - 6;
1719 if (graph_width < 6)
1723 if (options->stat_graph_width &&
1724 graph_width > options->stat_graph_width)
1725 graph_width = options->stat_graph_width;
1726 if (name_width > width - number_width - 6 - graph_width)
1727 name_width = width - number_width - 6 - graph_width;
1729 graph_width = width - number_width - 6 - name_width;
1733 * From here name_width is the width of the name area,
1734 * and graph_width is the width of the graph area.
1735 * max_change is used to scale graph properly.
1737 for (i = 0; i < count; i++) {
1738 const char *prefix = "";
1739 struct diffstat_file *file = data->files[i];
1740 char *name = file->print_name;
1741 uintmax_t added = file->added;
1742 uintmax_t deleted = file->deleted;
1745 if (!file->is_interesting && (added + deleted == 0))
1749 * "scale" the filename
1752 name_len = strlen(name);
1753 if (name_width < name_len) {
1757 name += name_len - len;
1758 slash = strchr(name, '/');
1763 if (file->is_binary) {
1764 fprintf(options->file, "%s", line_prefix);
1765 show_name(options->file, prefix, name, len);
1766 fprintf(options->file, " %*s", number_width, "Bin");
1767 if (!added && !deleted) {
1768 putc('\n', options->file);
1771 fprintf(options->file, " %s%"PRIuMAX"%s",
1772 del_c, deleted, reset);
1773 fprintf(options->file, " -> ");
1774 fprintf(options->file, "%s%"PRIuMAX"%s",
1775 add_c, added, reset);
1776 fprintf(options->file, " bytes");
1777 fprintf(options->file, "\n");
1780 else if (file->is_unmerged) {
1781 fprintf(options->file, "%s", line_prefix);
1782 show_name(options->file, prefix, name, len);
1783 fprintf(options->file, " Unmerged\n");
1788 * scale the add/delete
1793 if (graph_width <= max_change) {
1794 int total = scale_linear(add + del, graph_width, max_change);
1795 if (total < 2 && add && del)
1796 /* width >= 2 due to the sanity check */
1799 add = scale_linear(add, graph_width, max_change);
1802 del = scale_linear(del, graph_width, max_change);
1806 fprintf(options->file, "%s", line_prefix);
1807 show_name(options->file, prefix, name, len);
1808 fprintf(options->file, " %*"PRIuMAX"%s",
1809 number_width, added + deleted,
1810 added + deleted ? " " : "");
1811 show_graph(options->file, '+', add, add_c, reset);
1812 show_graph(options->file, '-', del, del_c, reset);
1813 fprintf(options->file, "\n");
1816 for (i = 0; i < data->nr; i++) {
1817 struct diffstat_file *file = data->files[i];
1818 uintmax_t added = file->added;
1819 uintmax_t deleted = file->deleted;
1821 if (file->is_unmerged ||
1822 (!file->is_interesting && (added + deleted == 0))) {
1827 if (!file->is_binary) {
1834 fprintf(options->file, "%s ...\n", line_prefix);
1837 fprintf(options->file, "%s", line_prefix);
1838 print_stat_summary(options->file, total_files, adds, dels);
1841 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1843 int i, adds = 0, dels = 0, total_files = data->nr;
1848 for (i = 0; i < data->nr; i++) {
1849 int added = data->files[i]->added;
1850 int deleted= data->files[i]->deleted;
1852 if (data->files[i]->is_unmerged ||
1853 (!data->files[i]->is_interesting && (added + deleted == 0))) {
1855 } else if (!data->files[i]->is_binary) { /* don't count bytes */
1860 fprintf(options->file, "%s", diff_line_prefix(options));
1861 print_stat_summary(options->file, total_files, adds, dels);
1864 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1871 for (i = 0; i < data->nr; i++) {
1872 struct diffstat_file *file = data->files[i];
1874 fprintf(options->file, "%s", diff_line_prefix(options));
1876 if (file->is_binary)
1877 fprintf(options->file, "-\t-\t");
1879 fprintf(options->file,
1880 "%"PRIuMAX"\t%"PRIuMAX"\t",
1881 file->added, file->deleted);
1882 if (options->line_termination) {
1883 fill_print_name(file);
1884 if (!file->is_renamed)
1885 write_name_quoted(file->name, options->file,
1886 options->line_termination);
1888 fputs(file->print_name, options->file);
1889 putc(options->line_termination, options->file);
1892 if (file->is_renamed) {
1893 putc('\0', options->file);
1894 write_name_quoted(file->from_name, options->file, '\0');
1896 write_name_quoted(file->name, options->file, '\0');
1901 struct dirstat_file {
1903 unsigned long changed;
1906 struct dirstat_dir {
1907 struct dirstat_file *files;
1908 int alloc, nr, permille, cumulative;
1911 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1912 unsigned long changed, const char *base, int baselen)
1914 unsigned long this_dir = 0;
1915 unsigned int sources = 0;
1916 const char *line_prefix = diff_line_prefix(opt);
1919 struct dirstat_file *f = dir->files;
1920 int namelen = strlen(f->name);
1924 if (namelen < baselen)
1926 if (memcmp(f->name, base, baselen))
1928 slash = strchr(f->name + baselen, '/');
1930 int newbaselen = slash + 1 - f->name;
1931 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1943 * We don't report dirstat's for
1945 * - or cases where everything came from a single directory
1946 * under this directory (sources == 1).
1948 if (baselen && sources != 1) {
1950 int permille = this_dir * 1000 / changed;
1951 if (permille >= dir->permille) {
1952 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1953 permille / 10, permille % 10, baselen, base);
1954 if (!dir->cumulative)
1962 static int dirstat_compare(const void *_a, const void *_b)
1964 const struct dirstat_file *a = _a;
1965 const struct dirstat_file *b = _b;
1966 return strcmp(a->name, b->name);
1969 static void show_dirstat(struct diff_options *options)
1972 unsigned long changed;
1973 struct dirstat_dir dir;
1974 struct diff_queue_struct *q = &diff_queued_diff;
1979 dir.permille = options->dirstat_permille;
1980 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1983 for (i = 0; i < q->nr; i++) {
1984 struct diff_filepair *p = q->queue[i];
1986 unsigned long copied, added, damage;
1987 int content_changed;
1989 name = p->two->path ? p->two->path : p->one->path;
1991 if (p->one->oid_valid && p->two->oid_valid)
1992 content_changed = oidcmp(&p->one->oid, &p->two->oid);
1994 content_changed = 1;
1996 if (!content_changed) {
1998 * The SHA1 has not changed, so pre-/post-content is
1999 * identical. We can therefore skip looking at the
2000 * file contents altogether.
2006 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
2008 * In --dirstat-by-file mode, we don't really need to
2009 * look at the actual file contents at all.
2010 * The fact that the SHA1 changed is enough for us to
2011 * add this file to the list of results
2012 * (with each file contributing equal damage).
2018 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2019 diff_populate_filespec(p->one, 0);
2020 diff_populate_filespec(p->two, 0);
2021 diffcore_count_changes(p->one, p->two, NULL, NULL,
2023 diff_free_filespec_data(p->one);
2024 diff_free_filespec_data(p->two);
2025 } else if (DIFF_FILE_VALID(p->one)) {
2026 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
2028 diff_free_filespec_data(p->one);
2029 } else if (DIFF_FILE_VALID(p->two)) {
2030 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
2032 added = p->two->size;
2033 diff_free_filespec_data(p->two);
2038 * Original minus copied is the removed material,
2039 * added is the new material. They are both damages
2040 * made to the preimage.
2041 * If the resulting damage is zero, we know that
2042 * diffcore_count_changes() considers the two entries to
2043 * be identical, but since content_changed is true, we
2044 * know that there must have been _some_ kind of change,
2045 * so we force all entries to have damage > 0.
2047 damage = (p->one->size - copied) + added;
2052 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2053 dir.files[dir.nr].name = name;
2054 dir.files[dir.nr].changed = damage;
2059 /* This can happen even with many files, if everything was renames */
2063 /* Show all directories with more than x% of the changes */
2064 QSORT(dir.files, dir.nr, dirstat_compare);
2065 gather_dirstat(options, &dir, changed, "", 0);
2068 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2071 unsigned long changed;
2072 struct dirstat_dir dir;
2080 dir.permille = options->dirstat_permille;
2081 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2084 for (i = 0; i < data->nr; i++) {
2085 struct diffstat_file *file = data->files[i];
2086 unsigned long damage = file->added + file->deleted;
2087 if (file->is_binary)
2089 * binary files counts bytes, not lines. Must find some
2090 * way to normalize binary bytes vs. textual lines.
2091 * The following heuristic assumes that there are 64
2093 * This is stupid and ugly, but very cheap...
2095 damage = DIV_ROUND_UP(damage, 64);
2096 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2097 dir.files[dir.nr].name = file->name;
2098 dir.files[dir.nr].changed = damage;
2103 /* This can happen even with many files, if everything was renames */
2107 /* Show all directories with more than x% of the changes */
2108 QSORT(dir.files, dir.nr, dirstat_compare);
2109 gather_dirstat(options, &dir, changed, "", 0);
2112 static void free_diffstat_info(struct diffstat_t *diffstat)
2115 for (i = 0; i < diffstat->nr; i++) {
2116 struct diffstat_file *f = diffstat->files[i];
2117 if (f->name != f->print_name)
2118 free(f->print_name);
2123 free(diffstat->files);
2126 struct checkdiff_t {
2127 const char *filename;
2129 int conflict_marker_size;
2130 struct diff_options *o;
2135 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2140 if (len < marker_size + 1)
2142 firstchar = line[0];
2143 switch (firstchar) {
2144 case '=': case '>': case '<': case '|':
2149 for (cnt = 1; cnt < marker_size; cnt++)
2150 if (line[cnt] != firstchar)
2152 /* line[1] thru line[marker_size-1] are same as firstchar */
2153 if (len < marker_size + 1 || !isspace(line[marker_size]))
2158 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2160 struct checkdiff_t *data = priv;
2161 int marker_size = data->conflict_marker_size;
2162 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2163 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2164 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2166 const char *line_prefix;
2169 line_prefix = diff_line_prefix(data->o);
2171 if (line[0] == '+') {
2174 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2176 fprintf(data->o->file,
2177 "%s%s:%d: leftover conflict marker\n",
2178 line_prefix, data->filename, data->lineno);
2180 bad = ws_check(line + 1, len - 1, data->ws_rule);
2183 data->status |= bad;
2184 err = whitespace_error_string(bad);
2185 fprintf(data->o->file, "%s%s:%d: %s.\n",
2186 line_prefix, data->filename, data->lineno, err);
2188 emit_line(data->o, set, reset, line, 1);
2189 ws_check_emit(line + 1, len - 1, data->ws_rule,
2190 data->o->file, set, reset, ws);
2191 } else if (line[0] == ' ') {
2193 } else if (line[0] == '@') {
2194 char *plus = strchr(line, '+');
2196 data->lineno = strtol(plus, NULL, 10) - 1;
2198 die("invalid diff");
2202 static unsigned char *deflate_it(char *data,
2204 unsigned long *result_size)
2207 unsigned char *deflated;
2210 git_deflate_init(&stream, zlib_compression_level);
2211 bound = git_deflate_bound(&stream, size);
2212 deflated = xmalloc(bound);
2213 stream.next_out = deflated;
2214 stream.avail_out = bound;
2216 stream.next_in = (unsigned char *)data;
2217 stream.avail_in = size;
2218 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2220 git_deflate_end(&stream);
2221 *result_size = stream.total_out;
2225 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two,
2232 unsigned long orig_size;
2233 unsigned long delta_size;
2234 unsigned long deflate_size;
2235 unsigned long data_size;
2237 /* We could do deflated delta, or we could do just deflated two,
2238 * whichever is smaller.
2241 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2242 if (one->size && two->size) {
2243 delta = diff_delta(one->ptr, one->size,
2244 two->ptr, two->size,
2245 &delta_size, deflate_size);
2247 void *to_free = delta;
2248 orig_size = delta_size;
2249 delta = deflate_it(delta, delta_size, &delta_size);
2254 if (delta && delta_size < deflate_size) {
2255 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2258 data_size = delta_size;
2261 fprintf(file, "%sliteral %lu\n", prefix, two->size);
2264 data_size = deflate_size;
2267 /* emit data encoded in base85 */
2270 int bytes = (52 < data_size) ? 52 : data_size;
2274 line[0] = bytes + 'A' - 1;
2276 line[0] = bytes - 26 + 'a' - 1;
2277 encode_85(line + 1, cp, bytes);
2278 cp = (char *) cp + bytes;
2279 fprintf(file, "%s", prefix);
2283 fprintf(file, "%s\n", prefix);
2287 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two,
2290 fprintf(file, "%sGIT binary patch\n", prefix);
2291 emit_binary_diff_body(file, one, two, prefix);
2292 emit_binary_diff_body(file, two, one, prefix);
2295 int diff_filespec_is_binary(struct diff_filespec *one)
2297 if (one->is_binary == -1) {
2298 diff_filespec_load_driver(one);
2299 if (one->driver->binary != -1)
2300 one->is_binary = one->driver->binary;
2302 if (!one->data && DIFF_FILE_VALID(one))
2303 diff_populate_filespec(one, CHECK_BINARY);
2304 if (one->is_binary == -1 && one->data)
2305 one->is_binary = buffer_is_binary(one->data,
2307 if (one->is_binary == -1)
2311 return one->is_binary;
2314 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2316 diff_filespec_load_driver(one);
2317 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2320 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2322 if (!options->a_prefix)
2323 options->a_prefix = a;
2324 if (!options->b_prefix)
2325 options->b_prefix = b;
2328 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2330 if (!DIFF_FILE_VALID(one))
2333 diff_filespec_load_driver(one);
2334 return userdiff_get_textconv(one->driver);
2337 static void builtin_diff(const char *name_a,
2339 struct diff_filespec *one,
2340 struct diff_filespec *two,
2341 const char *xfrm_msg,
2342 int must_show_header,
2343 struct diff_options *o,
2344 int complete_rewrite)
2348 char *a_one, *b_two;
2349 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2350 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2351 const char *a_prefix, *b_prefix;
2352 struct userdiff_driver *textconv_one = NULL;
2353 struct userdiff_driver *textconv_two = NULL;
2354 struct strbuf header = STRBUF_INIT;
2355 const char *line_prefix = diff_line_prefix(o);
2357 diff_set_mnemonic_prefix(o, "a/", "b/");
2358 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2359 a_prefix = o->b_prefix;
2360 b_prefix = o->a_prefix;
2362 a_prefix = o->a_prefix;
2363 b_prefix = o->b_prefix;
2366 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
2367 (!one->mode || S_ISGITLINK(one->mode)) &&
2368 (!two->mode || S_ISGITLINK(two->mode))) {
2369 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2370 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2371 show_submodule_summary(o->file, one->path ? one->path : two->path,
2373 &one->oid, &two->oid,
2374 two->dirty_submodule,
2375 meta, del, add, reset);
2377 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
2378 (!one->mode || S_ISGITLINK(one->mode)) &&
2379 (!two->mode || S_ISGITLINK(two->mode))) {
2380 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2381 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2382 show_submodule_inline_diff(o->file, one->path ? one->path : two->path,
2384 &one->oid, &two->oid,
2385 two->dirty_submodule,
2386 meta, del, add, reset, o);
2390 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2391 textconv_one = get_textconv(one);
2392 textconv_two = get_textconv(two);
2395 /* Never use a non-valid filename anywhere if at all possible */
2396 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2397 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2399 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2400 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2401 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2402 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2403 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2404 if (lbl[0][0] == '/') {
2406 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2408 strbuf_addstr(&header, xfrm_msg);
2409 must_show_header = 1;
2411 else if (lbl[1][0] == '/') {
2412 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2414 strbuf_addstr(&header, xfrm_msg);
2415 must_show_header = 1;
2418 if (one->mode != two->mode) {
2419 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2420 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2421 must_show_header = 1;
2424 strbuf_addstr(&header, xfrm_msg);
2427 * we do not run diff between different kind
2430 if ((one->mode ^ two->mode) & S_IFMT)
2431 goto free_ab_and_return;
2432 if (complete_rewrite &&
2433 (textconv_one || !diff_filespec_is_binary(one)) &&
2434 (textconv_two || !diff_filespec_is_binary(two))) {
2435 fprintf(o->file, "%s", header.buf);
2436 strbuf_reset(&header);
2437 emit_rewrite_diff(name_a, name_b, one, two,
2438 textconv_one, textconv_two, o);
2439 o->found_changes = 1;
2440 goto free_ab_and_return;
2444 if (o->irreversible_delete && lbl[1][0] == '/') {
2445 fprintf(o->file, "%s", header.buf);
2446 strbuf_reset(&header);
2447 goto free_ab_and_return;
2448 } else if (!DIFF_OPT_TST(o, TEXT) &&
2449 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2450 (!textconv_two && diff_filespec_is_binary(two)) )) {
2451 if (!one->data && !two->data &&
2452 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2453 !DIFF_OPT_TST(o, BINARY)) {
2454 if (!oidcmp(&one->oid, &two->oid)) {
2455 if (must_show_header)
2456 fprintf(o->file, "%s", header.buf);
2457 goto free_ab_and_return;
2459 fprintf(o->file, "%s", header.buf);
2460 fprintf(o->file, "%sBinary files %s and %s differ\n",
2461 line_prefix, lbl[0], lbl[1]);
2462 goto free_ab_and_return;
2464 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2465 die("unable to read files to diff");
2466 /* Quite common confusing case */
2467 if (mf1.size == mf2.size &&
2468 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2469 if (must_show_header)
2470 fprintf(o->file, "%s", header.buf);
2471 goto free_ab_and_return;
2473 fprintf(o->file, "%s", header.buf);
2474 strbuf_reset(&header);
2475 if (DIFF_OPT_TST(o, BINARY))
2476 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2478 fprintf(o->file, "%sBinary files %s and %s differ\n",
2479 line_prefix, lbl[0], lbl[1]);
2480 o->found_changes = 1;
2482 /* Crazy xdl interfaces.. */
2483 const char *diffopts = getenv("GIT_DIFF_OPTS");
2487 struct emit_callback ecbdata;
2488 const struct userdiff_funcname *pe;
2490 if (must_show_header) {
2491 fprintf(o->file, "%s", header.buf);
2492 strbuf_reset(&header);
2495 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2496 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2498 pe = diff_funcname_pattern(one);
2500 pe = diff_funcname_pattern(two);
2502 memset(&xpp, 0, sizeof(xpp));
2503 memset(&xecfg, 0, sizeof(xecfg));
2504 memset(&ecbdata, 0, sizeof(ecbdata));
2505 ecbdata.label_path = lbl;
2506 ecbdata.color_diff = want_color(o->use_color);
2507 ecbdata.ws_rule = whitespace_rule(name_b);
2508 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2509 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2511 ecbdata.header = header.len ? &header : NULL;
2512 xpp.flags = o->xdl_opts;
2513 xecfg.ctxlen = o->context;
2514 xecfg.interhunkctxlen = o->interhunkcontext;
2515 xecfg.flags = XDL_EMIT_FUNCNAMES;
2516 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2517 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2519 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2522 else if (skip_prefix(diffopts, "--unified=", &v))
2523 xecfg.ctxlen = strtoul(v, NULL, 10);
2524 else if (skip_prefix(diffopts, "-u", &v))
2525 xecfg.ctxlen = strtoul(v, NULL, 10);
2527 init_diff_words_data(&ecbdata, o, one, two);
2528 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2530 die("unable to generate diff for %s", one->path);
2532 free_diff_words_data(&ecbdata);
2537 xdiff_clear_find_func(&xecfg);
2541 strbuf_release(&header);
2542 diff_free_filespec_data(one);
2543 diff_free_filespec_data(two);
2549 static void builtin_diffstat(const char *name_a, const char *name_b,
2550 struct diff_filespec *one,
2551 struct diff_filespec *two,
2552 struct diffstat_t *diffstat,
2553 struct diff_options *o,
2554 struct diff_filepair *p)
2557 struct diffstat_file *data;
2559 int complete_rewrite = 0;
2561 if (!DIFF_PAIR_UNMERGED(p)) {
2562 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2563 complete_rewrite = 1;
2566 data = diffstat_add(diffstat, name_a, name_b);
2567 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2570 data->is_unmerged = 1;
2574 same_contents = !oidcmp(&one->oid, &two->oid);
2576 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2577 data->is_binary = 1;
2578 if (same_contents) {
2582 data->added = diff_filespec_size(two);
2583 data->deleted = diff_filespec_size(one);
2587 else if (complete_rewrite) {
2588 diff_populate_filespec(one, 0);
2589 diff_populate_filespec(two, 0);
2590 data->deleted = count_lines(one->data, one->size);
2591 data->added = count_lines(two->data, two->size);
2594 else if (!same_contents) {
2595 /* Crazy xdl interfaces.. */
2599 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2600 die("unable to read files to diff");
2602 memset(&xpp, 0, sizeof(xpp));
2603 memset(&xecfg, 0, sizeof(xecfg));
2604 xpp.flags = o->xdl_opts;
2605 xecfg.ctxlen = o->context;
2606 xecfg.interhunkctxlen = o->interhunkcontext;
2607 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2609 die("unable to generate diffstat for %s", one->path);
2612 diff_free_filespec_data(one);
2613 diff_free_filespec_data(two);
2616 static void builtin_checkdiff(const char *name_a, const char *name_b,
2617 const char *attr_path,
2618 struct diff_filespec *one,
2619 struct diff_filespec *two,
2620 struct diff_options *o)
2623 struct checkdiff_t data;
2628 memset(&data, 0, sizeof(data));
2629 data.filename = name_b ? name_b : name_a;
2632 data.ws_rule = whitespace_rule(attr_path);
2633 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2635 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2636 die("unable to read files to diff");
2639 * All the other codepaths check both sides, but not checking
2640 * the "old" side here is deliberate. We are checking the newly
2641 * introduced changes, and as long as the "new" side is text, we
2642 * can and should check what it introduces.
2644 if (diff_filespec_is_binary(two))
2645 goto free_and_return;
2647 /* Crazy xdl interfaces.. */
2651 memset(&xpp, 0, sizeof(xpp));
2652 memset(&xecfg, 0, sizeof(xecfg));
2653 xecfg.ctxlen = 1; /* at least one context line */
2655 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2657 die("unable to generate checkdiff for %s", one->path);
2659 if (data.ws_rule & WS_BLANK_AT_EOF) {
2660 struct emit_callback ecbdata;
2663 ecbdata.ws_rule = data.ws_rule;
2664 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2665 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2670 err = whitespace_error_string(WS_BLANK_AT_EOF);
2671 fprintf(o->file, "%s:%d: %s.\n",
2672 data.filename, blank_at_eof, err);
2673 data.status = 1; /* report errors */
2678 diff_free_filespec_data(one);
2679 diff_free_filespec_data(two);
2681 DIFF_OPT_SET(o, CHECK_FAILED);
2684 struct diff_filespec *alloc_filespec(const char *path)
2686 struct diff_filespec *spec;
2688 FLEXPTR_ALLOC_STR(spec, path, path);
2690 spec->is_binary = -1;
2694 void free_filespec(struct diff_filespec *spec)
2696 if (!--spec->count) {
2697 diff_free_filespec_data(spec);
2702 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
2703 int oid_valid, unsigned short mode)
2706 spec->mode = canon_mode(mode);
2707 oidcpy(&spec->oid, oid);
2708 spec->oid_valid = oid_valid;
2713 * Given a name and sha1 pair, if the index tells us the file in
2714 * the work tree has that object contents, return true, so that
2715 * prepare_temp_file() does not have to inflate and extract.
2717 static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
2719 const struct cache_entry *ce;
2724 * We do not read the cache ourselves here, because the
2725 * benchmark with my previous version that always reads cache
2726 * shows that it makes things worse for diff-tree comparing
2727 * two linux-2.6 kernel trees in an already checked out work
2728 * tree. This is because most diff-tree comparisons deal with
2729 * only a small number of files, while reading the cache is
2730 * expensive for a large project, and its cost outweighs the
2731 * savings we get by not inflating the object to a temporary
2732 * file. Practically, this code only helps when we are used
2733 * by diff-cache --cached, which does read the cache before
2739 /* We want to avoid the working directory if our caller
2740 * doesn't need the data in a normal file, this system
2741 * is rather slow with its stat/open/mmap/close syscalls,
2742 * and the object is contained in a pack file. The pack
2743 * is probably already open and will be faster to obtain
2744 * the data through than the working directory. Loose
2745 * objects however would tend to be slower as they need
2746 * to be individually opened and inflated.
2748 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
2752 * Similarly, if we'd have to convert the file contents anyway, that
2753 * makes the optimization not worthwhile.
2755 if (!want_file && would_convert_to_git(&the_index, name))
2759 pos = cache_name_pos(name, len);
2762 ce = active_cache[pos];
2765 * This is not the sha1 we are looking for, or
2766 * unreusable because it is not a regular file.
2768 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
2772 * If ce is marked as "assume unchanged", there is no
2773 * guarantee that work tree matches what we are looking for.
2775 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2779 * If ce matches the file in the work tree, we can reuse it.
2781 if (ce_uptodate(ce) ||
2782 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2788 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2790 struct strbuf buf = STRBUF_INIT;
2793 /* Are we looking at the work tree? */
2794 if (s->dirty_submodule)
2797 strbuf_addf(&buf, "Subproject commit %s%s\n",
2798 oid_to_hex(&s->oid), dirty);
2802 strbuf_release(&buf);
2804 s->data = strbuf_detach(&buf, NULL);
2811 * While doing rename detection and pickaxe operation, we may need to
2812 * grab the data for the blob (or file) for our own in-core comparison.
2813 * diff_filespec has data and size fields for this purpose.
2815 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
2817 int size_only = flags & CHECK_SIZE_ONLY;
2820 * demote FAIL to WARN to allow inspecting the situation
2821 * instead of refusing.
2823 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
2827 if (!DIFF_FILE_VALID(s))
2828 die("internal error: asking to populate invalid file.");
2829 if (S_ISDIR(s->mode))
2835 if (size_only && 0 < s->size)
2838 if (S_ISGITLINK(s->mode))
2839 return diff_populate_gitlink(s, size_only);
2841 if (!s->oid_valid ||
2842 reuse_worktree_file(s->path, &s->oid, 0)) {
2843 struct strbuf buf = STRBUF_INIT;
2847 if (lstat(s->path, &st) < 0) {
2848 if (errno == ENOENT) {
2852 s->data = (char *)"";
2857 s->size = xsize_t(st.st_size);
2860 if (S_ISLNK(st.st_mode)) {
2861 struct strbuf sb = STRBUF_INIT;
2863 if (strbuf_readlink(&sb, s->path, s->size))
2866 s->data = strbuf_detach(&sb, NULL);
2872 * Even if the caller would be happy with getting
2873 * only the size, we cannot return early at this
2874 * point if the path requires us to run the content
2877 if (size_only && !would_convert_to_git(&the_index, s->path))
2881 * Note: this check uses xsize_t(st.st_size) that may
2882 * not be the true size of the blob after it goes
2883 * through convert_to_git(). This may not strictly be
2884 * correct, but the whole point of big_file_threshold
2885 * and is_binary check being that we want to avoid
2886 * opening the file and inspecting the contents, this
2889 if ((flags & CHECK_BINARY) &&
2890 s->size > big_file_threshold && s->is_binary == -1) {
2894 fd = open(s->path, O_RDONLY);
2897 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2899 s->should_munmap = 1;
2902 * Convert from working tree format to canonical git format
2904 if (convert_to_git(&the_index, s->path, s->data, s->size, &buf, crlf_warn)) {
2906 munmap(s->data, s->size);
2907 s->should_munmap = 0;
2908 s->data = strbuf_detach(&buf, &size);
2914 enum object_type type;
2915 if (size_only || (flags & CHECK_BINARY)) {
2916 type = sha1_object_info(s->oid.hash, &s->size);
2918 die("unable to read %s",
2919 oid_to_hex(&s->oid));
2922 if (s->size > big_file_threshold && s->is_binary == -1) {
2927 s->data = read_sha1_file(s->oid.hash, &type, &s->size);
2929 die("unable to read %s", oid_to_hex(&s->oid));
2935 void diff_free_filespec_blob(struct diff_filespec *s)
2939 else if (s->should_munmap)
2940 munmap(s->data, s->size);
2942 if (s->should_free || s->should_munmap) {
2943 s->should_free = s->should_munmap = 0;
2948 void diff_free_filespec_data(struct diff_filespec *s)
2950 diff_free_filespec_blob(s);
2951 FREE_AND_NULL(s->cnt_data);
2954 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2957 const struct object_id *oid,
2961 struct strbuf buf = STRBUF_INIT;
2962 struct strbuf template = STRBUF_INIT;
2963 char *path_dup = xstrdup(path);
2964 const char *base = basename(path_dup);
2966 /* Generate "XXXXXX_basename.ext" */
2967 strbuf_addstr(&template, "XXXXXX_");
2968 strbuf_addstr(&template, base);
2970 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
2972 die_errno("unable to create temp-file");
2973 if (convert_to_working_tree(path,
2974 (const char *)blob, (size_t)size, &buf)) {
2978 if (write_in_full(fd, blob, size) != size)
2979 die_errno("unable to write temp-file");
2980 close_tempfile(&temp->tempfile);
2981 temp->name = get_tempfile_path(&temp->tempfile);
2982 oid_to_hex_r(temp->hex, oid);
2983 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
2984 strbuf_release(&buf);
2985 strbuf_release(&template);
2989 static struct diff_tempfile *prepare_temp_file(const char *name,
2990 struct diff_filespec *one)
2992 struct diff_tempfile *temp = claim_diff_tempfile();
2994 if (!DIFF_FILE_VALID(one)) {
2996 /* A '-' entry produces this for file-2, and
2997 * a '+' entry produces this for file-1.
2999 temp->name = "/dev/null";
3000 xsnprintf(temp->hex, sizeof(temp->hex), ".");
3001 xsnprintf(temp->mode, sizeof(temp->mode), ".");
3005 if (!S_ISGITLINK(one->mode) &&
3007 reuse_worktree_file(name, &one->oid, 1))) {
3009 if (lstat(name, &st) < 0) {
3010 if (errno == ENOENT)
3011 goto not_a_valid_file;
3012 die_errno("stat(%s)", name);
3014 if (S_ISLNK(st.st_mode)) {
3015 struct strbuf sb = STRBUF_INIT;
3016 if (strbuf_readlink(&sb, name, st.st_size) < 0)
3017 die_errno("readlink(%s)", name);
3018 prep_temp_blob(name, temp, sb.buf, sb.len,
3020 &one->oid : &null_oid),
3022 one->mode : S_IFLNK));
3023 strbuf_release(&sb);
3026 /* we can borrow from the file in the work tree */
3028 if (!one->oid_valid)
3029 oid_to_hex_r(temp->hex, &null_oid);
3031 oid_to_hex_r(temp->hex, &one->oid);
3032 /* Even though we may sometimes borrow the
3033 * contents from the work tree, we always want
3034 * one->mode. mode is trustworthy even when
3035 * !(one->oid_valid), as long as
3036 * DIFF_FILE_VALID(one).
3038 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
3043 if (diff_populate_filespec(one, 0))
3044 die("cannot read data blob for %s", one->path);
3045 prep_temp_blob(name, temp, one->data, one->size,
3046 &one->oid, one->mode);
3051 static void add_external_diff_name(struct argv_array *argv,
3053 struct diff_filespec *df)
3055 struct diff_tempfile *temp = prepare_temp_file(name, df);
3056 argv_array_push(argv, temp->name);
3057 argv_array_push(argv, temp->hex);
3058 argv_array_push(argv, temp->mode);
3061 /* An external diff command takes:
3063 * diff-cmd name infile1 infile1-sha1 infile1-mode \
3064 * infile2 infile2-sha1 infile2-mode [ rename-to ]
3067 static void run_external_diff(const char *pgm,
3070 struct diff_filespec *one,
3071 struct diff_filespec *two,
3072 const char *xfrm_msg,
3073 int complete_rewrite,
3074 struct diff_options *o)
3076 struct argv_array argv = ARGV_ARRAY_INIT;
3077 struct argv_array env = ARGV_ARRAY_INIT;
3078 struct diff_queue_struct *q = &diff_queued_diff;
3080 argv_array_push(&argv, pgm);
3081 argv_array_push(&argv, name);
3084 add_external_diff_name(&argv, name, one);
3086 add_external_diff_name(&argv, name, two);
3088 add_external_diff_name(&argv, other, two);
3089 argv_array_push(&argv, other);
3090 argv_array_push(&argv, xfrm_msg);
3094 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3095 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3097 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3098 die(_("external diff died, stopping at %s"), name);
3101 argv_array_clear(&argv);
3102 argv_array_clear(&env);
3105 static int similarity_index(struct diff_filepair *p)
3107 return p->score * 100 / MAX_SCORE;
3110 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
3112 if (startup_info->have_repository)
3113 return find_unique_abbrev(oid->hash, abbrev);
3115 char *hex = oid_to_hex(oid);
3117 abbrev = FALLBACK_DEFAULT_ABBREV;
3118 if (abbrev > GIT_SHA1_HEXSZ)
3119 die("BUG: oid abbreviation out of range: %d", abbrev);
3126 static void fill_metainfo(struct strbuf *msg,
3129 struct diff_filespec *one,
3130 struct diff_filespec *two,
3131 struct diff_options *o,
3132 struct diff_filepair *p,
3133 int *must_show_header,
3136 const char *set = diff_get_color(use_color, DIFF_METAINFO);
3137 const char *reset = diff_get_color(use_color, DIFF_RESET);
3138 const char *line_prefix = diff_line_prefix(o);
3140 *must_show_header = 1;
3141 strbuf_init(msg, PATH_MAX * 2 + 300);
3142 switch (p->status) {
3143 case DIFF_STATUS_COPIED:
3144 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3145 line_prefix, set, similarity_index(p));
3146 strbuf_addf(msg, "%s\n%s%scopy from ",
3147 reset, line_prefix, set);
3148 quote_c_style(name, msg, NULL, 0);
3149 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3150 quote_c_style(other, msg, NULL, 0);
3151 strbuf_addf(msg, "%s\n", reset);
3153 case DIFF_STATUS_RENAMED:
3154 strbuf_addf(msg, "%s%ssimilarity index %d%%",
3155 line_prefix, set, similarity_index(p));
3156 strbuf_addf(msg, "%s\n%s%srename from ",
3157 reset, line_prefix, set);
3158 quote_c_style(name, msg, NULL, 0);
3159 strbuf_addf(msg, "%s\n%s%srename to ",
3160 reset, line_prefix, set);
3161 quote_c_style(other, msg, NULL, 0);
3162 strbuf_addf(msg, "%s\n", reset);
3164 case DIFF_STATUS_MODIFIED:
3166 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3168 set, similarity_index(p), reset);
3173 *must_show_header = 0;
3175 if (one && two && oidcmp(&one->oid, &two->oid)) {
3176 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3178 if (DIFF_OPT_TST(o, BINARY)) {
3180 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3181 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3184 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
3185 diff_abbrev_oid(&one->oid, abbrev),
3186 diff_abbrev_oid(&two->oid, abbrev));
3187 if (one->mode == two->mode)
3188 strbuf_addf(msg, " %06o", one->mode);
3189 strbuf_addf(msg, "%s\n", reset);
3193 static void run_diff_cmd(const char *pgm,
3196 const char *attr_path,
3197 struct diff_filespec *one,
3198 struct diff_filespec *two,
3200 struct diff_options *o,
3201 struct diff_filepair *p)
3203 const char *xfrm_msg = NULL;
3204 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3205 int must_show_header = 0;
3208 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3209 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3210 if (drv && drv->external)
3211 pgm = drv->external;
3216 * don't use colors when the header is intended for an
3217 * external diff driver
3219 fill_metainfo(msg, name, other, one, two, o, p,
3221 want_color(o->use_color) && !pgm);
3222 xfrm_msg = msg->len ? msg->buf : NULL;
3226 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3227 complete_rewrite, o);
3231 builtin_diff(name, other ? other : name,
3232 one, two, xfrm_msg, must_show_header,
3233 o, complete_rewrite);
3235 fprintf(o->file, "* Unmerged path %s\n", name);
3238 static void diff_fill_oid_info(struct diff_filespec *one)
3240 if (DIFF_FILE_VALID(one)) {
3241 if (!one->oid_valid) {
3243 if (one->is_stdin) {
3247 if (lstat(one->path, &st) < 0)
3248 die_errno("stat '%s'", one->path);
3249 if (index_path(one->oid.hash, one->path, &st, 0))
3250 die("cannot hash %s", one->path);
3257 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3259 /* Strip the prefix but do not molest /dev/null and absolute paths */
3260 if (*namep && **namep != '/') {
3261 *namep += prefix_length;
3265 if (*otherp && **otherp != '/') {
3266 *otherp += prefix_length;
3267 if (**otherp == '/')
3272 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3274 const char *pgm = external_diff();
3276 struct diff_filespec *one = p->one;
3277 struct diff_filespec *two = p->two;
3280 const char *attr_path;
3282 name = p->one->path;
3283 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3285 if (o->prefix_length)
3286 strip_prefix(o->prefix_length, &name, &other);
3288 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3291 if (DIFF_PAIR_UNMERGED(p)) {
3292 run_diff_cmd(pgm, name, NULL, attr_path,
3293 NULL, NULL, NULL, o, p);
3297 diff_fill_oid_info(one);
3298 diff_fill_oid_info(two);
3301 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3302 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3304 * a filepair that changes between file and symlink
3305 * needs to be split into deletion and creation.
3307 struct diff_filespec *null = alloc_filespec(two->path);
3308 run_diff_cmd(NULL, name, other, attr_path,
3309 one, null, &msg, o, p);
3311 strbuf_release(&msg);
3313 null = alloc_filespec(one->path);
3314 run_diff_cmd(NULL, name, other, attr_path,
3315 null, two, &msg, o, p);
3319 run_diff_cmd(pgm, name, other, attr_path,
3320 one, two, &msg, o, p);
3322 strbuf_release(&msg);
3325 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3326 struct diffstat_t *diffstat)
3331 if (DIFF_PAIR_UNMERGED(p)) {
3333 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3337 name = p->one->path;
3338 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3340 if (o->prefix_length)
3341 strip_prefix(o->prefix_length, &name, &other);
3343 diff_fill_oid_info(p->one);
3344 diff_fill_oid_info(p->two);
3346 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3349 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3353 const char *attr_path;
3355 if (DIFF_PAIR_UNMERGED(p)) {
3360 name = p->one->path;
3361 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3362 attr_path = other ? other : name;
3364 if (o->prefix_length)
3365 strip_prefix(o->prefix_length, &name, &other);
3367 diff_fill_oid_info(p->one);
3368 diff_fill_oid_info(p->two);
3370 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3373 void diff_setup(struct diff_options *options)
3375 memcpy(options, &default_diff_options, sizeof(*options));
3377 options->file = stdout;
3379 options->abbrev = DEFAULT_ABBREV;
3380 options->line_termination = '\n';
3381 options->break_opt = -1;
3382 options->rename_limit = -1;
3383 options->dirstat_permille = diff_dirstat_permille_default;
3384 options->context = diff_context_default;
3385 options->interhunkcontext = diff_interhunk_context_default;
3386 options->ws_error_highlight = ws_error_highlight_default;
3387 DIFF_OPT_SET(options, RENAME_EMPTY);
3389 /* pathchange left =NULL by default */
3390 options->change = diff_change;
3391 options->add_remove = diff_addremove;
3392 options->use_color = diff_use_color_default;
3393 options->detect_rename = diff_detect_rename_default;
3394 options->xdl_opts |= diff_algorithm;
3395 if (diff_indent_heuristic)
3396 DIFF_XDL_SET(options, INDENT_HEURISTIC);
3398 options->orderfile = diff_order_file_cfg;
3400 if (diff_no_prefix) {
3401 options->a_prefix = options->b_prefix = "";
3402 } else if (!diff_mnemonic_prefix) {
3403 options->a_prefix = "a/";
3404 options->b_prefix = "b/";
3408 void diff_setup_done(struct diff_options *options)
3412 if (options->set_default)
3413 options->set_default(options);
3415 if (options->output_format & DIFF_FORMAT_NAME)
3417 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3419 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3421 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3424 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
3427 * Most of the time we can say "there are changes"
3428 * only by checking if there are changed paths, but
3429 * --ignore-whitespace* options force us to look
3433 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3434 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3435 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3436 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3438 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3440 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3441 options->detect_rename = DIFF_DETECT_COPY;
3443 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3444 options->prefix = NULL;
3445 if (options->prefix)
3446 options->prefix_length = strlen(options->prefix);
3448 options->prefix_length = 0;
3450 if (options->output_format & (DIFF_FORMAT_NAME |
3451 DIFF_FORMAT_NAME_STATUS |
3452 DIFF_FORMAT_CHECKDIFF |
3453 DIFF_FORMAT_NO_OUTPUT))
3454 options->output_format &= ~(DIFF_FORMAT_RAW |
3455 DIFF_FORMAT_NUMSTAT |
3456 DIFF_FORMAT_DIFFSTAT |
3457 DIFF_FORMAT_SHORTSTAT |
3458 DIFF_FORMAT_DIRSTAT |
3459 DIFF_FORMAT_SUMMARY |
3463 * These cases always need recursive; we do not drop caller-supplied
3464 * recursive bits for other formats here.
3466 if (options->output_format & (DIFF_FORMAT_PATCH |
3467 DIFF_FORMAT_NUMSTAT |
3468 DIFF_FORMAT_DIFFSTAT |
3469 DIFF_FORMAT_SHORTSTAT |
3470 DIFF_FORMAT_DIRSTAT |
3471 DIFF_FORMAT_SUMMARY |
3472 DIFF_FORMAT_CHECKDIFF))
3473 DIFF_OPT_SET(options, RECURSIVE);
3475 * Also pickaxe would not work very well if you do not say recursive
3477 if (options->pickaxe)
3478 DIFF_OPT_SET(options, RECURSIVE);
3480 * When patches are generated, submodules diffed against the work tree
3481 * must be checked for dirtiness too so it can be shown in the output
3483 if (options->output_format & DIFF_FORMAT_PATCH)
3484 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3486 if (options->detect_rename && options->rename_limit < 0)
3487 options->rename_limit = diff_rename_limit_default;
3488 if (options->setup & DIFF_SETUP_USE_CACHE) {
3490 /* read-cache does not die even when it fails
3491 * so it is safe for us to do this here. Also
3492 * it does not smudge active_cache or active_nr
3493 * when it fails, so we do not have to worry about
3494 * cleaning it up ourselves either.
3498 if (40 < options->abbrev)
3499 options->abbrev = 40; /* full */
3502 * It does not make sense to show the first hit we happened
3503 * to have found. It does not make sense not to return with
3504 * exit code in such a case either.
3506 if (DIFF_OPT_TST(options, QUICK)) {
3507 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3508 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3511 options->diff_path_counter = 0;
3513 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3514 die(_("--follow requires exactly one pathspec"));
3517 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3527 if (c == arg_short) {
3531 if (val && isdigit(c)) {
3533 int n = strtoul(arg, &end, 10);
3544 eq = strchrnul(arg, '=');
3546 if (!len || strncmp(arg, arg_long, len))
3551 if (!isdigit(*++eq))
3553 n = strtoul(eq, &end, 10);
3561 static int diff_scoreopt_parse(const char *opt);
3563 static inline int short_opt(char opt, const char **argv,
3564 const char **optarg)
3566 const char *arg = argv[0];
3567 if (arg[0] != '-' || arg[1] != opt)
3569 if (arg[2] != '\0') {
3574 die("Option '%c' requires a value", opt);
3579 int parse_long_opt(const char *opt, const char **argv,
3580 const char **optarg)
3582 const char *arg = argv[0];
3583 if (!skip_prefix(arg, "--", &arg))
3585 if (!skip_prefix(arg, opt, &arg))
3587 if (*arg == '=') { /* stuck form: --option=value */
3593 /* separate form: --option value */
3595 die("Option '--%s' requires a value", opt);
3600 static int stat_opt(struct diff_options *options, const char **av)
3602 const char *arg = av[0];
3604 int width = options->stat_width;
3605 int name_width = options->stat_name_width;
3606 int graph_width = options->stat_graph_width;
3607 int count = options->stat_count;
3610 if (!skip_prefix(arg, "--stat", &arg))
3611 die("BUG: stat option does not begin with --stat: %s", arg);
3616 if (skip_prefix(arg, "-width", &arg)) {
3618 width = strtoul(arg + 1, &end, 10);
3619 else if (!*arg && !av[1])
3620 die_want_option("--stat-width");
3622 width = strtoul(av[1], &end, 10);
3625 } else if (skip_prefix(arg, "-name-width", &arg)) {
3627 name_width = strtoul(arg + 1, &end, 10);
3628 else if (!*arg && !av[1])
3629 die_want_option("--stat-name-width");
3631 name_width = strtoul(av[1], &end, 10);
3634 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3636 graph_width = strtoul(arg + 1, &end, 10);
3637 else if (!*arg && !av[1])
3638 die_want_option("--stat-graph-width");
3640 graph_width = strtoul(av[1], &end, 10);
3643 } else if (skip_prefix(arg, "-count", &arg)) {
3645 count = strtoul(arg + 1, &end, 10);
3646 else if (!*arg && !av[1])
3647 die_want_option("--stat-count");
3649 count = strtoul(av[1], &end, 10);
3655 width = strtoul(arg+1, &end, 10);
3657 name_width = strtoul(end+1, &end, 10);
3659 count = strtoul(end+1, &end, 10);
3662 /* Important! This checks all the error cases! */
3665 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3666 options->stat_name_width = name_width;
3667 options->stat_graph_width = graph_width;
3668 options->stat_width = width;
3669 options->stat_count = count;
3673 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3675 struct strbuf errmsg = STRBUF_INIT;
3676 if (parse_dirstat_params(options, params, &errmsg))
3677 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3679 strbuf_release(&errmsg);
3681 * The caller knows a dirstat-related option is given from the command
3682 * line; allow it to say "return this_function();"
3684 options->output_format |= DIFF_FORMAT_DIRSTAT;
3688 static int parse_submodule_opt(struct diff_options *options, const char *value)
3690 if (parse_submodule_params(options, value))
3691 die(_("Failed to parse --submodule option parameter: '%s'"),
3696 static const char diff_status_letters[] = {
3699 DIFF_STATUS_DELETED,
3700 DIFF_STATUS_MODIFIED,
3701 DIFF_STATUS_RENAMED,
3702 DIFF_STATUS_TYPE_CHANGED,
3703 DIFF_STATUS_UNKNOWN,
3704 DIFF_STATUS_UNMERGED,
3705 DIFF_STATUS_FILTER_AON,
3706 DIFF_STATUS_FILTER_BROKEN,
3710 static unsigned int filter_bit['Z' + 1];
3712 static void prepare_filter_bits(void)
3716 if (!filter_bit[DIFF_STATUS_ADDED]) {
3717 for (i = 0; diff_status_letters[i]; i++)
3718 filter_bit[(int) diff_status_letters[i]] = (1 << i);
3722 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
3724 return opt->filter & filter_bit[(int) status];
3727 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
3731 prepare_filter_bits();
3734 * If there is a negation e.g. 'd' in the input, and we haven't
3735 * initialized the filter field with another --diff-filter, start
3736 * from full set of bits, except for AON.
3739 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3740 if (optch < 'a' || 'z' < optch)
3742 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
3743 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
3748 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3752 if ('a' <= optch && optch <= 'z') {
3754 optch = toupper(optch);
3759 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
3763 opt->filter &= ~bit;
3770 static void enable_patch_output(int *fmt) {
3771 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
3772 *fmt |= DIFF_FORMAT_PATCH;
3775 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
3777 int val = parse_ws_error_highlight(arg);
3780 error("unknown value after ws-error-highlight=%.*s",
3784 opt->ws_error_highlight = val;
3788 int diff_opt_parse(struct diff_options *options,
3789 const char **av, int ac, const char *prefix)
3791 const char *arg = av[0];
3798 /* Output format options */
3799 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
3800 || opt_arg(arg, 'U', "unified", &options->context))
3801 enable_patch_output(&options->output_format);
3802 else if (!strcmp(arg, "--raw"))
3803 options->output_format |= DIFF_FORMAT_RAW;
3804 else if (!strcmp(arg, "--patch-with-raw")) {
3805 enable_patch_output(&options->output_format);
3806 options->output_format |= DIFF_FORMAT_RAW;
3807 } else if (!strcmp(arg, "--numstat"))
3808 options->output_format |= DIFF_FORMAT_NUMSTAT;
3809 else if (!strcmp(arg, "--shortstat"))
3810 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3811 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3812 return parse_dirstat_opt(options, "");
3813 else if (skip_prefix(arg, "-X", &arg))
3814 return parse_dirstat_opt(options, arg);
3815 else if (skip_prefix(arg, "--dirstat=", &arg))
3816 return parse_dirstat_opt(options, arg);
3817 else if (!strcmp(arg, "--cumulative"))
3818 return parse_dirstat_opt(options, "cumulative");
3819 else if (!strcmp(arg, "--dirstat-by-file"))
3820 return parse_dirstat_opt(options, "files");
3821 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
3822 parse_dirstat_opt(options, "files");
3823 return parse_dirstat_opt(options, arg);
3825 else if (!strcmp(arg, "--check"))
3826 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3827 else if (!strcmp(arg, "--summary"))
3828 options->output_format |= DIFF_FORMAT_SUMMARY;
3829 else if (!strcmp(arg, "--patch-with-stat")) {
3830 enable_patch_output(&options->output_format);
3831 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3832 } else if (!strcmp(arg, "--name-only"))
3833 options->output_format |= DIFF_FORMAT_NAME;
3834 else if (!strcmp(arg, "--name-status"))
3835 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3836 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
3837 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3838 else if (starts_with(arg, "--stat"))
3839 /* --stat, --stat-width, --stat-name-width, or --stat-count */
3840 return stat_opt(options, av);
3842 /* renames options */
3843 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
3844 !strcmp(arg, "--break-rewrites")) {
3845 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3846 return error("invalid argument to -B: %s", arg+2);
3848 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
3849 !strcmp(arg, "--find-renames")) {
3850 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3851 return error("invalid argument to -M: %s", arg+2);
3852 options->detect_rename = DIFF_DETECT_RENAME;
3854 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3855 options->irreversible_delete = 1;
3857 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
3858 !strcmp(arg, "--find-copies")) {
3859 if (options->detect_rename == DIFF_DETECT_COPY)
3860 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3861 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3862 return error("invalid argument to -C: %s", arg+2);
3863 options->detect_rename = DIFF_DETECT_COPY;
3865 else if (!strcmp(arg, "--no-renames"))
3866 options->detect_rename = 0;
3867 else if (!strcmp(arg, "--rename-empty"))
3868 DIFF_OPT_SET(options, RENAME_EMPTY);
3869 else if (!strcmp(arg, "--no-rename-empty"))
3870 DIFF_OPT_CLR(options, RENAME_EMPTY);
3871 else if (!strcmp(arg, "--relative"))
3872 DIFF_OPT_SET(options, RELATIVE_NAME);
3873 else if (skip_prefix(arg, "--relative=", &arg)) {
3874 DIFF_OPT_SET(options, RELATIVE_NAME);
3875 options->prefix = arg;
3879 else if (!strcmp(arg, "--minimal"))
3880 DIFF_XDL_SET(options, NEED_MINIMAL);
3881 else if (!strcmp(arg, "--no-minimal"))
3882 DIFF_XDL_CLR(options, NEED_MINIMAL);
3883 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3884 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3885 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3886 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3887 else if (!strcmp(arg, "--ignore-space-at-eol"))
3888 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3889 else if (!strcmp(arg, "--ignore-blank-lines"))
3890 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
3891 else if (!strcmp(arg, "--indent-heuristic"))
3892 DIFF_XDL_SET(options, INDENT_HEURISTIC);
3893 else if (!strcmp(arg, "--no-indent-heuristic"))
3894 DIFF_XDL_CLR(options, INDENT_HEURISTIC);
3895 else if (!strcmp(arg, "--patience"))
3896 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
3897 else if (!strcmp(arg, "--histogram"))
3898 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
3899 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
3900 long value = parse_algorithm_value(optarg);
3902 return error("option diff-algorithm accepts \"myers\", "
3903 "\"minimal\", \"patience\" and \"histogram\"");
3904 /* clear out previous settings */
3905 DIFF_XDL_CLR(options, NEED_MINIMAL);
3906 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3907 options->xdl_opts |= value;
3912 else if (!strcmp(arg, "--binary")) {
3913 enable_patch_output(&options->output_format);
3914 DIFF_OPT_SET(options, BINARY);
3916 else if (!strcmp(arg, "--full-index"))
3917 DIFF_OPT_SET(options, FULL_INDEX);
3918 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3919 DIFF_OPT_SET(options, TEXT);
3920 else if (!strcmp(arg, "-R"))
3921 DIFF_OPT_SET(options, REVERSE_DIFF);
3922 else if (!strcmp(arg, "--find-copies-harder"))
3923 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3924 else if (!strcmp(arg, "--follow"))
3925 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3926 else if (!strcmp(arg, "--no-follow")) {
3927 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
3928 DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
3929 } else if (!strcmp(arg, "--color"))
3930 options->use_color = 1;
3931 else if (skip_prefix(arg, "--color=", &arg)) {
3932 int value = git_config_colorbool(NULL, arg);
3934 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3935 options->use_color = value;
3937 else if (!strcmp(arg, "--no-color"))
3938 options->use_color = 0;
3939 else if (!strcmp(arg, "--color-words")) {
3940 options->use_color = 1;
3941 options->word_diff = DIFF_WORDS_COLOR;
3943 else if (skip_prefix(arg, "--color-words=", &arg)) {
3944 options->use_color = 1;
3945 options->word_diff = DIFF_WORDS_COLOR;
3946 options->word_regex = arg;
3948 else if (!strcmp(arg, "--word-diff")) {
3949 if (options->word_diff == DIFF_WORDS_NONE)
3950 options->word_diff = DIFF_WORDS_PLAIN;
3952 else if (skip_prefix(arg, "--word-diff=", &arg)) {
3953 if (!strcmp(arg, "plain"))
3954 options->word_diff = DIFF_WORDS_PLAIN;
3955 else if (!strcmp(arg, "color")) {
3956 options->use_color = 1;
3957 options->word_diff = DIFF_WORDS_COLOR;
3959 else if (!strcmp(arg, "porcelain"))
3960 options->word_diff = DIFF_WORDS_PORCELAIN;
3961 else if (!strcmp(arg, "none"))
3962 options->word_diff = DIFF_WORDS_NONE;
3964 die("bad --word-diff argument: %s", arg);
3966 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3967 if (options->word_diff == DIFF_WORDS_NONE)
3968 options->word_diff = DIFF_WORDS_PLAIN;
3969 options->word_regex = optarg;
3972 else if (!strcmp(arg, "--exit-code"))
3973 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3974 else if (!strcmp(arg, "--quiet"))
3975 DIFF_OPT_SET(options, QUICK);
3976 else if (!strcmp(arg, "--ext-diff"))
3977 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3978 else if (!strcmp(arg, "--no-ext-diff"))
3979 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3980 else if (!strcmp(arg, "--textconv"))
3981 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3982 else if (!strcmp(arg, "--no-textconv"))
3983 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3984 else if (!strcmp(arg, "--ignore-submodules")) {
3985 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3986 handle_ignore_submodules_arg(options, "all");
3987 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
3988 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3989 handle_ignore_submodules_arg(options, arg);
3990 } else if (!strcmp(arg, "--submodule"))
3991 options->submodule_format = DIFF_SUBMODULE_LOG;
3992 else if (skip_prefix(arg, "--submodule=", &arg))
3993 return parse_submodule_opt(options, arg);
3994 else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
3995 return parse_ws_error_highlight_opt(options, arg);
3996 else if (!strcmp(arg, "--ita-invisible-in-index"))
3997 options->ita_invisible_in_index = 1;
3998 else if (!strcmp(arg, "--ita-visible-in-index"))
3999 options->ita_invisible_in_index = 0;
4002 else if (!strcmp(arg, "-z"))
4003 options->line_termination = 0;
4004 else if ((argcount = short_opt('l', av, &optarg))) {
4005 options->rename_limit = strtoul(optarg, NULL, 10);
4008 else if ((argcount = short_opt('S', av, &optarg))) {
4009 options->pickaxe = optarg;
4010 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
4012 } else if ((argcount = short_opt('G', av, &optarg))) {
4013 options->pickaxe = optarg;
4014 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
4017 else if (!strcmp(arg, "--pickaxe-all"))
4018 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
4019 else if (!strcmp(arg, "--pickaxe-regex"))
4020 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
4021 else if ((argcount = short_opt('O', av, &optarg))) {
4022 options->orderfile = prefix_filename(prefix, optarg);
4025 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
4026 int offending = parse_diff_filter_opt(optarg, options);
4028 die("unknown change class '%c' in --diff-filter=%s",
4032 else if (!strcmp(arg, "--no-abbrev"))
4033 options->abbrev = 0;
4034 else if (!strcmp(arg, "--abbrev"))
4035 options->abbrev = DEFAULT_ABBREV;
4036 else if (skip_prefix(arg, "--abbrev=", &arg)) {
4037 options->abbrev = strtoul(arg, NULL, 10);
4038 if (options->abbrev < MINIMUM_ABBREV)
4039 options->abbrev = MINIMUM_ABBREV;
4040 else if (40 < options->abbrev)
4041 options->abbrev = 40;
4043 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
4044 options->a_prefix = optarg;
4047 else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
4048 options->line_prefix = optarg;
4049 options->line_prefix_length = strlen(options->line_prefix);
4050 graph_setup_line_prefix(options);
4053 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
4054 options->b_prefix = optarg;
4057 else if (!strcmp(arg, "--no-prefix"))
4058 options->a_prefix = options->b_prefix = "";
4059 else if (opt_arg(arg, '\0', "inter-hunk-context",
4060 &options->interhunkcontext))
4062 else if (!strcmp(arg, "-W"))
4063 DIFF_OPT_SET(options, FUNCCONTEXT);
4064 else if (!strcmp(arg, "--function-context"))
4065 DIFF_OPT_SET(options, FUNCCONTEXT);
4066 else if (!strcmp(arg, "--no-function-context"))
4067 DIFF_OPT_CLR(options, FUNCCONTEXT);
4068 else if ((argcount = parse_long_opt("output", av, &optarg))) {
4069 char *path = prefix_filename(prefix, optarg);
4070 options->file = xfopen(path, "w");
4071 options->close_file = 1;
4072 if (options->use_color != GIT_COLOR_ALWAYS)
4073 options->use_color = GIT_COLOR_NEVER;
4081 int parse_rename_score(const char **cp_p)
4083 unsigned long num, scale;
4085 const char *cp = *cp_p;
4092 if ( !dot && ch == '.' ) {
4095 } else if ( ch == '%' ) {
4096 scale = dot ? scale*100 : 100;
4097 cp++; /* % is always at the end */
4099 } else if ( ch >= '0' && ch <= '9' ) {
4100 if ( scale < 100000 ) {
4102 num = (num*10) + (ch-'0');
4111 /* user says num divided by scale and we say internally that
4112 * is MAX_SCORE * num / scale.
4114 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4117 static int diff_scoreopt_parse(const char *opt)
4119 int opt1, opt2, cmd;
4125 /* convert the long-form arguments into short-form versions */
4126 if (skip_prefix(opt, "break-rewrites", &opt)) {
4127 if (*opt == 0 || *opt++ == '=')
4129 } else if (skip_prefix(opt, "find-copies", &opt)) {
4130 if (*opt == 0 || *opt++ == '=')
4132 } else if (skip_prefix(opt, "find-renames", &opt)) {
4133 if (*opt == 0 || *opt++ == '=')
4137 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4138 return -1; /* that is not a -M, -C, or -B option */
4140 opt1 = parse_rename_score(&opt);
4146 else if (*opt != '/')
4147 return -1; /* we expect -B80/99 or -B80 */
4150 opt2 = parse_rename_score(&opt);
4155 return opt1 | (opt2 << 16);
4158 struct diff_queue_struct diff_queued_diff;
4160 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4162 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4163 queue->queue[queue->nr++] = dp;
4166 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4167 struct diff_filespec *one,
4168 struct diff_filespec *two)
4170 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4178 void diff_free_filepair(struct diff_filepair *p)
4180 free_filespec(p->one);
4181 free_filespec(p->two);
4185 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
4190 if (len == GIT_SHA1_HEXSZ)
4191 return oid_to_hex(oid);
4193 abbrev = diff_abbrev_oid(oid, len);
4194 abblen = strlen(abbrev);
4197 * In well-behaved cases, where the abbbreviated result is the
4198 * same as the requested length, append three dots after the
4199 * abbreviation (hence the whole logic is limited to the case
4200 * where abblen < 37); when the actual abbreviated result is a
4201 * bit longer than the requested length, we reduce the number
4202 * of dots so that they match the well-behaved ones. However,
4203 * if the actual abbreviation is longer than the requested
4204 * length by more than three, we give up on aligning, and add
4205 * three dots anyway, to indicate that the output is not the
4206 * full object name. Yes, this may be suboptimal, but this
4207 * appears only in "diff --raw --abbrev" output and it is not
4208 * worth the effort to change it now. Note that this would
4209 * likely to work fine when the automatic sizing of default
4210 * abbreviation length is used--we would be fed -1 in "len" in
4211 * that case, and will end up always appending three-dots, but
4212 * the automatic sizing is supposed to give abblen that ensures
4213 * uniqueness across all objects (statistically speaking).
4215 if (abblen < GIT_SHA1_HEXSZ - 3) {
4216 static char hex[GIT_MAX_HEXSZ + 1];
4217 if (len < abblen && abblen <= len + 2)
4218 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4220 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4224 return oid_to_hex(oid);
4227 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4229 int line_termination = opt->line_termination;
4230 int inter_name_termination = line_termination ? '\t' : '\0';
4232 fprintf(opt->file, "%s", diff_line_prefix(opt));
4233 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4234 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4235 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
4236 fprintf(opt->file, "%s ",
4237 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
4240 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4241 inter_name_termination);
4243 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4246 if (p->status == DIFF_STATUS_COPIED ||
4247 p->status == DIFF_STATUS_RENAMED) {
4248 const char *name_a, *name_b;
4249 name_a = p->one->path;
4250 name_b = p->two->path;
4251 strip_prefix(opt->prefix_length, &name_a, &name_b);
4252 write_name_quoted(name_a, opt->file, inter_name_termination);
4253 write_name_quoted(name_b, opt->file, line_termination);
4255 const char *name_a, *name_b;
4256 name_a = p->one->mode ? p->one->path : p->two->path;
4258 strip_prefix(opt->prefix_length, &name_a, &name_b);
4259 write_name_quoted(name_a, opt->file, line_termination);
4263 int diff_unmodified_pair(struct diff_filepair *p)
4265 /* This function is written stricter than necessary to support
4266 * the currently implemented transformers, but the idea is to
4267 * let transformers to produce diff_filepairs any way they want,
4268 * and filter and clean them up here before producing the output.
4270 struct diff_filespec *one = p->one, *two = p->two;
4272 if (DIFF_PAIR_UNMERGED(p))
4273 return 0; /* unmerged is interesting */
4275 /* deletion, addition, mode or type change
4276 * and rename are all interesting.
4278 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4279 DIFF_PAIR_MODE_CHANGED(p) ||
4280 strcmp(one->path, two->path))
4283 /* both are valid and point at the same path. that is, we are
4284 * dealing with a change.
4286 if (one->oid_valid && two->oid_valid &&
4287 !oidcmp(&one->oid, &two->oid) &&
4288 !one->dirty_submodule && !two->dirty_submodule)
4289 return 1; /* no change */
4290 if (!one->oid_valid && !two->oid_valid)
4291 return 1; /* both look at the same file on the filesystem. */
4295 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4297 if (diff_unmodified_pair(p))
4300 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4301 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4302 return; /* no tree diffs in patch format */
4307 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4308 struct diffstat_t *diffstat)
4310 if (diff_unmodified_pair(p))
4313 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4314 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4315 return; /* no useful stat for tree diffs */
4317 run_diffstat(p, o, diffstat);
4320 static void diff_flush_checkdiff(struct diff_filepair *p,
4321 struct diff_options *o)
4323 if (diff_unmodified_pair(p))
4326 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4327 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4328 return; /* nothing to check in tree diffs */
4330 run_checkdiff(p, o);
4333 int diff_queue_is_empty(void)
4335 struct diff_queue_struct *q = &diff_queued_diff;
4337 for (i = 0; i < q->nr; i++)
4338 if (!diff_unmodified_pair(q->queue[i]))
4344 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4346 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4349 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4351 s->oid_valid ? oid_to_hex(&s->oid) : "");
4352 fprintf(stderr, "queue[%d] %s size %lu\n",
4357 void diff_debug_filepair(const struct diff_filepair *p, int i)
4359 diff_debug_filespec(p->one, i, "one");
4360 diff_debug_filespec(p->two, i, "two");
4361 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4362 p->score, p->status ? p->status : '?',
4363 p->one->rename_used, p->broken_pair);
4366 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4370 fprintf(stderr, "%s\n", msg);
4371 fprintf(stderr, "q->nr = %d\n", q->nr);
4372 for (i = 0; i < q->nr; i++) {
4373 struct diff_filepair *p = q->queue[i];
4374 diff_debug_filepair(p, i);
4379 static void diff_resolve_rename_copy(void)
4382 struct diff_filepair *p;
4383 struct diff_queue_struct *q = &diff_queued_diff;
4385 diff_debug_queue("resolve-rename-copy", q);
4387 for (i = 0; i < q->nr; i++) {
4389 p->status = 0; /* undecided */
4390 if (DIFF_PAIR_UNMERGED(p))
4391 p->status = DIFF_STATUS_UNMERGED;
4392 else if (!DIFF_FILE_VALID(p->one))
4393 p->status = DIFF_STATUS_ADDED;
4394 else if (!DIFF_FILE_VALID(p->two))
4395 p->status = DIFF_STATUS_DELETED;
4396 else if (DIFF_PAIR_TYPE_CHANGED(p))
4397 p->status = DIFF_STATUS_TYPE_CHANGED;
4399 /* from this point on, we are dealing with a pair
4400 * whose both sides are valid and of the same type, i.e.
4401 * either in-place edit or rename/copy edit.
4403 else if (DIFF_PAIR_RENAME(p)) {
4405 * A rename might have re-connected a broken
4406 * pair up, causing the pathnames to be the
4407 * same again. If so, that's not a rename at
4408 * all, just a modification..
4410 * Otherwise, see if this source was used for
4411 * multiple renames, in which case we decrement
4412 * the count, and call it a copy.
4414 if (!strcmp(p->one->path, p->two->path))
4415 p->status = DIFF_STATUS_MODIFIED;
4416 else if (--p->one->rename_used > 0)
4417 p->status = DIFF_STATUS_COPIED;
4419 p->status = DIFF_STATUS_RENAMED;
4421 else if (oidcmp(&p->one->oid, &p->two->oid) ||
4422 p->one->mode != p->two->mode ||
4423 p->one->dirty_submodule ||
4424 p->two->dirty_submodule ||
4425 is_null_oid(&p->one->oid))
4426 p->status = DIFF_STATUS_MODIFIED;
4428 /* This is a "no-change" entry and should not
4429 * happen anymore, but prepare for broken callers.
4431 error("feeding unmodified %s to diffcore",
4433 p->status = DIFF_STATUS_UNKNOWN;
4436 diff_debug_queue("resolve-rename-copy done", q);
4439 static int check_pair_status(struct diff_filepair *p)
4441 switch (p->status) {
4442 case DIFF_STATUS_UNKNOWN:
4445 die("internal error in diff-resolve-rename-copy");
4451 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4453 int fmt = opt->output_format;
4455 if (fmt & DIFF_FORMAT_CHECKDIFF)
4456 diff_flush_checkdiff(p, opt);
4457 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4458 diff_flush_raw(p, opt);
4459 else if (fmt & DIFF_FORMAT_NAME) {
4460 const char *name_a, *name_b;
4461 name_a = p->two->path;
4463 strip_prefix(opt->prefix_length, &name_a, &name_b);
4464 fprintf(opt->file, "%s", diff_line_prefix(opt));
4465 write_name_quoted(name_a, opt->file, opt->line_termination);
4469 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4472 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4474 fprintf(file, " %s ", newdelete);
4475 write_name_quoted(fs->path, file, '\n');
4479 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4480 const char *line_prefix)
4482 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4483 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4484 p->two->mode, show_name ? ' ' : '\n');
4486 write_name_quoted(p->two->path, file, '\n');
4491 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4492 const char *line_prefix)
4494 char *names = pprint_rename(p->one->path, p->two->path);
4496 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4498 show_mode_change(file, p, 0, line_prefix);
4501 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4503 FILE *file = opt->file;
4504 const char *line_prefix = diff_line_prefix(opt);
4507 case DIFF_STATUS_DELETED:
4508 fputs(line_prefix, file);
4509 show_file_mode_name(file, "delete", p->one);
4511 case DIFF_STATUS_ADDED:
4512 fputs(line_prefix, file);
4513 show_file_mode_name(file, "create", p->two);
4515 case DIFF_STATUS_COPIED:
4516 fputs(line_prefix, file);
4517 show_rename_copy(file, "copy", p, line_prefix);
4519 case DIFF_STATUS_RENAMED:
4520 fputs(line_prefix, file);
4521 show_rename_copy(file, "rename", p, line_prefix);
4525 fprintf(file, "%s rewrite ", line_prefix);
4526 write_name_quoted(p->two->path, file, ' ');
4527 fprintf(file, "(%d%%)\n", similarity_index(p));
4529 show_mode_change(file, p, !p->score, line_prefix);
4539 static int remove_space(char *line, int len)
4545 for (i = 0; i < len; i++)
4546 if (!isspace((c = line[i])))
4552 static void patch_id_consume(void *priv, char *line, unsigned long len)
4554 struct patch_id_t *data = priv;
4557 /* Ignore line numbers when computing the SHA1 of the patch */
4558 if (starts_with(line, "@@ -"))
4561 new_len = remove_space(line, len);
4563 git_SHA1_Update(data->ctx, line, new_len);
4564 data->patchlen += new_len;
4567 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
4569 git_SHA1_Update(ctx, str, strlen(str));
4572 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
4574 /* large enough for 2^32 in octal */
4576 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
4577 git_SHA1_Update(ctx, buf, len);
4580 /* returns 0 upon success, and writes result into sha1 */
4581 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
4583 struct diff_queue_struct *q = &diff_queued_diff;
4586 struct patch_id_t data;
4588 git_SHA1_Init(&ctx);
4589 memset(&data, 0, sizeof(struct patch_id_t));
4592 for (i = 0; i < q->nr; i++) {
4596 struct diff_filepair *p = q->queue[i];
4599 memset(&xpp, 0, sizeof(xpp));
4600 memset(&xecfg, 0, sizeof(xecfg));
4602 return error("internal diff status error");
4603 if (p->status == DIFF_STATUS_UNKNOWN)
4605 if (diff_unmodified_pair(p))
4607 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4608 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4610 if (DIFF_PAIR_UNMERGED(p))
4613 diff_fill_oid_info(p->one);
4614 diff_fill_oid_info(p->two);
4616 len1 = remove_space(p->one->path, strlen(p->one->path));
4617 len2 = remove_space(p->two->path, strlen(p->two->path));
4618 patch_id_add_string(&ctx, "diff--git");
4619 patch_id_add_string(&ctx, "a/");
4620 git_SHA1_Update(&ctx, p->one->path, len1);
4621 patch_id_add_string(&ctx, "b/");
4622 git_SHA1_Update(&ctx, p->two->path, len2);
4624 if (p->one->mode == 0) {
4625 patch_id_add_string(&ctx, "newfilemode");
4626 patch_id_add_mode(&ctx, p->two->mode);
4627 patch_id_add_string(&ctx, "---/dev/null");
4628 patch_id_add_string(&ctx, "+++b/");
4629 git_SHA1_Update(&ctx, p->two->path, len2);
4630 } else if (p->two->mode == 0) {
4631 patch_id_add_string(&ctx, "deletedfilemode");
4632 patch_id_add_mode(&ctx, p->one->mode);
4633 patch_id_add_string(&ctx, "---a/");
4634 git_SHA1_Update(&ctx, p->one->path, len1);
4635 patch_id_add_string(&ctx, "+++/dev/null");
4637 patch_id_add_string(&ctx, "---a/");
4638 git_SHA1_Update(&ctx, p->one->path, len1);
4639 patch_id_add_string(&ctx, "+++b/");
4640 git_SHA1_Update(&ctx, p->two->path, len2);
4643 if (diff_header_only)
4646 if (fill_mmfile(&mf1, p->one) < 0 ||
4647 fill_mmfile(&mf2, p->two) < 0)
4648 return error("unable to read files to diff");
4650 if (diff_filespec_is_binary(p->one) ||
4651 diff_filespec_is_binary(p->two)) {
4652 git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
4654 git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
4662 if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4664 return error("unable to generate patch-id diff for %s",
4668 git_SHA1_Final(oid->hash, &ctx);
4672 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
4674 struct diff_queue_struct *q = &diff_queued_diff;
4676 int result = diff_get_patch_id(options, oid, diff_header_only);
4678 for (i = 0; i < q->nr; i++)
4679 diff_free_filepair(q->queue[i]);
4682 DIFF_QUEUE_CLEAR(q);
4687 static int is_summary_empty(const struct diff_queue_struct *q)
4691 for (i = 0; i < q->nr; i++) {
4692 const struct diff_filepair *p = q->queue[i];
4694 switch (p->status) {
4695 case DIFF_STATUS_DELETED:
4696 case DIFF_STATUS_ADDED:
4697 case DIFF_STATUS_COPIED:
4698 case DIFF_STATUS_RENAMED:
4703 if (p->one->mode && p->two->mode &&
4704 p->one->mode != p->two->mode)
4712 static const char rename_limit_warning[] =
4713 N_("inexact rename detection was skipped due to too many files.");
4715 static const char degrade_cc_to_c_warning[] =
4716 N_("only found copies from modified paths due to too many files.");
4718 static const char rename_limit_advice[] =
4719 N_("you may want to set your %s variable to at least "
4720 "%d and retry the command.");
4722 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4725 warning(_(degrade_cc_to_c_warning));
4727 warning(_(rename_limit_warning));
4730 if (0 < needed && needed < 32767)
4731 warning(_(rename_limit_advice), varname, needed);
4734 void diff_flush(struct diff_options *options)
4736 struct diff_queue_struct *q = &diff_queued_diff;
4737 int i, output_format = options->output_format;
4739 int dirstat_by_line = 0;
4742 * Order: raw, stat, summary, patch
4743 * or: name/name-status/checkdiff (other bits clear)
4748 if (output_format & (DIFF_FORMAT_RAW |
4750 DIFF_FORMAT_NAME_STATUS |
4751 DIFF_FORMAT_CHECKDIFF)) {
4752 for (i = 0; i < q->nr; i++) {
4753 struct diff_filepair *p = q->queue[i];
4754 if (check_pair_status(p))
4755 flush_one_pair(p, options);
4760 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4761 dirstat_by_line = 1;
4763 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4765 struct diffstat_t diffstat;
4767 memset(&diffstat, 0, sizeof(struct diffstat_t));
4768 for (i = 0; i < q->nr; i++) {
4769 struct diff_filepair *p = q->queue[i];
4770 if (check_pair_status(p))
4771 diff_flush_stat(p, options, &diffstat);
4773 if (output_format & DIFF_FORMAT_NUMSTAT)
4774 show_numstat(&diffstat, options);
4775 if (output_format & DIFF_FORMAT_DIFFSTAT)
4776 show_stats(&diffstat, options);
4777 if (output_format & DIFF_FORMAT_SHORTSTAT)
4778 show_shortstats(&diffstat, options);
4779 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
4780 show_dirstat_by_line(&diffstat, options);
4781 free_diffstat_info(&diffstat);
4784 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4785 show_dirstat(options);
4787 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4788 for (i = 0; i < q->nr; i++) {
4789 diff_summary(options, q->queue[i]);
4794 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4795 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4796 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4798 * run diff_flush_patch for the exit status. setting
4799 * options->file to /dev/null should be safe, because we
4800 * aren't supposed to produce any output anyway.
4802 if (options->close_file)
4803 fclose(options->file);
4804 options->file = xfopen("/dev/null", "w");
4805 options->close_file = 1;
4806 for (i = 0; i < q->nr; i++) {
4807 struct diff_filepair *p = q->queue[i];
4808 if (check_pair_status(p))
4809 diff_flush_patch(p, options);
4810 if (options->found_changes)
4815 if (output_format & DIFF_FORMAT_PATCH) {
4817 fprintf(options->file, "%s%c",
4818 diff_line_prefix(options),
4819 options->line_termination);
4820 if (options->stat_sep) {
4821 /* attach patch instead of inline */
4822 fputs(options->stat_sep, options->file);
4826 for (i = 0; i < q->nr; i++) {
4827 struct diff_filepair *p = q->queue[i];
4828 if (check_pair_status(p))
4829 diff_flush_patch(p, options);
4833 if (output_format & DIFF_FORMAT_CALLBACK)
4834 options->format_callback(q, options, options->format_callback_data);
4836 for (i = 0; i < q->nr; i++)
4837 diff_free_filepair(q->queue[i]);
4840 DIFF_QUEUE_CLEAR(q);
4841 if (options->close_file)
4842 fclose(options->file);
4845 * Report the content-level differences with HAS_CHANGES;
4846 * diff_addremove/diff_change does not set the bit when
4847 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4849 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4850 if (options->found_changes)
4851 DIFF_OPT_SET(options, HAS_CHANGES);
4853 DIFF_OPT_CLR(options, HAS_CHANGES);
4857 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
4859 return (((p->status == DIFF_STATUS_MODIFIED) &&
4861 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
4863 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
4864 ((p->status != DIFF_STATUS_MODIFIED) &&
4865 filter_bit_tst(p->status, options)));
4868 static void diffcore_apply_filter(struct diff_options *options)
4871 struct diff_queue_struct *q = &diff_queued_diff;
4872 struct diff_queue_struct outq;
4874 DIFF_QUEUE_CLEAR(&outq);
4876 if (!options->filter)
4879 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
4881 for (i = found = 0; !found && i < q->nr; i++) {
4882 if (match_filter(options, q->queue[i]))
4888 /* otherwise we will clear the whole queue
4889 * by copying the empty outq at the end of this
4890 * function, but first clear the current entries
4893 for (i = 0; i < q->nr; i++)
4894 diff_free_filepair(q->queue[i]);
4897 /* Only the matching ones */
4898 for (i = 0; i < q->nr; i++) {
4899 struct diff_filepair *p = q->queue[i];
4900 if (match_filter(options, p))
4903 diff_free_filepair(p);
4910 /* Check whether two filespecs with the same mode and size are identical */
4911 static int diff_filespec_is_identical(struct diff_filespec *one,
4912 struct diff_filespec *two)
4914 if (S_ISGITLINK(one->mode))
4916 if (diff_populate_filespec(one, 0))
4918 if (diff_populate_filespec(two, 0))
4920 return !memcmp(one->data, two->data, one->size);
4923 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
4925 if (p->done_skip_stat_unmatch)
4926 return p->skip_stat_unmatch_result;
4928 p->done_skip_stat_unmatch = 1;
4929 p->skip_stat_unmatch_result = 0;
4931 * 1. Entries that come from stat info dirtiness
4932 * always have both sides (iow, not create/delete),
4933 * one side of the object name is unknown, with
4934 * the same mode and size. Keep the ones that
4935 * do not match these criteria. They have real
4938 * 2. At this point, the file is known to be modified,
4939 * with the same mode and size, and the object
4940 * name of one side is unknown. Need to inspect
4941 * the identical contents.
4943 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4944 !DIFF_FILE_VALID(p->two) ||
4945 (p->one->oid_valid && p->two->oid_valid) ||
4946 (p->one->mode != p->two->mode) ||
4947 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
4948 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
4949 (p->one->size != p->two->size) ||
4950 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4951 p->skip_stat_unmatch_result = 1;
4952 return p->skip_stat_unmatch_result;
4955 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4958 struct diff_queue_struct *q = &diff_queued_diff;
4959 struct diff_queue_struct outq;
4960 DIFF_QUEUE_CLEAR(&outq);
4962 for (i = 0; i < q->nr; i++) {
4963 struct diff_filepair *p = q->queue[i];
4965 if (diff_filespec_check_stat_unmatch(p))
4969 * The caller can subtract 1 from skip_stat_unmatch
4970 * to determine how many paths were dirty only
4971 * due to stat info mismatch.
4973 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4974 diffopt->skip_stat_unmatch++;
4975 diff_free_filepair(p);
4982 static int diffnamecmp(const void *a_, const void *b_)
4984 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4985 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4986 const char *name_a, *name_b;
4988 name_a = a->one ? a->one->path : a->two->path;
4989 name_b = b->one ? b->one->path : b->two->path;
4990 return strcmp(name_a, name_b);
4993 void diffcore_fix_diff_index(struct diff_options *options)
4995 struct diff_queue_struct *q = &diff_queued_diff;
4996 QSORT(q->queue, q->nr, diffnamecmp);
4999 void diffcore_std(struct diff_options *options)
5001 /* NOTE please keep the following in sync with diff_tree_combined() */
5002 if (options->skip_stat_unmatch)
5003 diffcore_skip_stat_unmatch(options);
5004 if (!options->found_follow) {
5005 /* See try_to_follow_renames() in tree-diff.c */
5006 if (options->break_opt != -1)
5007 diffcore_break(options->break_opt);
5008 if (options->detect_rename)
5009 diffcore_rename(options);
5010 if (options->break_opt != -1)
5011 diffcore_merge_broken();
5013 if (options->pickaxe)
5014 diffcore_pickaxe(options);
5015 if (options->orderfile)
5016 diffcore_order(options->orderfile);
5017 if (!options->found_follow)
5018 /* See try_to_follow_renames() in tree-diff.c */
5019 diff_resolve_rename_copy();
5020 diffcore_apply_filter(options);
5022 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5023 DIFF_OPT_SET(options, HAS_CHANGES);
5025 DIFF_OPT_CLR(options, HAS_CHANGES);
5027 options->found_follow = 0;
5030 int diff_result_code(struct diff_options *opt, int status)
5034 diff_warn_rename_limit("diff.renameLimit",
5035 opt->needed_rename_limit,
5036 opt->degraded_cc_to_c);
5037 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5038 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
5040 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5041 DIFF_OPT_TST(opt, HAS_CHANGES))
5043 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
5044 DIFF_OPT_TST(opt, CHECK_FAILED))
5049 int diff_can_quit_early(struct diff_options *opt)
5051 return (DIFF_OPT_TST(opt, QUICK) &&
5053 DIFF_OPT_TST(opt, HAS_CHANGES));
5057 * Shall changes to this submodule be ignored?
5059 * Submodule changes can be configured to be ignored separately for each path,
5060 * but that configuration can be overridden from the command line.
5062 static int is_submodule_ignored(const char *path, struct diff_options *options)
5065 unsigned orig_flags = options->flags;
5066 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
5067 set_diffopt_flags_from_submodule_config(options, path);
5068 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
5070 options->flags = orig_flags;
5074 void diff_addremove(struct diff_options *options,
5075 int addremove, unsigned mode,
5076 const struct object_id *oid,
5078 const char *concatpath, unsigned dirty_submodule)
5080 struct diff_filespec *one, *two;
5082 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
5085 /* This may look odd, but it is a preparation for
5086 * feeding "there are unchanged files which should
5087 * not produce diffs, but when you are doing copy
5088 * detection you would need them, so here they are"
5089 * entries to the diff-core. They will be prefixed
5090 * with something like '=' or '*' (I haven't decided
5091 * which but should not make any difference).
5092 * Feeding the same new and old to diff_change()
5093 * also has the same effect.
5094 * Before the final output happens, they are pruned after
5095 * merged into rename/copy pairs as appropriate.
5097 if (DIFF_OPT_TST(options, REVERSE_DIFF))
5098 addremove = (addremove == '+' ? '-' :
5099 addremove == '-' ? '+' : addremove);
5101 if (options->prefix &&
5102 strncmp(concatpath, options->prefix, options->prefix_length))
5105 one = alloc_filespec(concatpath);
5106 two = alloc_filespec(concatpath);
5108 if (addremove != '+')
5109 fill_filespec(one, oid, oid_valid, mode);
5110 if (addremove != '-') {
5111 fill_filespec(two, oid, oid_valid, mode);
5112 two->dirty_submodule = dirty_submodule;
5115 diff_queue(&diff_queued_diff, one, two);
5116 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5117 DIFF_OPT_SET(options, HAS_CHANGES);
5120 void diff_change(struct diff_options *options,
5121 unsigned old_mode, unsigned new_mode,
5122 const struct object_id *old_oid,
5123 const struct object_id *new_oid,
5124 int old_oid_valid, int new_oid_valid,
5125 const char *concatpath,
5126 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5128 struct diff_filespec *one, *two;
5129 struct diff_filepair *p;
5131 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5132 is_submodule_ignored(concatpath, options))
5135 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5136 SWAP(old_mode, new_mode);
5137 SWAP(old_oid, new_oid);
5138 SWAP(old_oid_valid, new_oid_valid);
5139 SWAP(old_dirty_submodule, new_dirty_submodule);
5142 if (options->prefix &&
5143 strncmp(concatpath, options->prefix, options->prefix_length))
5146 one = alloc_filespec(concatpath);
5147 two = alloc_filespec(concatpath);
5148 fill_filespec(one, old_oid, old_oid_valid, old_mode);
5149 fill_filespec(two, new_oid, new_oid_valid, new_mode);
5150 one->dirty_submodule = old_dirty_submodule;
5151 two->dirty_submodule = new_dirty_submodule;
5152 p = diff_queue(&diff_queued_diff, one, two);
5154 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5157 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5158 !diff_filespec_check_stat_unmatch(p))
5161 DIFF_OPT_SET(options, HAS_CHANGES);
5164 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5166 struct diff_filepair *pair;
5167 struct diff_filespec *one, *two;
5169 if (options->prefix &&
5170 strncmp(path, options->prefix, options->prefix_length))
5173 one = alloc_filespec(path);
5174 two = alloc_filespec(path);
5175 pair = diff_queue(&diff_queued_diff, one, two);
5176 pair->is_unmerged = 1;
5180 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5183 struct diff_tempfile *temp;
5184 const char *argv[3];
5185 const char **arg = argv;
5186 struct child_process child = CHILD_PROCESS_INIT;
5187 struct strbuf buf = STRBUF_INIT;
5190 temp = prepare_temp_file(spec->path, spec);
5192 *arg++ = temp->name;
5195 child.use_shell = 1;
5198 if (start_command(&child)) {
5203 if (strbuf_read(&buf, child.out, 0) < 0)
5204 err = error("error reading from textconv command '%s'", pgm);
5207 if (finish_command(&child) || err) {
5208 strbuf_release(&buf);
5214 return strbuf_detach(&buf, outsize);
5217 size_t fill_textconv(struct userdiff_driver *driver,
5218 struct diff_filespec *df,
5224 if (!DIFF_FILE_VALID(df)) {
5228 if (diff_populate_filespec(df, 0))
5229 die("unable to read files to diff");
5234 if (!driver->textconv)
5235 die("BUG: fill_textconv called with non-textconv driver");
5237 if (driver->textconv_cache && df->oid_valid) {
5238 *outbuf = notes_cache_get(driver->textconv_cache,
5245 *outbuf = run_textconv(driver->textconv, df, &size);
5247 die("unable to read files to diff");
5249 if (driver->textconv_cache && df->oid_valid) {
5250 /* ignore errors, as we might be in a readonly repository */
5251 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
5254 * we could save up changes and flush them all at the end,
5255 * but we would need an extra call after all diffing is done.
5256 * Since generating a cache entry is the slow path anyway,
5257 * this extra overhead probably isn't a big deal.
5259 notes_cache_write(driver->textconv_cache);
5265 int textconv_object(const char *path,
5267 const struct object_id *oid,
5270 unsigned long *buf_size)
5272 struct diff_filespec *df;
5273 struct userdiff_driver *textconv;
5275 df = alloc_filespec(path);
5276 fill_filespec(df, oid, oid_valid, mode);
5277 textconv = get_textconv(df);
5283 *buf_size = fill_textconv(textconv, df, buf);
5288 void setup_diff_pager(struct diff_options *opt)
5291 * If the user asked for our exit code, then either they want --quiet
5292 * or --exit-code. We should definitely not bother with a pager in the
5293 * former case, as we will generate no output. Since we still properly
5294 * report our exit code even when a pager is run, we _could_ run a
5295 * pager with --exit-code. But since we have not done so historically,
5296 * and because it is easy to find people oneline advising "git diff
5297 * --exit-code" in hooks and other scripts, we do not do so.
5299 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5300 check_pager_config("diff") != 0)