2 * Copyright (C) 2005 Junio C Hamano
10 #include "xdiff-interface.h"
13 #include "run-command.h"
16 #include "submodule.h"
18 #include "string-list.h"
19 #include "argv-array.h"
21 #ifdef NO_FAST_WORKING_DIRECTORY
22 #define FAST_WORKING_DIRECTORY 0
24 #define FAST_WORKING_DIRECTORY 1
27 static int diff_detect_rename_default;
28 static int diff_rename_limit_default = 400;
29 static int diff_suppress_blank_empty;
30 static int diff_use_color_default = -1;
31 static int diff_context_default = 3;
32 static const char *diff_word_regex_cfg;
33 static const char *external_diff_cmd_cfg;
34 static const char *diff_order_file_cfg;
35 int diff_auto_refresh_index = 1;
36 static int diff_mnemonic_prefix;
37 static int diff_no_prefix;
38 static int diff_stat_graph_width;
39 static int diff_dirstat_permille_default = 30;
40 static struct diff_options default_diff_options;
41 static long diff_algorithm;
43 static char diff_colors[][COLOR_MAXLEN] = {
45 GIT_COLOR_NORMAL, /* PLAIN */
46 GIT_COLOR_BOLD, /* METAINFO */
47 GIT_COLOR_CYAN, /* FRAGINFO */
48 GIT_COLOR_RED, /* OLD */
49 GIT_COLOR_GREEN, /* NEW */
50 GIT_COLOR_YELLOW, /* COMMIT */
51 GIT_COLOR_BG_RED, /* WHITESPACE */
52 GIT_COLOR_NORMAL, /* FUNCINFO */
55 static int parse_diff_color_slot(const char *var)
57 if (!strcasecmp(var, "plain"))
59 if (!strcasecmp(var, "meta"))
61 if (!strcasecmp(var, "frag"))
63 if (!strcasecmp(var, "old"))
65 if (!strcasecmp(var, "new"))
67 if (!strcasecmp(var, "commit"))
69 if (!strcasecmp(var, "whitespace"))
70 return DIFF_WHITESPACE;
71 if (!strcasecmp(var, "func"))
76 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
77 struct strbuf *errmsg)
79 char *params_copy = xstrdup(params_string);
80 struct string_list params = STRING_LIST_INIT_NODUP;
85 string_list_split_in_place(¶ms, params_copy, ',', -1);
86 for (i = 0; i < params.nr; i++) {
87 const char *p = params.items[i].string;
88 if (!strcmp(p, "changes")) {
89 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
90 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
91 } else if (!strcmp(p, "lines")) {
92 DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
93 DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
94 } else if (!strcmp(p, "files")) {
95 DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
96 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
97 } else if (!strcmp(p, "noncumulative")) {
98 DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
99 } else if (!strcmp(p, "cumulative")) {
100 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
101 } else if (isdigit(*p)) {
103 int permille = strtoul(p, &end, 10) * 10;
104 if (*end == '.' && isdigit(*++end)) {
105 /* only use first digit */
106 permille += *end - '0';
107 /* .. and ignore any further digits */
108 while (isdigit(*++end))
112 options->dirstat_permille = permille;
114 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
119 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
124 string_list_clear(¶ms, 0);
129 static int parse_submodule_params(struct diff_options *options, const char *value)
131 if (!strcmp(value, "log"))
132 DIFF_OPT_SET(options, SUBMODULE_LOG);
133 else if (!strcmp(value, "short"))
134 DIFF_OPT_CLR(options, SUBMODULE_LOG);
140 static int git_config_rename(const char *var, const char *value)
143 return DIFF_DETECT_RENAME;
144 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
145 return DIFF_DETECT_COPY;
146 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
149 long parse_algorithm_value(const char *value)
153 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
155 else if (!strcasecmp(value, "minimal"))
156 return XDF_NEED_MINIMAL;
157 else if (!strcasecmp(value, "patience"))
158 return XDF_PATIENCE_DIFF;
159 else if (!strcasecmp(value, "histogram"))
160 return XDF_HISTOGRAM_DIFF;
165 * These are to give UI layer defaults.
166 * The core-level commands such as git-diff-files should
167 * never be affected by the setting of diff.renames
168 * the user happens to have in the configuration file.
170 int git_diff_ui_config(const char *var, const char *value, void *cb)
172 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
173 diff_use_color_default = git_config_colorbool(var, value);
176 if (!strcmp(var, "diff.context")) {
177 diff_context_default = git_config_int(var, value);
178 if (diff_context_default < 0)
182 if (!strcmp(var, "diff.renames")) {
183 diff_detect_rename_default = git_config_rename(var, value);
186 if (!strcmp(var, "diff.autorefreshindex")) {
187 diff_auto_refresh_index = git_config_bool(var, value);
190 if (!strcmp(var, "diff.mnemonicprefix")) {
191 diff_mnemonic_prefix = git_config_bool(var, value);
194 if (!strcmp(var, "diff.noprefix")) {
195 diff_no_prefix = git_config_bool(var, value);
198 if (!strcmp(var, "diff.statgraphwidth")) {
199 diff_stat_graph_width = git_config_int(var, value);
202 if (!strcmp(var, "diff.external"))
203 return git_config_string(&external_diff_cmd_cfg, var, value);
204 if (!strcmp(var, "diff.wordregex"))
205 return git_config_string(&diff_word_regex_cfg, var, value);
206 if (!strcmp(var, "diff.orderfile"))
207 return git_config_pathname(&diff_order_file_cfg, var, value);
209 if (!strcmp(var, "diff.ignoresubmodules"))
210 handle_ignore_submodules_arg(&default_diff_options, value);
212 if (!strcmp(var, "diff.submodule")) {
213 if (parse_submodule_params(&default_diff_options, value))
214 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
219 if (!strcmp(var, "diff.algorithm")) {
220 diff_algorithm = parse_algorithm_value(value);
221 if (diff_algorithm < 0)
226 if (git_color_config(var, value, cb) < 0)
229 return git_diff_basic_config(var, value, cb);
232 int git_diff_basic_config(const char *var, const char *value, void *cb)
236 if (!strcmp(var, "diff.renamelimit")) {
237 diff_rename_limit_default = git_config_int(var, value);
241 if (userdiff_config(var, value) < 0)
244 if (skip_prefix(var, "diff.color.", &name) ||
245 skip_prefix(var, "color.diff.", &name)) {
246 int slot = parse_diff_color_slot(name);
250 return config_error_nonbool(var);
251 return color_parse(value, diff_colors[slot]);
254 /* like GNU diff's --suppress-blank-empty option */
255 if (!strcmp(var, "diff.suppressblankempty") ||
256 /* for backwards compatibility */
257 !strcmp(var, "diff.suppress-blank-empty")) {
258 diff_suppress_blank_empty = git_config_bool(var, value);
262 if (!strcmp(var, "diff.dirstat")) {
263 struct strbuf errmsg = STRBUF_INIT;
264 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
265 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
266 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
268 strbuf_release(&errmsg);
269 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
273 if (starts_with(var, "submodule."))
274 return parse_submodule_config_option(var, value);
276 return git_default_config(var, value, cb);
279 static char *quote_two(const char *one, const char *two)
281 int need_one = quote_c_style(one, NULL, NULL, 1);
282 int need_two = quote_c_style(two, NULL, NULL, 1);
283 struct strbuf res = STRBUF_INIT;
285 if (need_one + need_two) {
286 strbuf_addch(&res, '"');
287 quote_c_style(one, &res, NULL, 1);
288 quote_c_style(two, &res, NULL, 1);
289 strbuf_addch(&res, '"');
291 strbuf_addstr(&res, one);
292 strbuf_addstr(&res, two);
294 return strbuf_detach(&res, NULL);
297 static const char *external_diff(void)
299 static const char *external_diff_cmd = NULL;
300 static int done_preparing = 0;
303 return external_diff_cmd;
304 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
305 if (!external_diff_cmd)
306 external_diff_cmd = external_diff_cmd_cfg;
308 return external_diff_cmd;
312 * Keep track of files used for diffing. Sometimes such an entry
313 * refers to a temporary file, sometimes to an existing file, and
314 * sometimes to "/dev/null".
316 static struct diff_tempfile {
318 * filename external diff should read from, or NULL if this
319 * entry is currently not in use:
327 * If this diff_tempfile instance refers to a temporary file,
328 * this tempfile object is used to manage its lifetime.
330 struct tempfile tempfile;
333 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
335 struct emit_callback {
338 int blank_at_eof_in_preimage;
339 int blank_at_eof_in_postimage;
341 int lno_in_postimage;
342 sane_truncate_fn truncate;
343 const char **label_path;
344 struct diff_words_data *diff_words;
345 struct diff_options *opt;
347 struct strbuf *header;
350 static int count_lines(const char *data, int size)
352 int count, ch, completely_empty = 1, nl_just_seen = 0;
359 completely_empty = 0;
363 completely_empty = 0;
366 if (completely_empty)
369 count++; /* no trailing newline */
373 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
375 if (!DIFF_FILE_VALID(one)) {
376 mf->ptr = (char *)""; /* does not matter */
380 else if (diff_populate_filespec(one, 0))
384 mf->size = one->size;
388 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
389 static unsigned long diff_filespec_size(struct diff_filespec *one)
391 if (!DIFF_FILE_VALID(one))
393 diff_populate_filespec(one, CHECK_SIZE_ONLY);
397 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
400 long size = mf->size;
405 ptr += size - 1; /* pointing at the very end */
407 ; /* incomplete line */
409 ptr--; /* skip the last LF */
410 while (mf->ptr < ptr) {
412 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
413 if (*prev_eol == '\n')
415 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
423 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
424 struct emit_callback *ecbdata)
427 unsigned ws_rule = ecbdata->ws_rule;
428 l1 = count_trailing_blank(mf1, ws_rule);
429 l2 = count_trailing_blank(mf2, ws_rule);
431 ecbdata->blank_at_eof_in_preimage = 0;
432 ecbdata->blank_at_eof_in_postimage = 0;
435 at = count_lines(mf1->ptr, mf1->size);
436 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
438 at = count_lines(mf2->ptr, mf2->size);
439 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
442 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
443 int first, const char *line, int len)
445 int has_trailing_newline, has_trailing_carriage_return;
447 FILE *file = o->file;
449 fputs(diff_line_prefix(o), file);
452 has_trailing_newline = (first == '\n');
453 has_trailing_carriage_return = (!has_trailing_newline &&
455 nofirst = has_trailing_newline || has_trailing_carriage_return;
457 has_trailing_newline = (len > 0 && line[len-1] == '\n');
458 if (has_trailing_newline)
460 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
461 if (has_trailing_carriage_return)
466 if (len || !nofirst) {
470 fwrite(line, len, 1, file);
473 if (has_trailing_carriage_return)
475 if (has_trailing_newline)
479 static void emit_line(struct diff_options *o, const char *set, const char *reset,
480 const char *line, int len)
482 emit_line_0(o, set, reset, line[0], line+1, len-1);
485 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
487 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
488 ecbdata->blank_at_eof_in_preimage &&
489 ecbdata->blank_at_eof_in_postimage &&
490 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
491 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
493 return ws_blank_line(line, len, ecbdata->ws_rule);
496 static void emit_add_line(const char *reset,
497 struct emit_callback *ecbdata,
498 const char *line, int len)
500 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
501 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
504 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
505 else if (new_blank_line_at_eof(ecbdata, line, len))
506 /* Blank line at EOF - paint '+' as well */
507 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
509 /* Emit just the prefix, then the rest. */
510 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
511 ws_check_emit(line, len, ecbdata->ws_rule,
512 ecbdata->opt->file, set, reset, ws);
516 static void emit_hunk_header(struct emit_callback *ecbdata,
517 const char *line, int len)
519 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
520 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
521 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
522 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
523 static const char atat[2] = { '@', '@' };
525 struct strbuf msgbuf = STRBUF_INIT;
530 * As a hunk header must begin with "@@ -<old>, +<new> @@",
531 * it always is at least 10 bytes long.
534 memcmp(line, atat, 2) ||
535 !(ep = memmem(line + 2, len - 2, atat, 2))) {
536 emit_line(ecbdata->opt, plain, reset, line, len);
539 ep += 2; /* skip over @@ */
541 /* The hunk header in fraginfo color */
542 strbuf_addstr(&msgbuf, frag);
543 strbuf_add(&msgbuf, line, ep - line);
544 strbuf_addstr(&msgbuf, reset);
550 if (line[len - i] == '\r' || line[len - i] == '\n')
553 /* blank before the func header */
554 for (cp = ep; ep - line < len; ep++)
555 if (*ep != ' ' && *ep != '\t')
558 strbuf_addstr(&msgbuf, plain);
559 strbuf_add(&msgbuf, cp, ep - cp);
560 strbuf_addstr(&msgbuf, reset);
563 if (ep < line + len) {
564 strbuf_addstr(&msgbuf, func);
565 strbuf_add(&msgbuf, ep, line + len - ep);
566 strbuf_addstr(&msgbuf, reset);
569 strbuf_add(&msgbuf, line + len, org_len - len);
570 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
571 strbuf_release(&msgbuf);
574 static struct diff_tempfile *claim_diff_tempfile(void) {
576 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
577 if (!diff_temp[i].name)
578 return diff_temp + i;
579 die("BUG: diff is failing to clean up its tempfiles");
582 static void remove_tempfile(void)
585 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
586 if (is_tempfile_active(&diff_temp[i].tempfile))
587 delete_tempfile(&diff_temp[i].tempfile);
588 diff_temp[i].name = NULL;
592 static void print_line_count(FILE *file, int count)
596 fprintf(file, "0,0");
602 fprintf(file, "1,%d", count);
607 static void emit_rewrite_lines(struct emit_callback *ecb,
608 int prefix, const char *data, int size)
610 const char *endp = NULL;
611 static const char *nneof = " No newline at end of file\n";
612 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
613 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
618 endp = memchr(data, '\n', size);
619 len = endp ? (endp - data + 1) : size;
621 ecb->lno_in_preimage++;
622 emit_line_0(ecb->opt, old, reset, '-',
625 ecb->lno_in_postimage++;
626 emit_add_line(reset, ecb, data, len);
632 const char *plain = diff_get_color(ecb->color_diff,
634 putc('\n', ecb->opt->file);
635 emit_line_0(ecb->opt, plain, reset, '\\',
636 nneof, strlen(nneof));
640 static void emit_rewrite_diff(const char *name_a,
642 struct diff_filespec *one,
643 struct diff_filespec *two,
644 struct userdiff_driver *textconv_one,
645 struct userdiff_driver *textconv_two,
646 struct diff_options *o)
649 const char *name_a_tab, *name_b_tab;
650 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
651 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
652 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
653 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
654 const char *a_prefix, *b_prefix;
655 char *data_one, *data_two;
656 size_t size_one, size_two;
657 struct emit_callback ecbdata;
658 const char *line_prefix = diff_line_prefix(o);
660 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
661 a_prefix = o->b_prefix;
662 b_prefix = o->a_prefix;
664 a_prefix = o->a_prefix;
665 b_prefix = o->b_prefix;
668 name_a += (*name_a == '/');
669 name_b += (*name_b == '/');
670 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
671 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
673 strbuf_reset(&a_name);
674 strbuf_reset(&b_name);
675 quote_two_c_style(&a_name, a_prefix, name_a, 0);
676 quote_two_c_style(&b_name, b_prefix, name_b, 0);
678 size_one = fill_textconv(textconv_one, one, &data_one);
679 size_two = fill_textconv(textconv_two, two, &data_two);
681 memset(&ecbdata, 0, sizeof(ecbdata));
682 ecbdata.color_diff = want_color(o->use_color);
683 ecbdata.found_changesp = &o->found_changes;
684 ecbdata.ws_rule = whitespace_rule(name_b);
686 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
688 mf1.ptr = (char *)data_one;
689 mf2.ptr = (char *)data_two;
692 check_blank_at_eof(&mf1, &mf2, &ecbdata);
694 ecbdata.lno_in_preimage = 1;
695 ecbdata.lno_in_postimage = 1;
697 lc_a = count_lines(data_one, size_one);
698 lc_b = count_lines(data_two, size_two);
700 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
701 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
702 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
703 line_prefix, fraginfo);
704 if (!o->irreversible_delete)
705 print_line_count(o->file, lc_a);
707 fprintf(o->file, "?,?");
708 fprintf(o->file, " +");
709 print_line_count(o->file, lc_b);
710 fprintf(o->file, " @@%s\n", reset);
711 if (lc_a && !o->irreversible_delete)
712 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
714 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
716 free((char *)data_one);
718 free((char *)data_two);
721 struct diff_words_buffer {
724 struct diff_words_orig {
725 const char *begin, *end;
727 int orig_nr, orig_alloc;
730 static void diff_words_append(char *line, unsigned long len,
731 struct diff_words_buffer *buffer)
733 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
736 memcpy(buffer->text.ptr + buffer->text.size, line, len);
737 buffer->text.size += len;
738 buffer->text.ptr[buffer->text.size] = '\0';
741 struct diff_words_style_elem {
744 const char *color; /* NULL; filled in by the setup code if
745 * color is enabled */
748 struct diff_words_style {
749 enum diff_words_type type;
750 struct diff_words_style_elem new, old, ctx;
754 static struct diff_words_style diff_words_styles[] = {
755 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
756 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
757 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
760 struct diff_words_data {
761 struct diff_words_buffer minus, plus;
762 const char *current_plus;
764 struct diff_options *opt;
766 enum diff_words_type type;
767 struct diff_words_style *style;
770 static int fn_out_diff_words_write_helper(FILE *fp,
771 struct diff_words_style_elem *st_el,
773 size_t count, const char *buf,
774 const char *line_prefix)
779 char *p = memchr(buf, '\n', count);
781 fputs(line_prefix, fp);
783 if (st_el->color && fputs(st_el->color, fp) < 0)
785 if (fputs(st_el->prefix, fp) < 0 ||
786 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
787 fputs(st_el->suffix, fp) < 0)
789 if (st_el->color && *st_el->color
790 && fputs(GIT_COLOR_RESET, fp) < 0)
795 if (fputs(newline, fp) < 0)
797 count -= p + 1 - buf;
805 * '--color-words' algorithm can be described as:
807 * 1. collect a the minus/plus lines of a diff hunk, divided into
808 * minus-lines and plus-lines;
810 * 2. break both minus-lines and plus-lines into words and
811 * place them into two mmfile_t with one word for each line;
813 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
815 * And for the common parts of the both file, we output the plus side text.
816 * diff_words->current_plus is used to trace the current position of the plus file
817 * which printed. diff_words->last_minus is used to trace the last minus word
820 * For '--graph' to work with '--color-words', we need to output the graph prefix
821 * on each line of color words output. Generally, there are two conditions on
822 * which we should output the prefix.
824 * 1. diff_words->last_minus == 0 &&
825 * diff_words->current_plus == diff_words->plus.text.ptr
827 * that is: the plus text must start as a new line, and if there is no minus
828 * word printed, a graph prefix must be printed.
830 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
831 * *(diff_words->current_plus - 1) == '\n'
833 * that is: a graph prefix must be printed following a '\n'
835 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
837 if ((diff_words->last_minus == 0 &&
838 diff_words->current_plus == diff_words->plus.text.ptr) ||
839 (diff_words->current_plus > diff_words->plus.text.ptr &&
840 *(diff_words->current_plus - 1) == '\n')) {
847 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
849 struct diff_words_data *diff_words = priv;
850 struct diff_words_style *style = diff_words->style;
851 int minus_first, minus_len, plus_first, plus_len;
852 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
853 struct diff_options *opt = diff_words->opt;
854 const char *line_prefix;
856 if (line[0] != '@' || parse_hunk_header(line, len,
857 &minus_first, &minus_len, &plus_first, &plus_len))
861 line_prefix = diff_line_prefix(opt);
863 /* POSIX requires that first be decremented by one if len == 0... */
865 minus_begin = diff_words->minus.orig[minus_first].begin;
867 diff_words->minus.orig[minus_first + minus_len - 1].end;
869 minus_begin = minus_end =
870 diff_words->minus.orig[minus_first].end;
873 plus_begin = diff_words->plus.orig[plus_first].begin;
874 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
876 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
878 if (color_words_output_graph_prefix(diff_words)) {
879 fputs(line_prefix, diff_words->opt->file);
881 if (diff_words->current_plus != plus_begin) {
882 fn_out_diff_words_write_helper(diff_words->opt->file,
883 &style->ctx, style->newline,
884 plus_begin - diff_words->current_plus,
885 diff_words->current_plus, line_prefix);
886 if (*(plus_begin - 1) == '\n')
887 fputs(line_prefix, diff_words->opt->file);
889 if (minus_begin != minus_end) {
890 fn_out_diff_words_write_helper(diff_words->opt->file,
891 &style->old, style->newline,
892 minus_end - minus_begin, minus_begin,
895 if (plus_begin != plus_end) {
896 fn_out_diff_words_write_helper(diff_words->opt->file,
897 &style->new, style->newline,
898 plus_end - plus_begin, plus_begin,
902 diff_words->current_plus = plus_end;
903 diff_words->last_minus = minus_first;
906 /* This function starts looking at *begin, and returns 0 iff a word was found. */
907 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
908 int *begin, int *end)
910 if (word_regex && *begin < buffer->size) {
912 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
913 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
914 '\n', match[0].rm_eo - match[0].rm_so);
915 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
916 *begin += match[0].rm_so;
917 return *begin >= *end;
922 /* find the next word */
923 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
925 if (*begin >= buffer->size)
928 /* find the end of the word */
930 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
937 * This function splits the words in buffer->text, stores the list with
938 * newline separator into out, and saves the offsets of the original words
941 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
950 /* fake an empty "0th" word */
951 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
952 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
955 for (i = 0; i < buffer->text.size; i++) {
956 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
959 /* store original boundaries */
960 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
962 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
963 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
967 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
968 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
969 out->ptr[out->size + j - i] = '\n';
970 out->size += j - i + 1;
976 /* this executes the word diff on the accumulated buffers */
977 static void diff_words_show(struct diff_words_data *diff_words)
981 mmfile_t minus, plus;
982 struct diff_words_style *style = diff_words->style;
984 struct diff_options *opt = diff_words->opt;
985 const char *line_prefix;
988 line_prefix = diff_line_prefix(opt);
990 /* special case: only removal */
991 if (!diff_words->plus.text.size) {
992 fputs(line_prefix, diff_words->opt->file);
993 fn_out_diff_words_write_helper(diff_words->opt->file,
994 &style->old, style->newline,
995 diff_words->minus.text.size,
996 diff_words->minus.text.ptr, line_prefix);
997 diff_words->minus.text.size = 0;
1001 diff_words->current_plus = diff_words->plus.text.ptr;
1002 diff_words->last_minus = 0;
1004 memset(&xpp, 0, sizeof(xpp));
1005 memset(&xecfg, 0, sizeof(xecfg));
1006 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1007 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1009 /* as only the hunk header will be parsed, we need a 0-context */
1011 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1015 if (diff_words->current_plus != diff_words->plus.text.ptr +
1016 diff_words->plus.text.size) {
1017 if (color_words_output_graph_prefix(diff_words))
1018 fputs(line_prefix, diff_words->opt->file);
1019 fn_out_diff_words_write_helper(diff_words->opt->file,
1020 &style->ctx, style->newline,
1021 diff_words->plus.text.ptr + diff_words->plus.text.size
1022 - diff_words->current_plus, diff_words->current_plus,
1025 diff_words->minus.text.size = diff_words->plus.text.size = 0;
1028 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
1029 static void diff_words_flush(struct emit_callback *ecbdata)
1031 if (ecbdata->diff_words->minus.text.size ||
1032 ecbdata->diff_words->plus.text.size)
1033 diff_words_show(ecbdata->diff_words);
1036 static void diff_filespec_load_driver(struct diff_filespec *one)
1038 /* Use already-loaded driver */
1042 if (S_ISREG(one->mode))
1043 one->driver = userdiff_find_by_path(one->path);
1045 /* Fallback to default settings */
1047 one->driver = userdiff_find_by_name("default");
1050 static const char *userdiff_word_regex(struct diff_filespec *one)
1052 diff_filespec_load_driver(one);
1053 return one->driver->word_regex;
1056 static void init_diff_words_data(struct emit_callback *ecbdata,
1057 struct diff_options *orig_opts,
1058 struct diff_filespec *one,
1059 struct diff_filespec *two)
1062 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1063 memcpy(o, orig_opts, sizeof(struct diff_options));
1065 ecbdata->diff_words =
1066 xcalloc(1, sizeof(struct diff_words_data));
1067 ecbdata->diff_words->type = o->word_diff;
1068 ecbdata->diff_words->opt = o;
1070 o->word_regex = userdiff_word_regex(one);
1072 o->word_regex = userdiff_word_regex(two);
1074 o->word_regex = diff_word_regex_cfg;
1075 if (o->word_regex) {
1076 ecbdata->diff_words->word_regex = (regex_t *)
1077 xmalloc(sizeof(regex_t));
1078 if (regcomp(ecbdata->diff_words->word_regex,
1080 REG_EXTENDED | REG_NEWLINE))
1081 die ("Invalid regular expression: %s",
1084 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1085 if (o->word_diff == diff_words_styles[i].type) {
1086 ecbdata->diff_words->style =
1087 &diff_words_styles[i];
1091 if (want_color(o->use_color)) {
1092 struct diff_words_style *st = ecbdata->diff_words->style;
1093 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1094 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1095 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1099 static void free_diff_words_data(struct emit_callback *ecbdata)
1101 if (ecbdata->diff_words) {
1102 diff_words_flush(ecbdata);
1103 free (ecbdata->diff_words->opt);
1104 free (ecbdata->diff_words->minus.text.ptr);
1105 free (ecbdata->diff_words->minus.orig);
1106 free (ecbdata->diff_words->plus.text.ptr);
1107 free (ecbdata->diff_words->plus.orig);
1108 if (ecbdata->diff_words->word_regex) {
1109 regfree(ecbdata->diff_words->word_regex);
1110 free(ecbdata->diff_words->word_regex);
1112 free(ecbdata->diff_words);
1113 ecbdata->diff_words = NULL;
1117 const char *diff_get_color(int diff_use_color, enum color_diff ix)
1119 if (want_color(diff_use_color))
1120 return diff_colors[ix];
1124 const char *diff_line_prefix(struct diff_options *opt)
1126 struct strbuf *msgbuf;
1127 if (!opt->output_prefix)
1130 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1134 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1137 unsigned long allot;
1141 return ecb->truncate(line, len);
1145 (void) utf8_width(&cp, &l);
1147 break; /* truncated in the middle? */
1152 static void find_lno(const char *line, struct emit_callback *ecbdata)
1155 ecbdata->lno_in_preimage = 0;
1156 ecbdata->lno_in_postimage = 0;
1157 p = strchr(line, '-');
1159 return; /* cannot happen */
1160 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1163 return; /* cannot happen */
1164 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1167 static void fn_out_consume(void *priv, char *line, unsigned long len)
1169 struct emit_callback *ecbdata = priv;
1170 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1171 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
1172 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1173 struct diff_options *o = ecbdata->opt;
1174 const char *line_prefix = diff_line_prefix(o);
1176 if (ecbdata->header) {
1177 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
1178 strbuf_reset(ecbdata->header);
1179 ecbdata->header = NULL;
1181 *(ecbdata->found_changesp) = 1;
1183 if (ecbdata->label_path[0]) {
1184 const char *name_a_tab, *name_b_tab;
1186 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1187 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1189 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1190 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1191 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1192 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1193 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1196 if (diff_suppress_blank_empty
1197 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1202 if (line[0] == '@') {
1203 if (ecbdata->diff_words)
1204 diff_words_flush(ecbdata);
1205 len = sane_truncate_line(ecbdata, line, len);
1206 find_lno(line, ecbdata);
1207 emit_hunk_header(ecbdata, line, len);
1208 if (line[len-1] != '\n')
1209 putc('\n', ecbdata->opt->file);
1214 emit_line(ecbdata->opt, reset, reset, line, len);
1215 if (ecbdata->diff_words
1216 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1217 fputs("~\n", ecbdata->opt->file);
1221 if (ecbdata->diff_words) {
1222 if (line[0] == '-') {
1223 diff_words_append(line, len,
1224 &ecbdata->diff_words->minus);
1226 } else if (line[0] == '+') {
1227 diff_words_append(line, len,
1228 &ecbdata->diff_words->plus);
1230 } else if (starts_with(line, "\\ ")) {
1232 * Eat the "no newline at eof" marker as if we
1233 * saw a "+" or "-" line with nothing on it,
1234 * and return without diff_words_flush() to
1235 * defer processing. If this is the end of
1236 * preimage, more "+" lines may come after it.
1240 diff_words_flush(ecbdata);
1241 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1242 emit_line(ecbdata->opt, plain, reset, line, len);
1243 fputs("~\n", ecbdata->opt->file);
1246 * Skip the prefix character, if any. With
1247 * diff_suppress_blank_empty, there may be
1250 if (line[0] != '\n') {
1254 emit_line(ecbdata->opt, plain, reset, line, len);
1259 if (line[0] != '+') {
1261 diff_get_color(ecbdata->color_diff,
1262 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1263 ecbdata->lno_in_preimage++;
1265 ecbdata->lno_in_postimage++;
1266 emit_line(ecbdata->opt, color, reset, line, len);
1268 ecbdata->lno_in_postimage++;
1269 emit_add_line(reset, ecbdata, line + 1, len - 1);
1273 static char *pprint_rename(const char *a, const char *b)
1275 const char *old = a;
1276 const char *new = b;
1277 struct strbuf name = STRBUF_INIT;
1278 int pfx_length, sfx_length;
1279 int pfx_adjust_for_slash;
1280 int len_a = strlen(a);
1281 int len_b = strlen(b);
1282 int a_midlen, b_midlen;
1283 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1284 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1286 if (qlen_a || qlen_b) {
1287 quote_c_style(a, &name, NULL, 0);
1288 strbuf_addstr(&name, " => ");
1289 quote_c_style(b, &name, NULL, 0);
1290 return strbuf_detach(&name, NULL);
1293 /* Find common prefix */
1295 while (*old && *new && *old == *new) {
1297 pfx_length = old - a + 1;
1302 /* Find common suffix */
1307 * If there is a common prefix, it must end in a slash. In
1308 * that case we let this loop run 1 into the prefix to see the
1311 * If there is no common prefix, we cannot do this as it would
1312 * underrun the input strings.
1314 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1315 while (a + pfx_length - pfx_adjust_for_slash <= old &&
1316 b + pfx_length - pfx_adjust_for_slash <= new &&
1319 sfx_length = len_a - (old - a);
1325 * pfx{mid-a => mid-b}sfx
1326 * {pfx-a => pfx-b}sfx
1327 * pfx{sfx-a => sfx-b}
1330 a_midlen = len_a - pfx_length - sfx_length;
1331 b_midlen = len_b - pfx_length - sfx_length;
1337 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1338 if (pfx_length + sfx_length) {
1339 strbuf_add(&name, a, pfx_length);
1340 strbuf_addch(&name, '{');
1342 strbuf_add(&name, a + pfx_length, a_midlen);
1343 strbuf_addstr(&name, " => ");
1344 strbuf_add(&name, b + pfx_length, b_midlen);
1345 if (pfx_length + sfx_length) {
1346 strbuf_addch(&name, '}');
1347 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1349 return strbuf_detach(&name, NULL);
1355 struct diffstat_file {
1359 unsigned is_unmerged:1;
1360 unsigned is_binary:1;
1361 unsigned is_renamed:1;
1362 unsigned is_interesting:1;
1363 uintmax_t added, deleted;
1367 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1371 struct diffstat_file *x;
1372 x = xcalloc(1, sizeof(*x));
1373 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1374 diffstat->files[diffstat->nr++] = x;
1376 x->from_name = xstrdup(name_a);
1377 x->name = xstrdup(name_b);
1381 x->from_name = NULL;
1382 x->name = xstrdup(name_a);
1387 static void diffstat_consume(void *priv, char *line, unsigned long len)
1389 struct diffstat_t *diffstat = priv;
1390 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1394 else if (line[0] == '-')
1398 const char mime_boundary_leader[] = "------------";
1400 static int scale_linear(int it, int width, int max_change)
1405 * make sure that at least one '-' or '+' is printed if
1406 * there is any change to this path. The easiest way is to
1407 * scale linearly as if the alloted width is one column shorter
1408 * than it is, and then add 1 to the result.
1410 return 1 + (it * (width - 1) / max_change);
1413 static void show_name(FILE *file,
1414 const char *prefix, const char *name, int len)
1416 fprintf(file, " %s%-*s |", prefix, len, name);
1419 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1423 fprintf(file, "%s", set);
1426 fprintf(file, "%s", reset);
1429 static void fill_print_name(struct diffstat_file *file)
1433 if (file->print_name)
1436 if (!file->is_renamed) {
1437 struct strbuf buf = STRBUF_INIT;
1438 if (quote_c_style(file->name, &buf, NULL, 0)) {
1439 pname = strbuf_detach(&buf, NULL);
1442 strbuf_release(&buf);
1445 pname = pprint_rename(file->from_name, file->name);
1447 file->print_name = pname;
1450 int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1452 struct strbuf sb = STRBUF_INIT;
1456 assert(insertions == 0 && deletions == 0);
1457 return fprintf(fp, "%s\n", " 0 files changed");
1461 (files == 1) ? " %d file changed" : " %d files changed",
1465 * For binary diff, the caller may want to print "x files
1466 * changed" with insertions == 0 && deletions == 0.
1468 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1469 * is probably less confusing (i.e skip over "2 files changed
1470 * but nothing about added/removed lines? Is this a bug in Git?").
1472 if (insertions || deletions == 0) {
1474 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1478 if (deletions || insertions == 0) {
1480 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1483 strbuf_addch(&sb, '\n');
1484 ret = fputs(sb.buf, fp);
1485 strbuf_release(&sb);
1489 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1491 int i, len, add, del, adds = 0, dels = 0;
1492 uintmax_t max_change = 0, max_len = 0;
1493 int total_files = data->nr, count;
1494 int width, name_width, graph_width, number_width = 0, bin_width = 0;
1495 const char *reset, *add_c, *del_c;
1496 const char *line_prefix = "";
1497 int extra_shown = 0;
1502 line_prefix = diff_line_prefix(options);
1503 count = options->stat_count ? options->stat_count : data->nr;
1505 reset = diff_get_color_opt(options, DIFF_RESET);
1506 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1507 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1510 * Find the longest filename and max number of changes
1512 for (i = 0; (i < count) && (i < data->nr); i++) {
1513 struct diffstat_file *file = data->files[i];
1514 uintmax_t change = file->added + file->deleted;
1516 if (!file->is_interesting && (change == 0)) {
1517 count++; /* not shown == room for one more */
1520 fill_print_name(file);
1521 len = strlen(file->print_name);
1525 if (file->is_unmerged) {
1526 /* "Unmerged" is 8 characters */
1527 bin_width = bin_width < 8 ? 8 : bin_width;
1530 if (file->is_binary) {
1531 /* "Bin XXX -> YYY bytes" */
1532 int w = 14 + decimal_width(file->added)
1533 + decimal_width(file->deleted);
1534 bin_width = bin_width < w ? w : bin_width;
1535 /* Display change counts aligned with "Bin" */
1540 if (max_change < change)
1541 max_change = change;
1543 count = i; /* where we can stop scanning in data->files[] */
1546 * We have width = stat_width or term_columns() columns total.
1547 * We want a maximum of min(max_len, stat_name_width) for the name part.
1548 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1549 * We also need 1 for " " and 4 + decimal_width(max_change)
1550 * for " | NNNN " and one the empty column at the end, altogether
1551 * 6 + decimal_width(max_change).
1553 * If there's not enough space, we will use the smaller of
1554 * stat_name_width (if set) and 5/8*width for the filename,
1555 * and the rest for constant elements + graph part, but no more
1556 * than stat_graph_width for the graph part.
1557 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1558 * for the standard terminal size).
1560 * In other words: stat_width limits the maximum width, and
1561 * stat_name_width fixes the maximum width of the filename,
1562 * and is also used to divide available columns if there
1565 * Binary files are displayed with "Bin XXX -> YYY bytes"
1566 * instead of the change count and graph. This part is treated
1567 * similarly to the graph part, except that it is not
1568 * "scaled". If total width is too small to accommodate the
1569 * guaranteed minimum width of the filename part and the
1570 * separators and this message, this message will "overflow"
1571 * making the line longer than the maximum width.
1574 if (options->stat_width == -1)
1575 width = term_columns() - options->output_prefix_length;
1577 width = options->stat_width ? options->stat_width : 80;
1578 number_width = decimal_width(max_change) > number_width ?
1579 decimal_width(max_change) : number_width;
1581 if (options->stat_graph_width == -1)
1582 options->stat_graph_width = diff_stat_graph_width;
1585 * Guarantee 3/8*16==6 for the graph part
1586 * and 5/8*16==10 for the filename part
1588 if (width < 16 + 6 + number_width)
1589 width = 16 + 6 + number_width;
1592 * First assign sizes that are wanted, ignoring available width.
1593 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1594 * starting from "XXX" should fit in graph_width.
1596 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1597 if (options->stat_graph_width &&
1598 options->stat_graph_width < graph_width)
1599 graph_width = options->stat_graph_width;
1601 name_width = (options->stat_name_width > 0 &&
1602 options->stat_name_width < max_len) ?
1603 options->stat_name_width : max_len;
1606 * Adjust adjustable widths not to exceed maximum width
1608 if (name_width + number_width + 6 + graph_width > width) {
1609 if (graph_width > width * 3/8 - number_width - 6) {
1610 graph_width = width * 3/8 - number_width - 6;
1611 if (graph_width < 6)
1615 if (options->stat_graph_width &&
1616 graph_width > options->stat_graph_width)
1617 graph_width = options->stat_graph_width;
1618 if (name_width > width - number_width - 6 - graph_width)
1619 name_width = width - number_width - 6 - graph_width;
1621 graph_width = width - number_width - 6 - name_width;
1625 * From here name_width is the width of the name area,
1626 * and graph_width is the width of the graph area.
1627 * max_change is used to scale graph properly.
1629 for (i = 0; i < count; i++) {
1630 const char *prefix = "";
1631 struct diffstat_file *file = data->files[i];
1632 char *name = file->print_name;
1633 uintmax_t added = file->added;
1634 uintmax_t deleted = file->deleted;
1637 if (!file->is_interesting && (added + deleted == 0))
1641 * "scale" the filename
1644 name_len = strlen(name);
1645 if (name_width < name_len) {
1649 name += name_len - len;
1650 slash = strchr(name, '/');
1655 if (file->is_binary) {
1656 fprintf(options->file, "%s", line_prefix);
1657 show_name(options->file, prefix, name, len);
1658 fprintf(options->file, " %*s", number_width, "Bin");
1659 if (!added && !deleted) {
1660 putc('\n', options->file);
1663 fprintf(options->file, " %s%"PRIuMAX"%s",
1664 del_c, deleted, reset);
1665 fprintf(options->file, " -> ");
1666 fprintf(options->file, "%s%"PRIuMAX"%s",
1667 add_c, added, reset);
1668 fprintf(options->file, " bytes");
1669 fprintf(options->file, "\n");
1672 else if (file->is_unmerged) {
1673 fprintf(options->file, "%s", line_prefix);
1674 show_name(options->file, prefix, name, len);
1675 fprintf(options->file, " Unmerged\n");
1680 * scale the add/delete
1685 if (graph_width <= max_change) {
1686 int total = scale_linear(add + del, graph_width, max_change);
1687 if (total < 2 && add && del)
1688 /* width >= 2 due to the sanity check */
1691 add = scale_linear(add, graph_width, max_change);
1694 del = scale_linear(del, graph_width, max_change);
1698 fprintf(options->file, "%s", line_prefix);
1699 show_name(options->file, prefix, name, len);
1700 fprintf(options->file, " %*"PRIuMAX"%s",
1701 number_width, added + deleted,
1702 added + deleted ? " " : "");
1703 show_graph(options->file, '+', add, add_c, reset);
1704 show_graph(options->file, '-', del, del_c, reset);
1705 fprintf(options->file, "\n");
1708 for (i = 0; i < data->nr; i++) {
1709 struct diffstat_file *file = data->files[i];
1710 uintmax_t added = file->added;
1711 uintmax_t deleted = file->deleted;
1713 if (file->is_unmerged ||
1714 (!file->is_interesting && (added + deleted == 0))) {
1719 if (!file->is_binary) {
1726 fprintf(options->file, "%s ...\n", line_prefix);
1729 fprintf(options->file, "%s", line_prefix);
1730 print_stat_summary(options->file, total_files, adds, dels);
1733 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1735 int i, adds = 0, dels = 0, total_files = data->nr;
1740 for (i = 0; i < data->nr; i++) {
1741 int added = data->files[i]->added;
1742 int deleted= data->files[i]->deleted;
1744 if (data->files[i]->is_unmerged ||
1745 (!data->files[i]->is_interesting && (added + deleted == 0))) {
1747 } else if (!data->files[i]->is_binary) { /* don't count bytes */
1752 fprintf(options->file, "%s", diff_line_prefix(options));
1753 print_stat_summary(options->file, total_files, adds, dels);
1756 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1763 for (i = 0; i < data->nr; i++) {
1764 struct diffstat_file *file = data->files[i];
1766 fprintf(options->file, "%s", diff_line_prefix(options));
1768 if (file->is_binary)
1769 fprintf(options->file, "-\t-\t");
1771 fprintf(options->file,
1772 "%"PRIuMAX"\t%"PRIuMAX"\t",
1773 file->added, file->deleted);
1774 if (options->line_termination) {
1775 fill_print_name(file);
1776 if (!file->is_renamed)
1777 write_name_quoted(file->name, options->file,
1778 options->line_termination);
1780 fputs(file->print_name, options->file);
1781 putc(options->line_termination, options->file);
1784 if (file->is_renamed) {
1785 putc('\0', options->file);
1786 write_name_quoted(file->from_name, options->file, '\0');
1788 write_name_quoted(file->name, options->file, '\0');
1793 struct dirstat_file {
1795 unsigned long changed;
1798 struct dirstat_dir {
1799 struct dirstat_file *files;
1800 int alloc, nr, permille, cumulative;
1803 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1804 unsigned long changed, const char *base, int baselen)
1806 unsigned long this_dir = 0;
1807 unsigned int sources = 0;
1808 const char *line_prefix = diff_line_prefix(opt);
1811 struct dirstat_file *f = dir->files;
1812 int namelen = strlen(f->name);
1816 if (namelen < baselen)
1818 if (memcmp(f->name, base, baselen))
1820 slash = strchr(f->name + baselen, '/');
1822 int newbaselen = slash + 1 - f->name;
1823 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1835 * We don't report dirstat's for
1837 * - or cases where everything came from a single directory
1838 * under this directory (sources == 1).
1840 if (baselen && sources != 1) {
1842 int permille = this_dir * 1000 / changed;
1843 if (permille >= dir->permille) {
1844 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1845 permille / 10, permille % 10, baselen, base);
1846 if (!dir->cumulative)
1854 static int dirstat_compare(const void *_a, const void *_b)
1856 const struct dirstat_file *a = _a;
1857 const struct dirstat_file *b = _b;
1858 return strcmp(a->name, b->name);
1861 static void show_dirstat(struct diff_options *options)
1864 unsigned long changed;
1865 struct dirstat_dir dir;
1866 struct diff_queue_struct *q = &diff_queued_diff;
1871 dir.permille = options->dirstat_permille;
1872 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1875 for (i = 0; i < q->nr; i++) {
1876 struct diff_filepair *p = q->queue[i];
1878 unsigned long copied, added, damage;
1879 int content_changed;
1881 name = p->two->path ? p->two->path : p->one->path;
1883 if (p->one->sha1_valid && p->two->sha1_valid)
1884 content_changed = hashcmp(p->one->sha1, p->two->sha1);
1886 content_changed = 1;
1888 if (!content_changed) {
1890 * The SHA1 has not changed, so pre-/post-content is
1891 * identical. We can therefore skip looking at the
1892 * file contents altogether.
1898 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1900 * In --dirstat-by-file mode, we don't really need to
1901 * look at the actual file contents at all.
1902 * The fact that the SHA1 changed is enough for us to
1903 * add this file to the list of results
1904 * (with each file contributing equal damage).
1910 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1911 diff_populate_filespec(p->one, 0);
1912 diff_populate_filespec(p->two, 0);
1913 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1915 diff_free_filespec_data(p->one);
1916 diff_free_filespec_data(p->two);
1917 } else if (DIFF_FILE_VALID(p->one)) {
1918 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
1920 diff_free_filespec_data(p->one);
1921 } else if (DIFF_FILE_VALID(p->two)) {
1922 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
1924 added = p->two->size;
1925 diff_free_filespec_data(p->two);
1930 * Original minus copied is the removed material,
1931 * added is the new material. They are both damages
1932 * made to the preimage.
1933 * If the resulting damage is zero, we know that
1934 * diffcore_count_changes() considers the two entries to
1935 * be identical, but since content_changed is true, we
1936 * know that there must have been _some_ kind of change,
1937 * so we force all entries to have damage > 0.
1939 damage = (p->one->size - copied) + added;
1944 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1945 dir.files[dir.nr].name = name;
1946 dir.files[dir.nr].changed = damage;
1951 /* This can happen even with many files, if everything was renames */
1955 /* Show all directories with more than x% of the changes */
1956 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1957 gather_dirstat(options, &dir, changed, "", 0);
1960 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
1963 unsigned long changed;
1964 struct dirstat_dir dir;
1972 dir.permille = options->dirstat_permille;
1973 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1976 for (i = 0; i < data->nr; i++) {
1977 struct diffstat_file *file = data->files[i];
1978 unsigned long damage = file->added + file->deleted;
1979 if (file->is_binary)
1981 * binary files counts bytes, not lines. Must find some
1982 * way to normalize binary bytes vs. textual lines.
1983 * The following heuristic assumes that there are 64
1985 * This is stupid and ugly, but very cheap...
1987 damage = (damage + 63) / 64;
1988 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1989 dir.files[dir.nr].name = file->name;
1990 dir.files[dir.nr].changed = damage;
1995 /* This can happen even with many files, if everything was renames */
1999 /* Show all directories with more than x% of the changes */
2000 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2001 gather_dirstat(options, &dir, changed, "", 0);
2004 static void free_diffstat_info(struct diffstat_t *diffstat)
2007 for (i = 0; i < diffstat->nr; i++) {
2008 struct diffstat_file *f = diffstat->files[i];
2009 if (f->name != f->print_name)
2010 free(f->print_name);
2015 free(diffstat->files);
2018 struct checkdiff_t {
2019 const char *filename;
2021 int conflict_marker_size;
2022 struct diff_options *o;
2027 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2032 if (len < marker_size + 1)
2034 firstchar = line[0];
2035 switch (firstchar) {
2036 case '=': case '>': case '<': case '|':
2041 for (cnt = 1; cnt < marker_size; cnt++)
2042 if (line[cnt] != firstchar)
2044 /* line[1] thru line[marker_size-1] are same as firstchar */
2045 if (len < marker_size + 1 || !isspace(line[marker_size]))
2050 static void checkdiff_consume(void *priv, char *line, unsigned long len)
2052 struct checkdiff_t *data = priv;
2053 int marker_size = data->conflict_marker_size;
2054 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2055 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2056 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2058 const char *line_prefix;
2061 line_prefix = diff_line_prefix(data->o);
2063 if (line[0] == '+') {
2066 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2068 fprintf(data->o->file,
2069 "%s%s:%d: leftover conflict marker\n",
2070 line_prefix, data->filename, data->lineno);
2072 bad = ws_check(line + 1, len - 1, data->ws_rule);
2075 data->status |= bad;
2076 err = whitespace_error_string(bad);
2077 fprintf(data->o->file, "%s%s:%d: %s.\n",
2078 line_prefix, data->filename, data->lineno, err);
2080 emit_line(data->o, set, reset, line, 1);
2081 ws_check_emit(line + 1, len - 1, data->ws_rule,
2082 data->o->file, set, reset, ws);
2083 } else if (line[0] == ' ') {
2085 } else if (line[0] == '@') {
2086 char *plus = strchr(line, '+');
2088 data->lineno = strtol(plus, NULL, 10) - 1;
2090 die("invalid diff");
2094 static unsigned char *deflate_it(char *data,
2096 unsigned long *result_size)
2099 unsigned char *deflated;
2102 git_deflate_init(&stream, zlib_compression_level);
2103 bound = git_deflate_bound(&stream, size);
2104 deflated = xmalloc(bound);
2105 stream.next_out = deflated;
2106 stream.avail_out = bound;
2108 stream.next_in = (unsigned char *)data;
2109 stream.avail_in = size;
2110 while (git_deflate(&stream, Z_FINISH) == Z_OK)
2112 git_deflate_end(&stream);
2113 *result_size = stream.total_out;
2117 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two,
2124 unsigned long orig_size;
2125 unsigned long delta_size;
2126 unsigned long deflate_size;
2127 unsigned long data_size;
2129 /* We could do deflated delta, or we could do just deflated two,
2130 * whichever is smaller.
2133 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2134 if (one->size && two->size) {
2135 delta = diff_delta(one->ptr, one->size,
2136 two->ptr, two->size,
2137 &delta_size, deflate_size);
2139 void *to_free = delta;
2140 orig_size = delta_size;
2141 delta = deflate_it(delta, delta_size, &delta_size);
2146 if (delta && delta_size < deflate_size) {
2147 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2150 data_size = delta_size;
2153 fprintf(file, "%sliteral %lu\n", prefix, two->size);
2156 data_size = deflate_size;
2159 /* emit data encoded in base85 */
2162 int bytes = (52 < data_size) ? 52 : data_size;
2166 line[0] = bytes + 'A' - 1;
2168 line[0] = bytes - 26 + 'a' - 1;
2169 encode_85(line + 1, cp, bytes);
2170 cp = (char *) cp + bytes;
2171 fprintf(file, "%s", prefix);
2175 fprintf(file, "%s\n", prefix);
2179 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two,
2182 fprintf(file, "%sGIT binary patch\n", prefix);
2183 emit_binary_diff_body(file, one, two, prefix);
2184 emit_binary_diff_body(file, two, one, prefix);
2187 int diff_filespec_is_binary(struct diff_filespec *one)
2189 if (one->is_binary == -1) {
2190 diff_filespec_load_driver(one);
2191 if (one->driver->binary != -1)
2192 one->is_binary = one->driver->binary;
2194 if (!one->data && DIFF_FILE_VALID(one))
2195 diff_populate_filespec(one, CHECK_BINARY);
2196 if (one->is_binary == -1 && one->data)
2197 one->is_binary = buffer_is_binary(one->data,
2199 if (one->is_binary == -1)
2203 return one->is_binary;
2206 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2208 diff_filespec_load_driver(one);
2209 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2212 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2214 if (!options->a_prefix)
2215 options->a_prefix = a;
2216 if (!options->b_prefix)
2217 options->b_prefix = b;
2220 struct userdiff_driver *get_textconv(struct diff_filespec *one)
2222 if (!DIFF_FILE_VALID(one))
2225 diff_filespec_load_driver(one);
2226 return userdiff_get_textconv(one->driver);
2229 static void builtin_diff(const char *name_a,
2231 struct diff_filespec *one,
2232 struct diff_filespec *two,
2233 const char *xfrm_msg,
2234 int must_show_header,
2235 struct diff_options *o,
2236 int complete_rewrite)
2240 char *a_one, *b_two;
2241 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2242 const char *reset = diff_get_color_opt(o, DIFF_RESET);
2243 const char *a_prefix, *b_prefix;
2244 struct userdiff_driver *textconv_one = NULL;
2245 struct userdiff_driver *textconv_two = NULL;
2246 struct strbuf header = STRBUF_INIT;
2247 const char *line_prefix = diff_line_prefix(o);
2249 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2250 (!one->mode || S_ISGITLINK(one->mode)) &&
2251 (!two->mode || S_ISGITLINK(two->mode))) {
2252 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2253 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2254 show_submodule_summary(o->file, one->path ? one->path : two->path,
2256 one->sha1, two->sha1, two->dirty_submodule,
2257 meta, del, add, reset);
2261 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2262 textconv_one = get_textconv(one);
2263 textconv_two = get_textconv(two);
2266 diff_set_mnemonic_prefix(o, "a/", "b/");
2267 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2268 a_prefix = o->b_prefix;
2269 b_prefix = o->a_prefix;
2271 a_prefix = o->a_prefix;
2272 b_prefix = o->b_prefix;
2275 /* Never use a non-valid filename anywhere if at all possible */
2276 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2277 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2279 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2280 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2281 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2282 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2283 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2284 if (lbl[0][0] == '/') {
2286 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2288 strbuf_addstr(&header, xfrm_msg);
2289 must_show_header = 1;
2291 else if (lbl[1][0] == '/') {
2292 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2294 strbuf_addstr(&header, xfrm_msg);
2295 must_show_header = 1;
2298 if (one->mode != two->mode) {
2299 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2300 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2301 must_show_header = 1;
2304 strbuf_addstr(&header, xfrm_msg);
2307 * we do not run diff between different kind
2310 if ((one->mode ^ two->mode) & S_IFMT)
2311 goto free_ab_and_return;
2312 if (complete_rewrite &&
2313 (textconv_one || !diff_filespec_is_binary(one)) &&
2314 (textconv_two || !diff_filespec_is_binary(two))) {
2315 fprintf(o->file, "%s", header.buf);
2316 strbuf_reset(&header);
2317 emit_rewrite_diff(name_a, name_b, one, two,
2318 textconv_one, textconv_two, o);
2319 o->found_changes = 1;
2320 goto free_ab_and_return;
2324 if (o->irreversible_delete && lbl[1][0] == '/') {
2325 fprintf(o->file, "%s", header.buf);
2326 strbuf_reset(&header);
2327 goto free_ab_and_return;
2328 } else if (!DIFF_OPT_TST(o, TEXT) &&
2329 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2330 (!textconv_two && diff_filespec_is_binary(two)) )) {
2331 if (!one->data && !two->data &&
2332 S_ISREG(one->mode) && S_ISREG(two->mode) &&
2333 !DIFF_OPT_TST(o, BINARY)) {
2334 if (!hashcmp(one->sha1, two->sha1)) {
2335 if (must_show_header)
2336 fprintf(o->file, "%s", header.buf);
2337 goto free_ab_and_return;
2339 fprintf(o->file, "%s", header.buf);
2340 fprintf(o->file, "%sBinary files %s and %s differ\n",
2341 line_prefix, lbl[0], lbl[1]);
2342 goto free_ab_and_return;
2344 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2345 die("unable to read files to diff");
2346 /* Quite common confusing case */
2347 if (mf1.size == mf2.size &&
2348 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2349 if (must_show_header)
2350 fprintf(o->file, "%s", header.buf);
2351 goto free_ab_and_return;
2353 fprintf(o->file, "%s", header.buf);
2354 strbuf_reset(&header);
2355 if (DIFF_OPT_TST(o, BINARY))
2356 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2358 fprintf(o->file, "%sBinary files %s and %s differ\n",
2359 line_prefix, lbl[0], lbl[1]);
2360 o->found_changes = 1;
2362 /* Crazy xdl interfaces.. */
2363 const char *diffopts = getenv("GIT_DIFF_OPTS");
2367 struct emit_callback ecbdata;
2368 const struct userdiff_funcname *pe;
2370 if (must_show_header) {
2371 fprintf(o->file, "%s", header.buf);
2372 strbuf_reset(&header);
2375 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2376 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2378 pe = diff_funcname_pattern(one);
2380 pe = diff_funcname_pattern(two);
2382 memset(&xpp, 0, sizeof(xpp));
2383 memset(&xecfg, 0, sizeof(xecfg));
2384 memset(&ecbdata, 0, sizeof(ecbdata));
2385 ecbdata.label_path = lbl;
2386 ecbdata.color_diff = want_color(o->use_color);
2387 ecbdata.found_changesp = &o->found_changes;
2388 ecbdata.ws_rule = whitespace_rule(name_b);
2389 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2390 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2392 ecbdata.header = header.len ? &header : NULL;
2393 xpp.flags = o->xdl_opts;
2394 xecfg.ctxlen = o->context;
2395 xecfg.interhunkctxlen = o->interhunkcontext;
2396 xecfg.flags = XDL_EMIT_FUNCNAMES;
2397 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2398 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2400 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2403 else if (skip_prefix(diffopts, "--unified=", &v))
2404 xecfg.ctxlen = strtoul(v, NULL, 10);
2405 else if (skip_prefix(diffopts, "-u", &v))
2406 xecfg.ctxlen = strtoul(v, NULL, 10);
2408 init_diff_words_data(&ecbdata, o, one, two);
2409 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2412 free_diff_words_data(&ecbdata);
2417 xdiff_clear_find_func(&xecfg);
2421 strbuf_release(&header);
2422 diff_free_filespec_data(one);
2423 diff_free_filespec_data(two);
2429 static void builtin_diffstat(const char *name_a, const char *name_b,
2430 struct diff_filespec *one,
2431 struct diff_filespec *two,
2432 struct diffstat_t *diffstat,
2433 struct diff_options *o,
2434 struct diff_filepair *p)
2437 struct diffstat_file *data;
2439 int complete_rewrite = 0;
2441 if (!DIFF_PAIR_UNMERGED(p)) {
2442 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2443 complete_rewrite = 1;
2446 data = diffstat_add(diffstat, name_a, name_b);
2447 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2450 data->is_unmerged = 1;
2454 same_contents = !hashcmp(one->sha1, two->sha1);
2456 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2457 data->is_binary = 1;
2458 if (same_contents) {
2462 data->added = diff_filespec_size(two);
2463 data->deleted = diff_filespec_size(one);
2467 else if (complete_rewrite) {
2468 diff_populate_filespec(one, 0);
2469 diff_populate_filespec(two, 0);
2470 data->deleted = count_lines(one->data, one->size);
2471 data->added = count_lines(two->data, two->size);
2474 else if (!same_contents) {
2475 /* Crazy xdl interfaces.. */
2479 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2480 die("unable to read files to diff");
2482 memset(&xpp, 0, sizeof(xpp));
2483 memset(&xecfg, 0, sizeof(xecfg));
2484 xpp.flags = o->xdl_opts;
2485 xecfg.ctxlen = o->context;
2486 xecfg.interhunkctxlen = o->interhunkcontext;
2487 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2491 diff_free_filespec_data(one);
2492 diff_free_filespec_data(two);
2495 static void builtin_checkdiff(const char *name_a, const char *name_b,
2496 const char *attr_path,
2497 struct diff_filespec *one,
2498 struct diff_filespec *two,
2499 struct diff_options *o)
2502 struct checkdiff_t data;
2507 memset(&data, 0, sizeof(data));
2508 data.filename = name_b ? name_b : name_a;
2511 data.ws_rule = whitespace_rule(attr_path);
2512 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2514 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2515 die("unable to read files to diff");
2518 * All the other codepaths check both sides, but not checking
2519 * the "old" side here is deliberate. We are checking the newly
2520 * introduced changes, and as long as the "new" side is text, we
2521 * can and should check what it introduces.
2523 if (diff_filespec_is_binary(two))
2524 goto free_and_return;
2526 /* Crazy xdl interfaces.. */
2530 memset(&xpp, 0, sizeof(xpp));
2531 memset(&xecfg, 0, sizeof(xecfg));
2532 xecfg.ctxlen = 1; /* at least one context line */
2534 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2537 if (data.ws_rule & WS_BLANK_AT_EOF) {
2538 struct emit_callback ecbdata;
2541 ecbdata.ws_rule = data.ws_rule;
2542 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2543 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2548 err = whitespace_error_string(WS_BLANK_AT_EOF);
2549 fprintf(o->file, "%s:%d: %s.\n",
2550 data.filename, blank_at_eof, err);
2551 data.status = 1; /* report errors */
2556 diff_free_filespec_data(one);
2557 diff_free_filespec_data(two);
2559 DIFF_OPT_SET(o, CHECK_FAILED);
2562 struct diff_filespec *alloc_filespec(const char *path)
2564 int namelen = strlen(path);
2565 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2567 memset(spec, 0, sizeof(*spec));
2568 spec->path = (char *)(spec + 1);
2569 memcpy(spec->path, path, namelen+1);
2571 spec->is_binary = -1;
2575 void free_filespec(struct diff_filespec *spec)
2577 if (!--spec->count) {
2578 diff_free_filespec_data(spec);
2583 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2584 int sha1_valid, unsigned short mode)
2587 spec->mode = canon_mode(mode);
2588 hashcpy(spec->sha1, sha1);
2589 spec->sha1_valid = sha1_valid;
2594 * Given a name and sha1 pair, if the index tells us the file in
2595 * the work tree has that object contents, return true, so that
2596 * prepare_temp_file() does not have to inflate and extract.
2598 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2600 const struct cache_entry *ce;
2605 * We do not read the cache ourselves here, because the
2606 * benchmark with my previous version that always reads cache
2607 * shows that it makes things worse for diff-tree comparing
2608 * two linux-2.6 kernel trees in an already checked out work
2609 * tree. This is because most diff-tree comparisons deal with
2610 * only a small number of files, while reading the cache is
2611 * expensive for a large project, and its cost outweighs the
2612 * savings we get by not inflating the object to a temporary
2613 * file. Practically, this code only helps when we are used
2614 * by diff-cache --cached, which does read the cache before
2620 /* We want to avoid the working directory if our caller
2621 * doesn't need the data in a normal file, this system
2622 * is rather slow with its stat/open/mmap/close syscalls,
2623 * and the object is contained in a pack file. The pack
2624 * is probably already open and will be faster to obtain
2625 * the data through than the working directory. Loose
2626 * objects however would tend to be slower as they need
2627 * to be individually opened and inflated.
2629 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2633 pos = cache_name_pos(name, len);
2636 ce = active_cache[pos];
2639 * This is not the sha1 we are looking for, or
2640 * unreusable because it is not a regular file.
2642 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2646 * If ce is marked as "assume unchanged", there is no
2647 * guarantee that work tree matches what we are looking for.
2649 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2653 * If ce matches the file in the work tree, we can reuse it.
2655 if (ce_uptodate(ce) ||
2656 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2662 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2665 char *data = xmalloc(100), *dirty = "";
2667 /* Are we looking at the work tree? */
2668 if (s->dirty_submodule)
2671 len = snprintf(data, 100,
2672 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2684 * While doing rename detection and pickaxe operation, we may need to
2685 * grab the data for the blob (or file) for our own in-core comparison.
2686 * diff_filespec has data and size fields for this purpose.
2688 int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
2690 int size_only = flags & CHECK_SIZE_ONLY;
2693 * demote FAIL to WARN to allow inspecting the situation
2694 * instead of refusing.
2696 enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
2700 if (!DIFF_FILE_VALID(s))
2701 die("internal error: asking to populate invalid file.");
2702 if (S_ISDIR(s->mode))
2708 if (size_only && 0 < s->size)
2711 if (S_ISGITLINK(s->mode))
2712 return diff_populate_gitlink(s, size_only);
2714 if (!s->sha1_valid ||
2715 reuse_worktree_file(s->path, s->sha1, 0)) {
2716 struct strbuf buf = STRBUF_INIT;
2720 if (lstat(s->path, &st) < 0) {
2721 if (errno == ENOENT) {
2725 s->data = (char *)"";
2730 s->size = xsize_t(st.st_size);
2733 if (S_ISLNK(st.st_mode)) {
2734 struct strbuf sb = STRBUF_INIT;
2736 if (strbuf_readlink(&sb, s->path, s->size))
2739 s->data = strbuf_detach(&sb, NULL);
2745 if ((flags & CHECK_BINARY) &&
2746 s->size > big_file_threshold && s->is_binary == -1) {
2750 fd = open(s->path, O_RDONLY);
2753 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2755 s->should_munmap = 1;
2758 * Convert from working tree format to canonical git format
2760 if (convert_to_git(s->path, s->data, s->size, &buf, crlf_warn)) {
2762 munmap(s->data, s->size);
2763 s->should_munmap = 0;
2764 s->data = strbuf_detach(&buf, &size);
2770 enum object_type type;
2771 if (size_only || (flags & CHECK_BINARY)) {
2772 type = sha1_object_info(s->sha1, &s->size);
2774 die("unable to read %s", sha1_to_hex(s->sha1));
2777 if (s->size > big_file_threshold && s->is_binary == -1) {
2782 s->data = read_sha1_file(s->sha1, &type, &s->size);
2784 die("unable to read %s", sha1_to_hex(s->sha1));
2790 void diff_free_filespec_blob(struct diff_filespec *s)
2794 else if (s->should_munmap)
2795 munmap(s->data, s->size);
2797 if (s->should_free || s->should_munmap) {
2798 s->should_free = s->should_munmap = 0;
2803 void diff_free_filespec_data(struct diff_filespec *s)
2805 diff_free_filespec_blob(s);
2810 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2813 const unsigned char *sha1,
2817 struct strbuf buf = STRBUF_INIT;
2818 struct strbuf template = STRBUF_INIT;
2819 char *path_dup = xstrdup(path);
2820 const char *base = basename(path_dup);
2822 /* Generate "XXXXXX_basename.ext" */
2823 strbuf_addstr(&template, "XXXXXX_");
2824 strbuf_addstr(&template, base);
2826 fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
2828 die_errno("unable to create temp-file");
2829 if (convert_to_working_tree(path,
2830 (const char *)blob, (size_t)size, &buf)) {
2834 if (write_in_full(fd, blob, size) != size)
2835 die_errno("unable to write temp-file");
2836 close_tempfile(&temp->tempfile);
2837 temp->name = get_tempfile_path(&temp->tempfile);
2838 strcpy(temp->hex, sha1_to_hex(sha1));
2840 sprintf(temp->mode, "%06o", mode);
2841 strbuf_release(&buf);
2842 strbuf_release(&template);
2846 static struct diff_tempfile *prepare_temp_file(const char *name,
2847 struct diff_filespec *one)
2849 struct diff_tempfile *temp = claim_diff_tempfile();
2851 if (!DIFF_FILE_VALID(one)) {
2853 /* A '-' entry produces this for file-2, and
2854 * a '+' entry produces this for file-1.
2856 temp->name = "/dev/null";
2857 strcpy(temp->hex, ".");
2858 strcpy(temp->mode, ".");
2862 if (!S_ISGITLINK(one->mode) &&
2863 (!one->sha1_valid ||
2864 reuse_worktree_file(name, one->sha1, 1))) {
2866 if (lstat(name, &st) < 0) {
2867 if (errno == ENOENT)
2868 goto not_a_valid_file;
2869 die_errno("stat(%s)", name);
2871 if (S_ISLNK(st.st_mode)) {
2872 struct strbuf sb = STRBUF_INIT;
2873 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2874 die_errno("readlink(%s)", name);
2875 prep_temp_blob(name, temp, sb.buf, sb.len,
2877 one->sha1 : null_sha1),
2879 one->mode : S_IFLNK));
2880 strbuf_release(&sb);
2883 /* we can borrow from the file in the work tree */
2885 if (!one->sha1_valid)
2886 strcpy(temp->hex, sha1_to_hex(null_sha1));
2888 strcpy(temp->hex, sha1_to_hex(one->sha1));
2889 /* Even though we may sometimes borrow the
2890 * contents from the work tree, we always want
2891 * one->mode. mode is trustworthy even when
2892 * !(one->sha1_valid), as long as
2893 * DIFF_FILE_VALID(one).
2895 sprintf(temp->mode, "%06o", one->mode);
2900 if (diff_populate_filespec(one, 0))
2901 die("cannot read data blob for %s", one->path);
2902 prep_temp_blob(name, temp, one->data, one->size,
2903 one->sha1, one->mode);
2908 static void add_external_diff_name(struct argv_array *argv,
2910 struct diff_filespec *df)
2912 struct diff_tempfile *temp = prepare_temp_file(name, df);
2913 argv_array_push(argv, temp->name);
2914 argv_array_push(argv, temp->hex);
2915 argv_array_push(argv, temp->mode);
2918 /* An external diff command takes:
2920 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2921 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2924 static void run_external_diff(const char *pgm,
2927 struct diff_filespec *one,
2928 struct diff_filespec *two,
2929 const char *xfrm_msg,
2930 int complete_rewrite,
2931 struct diff_options *o)
2933 struct argv_array argv = ARGV_ARRAY_INIT;
2934 struct argv_array env = ARGV_ARRAY_INIT;
2935 struct diff_queue_struct *q = &diff_queued_diff;
2937 argv_array_push(&argv, pgm);
2938 argv_array_push(&argv, name);
2941 add_external_diff_name(&argv, name, one);
2943 add_external_diff_name(&argv, name, two);
2945 add_external_diff_name(&argv, other, two);
2946 argv_array_push(&argv, other);
2947 argv_array_push(&argv, xfrm_msg);
2951 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
2952 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
2954 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
2955 die(_("external diff died, stopping at %s"), name);
2958 argv_array_clear(&argv);
2959 argv_array_clear(&env);
2962 static int similarity_index(struct diff_filepair *p)
2964 return p->score * 100 / MAX_SCORE;
2967 static void fill_metainfo(struct strbuf *msg,
2970 struct diff_filespec *one,
2971 struct diff_filespec *two,
2972 struct diff_options *o,
2973 struct diff_filepair *p,
2974 int *must_show_header,
2977 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2978 const char *reset = diff_get_color(use_color, DIFF_RESET);
2979 const char *line_prefix = diff_line_prefix(o);
2981 *must_show_header = 1;
2982 strbuf_init(msg, PATH_MAX * 2 + 300);
2983 switch (p->status) {
2984 case DIFF_STATUS_COPIED:
2985 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2986 line_prefix, set, similarity_index(p));
2987 strbuf_addf(msg, "%s\n%s%scopy from ",
2988 reset, line_prefix, set);
2989 quote_c_style(name, msg, NULL, 0);
2990 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
2991 quote_c_style(other, msg, NULL, 0);
2992 strbuf_addf(msg, "%s\n", reset);
2994 case DIFF_STATUS_RENAMED:
2995 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2996 line_prefix, set, similarity_index(p));
2997 strbuf_addf(msg, "%s\n%s%srename from ",
2998 reset, line_prefix, set);
2999 quote_c_style(name, msg, NULL, 0);
3000 strbuf_addf(msg, "%s\n%s%srename to ",
3001 reset, line_prefix, set);
3002 quote_c_style(other, msg, NULL, 0);
3003 strbuf_addf(msg, "%s\n", reset);
3005 case DIFF_STATUS_MODIFIED:
3007 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3009 set, similarity_index(p), reset);
3014 *must_show_header = 0;
3016 if (one && two && hashcmp(one->sha1, two->sha1)) {
3017 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3019 if (DIFF_OPT_TST(o, BINARY)) {
3021 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3022 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3025 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
3026 find_unique_abbrev(one->sha1, abbrev));
3027 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
3028 if (one->mode == two->mode)
3029 strbuf_addf(msg, " %06o", one->mode);
3030 strbuf_addf(msg, "%s\n", reset);
3034 static void run_diff_cmd(const char *pgm,
3037 const char *attr_path,
3038 struct diff_filespec *one,
3039 struct diff_filespec *two,
3041 struct diff_options *o,
3042 struct diff_filepair *p)
3044 const char *xfrm_msg = NULL;
3045 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3046 int must_show_header = 0;
3049 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3050 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3051 if (drv && drv->external)
3052 pgm = drv->external;
3057 * don't use colors when the header is intended for an
3058 * external diff driver
3060 fill_metainfo(msg, name, other, one, two, o, p,
3062 want_color(o->use_color) && !pgm);
3063 xfrm_msg = msg->len ? msg->buf : NULL;
3067 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3068 complete_rewrite, o);
3072 builtin_diff(name, other ? other : name,
3073 one, two, xfrm_msg, must_show_header,
3074 o, complete_rewrite);
3076 fprintf(o->file, "* Unmerged path %s\n", name);
3079 static void diff_fill_sha1_info(struct diff_filespec *one)
3081 if (DIFF_FILE_VALID(one)) {
3082 if (!one->sha1_valid) {
3084 if (one->is_stdin) {
3085 hashcpy(one->sha1, null_sha1);
3088 if (lstat(one->path, &st) < 0)
3089 die_errno("stat '%s'", one->path);
3090 if (index_path(one->sha1, one->path, &st, 0))
3091 die("cannot hash %s", one->path);
3098 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3100 /* Strip the prefix but do not molest /dev/null and absolute paths */
3101 if (*namep && **namep != '/') {
3102 *namep += prefix_length;
3106 if (*otherp && **otherp != '/') {
3107 *otherp += prefix_length;
3108 if (**otherp == '/')
3113 static void run_diff(struct diff_filepair *p, struct diff_options *o)
3115 const char *pgm = external_diff();
3117 struct diff_filespec *one = p->one;
3118 struct diff_filespec *two = p->two;
3121 const char *attr_path;
3123 name = p->one->path;
3124 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3126 if (o->prefix_length)
3127 strip_prefix(o->prefix_length, &name, &other);
3129 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3132 if (DIFF_PAIR_UNMERGED(p)) {
3133 run_diff_cmd(pgm, name, NULL, attr_path,
3134 NULL, NULL, NULL, o, p);
3138 diff_fill_sha1_info(one);
3139 diff_fill_sha1_info(two);
3142 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3143 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3145 * a filepair that changes between file and symlink
3146 * needs to be split into deletion and creation.
3148 struct diff_filespec *null = alloc_filespec(two->path);
3149 run_diff_cmd(NULL, name, other, attr_path,
3150 one, null, &msg, o, p);
3152 strbuf_release(&msg);
3154 null = alloc_filespec(one->path);
3155 run_diff_cmd(NULL, name, other, attr_path,
3156 null, two, &msg, o, p);
3160 run_diff_cmd(pgm, name, other, attr_path,
3161 one, two, &msg, o, p);
3163 strbuf_release(&msg);
3166 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3167 struct diffstat_t *diffstat)
3172 if (DIFF_PAIR_UNMERGED(p)) {
3174 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3178 name = p->one->path;
3179 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3181 if (o->prefix_length)
3182 strip_prefix(o->prefix_length, &name, &other);
3184 diff_fill_sha1_info(p->one);
3185 diff_fill_sha1_info(p->two);
3187 builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3190 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3194 const char *attr_path;
3196 if (DIFF_PAIR_UNMERGED(p)) {
3201 name = p->one->path;
3202 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3203 attr_path = other ? other : name;
3205 if (o->prefix_length)
3206 strip_prefix(o->prefix_length, &name, &other);
3208 diff_fill_sha1_info(p->one);
3209 diff_fill_sha1_info(p->two);
3211 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3214 void diff_setup(struct diff_options *options)
3216 memcpy(options, &default_diff_options, sizeof(*options));
3218 options->file = stdout;
3220 options->line_termination = '\n';
3221 options->break_opt = -1;
3222 options->rename_limit = -1;
3223 options->dirstat_permille = diff_dirstat_permille_default;
3224 options->context = diff_context_default;
3225 DIFF_OPT_SET(options, RENAME_EMPTY);
3227 /* pathchange left =NULL by default */
3228 options->change = diff_change;
3229 options->add_remove = diff_addremove;
3230 options->use_color = diff_use_color_default;
3231 options->detect_rename = diff_detect_rename_default;
3232 options->xdl_opts |= diff_algorithm;
3234 options->orderfile = diff_order_file_cfg;
3236 if (diff_no_prefix) {
3237 options->a_prefix = options->b_prefix = "";
3238 } else if (!diff_mnemonic_prefix) {
3239 options->a_prefix = "a/";
3240 options->b_prefix = "b/";
3244 void diff_setup_done(struct diff_options *options)
3248 if (options->set_default)
3249 options->set_default(options);
3251 if (options->output_format & DIFF_FORMAT_NAME)
3253 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3255 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3257 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3260 die("--name-only, --name-status, --check and -s are mutually exclusive");
3263 * Most of the time we can say "there are changes"
3264 * only by checking if there are changed paths, but
3265 * --ignore-whitespace* options force us to look
3269 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3270 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3271 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3272 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3274 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3276 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3277 options->detect_rename = DIFF_DETECT_COPY;
3279 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3280 options->prefix = NULL;
3281 if (options->prefix)
3282 options->prefix_length = strlen(options->prefix);
3284 options->prefix_length = 0;
3286 if (options->output_format & (DIFF_FORMAT_NAME |
3287 DIFF_FORMAT_NAME_STATUS |
3288 DIFF_FORMAT_CHECKDIFF |
3289 DIFF_FORMAT_NO_OUTPUT))
3290 options->output_format &= ~(DIFF_FORMAT_RAW |
3291 DIFF_FORMAT_NUMSTAT |
3292 DIFF_FORMAT_DIFFSTAT |
3293 DIFF_FORMAT_SHORTSTAT |
3294 DIFF_FORMAT_DIRSTAT |
3295 DIFF_FORMAT_SUMMARY |
3299 * These cases always need recursive; we do not drop caller-supplied
3300 * recursive bits for other formats here.
3302 if (options->output_format & (DIFF_FORMAT_PATCH |
3303 DIFF_FORMAT_NUMSTAT |
3304 DIFF_FORMAT_DIFFSTAT |
3305 DIFF_FORMAT_SHORTSTAT |
3306 DIFF_FORMAT_DIRSTAT |
3307 DIFF_FORMAT_SUMMARY |
3308 DIFF_FORMAT_CHECKDIFF))
3309 DIFF_OPT_SET(options, RECURSIVE);
3311 * Also pickaxe would not work very well if you do not say recursive
3313 if (options->pickaxe)
3314 DIFF_OPT_SET(options, RECURSIVE);
3316 * When patches are generated, submodules diffed against the work tree
3317 * must be checked for dirtiness too so it can be shown in the output
3319 if (options->output_format & DIFF_FORMAT_PATCH)
3320 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3322 if (options->detect_rename && options->rename_limit < 0)
3323 options->rename_limit = diff_rename_limit_default;
3324 if (options->setup & DIFF_SETUP_USE_CACHE) {
3326 /* read-cache does not die even when it fails
3327 * so it is safe for us to do this here. Also
3328 * it does not smudge active_cache or active_nr
3329 * when it fails, so we do not have to worry about
3330 * cleaning it up ourselves either.
3334 if (options->abbrev <= 0 || 40 < options->abbrev)
3335 options->abbrev = 40; /* full */
3338 * It does not make sense to show the first hit we happened
3339 * to have found. It does not make sense not to return with
3340 * exit code in such a case either.
3342 if (DIFF_OPT_TST(options, QUICK)) {
3343 options->output_format = DIFF_FORMAT_NO_OUTPUT;
3344 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3347 options->diff_path_counter = 0;
3349 if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3350 die(_("--follow requires exactly one pathspec"));
3353 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3363 if (c == arg_short) {
3367 if (val && isdigit(c)) {
3369 int n = strtoul(arg, &end, 10);
3380 eq = strchrnul(arg, '=');
3382 if (!len || strncmp(arg, arg_long, len))
3387 if (!isdigit(*++eq))
3389 n = strtoul(eq, &end, 10);
3397 static int diff_scoreopt_parse(const char *opt);
3399 static inline int short_opt(char opt, const char **argv,
3400 const char **optarg)
3402 const char *arg = argv[0];
3403 if (arg[0] != '-' || arg[1] != opt)
3405 if (arg[2] != '\0') {
3410 die("Option '%c' requires a value", opt);
3415 int parse_long_opt(const char *opt, const char **argv,
3416 const char **optarg)
3418 const char *arg = argv[0];
3419 if (!skip_prefix(arg, "--", &arg))
3421 if (!skip_prefix(arg, opt, &arg))
3423 if (*arg == '=') { /* stuck form: --option=value */
3429 /* separate form: --option value */
3431 die("Option '--%s' requires a value", opt);
3436 static int stat_opt(struct diff_options *options, const char **av)
3438 const char *arg = av[0];
3440 int width = options->stat_width;
3441 int name_width = options->stat_name_width;
3442 int graph_width = options->stat_graph_width;
3443 int count = options->stat_count;
3446 if (!skip_prefix(arg, "--stat", &arg))
3447 die("BUG: stat option does not begin with --stat: %s", arg);
3452 if (skip_prefix(arg, "-width", &arg)) {
3454 width = strtoul(arg + 1, &end, 10);
3455 else if (!*arg && !av[1])
3456 die("Option '--stat-width' requires a value");
3458 width = strtoul(av[1], &end, 10);
3461 } else if (skip_prefix(arg, "-name-width", &arg)) {
3463 name_width = strtoul(arg + 1, &end, 10);
3464 else if (!*arg && !av[1])
3465 die("Option '--stat-name-width' requires a value");
3467 name_width = strtoul(av[1], &end, 10);
3470 } else if (skip_prefix(arg, "-graph-width", &arg)) {
3472 graph_width = strtoul(arg + 1, &end, 10);
3473 else if (!*arg && !av[1])
3474 die("Option '--stat-graph-width' requires a value");
3476 graph_width = strtoul(av[1], &end, 10);
3479 } else if (skip_prefix(arg, "-count", &arg)) {
3481 count = strtoul(arg + 1, &end, 10);
3482 else if (!*arg && !av[1])
3483 die("Option '--stat-count' requires a value");
3485 count = strtoul(av[1], &end, 10);
3491 width = strtoul(arg+1, &end, 10);
3493 name_width = strtoul(end+1, &end, 10);
3495 count = strtoul(end+1, &end, 10);
3498 /* Important! This checks all the error cases! */
3501 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3502 options->stat_name_width = name_width;
3503 options->stat_graph_width = graph_width;
3504 options->stat_width = width;
3505 options->stat_count = count;
3509 static int parse_dirstat_opt(struct diff_options *options, const char *params)
3511 struct strbuf errmsg = STRBUF_INIT;
3512 if (parse_dirstat_params(options, params, &errmsg))
3513 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3515 strbuf_release(&errmsg);
3517 * The caller knows a dirstat-related option is given from the command
3518 * line; allow it to say "return this_function();"
3520 options->output_format |= DIFF_FORMAT_DIRSTAT;
3524 static int parse_submodule_opt(struct diff_options *options, const char *value)
3526 if (parse_submodule_params(options, value))
3527 die(_("Failed to parse --submodule option parameter: '%s'"),
3532 static const char diff_status_letters[] = {
3535 DIFF_STATUS_DELETED,
3536 DIFF_STATUS_MODIFIED,
3537 DIFF_STATUS_RENAMED,
3538 DIFF_STATUS_TYPE_CHANGED,
3539 DIFF_STATUS_UNKNOWN,
3540 DIFF_STATUS_UNMERGED,
3541 DIFF_STATUS_FILTER_AON,
3542 DIFF_STATUS_FILTER_BROKEN,
3546 static unsigned int filter_bit['Z' + 1];
3548 static void prepare_filter_bits(void)
3552 if (!filter_bit[DIFF_STATUS_ADDED]) {
3553 for (i = 0; diff_status_letters[i]; i++)
3554 filter_bit[(int) diff_status_letters[i]] = (1 << i);
3558 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
3560 return opt->filter & filter_bit[(int) status];
3563 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
3567 prepare_filter_bits();
3570 * If there is a negation e.g. 'd' in the input, and we haven't
3571 * initialized the filter field with another --diff-filter, start
3572 * from full set of bits, except for AON.
3575 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3576 if (optch < 'a' || 'z' < optch)
3578 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
3579 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
3584 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3588 if ('a' <= optch && optch <= 'z') {
3590 optch = toupper(optch);
3595 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
3599 opt->filter &= ~bit;
3606 static void enable_patch_output(int *fmt) {
3607 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
3608 *fmt |= DIFF_FORMAT_PATCH;
3611 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
3613 const char *arg = av[0];
3617 /* Output format options */
3618 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
3619 || opt_arg(arg, 'U', "unified", &options->context))
3620 enable_patch_output(&options->output_format);
3621 else if (!strcmp(arg, "--raw"))
3622 options->output_format |= DIFF_FORMAT_RAW;
3623 else if (!strcmp(arg, "--patch-with-raw")) {
3624 enable_patch_output(&options->output_format);
3625 options->output_format |= DIFF_FORMAT_RAW;
3626 } else if (!strcmp(arg, "--numstat"))
3627 options->output_format |= DIFF_FORMAT_NUMSTAT;
3628 else if (!strcmp(arg, "--shortstat"))
3629 options->output_format |= DIFF_FORMAT_SHORTSTAT;
3630 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3631 return parse_dirstat_opt(options, "");
3632 else if (skip_prefix(arg, "-X", &arg))
3633 return parse_dirstat_opt(options, arg);
3634 else if (skip_prefix(arg, "--dirstat=", &arg))
3635 return parse_dirstat_opt(options, arg);
3636 else if (!strcmp(arg, "--cumulative"))
3637 return parse_dirstat_opt(options, "cumulative");
3638 else if (!strcmp(arg, "--dirstat-by-file"))
3639 return parse_dirstat_opt(options, "files");
3640 else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
3641 parse_dirstat_opt(options, "files");
3642 return parse_dirstat_opt(options, arg);
3644 else if (!strcmp(arg, "--check"))
3645 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3646 else if (!strcmp(arg, "--summary"))
3647 options->output_format |= DIFF_FORMAT_SUMMARY;
3648 else if (!strcmp(arg, "--patch-with-stat")) {
3649 enable_patch_output(&options->output_format);
3650 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3651 } else if (!strcmp(arg, "--name-only"))
3652 options->output_format |= DIFF_FORMAT_NAME;
3653 else if (!strcmp(arg, "--name-status"))
3654 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3655 else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
3656 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3657 else if (starts_with(arg, "--stat"))
3658 /* --stat, --stat-width, --stat-name-width, or --stat-count */
3659 return stat_opt(options, av);
3661 /* renames options */
3662 else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
3663 !strcmp(arg, "--break-rewrites")) {
3664 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3665 return error("invalid argument to -B: %s", arg+2);
3667 else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
3668 !strcmp(arg, "--find-renames")) {
3669 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3670 return error("invalid argument to -M: %s", arg+2);
3671 options->detect_rename = DIFF_DETECT_RENAME;
3673 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3674 options->irreversible_delete = 1;
3676 else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
3677 !strcmp(arg, "--find-copies")) {
3678 if (options->detect_rename == DIFF_DETECT_COPY)
3679 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3680 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3681 return error("invalid argument to -C: %s", arg+2);
3682 options->detect_rename = DIFF_DETECT_COPY;
3684 else if (!strcmp(arg, "--no-renames"))
3685 options->detect_rename = 0;
3686 else if (!strcmp(arg, "--rename-empty"))
3687 DIFF_OPT_SET(options, RENAME_EMPTY);
3688 else if (!strcmp(arg, "--no-rename-empty"))
3689 DIFF_OPT_CLR(options, RENAME_EMPTY);
3690 else if (!strcmp(arg, "--relative"))
3691 DIFF_OPT_SET(options, RELATIVE_NAME);
3692 else if (skip_prefix(arg, "--relative=", &arg)) {
3693 DIFF_OPT_SET(options, RELATIVE_NAME);
3694 options->prefix = arg;
3698 else if (!strcmp(arg, "--minimal"))
3699 DIFF_XDL_SET(options, NEED_MINIMAL);
3700 else if (!strcmp(arg, "--no-minimal"))
3701 DIFF_XDL_CLR(options, NEED_MINIMAL);
3702 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3703 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3704 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3705 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3706 else if (!strcmp(arg, "--ignore-space-at-eol"))
3707 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3708 else if (!strcmp(arg, "--ignore-blank-lines"))
3709 DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
3710 else if (!strcmp(arg, "--patience"))
3711 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
3712 else if (!strcmp(arg, "--histogram"))
3713 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
3714 else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
3715 long value = parse_algorithm_value(optarg);
3717 return error("option diff-algorithm accepts \"myers\", "
3718 "\"minimal\", \"patience\" and \"histogram\"");
3719 /* clear out previous settings */
3720 DIFF_XDL_CLR(options, NEED_MINIMAL);
3721 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3722 options->xdl_opts |= value;
3727 else if (!strcmp(arg, "--binary")) {
3728 enable_patch_output(&options->output_format);
3729 DIFF_OPT_SET(options, BINARY);
3731 else if (!strcmp(arg, "--full-index"))
3732 DIFF_OPT_SET(options, FULL_INDEX);
3733 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3734 DIFF_OPT_SET(options, TEXT);
3735 else if (!strcmp(arg, "-R"))
3736 DIFF_OPT_SET(options, REVERSE_DIFF);
3737 else if (!strcmp(arg, "--find-copies-harder"))
3738 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3739 else if (!strcmp(arg, "--follow"))
3740 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3741 else if (!strcmp(arg, "--no-follow"))
3742 DIFF_OPT_CLR(options, FOLLOW_RENAMES);
3743 else if (!strcmp(arg, "--color"))
3744 options->use_color = 1;
3745 else if (skip_prefix(arg, "--color=", &arg)) {
3746 int value = git_config_colorbool(NULL, arg);
3748 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3749 options->use_color = value;
3751 else if (!strcmp(arg, "--no-color"))
3752 options->use_color = 0;
3753 else if (!strcmp(arg, "--color-words")) {
3754 options->use_color = 1;
3755 options->word_diff = DIFF_WORDS_COLOR;
3757 else if (skip_prefix(arg, "--color-words=", &arg)) {
3758 options->use_color = 1;
3759 options->word_diff = DIFF_WORDS_COLOR;
3760 options->word_regex = arg;
3762 else if (!strcmp(arg, "--word-diff")) {
3763 if (options->word_diff == DIFF_WORDS_NONE)
3764 options->word_diff = DIFF_WORDS_PLAIN;
3766 else if (skip_prefix(arg, "--word-diff=", &arg)) {
3767 if (!strcmp(arg, "plain"))
3768 options->word_diff = DIFF_WORDS_PLAIN;
3769 else if (!strcmp(arg, "color")) {
3770 options->use_color = 1;
3771 options->word_diff = DIFF_WORDS_COLOR;
3773 else if (!strcmp(arg, "porcelain"))
3774 options->word_diff = DIFF_WORDS_PORCELAIN;
3775 else if (!strcmp(arg, "none"))
3776 options->word_diff = DIFF_WORDS_NONE;
3778 die("bad --word-diff argument: %s", arg);
3780 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3781 if (options->word_diff == DIFF_WORDS_NONE)
3782 options->word_diff = DIFF_WORDS_PLAIN;
3783 options->word_regex = optarg;
3786 else if (!strcmp(arg, "--exit-code"))
3787 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3788 else if (!strcmp(arg, "--quiet"))
3789 DIFF_OPT_SET(options, QUICK);
3790 else if (!strcmp(arg, "--ext-diff"))
3791 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3792 else if (!strcmp(arg, "--no-ext-diff"))
3793 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3794 else if (!strcmp(arg, "--textconv"))
3795 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3796 else if (!strcmp(arg, "--no-textconv"))
3797 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3798 else if (!strcmp(arg, "--ignore-submodules")) {
3799 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3800 handle_ignore_submodules_arg(options, "all");
3801 } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
3802 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3803 handle_ignore_submodules_arg(options, arg);
3804 } else if (!strcmp(arg, "--submodule"))
3805 DIFF_OPT_SET(options, SUBMODULE_LOG);
3806 else if (skip_prefix(arg, "--submodule=", &arg))
3807 return parse_submodule_opt(options, arg);
3810 else if (!strcmp(arg, "-z"))
3811 options->line_termination = 0;
3812 else if ((argcount = short_opt('l', av, &optarg))) {
3813 options->rename_limit = strtoul(optarg, NULL, 10);
3816 else if ((argcount = short_opt('S', av, &optarg))) {
3817 options->pickaxe = optarg;
3818 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3820 } else if ((argcount = short_opt('G', av, &optarg))) {
3821 options->pickaxe = optarg;
3822 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3825 else if (!strcmp(arg, "--pickaxe-all"))
3826 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3827 else if (!strcmp(arg, "--pickaxe-regex"))
3828 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3829 else if ((argcount = short_opt('O', av, &optarg))) {
3830 options->orderfile = optarg;
3833 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3834 int offending = parse_diff_filter_opt(optarg, options);
3836 die("unknown change class '%c' in --diff-filter=%s",
3840 else if (!strcmp(arg, "--abbrev"))
3841 options->abbrev = DEFAULT_ABBREV;
3842 else if (skip_prefix(arg, "--abbrev=", &arg)) {
3843 options->abbrev = strtoul(arg, NULL, 10);
3844 if (options->abbrev < MINIMUM_ABBREV)
3845 options->abbrev = MINIMUM_ABBREV;
3846 else if (40 < options->abbrev)
3847 options->abbrev = 40;
3849 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3850 options->a_prefix = optarg;
3853 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3854 options->b_prefix = optarg;
3857 else if (!strcmp(arg, "--no-prefix"))
3858 options->a_prefix = options->b_prefix = "";
3859 else if (opt_arg(arg, '\0', "inter-hunk-context",
3860 &options->interhunkcontext))
3862 else if (!strcmp(arg, "-W"))
3863 DIFF_OPT_SET(options, FUNCCONTEXT);
3864 else if (!strcmp(arg, "--function-context"))
3865 DIFF_OPT_SET(options, FUNCCONTEXT);
3866 else if (!strcmp(arg, "--no-function-context"))
3867 DIFF_OPT_CLR(options, FUNCCONTEXT);
3868 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3869 options->file = fopen(optarg, "w");
3871 die_errno("Could not open '%s'", optarg);
3872 options->close_file = 1;
3879 int parse_rename_score(const char **cp_p)
3881 unsigned long num, scale;
3883 const char *cp = *cp_p;
3890 if ( !dot && ch == '.' ) {
3893 } else if ( ch == '%' ) {
3894 scale = dot ? scale*100 : 100;
3895 cp++; /* % is always at the end */
3897 } else if ( ch >= '0' && ch <= '9' ) {
3898 if ( scale < 100000 ) {
3900 num = (num*10) + (ch-'0');
3909 /* user says num divided by scale and we say internally that
3910 * is MAX_SCORE * num / scale.
3912 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3915 static int diff_scoreopt_parse(const char *opt)
3917 int opt1, opt2, cmd;
3923 /* convert the long-form arguments into short-form versions */
3924 if (skip_prefix(opt, "break-rewrites", &opt)) {
3925 if (*opt == 0 || *opt++ == '=')
3927 } else if (skip_prefix(opt, "find-copies", &opt)) {
3928 if (*opt == 0 || *opt++ == '=')
3930 } else if (skip_prefix(opt, "find-renames", &opt)) {
3931 if (*opt == 0 || *opt++ == '=')
3935 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3936 return -1; /* that is not a -M, -C, or -B option */
3938 opt1 = parse_rename_score(&opt);
3944 else if (*opt != '/')
3945 return -1; /* we expect -B80/99 or -B80 */
3948 opt2 = parse_rename_score(&opt);
3953 return opt1 | (opt2 << 16);
3956 struct diff_queue_struct diff_queued_diff;
3958 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3960 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
3961 queue->queue[queue->nr++] = dp;
3964 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3965 struct diff_filespec *one,
3966 struct diff_filespec *two)
3968 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3976 void diff_free_filepair(struct diff_filepair *p)
3978 free_filespec(p->one);
3979 free_filespec(p->two);
3983 /* This is different from find_unique_abbrev() in that
3984 * it stuffs the result with dots for alignment.
3986 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3991 return sha1_to_hex(sha1);
3993 abbrev = find_unique_abbrev(sha1, len);
3994 abblen = strlen(abbrev);
3996 static char hex[41];
3997 if (len < abblen && abblen <= len + 2)
3998 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
4000 sprintf(hex, "%s...", abbrev);
4003 return sha1_to_hex(sha1);
4006 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4008 int line_termination = opt->line_termination;
4009 int inter_name_termination = line_termination ? '\t' : '\0';
4011 fprintf(opt->file, "%s", diff_line_prefix(opt));
4012 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4013 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4014 diff_unique_abbrev(p->one->sha1, opt->abbrev));
4015 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
4018 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4019 inter_name_termination);
4021 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4024 if (p->status == DIFF_STATUS_COPIED ||
4025 p->status == DIFF_STATUS_RENAMED) {
4026 const char *name_a, *name_b;
4027 name_a = p->one->path;
4028 name_b = p->two->path;
4029 strip_prefix(opt->prefix_length, &name_a, &name_b);
4030 write_name_quoted(name_a, opt->file, inter_name_termination);
4031 write_name_quoted(name_b, opt->file, line_termination);
4033 const char *name_a, *name_b;
4034 name_a = p->one->mode ? p->one->path : p->two->path;
4036 strip_prefix(opt->prefix_length, &name_a, &name_b);
4037 write_name_quoted(name_a, opt->file, line_termination);
4041 int diff_unmodified_pair(struct diff_filepair *p)
4043 /* This function is written stricter than necessary to support
4044 * the currently implemented transformers, but the idea is to
4045 * let transformers to produce diff_filepairs any way they want,
4046 * and filter and clean them up here before producing the output.
4048 struct diff_filespec *one = p->one, *two = p->two;
4050 if (DIFF_PAIR_UNMERGED(p))
4051 return 0; /* unmerged is interesting */
4053 /* deletion, addition, mode or type change
4054 * and rename are all interesting.
4056 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4057 DIFF_PAIR_MODE_CHANGED(p) ||
4058 strcmp(one->path, two->path))
4061 /* both are valid and point at the same path. that is, we are
4062 * dealing with a change.
4064 if (one->sha1_valid && two->sha1_valid &&
4065 !hashcmp(one->sha1, two->sha1) &&
4066 !one->dirty_submodule && !two->dirty_submodule)
4067 return 1; /* no change */
4068 if (!one->sha1_valid && !two->sha1_valid)
4069 return 1; /* both look at the same file on the filesystem. */
4073 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4075 if (diff_unmodified_pair(p))
4078 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4079 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4080 return; /* no tree diffs in patch format */
4085 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4086 struct diffstat_t *diffstat)
4088 if (diff_unmodified_pair(p))
4091 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4092 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4093 return; /* no useful stat for tree diffs */
4095 run_diffstat(p, o, diffstat);
4098 static void diff_flush_checkdiff(struct diff_filepair *p,
4099 struct diff_options *o)
4101 if (diff_unmodified_pair(p))
4104 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4105 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4106 return; /* nothing to check in tree diffs */
4108 run_checkdiff(p, o);
4111 int diff_queue_is_empty(void)
4113 struct diff_queue_struct *q = &diff_queued_diff;
4115 for (i = 0; i < q->nr; i++)
4116 if (!diff_unmodified_pair(q->queue[i]))
4122 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4124 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4127 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4129 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
4130 fprintf(stderr, "queue[%d] %s size %lu\n",
4135 void diff_debug_filepair(const struct diff_filepair *p, int i)
4137 diff_debug_filespec(p->one, i, "one");
4138 diff_debug_filespec(p->two, i, "two");
4139 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4140 p->score, p->status ? p->status : '?',
4141 p->one->rename_used, p->broken_pair);
4144 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4148 fprintf(stderr, "%s\n", msg);
4149 fprintf(stderr, "q->nr = %d\n", q->nr);
4150 for (i = 0; i < q->nr; i++) {
4151 struct diff_filepair *p = q->queue[i];
4152 diff_debug_filepair(p, i);
4157 static void diff_resolve_rename_copy(void)
4160 struct diff_filepair *p;
4161 struct diff_queue_struct *q = &diff_queued_diff;
4163 diff_debug_queue("resolve-rename-copy", q);
4165 for (i = 0; i < q->nr; i++) {
4167 p->status = 0; /* undecided */
4168 if (DIFF_PAIR_UNMERGED(p))
4169 p->status = DIFF_STATUS_UNMERGED;
4170 else if (!DIFF_FILE_VALID(p->one))
4171 p->status = DIFF_STATUS_ADDED;
4172 else if (!DIFF_FILE_VALID(p->two))
4173 p->status = DIFF_STATUS_DELETED;
4174 else if (DIFF_PAIR_TYPE_CHANGED(p))
4175 p->status = DIFF_STATUS_TYPE_CHANGED;
4177 /* from this point on, we are dealing with a pair
4178 * whose both sides are valid and of the same type, i.e.
4179 * either in-place edit or rename/copy edit.
4181 else if (DIFF_PAIR_RENAME(p)) {
4183 * A rename might have re-connected a broken
4184 * pair up, causing the pathnames to be the
4185 * same again. If so, that's not a rename at
4186 * all, just a modification..
4188 * Otherwise, see if this source was used for
4189 * multiple renames, in which case we decrement
4190 * the count, and call it a copy.
4192 if (!strcmp(p->one->path, p->two->path))
4193 p->status = DIFF_STATUS_MODIFIED;
4194 else if (--p->one->rename_used > 0)
4195 p->status = DIFF_STATUS_COPIED;
4197 p->status = DIFF_STATUS_RENAMED;
4199 else if (hashcmp(p->one->sha1, p->two->sha1) ||
4200 p->one->mode != p->two->mode ||
4201 p->one->dirty_submodule ||
4202 p->two->dirty_submodule ||
4203 is_null_sha1(p->one->sha1))
4204 p->status = DIFF_STATUS_MODIFIED;
4206 /* This is a "no-change" entry and should not
4207 * happen anymore, but prepare for broken callers.
4209 error("feeding unmodified %s to diffcore",
4211 p->status = DIFF_STATUS_UNKNOWN;
4214 diff_debug_queue("resolve-rename-copy done", q);
4217 static int check_pair_status(struct diff_filepair *p)
4219 switch (p->status) {
4220 case DIFF_STATUS_UNKNOWN:
4223 die("internal error in diff-resolve-rename-copy");
4229 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4231 int fmt = opt->output_format;
4233 if (fmt & DIFF_FORMAT_CHECKDIFF)
4234 diff_flush_checkdiff(p, opt);
4235 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4236 diff_flush_raw(p, opt);
4237 else if (fmt & DIFF_FORMAT_NAME) {
4238 const char *name_a, *name_b;
4239 name_a = p->two->path;
4241 strip_prefix(opt->prefix_length, &name_a, &name_b);
4242 write_name_quoted(name_a, opt->file, opt->line_termination);
4246 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4249 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4251 fprintf(file, " %s ", newdelete);
4252 write_name_quoted(fs->path, file, '\n');
4256 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4257 const char *line_prefix)
4259 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4260 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4261 p->two->mode, show_name ? ' ' : '\n');
4263 write_name_quoted(p->two->path, file, '\n');
4268 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4269 const char *line_prefix)
4271 char *names = pprint_rename(p->one->path, p->two->path);
4273 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4275 show_mode_change(file, p, 0, line_prefix);
4278 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4280 FILE *file = opt->file;
4281 const char *line_prefix = diff_line_prefix(opt);
4284 case DIFF_STATUS_DELETED:
4285 fputs(line_prefix, file);
4286 show_file_mode_name(file, "delete", p->one);
4288 case DIFF_STATUS_ADDED:
4289 fputs(line_prefix, file);
4290 show_file_mode_name(file, "create", p->two);
4292 case DIFF_STATUS_COPIED:
4293 fputs(line_prefix, file);
4294 show_rename_copy(file, "copy", p, line_prefix);
4296 case DIFF_STATUS_RENAMED:
4297 fputs(line_prefix, file);
4298 show_rename_copy(file, "rename", p, line_prefix);
4302 fprintf(file, "%s rewrite ", line_prefix);
4303 write_name_quoted(p->two->path, file, ' ');
4304 fprintf(file, "(%d%%)\n", similarity_index(p));
4306 show_mode_change(file, p, !p->score, line_prefix);
4316 static int remove_space(char *line, int len)
4322 for (i = 0; i < len; i++)
4323 if (!isspace((c = line[i])))
4329 static void patch_id_consume(void *priv, char *line, unsigned long len)
4331 struct patch_id_t *data = priv;
4334 /* Ignore line numbers when computing the SHA1 of the patch */
4335 if (starts_with(line, "@@ -"))
4338 new_len = remove_space(line, len);
4340 git_SHA1_Update(data->ctx, line, new_len);
4341 data->patchlen += new_len;
4344 /* returns 0 upon success, and writes result into sha1 */
4345 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4347 struct diff_queue_struct *q = &diff_queued_diff;
4350 struct patch_id_t data;
4351 char buffer[PATH_MAX * 4 + 20];
4353 git_SHA1_Init(&ctx);
4354 memset(&data, 0, sizeof(struct patch_id_t));
4357 for (i = 0; i < q->nr; i++) {
4361 struct diff_filepair *p = q->queue[i];
4364 memset(&xpp, 0, sizeof(xpp));
4365 memset(&xecfg, 0, sizeof(xecfg));
4367 return error("internal diff status error");
4368 if (p->status == DIFF_STATUS_UNKNOWN)
4370 if (diff_unmodified_pair(p))
4372 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4373 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4375 if (DIFF_PAIR_UNMERGED(p))
4378 diff_fill_sha1_info(p->one);
4379 diff_fill_sha1_info(p->two);
4380 if (fill_mmfile(&mf1, p->one) < 0 ||
4381 fill_mmfile(&mf2, p->two) < 0)
4382 return error("unable to read files to diff");
4384 len1 = remove_space(p->one->path, strlen(p->one->path));
4385 len2 = remove_space(p->two->path, strlen(p->two->path));
4386 if (p->one->mode == 0)
4387 len1 = snprintf(buffer, sizeof(buffer),
4388 "diff--gita/%.*sb/%.*s"
4395 len2, p->two->path);
4396 else if (p->two->mode == 0)
4397 len1 = snprintf(buffer, sizeof(buffer),
4398 "diff--gita/%.*sb/%.*s"
4399 "deletedfilemode%06o"
4405 len1, p->one->path);
4407 len1 = snprintf(buffer, sizeof(buffer),
4408 "diff--gita/%.*sb/%.*s"
4414 len2, p->two->path);
4415 git_SHA1_Update(&ctx, buffer, len1);
4417 if (diff_filespec_is_binary(p->one) ||
4418 diff_filespec_is_binary(p->two)) {
4419 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4420 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4427 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4431 git_SHA1_Final(sha1, &ctx);
4435 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4437 struct diff_queue_struct *q = &diff_queued_diff;
4439 int result = diff_get_patch_id(options, sha1);
4441 for (i = 0; i < q->nr; i++)
4442 diff_free_filepair(q->queue[i]);
4445 DIFF_QUEUE_CLEAR(q);
4450 static int is_summary_empty(const struct diff_queue_struct *q)
4454 for (i = 0; i < q->nr; i++) {
4455 const struct diff_filepair *p = q->queue[i];
4457 switch (p->status) {
4458 case DIFF_STATUS_DELETED:
4459 case DIFF_STATUS_ADDED:
4460 case DIFF_STATUS_COPIED:
4461 case DIFF_STATUS_RENAMED:
4466 if (p->one->mode && p->two->mode &&
4467 p->one->mode != p->two->mode)
4475 static const char rename_limit_warning[] =
4476 "inexact rename detection was skipped due to too many files.";
4478 static const char degrade_cc_to_c_warning[] =
4479 "only found copies from modified paths due to too many files.";
4481 static const char rename_limit_advice[] =
4482 "you may want to set your %s variable to at least "
4483 "%d and retry the command.";
4485 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4488 warning(degrade_cc_to_c_warning);
4490 warning(rename_limit_warning);
4493 if (0 < needed && needed < 32767)
4494 warning(rename_limit_advice, varname, needed);
4497 void diff_flush(struct diff_options *options)
4499 struct diff_queue_struct *q = &diff_queued_diff;
4500 int i, output_format = options->output_format;
4502 int dirstat_by_line = 0;
4505 * Order: raw, stat, summary, patch
4506 * or: name/name-status/checkdiff (other bits clear)
4511 if (output_format & (DIFF_FORMAT_RAW |
4513 DIFF_FORMAT_NAME_STATUS |
4514 DIFF_FORMAT_CHECKDIFF)) {
4515 for (i = 0; i < q->nr; i++) {
4516 struct diff_filepair *p = q->queue[i];
4517 if (check_pair_status(p))
4518 flush_one_pair(p, options);
4523 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4524 dirstat_by_line = 1;
4526 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4528 struct diffstat_t diffstat;
4530 memset(&diffstat, 0, sizeof(struct diffstat_t));
4531 for (i = 0; i < q->nr; i++) {
4532 struct diff_filepair *p = q->queue[i];
4533 if (check_pair_status(p))
4534 diff_flush_stat(p, options, &diffstat);
4536 if (output_format & DIFF_FORMAT_NUMSTAT)
4537 show_numstat(&diffstat, options);
4538 if (output_format & DIFF_FORMAT_DIFFSTAT)
4539 show_stats(&diffstat, options);
4540 if (output_format & DIFF_FORMAT_SHORTSTAT)
4541 show_shortstats(&diffstat, options);
4542 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
4543 show_dirstat_by_line(&diffstat, options);
4544 free_diffstat_info(&diffstat);
4547 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4548 show_dirstat(options);
4550 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4551 for (i = 0; i < q->nr; i++) {
4552 diff_summary(options, q->queue[i]);
4557 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4558 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4559 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4561 * run diff_flush_patch for the exit status. setting
4562 * options->file to /dev/null should be safe, because we
4563 * aren't supposed to produce any output anyway.
4565 if (options->close_file)
4566 fclose(options->file);
4567 options->file = fopen("/dev/null", "w");
4569 die_errno("Could not open /dev/null");
4570 options->close_file = 1;
4571 for (i = 0; i < q->nr; i++) {
4572 struct diff_filepair *p = q->queue[i];
4573 if (check_pair_status(p))
4574 diff_flush_patch(p, options);
4575 if (options->found_changes)
4580 if (output_format & DIFF_FORMAT_PATCH) {
4582 fprintf(options->file, "%s%c",
4583 diff_line_prefix(options),
4584 options->line_termination);
4585 if (options->stat_sep) {
4586 /* attach patch instead of inline */
4587 fputs(options->stat_sep, options->file);
4591 for (i = 0; i < q->nr; i++) {
4592 struct diff_filepair *p = q->queue[i];
4593 if (check_pair_status(p))
4594 diff_flush_patch(p, options);
4598 if (output_format & DIFF_FORMAT_CALLBACK)
4599 options->format_callback(q, options, options->format_callback_data);
4601 for (i = 0; i < q->nr; i++)
4602 diff_free_filepair(q->queue[i]);
4605 DIFF_QUEUE_CLEAR(q);
4606 if (options->close_file)
4607 fclose(options->file);
4610 * Report the content-level differences with HAS_CHANGES;
4611 * diff_addremove/diff_change does not set the bit when
4612 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4614 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4615 if (options->found_changes)
4616 DIFF_OPT_SET(options, HAS_CHANGES);
4618 DIFF_OPT_CLR(options, HAS_CHANGES);
4622 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
4624 return (((p->status == DIFF_STATUS_MODIFIED) &&
4626 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
4628 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
4629 ((p->status != DIFF_STATUS_MODIFIED) &&
4630 filter_bit_tst(p->status, options)));
4633 static void diffcore_apply_filter(struct diff_options *options)
4636 struct diff_queue_struct *q = &diff_queued_diff;
4637 struct diff_queue_struct outq;
4639 DIFF_QUEUE_CLEAR(&outq);
4641 if (!options->filter)
4644 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
4646 for (i = found = 0; !found && i < q->nr; i++) {
4647 if (match_filter(options, q->queue[i]))
4653 /* otherwise we will clear the whole queue
4654 * by copying the empty outq at the end of this
4655 * function, but first clear the current entries
4658 for (i = 0; i < q->nr; i++)
4659 diff_free_filepair(q->queue[i]);
4662 /* Only the matching ones */
4663 for (i = 0; i < q->nr; i++) {
4664 struct diff_filepair *p = q->queue[i];
4665 if (match_filter(options, p))
4668 diff_free_filepair(p);
4675 /* Check whether two filespecs with the same mode and size are identical */
4676 static int diff_filespec_is_identical(struct diff_filespec *one,
4677 struct diff_filespec *two)
4679 if (S_ISGITLINK(one->mode))
4681 if (diff_populate_filespec(one, 0))
4683 if (diff_populate_filespec(two, 0))
4685 return !memcmp(one->data, two->data, one->size);
4688 static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
4690 if (p->done_skip_stat_unmatch)
4691 return p->skip_stat_unmatch_result;
4693 p->done_skip_stat_unmatch = 1;
4694 p->skip_stat_unmatch_result = 0;
4696 * 1. Entries that come from stat info dirtiness
4697 * always have both sides (iow, not create/delete),
4698 * one side of the object name is unknown, with
4699 * the same mode and size. Keep the ones that
4700 * do not match these criteria. They have real
4703 * 2. At this point, the file is known to be modified,
4704 * with the same mode and size, and the object
4705 * name of one side is unknown. Need to inspect
4706 * the identical contents.
4708 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4709 !DIFF_FILE_VALID(p->two) ||
4710 (p->one->sha1_valid && p->two->sha1_valid) ||
4711 (p->one->mode != p->two->mode) ||
4712 diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
4713 diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
4714 (p->one->size != p->two->size) ||
4715 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4716 p->skip_stat_unmatch_result = 1;
4717 return p->skip_stat_unmatch_result;
4720 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4723 struct diff_queue_struct *q = &diff_queued_diff;
4724 struct diff_queue_struct outq;
4725 DIFF_QUEUE_CLEAR(&outq);
4727 for (i = 0; i < q->nr; i++) {
4728 struct diff_filepair *p = q->queue[i];
4730 if (diff_filespec_check_stat_unmatch(p))
4734 * The caller can subtract 1 from skip_stat_unmatch
4735 * to determine how many paths were dirty only
4736 * due to stat info mismatch.
4738 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4739 diffopt->skip_stat_unmatch++;
4740 diff_free_filepair(p);
4747 static int diffnamecmp(const void *a_, const void *b_)
4749 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4750 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4751 const char *name_a, *name_b;
4753 name_a = a->one ? a->one->path : a->two->path;
4754 name_b = b->one ? b->one->path : b->two->path;
4755 return strcmp(name_a, name_b);
4758 void diffcore_fix_diff_index(struct diff_options *options)
4760 struct diff_queue_struct *q = &diff_queued_diff;
4761 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4764 void diffcore_std(struct diff_options *options)
4766 /* NOTE please keep the following in sync with diff_tree_combined() */
4767 if (options->skip_stat_unmatch)
4768 diffcore_skip_stat_unmatch(options);
4769 if (!options->found_follow) {
4770 /* See try_to_follow_renames() in tree-diff.c */
4771 if (options->break_opt != -1)
4772 diffcore_break(options->break_opt);
4773 if (options->detect_rename)
4774 diffcore_rename(options);
4775 if (options->break_opt != -1)
4776 diffcore_merge_broken();
4778 if (options->pickaxe)
4779 diffcore_pickaxe(options);
4780 if (options->orderfile)
4781 diffcore_order(options->orderfile);
4782 if (!options->found_follow)
4783 /* See try_to_follow_renames() in tree-diff.c */
4784 diff_resolve_rename_copy();
4785 diffcore_apply_filter(options);
4787 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4788 DIFF_OPT_SET(options, HAS_CHANGES);
4790 DIFF_OPT_CLR(options, HAS_CHANGES);
4792 options->found_follow = 0;
4795 int diff_result_code(struct diff_options *opt, int status)
4799 diff_warn_rename_limit("diff.renameLimit",
4800 opt->needed_rename_limit,
4801 opt->degraded_cc_to_c);
4802 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4803 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4805 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4806 DIFF_OPT_TST(opt, HAS_CHANGES))
4808 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4809 DIFF_OPT_TST(opt, CHECK_FAILED))
4814 int diff_can_quit_early(struct diff_options *opt)
4816 return (DIFF_OPT_TST(opt, QUICK) &&
4818 DIFF_OPT_TST(opt, HAS_CHANGES));
4822 * Shall changes to this submodule be ignored?
4824 * Submodule changes can be configured to be ignored separately for each path,
4825 * but that configuration can be overridden from the command line.
4827 static int is_submodule_ignored(const char *path, struct diff_options *options)
4830 unsigned orig_flags = options->flags;
4831 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4832 set_diffopt_flags_from_submodule_config(options, path);
4833 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4835 options->flags = orig_flags;
4839 void diff_addremove(struct diff_options *options,
4840 int addremove, unsigned mode,
4841 const unsigned char *sha1,
4843 const char *concatpath, unsigned dirty_submodule)
4845 struct diff_filespec *one, *two;
4847 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4850 /* This may look odd, but it is a preparation for
4851 * feeding "there are unchanged files which should
4852 * not produce diffs, but when you are doing copy
4853 * detection you would need them, so here they are"
4854 * entries to the diff-core. They will be prefixed
4855 * with something like '=' or '*' (I haven't decided
4856 * which but should not make any difference).
4857 * Feeding the same new and old to diff_change()
4858 * also has the same effect.
4859 * Before the final output happens, they are pruned after
4860 * merged into rename/copy pairs as appropriate.
4862 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4863 addremove = (addremove == '+' ? '-' :
4864 addremove == '-' ? '+' : addremove);
4866 if (options->prefix &&
4867 strncmp(concatpath, options->prefix, options->prefix_length))
4870 one = alloc_filespec(concatpath);
4871 two = alloc_filespec(concatpath);
4873 if (addremove != '+')
4874 fill_filespec(one, sha1, sha1_valid, mode);
4875 if (addremove != '-') {
4876 fill_filespec(two, sha1, sha1_valid, mode);
4877 two->dirty_submodule = dirty_submodule;
4880 diff_queue(&diff_queued_diff, one, two);
4881 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4882 DIFF_OPT_SET(options, HAS_CHANGES);
4885 void diff_change(struct diff_options *options,
4886 unsigned old_mode, unsigned new_mode,
4887 const unsigned char *old_sha1,
4888 const unsigned char *new_sha1,
4889 int old_sha1_valid, int new_sha1_valid,
4890 const char *concatpath,
4891 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4893 struct diff_filespec *one, *two;
4894 struct diff_filepair *p;
4896 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4897 is_submodule_ignored(concatpath, options))
4900 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4902 const unsigned char *tmp_c;
4903 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4904 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4905 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
4906 new_sha1_valid = tmp;
4907 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4908 new_dirty_submodule = tmp;
4911 if (options->prefix &&
4912 strncmp(concatpath, options->prefix, options->prefix_length))
4915 one = alloc_filespec(concatpath);
4916 two = alloc_filespec(concatpath);
4917 fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
4918 fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
4919 one->dirty_submodule = old_dirty_submodule;
4920 two->dirty_submodule = new_dirty_submodule;
4921 p = diff_queue(&diff_queued_diff, one, two);
4923 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4926 if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
4927 !diff_filespec_check_stat_unmatch(p))
4930 DIFF_OPT_SET(options, HAS_CHANGES);
4933 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
4935 struct diff_filepair *pair;
4936 struct diff_filespec *one, *two;
4938 if (options->prefix &&
4939 strncmp(path, options->prefix, options->prefix_length))
4942 one = alloc_filespec(path);
4943 two = alloc_filespec(path);
4944 pair = diff_queue(&diff_queued_diff, one, two);
4945 pair->is_unmerged = 1;
4949 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4952 struct diff_tempfile *temp;
4953 const char *argv[3];
4954 const char **arg = argv;
4955 struct child_process child = CHILD_PROCESS_INIT;
4956 struct strbuf buf = STRBUF_INIT;
4959 temp = prepare_temp_file(spec->path, spec);
4961 *arg++ = temp->name;
4964 child.use_shell = 1;
4967 if (start_command(&child)) {
4972 if (strbuf_read(&buf, child.out, 0) < 0)
4973 err = error("error reading from textconv command '%s'", pgm);
4976 if (finish_command(&child) || err) {
4977 strbuf_release(&buf);
4983 return strbuf_detach(&buf, outsize);
4986 size_t fill_textconv(struct userdiff_driver *driver,
4987 struct diff_filespec *df,
4992 if (!driver || !driver->textconv) {
4993 if (!DIFF_FILE_VALID(df)) {
4997 if (diff_populate_filespec(df, 0))
4998 die("unable to read files to diff");
5003 if (driver->textconv_cache && df->sha1_valid) {
5004 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
5010 *outbuf = run_textconv(driver->textconv, df, &size);
5012 die("unable to read files to diff");
5014 if (driver->textconv_cache && df->sha1_valid) {
5015 /* ignore errors, as we might be in a readonly repository */
5016 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
5019 * we could save up changes and flush them all at the end,
5020 * but we would need an extra call after all diffing is done.
5021 * Since generating a cache entry is the slow path anyway,
5022 * this extra overhead probably isn't a big deal.
5024 notes_cache_write(driver->textconv_cache);
5030 void setup_diff_pager(struct diff_options *opt)
5033 * If the user asked for our exit code, then either they want --quiet
5034 * or --exit-code. We should definitely not bother with a pager in the
5035 * former case, as we will generate no output. Since we still properly
5036 * report our exit code even when a pager is run, we _could_ run a
5037 * pager with --exit-code. But since we have not done so historically,
5038 * and because it is easy to find people oneline advising "git diff
5039 * --exit-code" in hooks and other scripts, we do not do so.
5041 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5042 check_pager_config("diff") != 0)