2 * Copyright (C) 2005 Junio C Hamano
9 #include "xdiff-interface.h"
12 #include "run-command.h"
16 #include "submodule.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
22 #define FAST_WORKING_DIRECTORY 1
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 200;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
34 static char diff_colors[][COLOR_MAXLEN] = {
36 GIT_COLOR_NORMAL, /* PLAIN */
37 GIT_COLOR_BOLD, /* METAINFO */
38 GIT_COLOR_CYAN, /* FRAGINFO */
39 GIT_COLOR_RED, /* OLD */
40 GIT_COLOR_GREEN, /* NEW */
41 GIT_COLOR_YELLOW, /* COMMIT */
42 GIT_COLOR_BG_RED, /* WHITESPACE */
43 GIT_COLOR_NORMAL, /* FUNCINFO */
46 static void diff_filespec_load_driver(struct diff_filespec *one);
47 static size_t fill_textconv(struct userdiff_driver *driver,
48 struct diff_filespec *df, char **outbuf);
50 static int parse_diff_color_slot(const char *var, int ofs)
52 if (!strcasecmp(var+ofs, "plain"))
54 if (!strcasecmp(var+ofs, "meta"))
56 if (!strcasecmp(var+ofs, "frag"))
58 if (!strcasecmp(var+ofs, "old"))
60 if (!strcasecmp(var+ofs, "new"))
62 if (!strcasecmp(var+ofs, "commit"))
64 if (!strcasecmp(var+ofs, "whitespace"))
65 return DIFF_WHITESPACE;
66 if (!strcasecmp(var+ofs, "func"))
71 static int git_config_rename(const char *var, const char *value)
74 return DIFF_DETECT_RENAME;
75 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
76 return DIFF_DETECT_COPY;
77 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
81 * These are to give UI layer defaults.
82 * The core-level commands such as git-diff-files should
83 * never be affected by the setting of diff.renames
84 * the user happens to have in the configuration file.
86 int git_diff_ui_config(const char *var, const char *value, void *cb)
88 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
89 diff_use_color_default = git_config_colorbool(var, value, -1);
92 if (!strcmp(var, "diff.renames")) {
93 diff_detect_rename_default = git_config_rename(var, value);
96 if (!strcmp(var, "diff.autorefreshindex")) {
97 diff_auto_refresh_index = git_config_bool(var, value);
100 if (!strcmp(var, "diff.mnemonicprefix")) {
101 diff_mnemonic_prefix = git_config_bool(var, value);
104 if (!strcmp(var, "diff.external"))
105 return git_config_string(&external_diff_cmd_cfg, var, value);
106 if (!strcmp(var, "diff.wordregex"))
107 return git_config_string(&diff_word_regex_cfg, var, value);
109 return git_diff_basic_config(var, value, cb);
112 int git_diff_basic_config(const char *var, const char *value, void *cb)
114 if (!strcmp(var, "diff.renamelimit")) {
115 diff_rename_limit_default = git_config_int(var, value);
119 switch (userdiff_config(var, value)) {
125 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
126 int slot = parse_diff_color_slot(var, 11);
130 return config_error_nonbool(var);
131 color_parse(value, var, diff_colors[slot]);
135 /* like GNU diff's --suppress-blank-empty option */
136 if (!strcmp(var, "diff.suppressblankempty") ||
137 /* for backwards compatibility */
138 !strcmp(var, "diff.suppress-blank-empty")) {
139 diff_suppress_blank_empty = git_config_bool(var, value);
143 return git_color_default_config(var, value, cb);
146 static char *quote_two(const char *one, const char *two)
148 int need_one = quote_c_style(one, NULL, NULL, 1);
149 int need_two = quote_c_style(two, NULL, NULL, 1);
150 struct strbuf res = STRBUF_INIT;
152 if (need_one + need_two) {
153 strbuf_addch(&res, '"');
154 quote_c_style(one, &res, NULL, 1);
155 quote_c_style(two, &res, NULL, 1);
156 strbuf_addch(&res, '"');
158 strbuf_addstr(&res, one);
159 strbuf_addstr(&res, two);
161 return strbuf_detach(&res, NULL);
164 static const char *external_diff(void)
166 static const char *external_diff_cmd = NULL;
167 static int done_preparing = 0;
170 return external_diff_cmd;
171 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
172 if (!external_diff_cmd)
173 external_diff_cmd = external_diff_cmd_cfg;
175 return external_diff_cmd;
178 static struct diff_tempfile {
179 const char *name; /* filename external diff should read from */
182 char tmp_path[PATH_MAX];
185 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
187 struct emit_callback {
190 int blank_at_eof_in_preimage;
191 int blank_at_eof_in_postimage;
193 int lno_in_postimage;
194 sane_truncate_fn truncate;
195 const char **label_path;
196 struct diff_words_data *diff_words;
197 struct diff_options *opt;
199 struct strbuf *header;
202 static int count_lines(const char *data, int size)
204 int count, ch, completely_empty = 1, nl_just_seen = 0;
211 completely_empty = 0;
215 completely_empty = 0;
218 if (completely_empty)
221 count++; /* no trailing newline */
225 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
227 if (!DIFF_FILE_VALID(one)) {
228 mf->ptr = (char *)""; /* does not matter */
232 else if (diff_populate_filespec(one, 0))
236 mf->size = one->size;
240 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
243 long size = mf->size;
248 ptr += size - 1; /* pointing at the very end */
250 ; /* incomplete line */
252 ptr--; /* skip the last LF */
253 while (mf->ptr < ptr) {
255 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
256 if (*prev_eol == '\n')
258 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
266 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
267 struct emit_callback *ecbdata)
270 unsigned ws_rule = ecbdata->ws_rule;
271 l1 = count_trailing_blank(mf1, ws_rule);
272 l2 = count_trailing_blank(mf2, ws_rule);
274 ecbdata->blank_at_eof_in_preimage = 0;
275 ecbdata->blank_at_eof_in_postimage = 0;
278 at = count_lines(mf1->ptr, mf1->size);
279 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
281 at = count_lines(mf2->ptr, mf2->size);
282 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
285 static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
286 int first, const char *line, int len)
288 int has_trailing_newline, has_trailing_carriage_return;
290 FILE *file = o->file;
292 if (o->output_prefix) {
293 struct strbuf *msg = NULL;
294 msg = o->output_prefix(o, o->output_prefix_data);
296 fwrite(msg->buf, msg->len, 1, file);
300 has_trailing_newline = (first == '\n');
301 has_trailing_carriage_return = (!has_trailing_newline &&
303 nofirst = has_trailing_newline || has_trailing_carriage_return;
305 has_trailing_newline = (len > 0 && line[len-1] == '\n');
306 if (has_trailing_newline)
308 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
309 if (has_trailing_carriage_return)
314 if (len || !nofirst) {
318 fwrite(line, len, 1, file);
321 if (has_trailing_carriage_return)
323 if (has_trailing_newline)
327 static void emit_line(struct diff_options *o, const char *set, const char *reset,
328 const char *line, int len)
330 emit_line_0(o, set, reset, line[0], line+1, len-1);
333 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
335 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
336 ecbdata->blank_at_eof_in_preimage &&
337 ecbdata->blank_at_eof_in_postimage &&
338 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
339 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
341 return ws_blank_line(line, len, ecbdata->ws_rule);
344 static void emit_add_line(const char *reset,
345 struct emit_callback *ecbdata,
346 const char *line, int len)
348 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
349 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
352 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
353 else if (new_blank_line_at_eof(ecbdata, line, len))
354 /* Blank line at EOF - paint '+' as well */
355 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
357 /* Emit just the prefix, then the rest. */
358 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
359 ws_check_emit(line, len, ecbdata->ws_rule,
360 ecbdata->opt->file, set, reset, ws);
364 static void emit_hunk_header(struct emit_callback *ecbdata,
365 const char *line, int len)
367 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
368 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
369 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
370 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
371 static const char atat[2] = { '@', '@' };
373 struct strbuf msgbuf = STRBUF_INIT;
378 * As a hunk header must begin with "@@ -<old>, +<new> @@",
379 * it always is at least 10 bytes long.
382 memcmp(line, atat, 2) ||
383 !(ep = memmem(line + 2, len - 2, atat, 2))) {
384 emit_line(ecbdata->opt, plain, reset, line, len);
387 ep += 2; /* skip over @@ */
389 /* The hunk header in fraginfo color */
390 strbuf_add(&msgbuf, frag, strlen(frag));
391 strbuf_add(&msgbuf, line, ep - line);
392 strbuf_add(&msgbuf, reset, strlen(reset));
398 if (line[len - i] == '\r' || line[len - i] == '\n')
401 /* blank before the func header */
402 for (cp = ep; ep - line < len; ep++)
403 if (*ep != ' ' && *ep != '\t')
406 strbuf_add(&msgbuf, plain, strlen(plain));
407 strbuf_add(&msgbuf, cp, ep - cp);
408 strbuf_add(&msgbuf, reset, strlen(reset));
411 if (ep < line + len) {
412 strbuf_add(&msgbuf, func, strlen(func));
413 strbuf_add(&msgbuf, ep, line + len - ep);
414 strbuf_add(&msgbuf, reset, strlen(reset));
417 strbuf_add(&msgbuf, line + len, org_len - len);
418 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
419 strbuf_release(&msgbuf);
422 static struct diff_tempfile *claim_diff_tempfile(void) {
424 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
425 if (!diff_temp[i].name)
426 return diff_temp + i;
427 die("BUG: diff is failing to clean up its tempfiles");
430 static int remove_tempfile_installed;
432 static void remove_tempfile(void)
435 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
436 if (diff_temp[i].name == diff_temp[i].tmp_path)
437 unlink_or_warn(diff_temp[i].name);
438 diff_temp[i].name = NULL;
442 static void remove_tempfile_on_signal(int signo)
449 static void print_line_count(FILE *file, int count)
453 fprintf(file, "0,0");
459 fprintf(file, "1,%d", count);
464 static void emit_rewrite_lines(struct emit_callback *ecb,
465 int prefix, const char *data, int size)
467 const char *endp = NULL;
468 static const char *nneof = " No newline at end of file\n";
469 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
470 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
475 endp = memchr(data, '\n', size);
476 len = endp ? (endp - data + 1) : size;
478 ecb->lno_in_preimage++;
479 emit_line_0(ecb->opt, old, reset, '-',
482 ecb->lno_in_postimage++;
483 emit_add_line(reset, ecb, data, len);
489 const char *plain = diff_get_color(ecb->color_diff,
491 emit_line_0(ecb->opt, plain, reset, '\\',
492 nneof, strlen(nneof));
496 static void emit_rewrite_diff(const char *name_a,
498 struct diff_filespec *one,
499 struct diff_filespec *two,
500 struct userdiff_driver *textconv_one,
501 struct userdiff_driver *textconv_two,
502 struct diff_options *o)
505 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
506 const char *name_a_tab, *name_b_tab;
507 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
508 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
509 const char *reset = diff_get_color(color_diff, DIFF_RESET);
510 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
511 const char *a_prefix, *b_prefix;
512 char *data_one, *data_two;
513 size_t size_one, size_two;
514 struct emit_callback ecbdata;
515 char *line_prefix = "";
516 struct strbuf *msgbuf;
518 if (o && o->output_prefix) {
519 msgbuf = o->output_prefix(o, o->output_prefix_data);
520 line_prefix = msgbuf->buf;
523 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
524 a_prefix = o->b_prefix;
525 b_prefix = o->a_prefix;
527 a_prefix = o->a_prefix;
528 b_prefix = o->b_prefix;
531 name_a += (*name_a == '/');
532 name_b += (*name_b == '/');
533 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
534 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
536 strbuf_reset(&a_name);
537 strbuf_reset(&b_name);
538 quote_two_c_style(&a_name, a_prefix, name_a, 0);
539 quote_two_c_style(&b_name, b_prefix, name_b, 0);
541 size_one = fill_textconv(textconv_one, one, &data_one);
542 size_two = fill_textconv(textconv_two, two, &data_two);
544 memset(&ecbdata, 0, sizeof(ecbdata));
545 ecbdata.color_diff = color_diff;
546 ecbdata.found_changesp = &o->found_changes;
547 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
549 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
551 mf1.ptr = (char *)data_one;
552 mf2.ptr = (char *)data_two;
555 check_blank_at_eof(&mf1, &mf2, &ecbdata);
557 ecbdata.lno_in_preimage = 1;
558 ecbdata.lno_in_postimage = 1;
560 lc_a = count_lines(data_one, size_one);
561 lc_b = count_lines(data_two, size_two);
563 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
564 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
565 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
566 line_prefix, fraginfo);
567 print_line_count(o->file, lc_a);
568 fprintf(o->file, " +");
569 print_line_count(o->file, lc_b);
570 fprintf(o->file, " @@%s\n", reset);
572 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
574 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
576 free((char *)data_one);
578 free((char *)data_two);
581 struct diff_words_buffer {
584 struct diff_words_orig {
585 const char *begin, *end;
587 int orig_nr, orig_alloc;
590 static void diff_words_append(char *line, unsigned long len,
591 struct diff_words_buffer *buffer)
593 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
596 memcpy(buffer->text.ptr + buffer->text.size, line, len);
597 buffer->text.size += len;
598 buffer->text.ptr[buffer->text.size] = '\0';
601 struct diff_words_style_elem
605 const char *color; /* NULL; filled in by the setup code if
606 * color is enabled */
609 struct diff_words_style
611 enum diff_words_type type;
612 struct diff_words_style_elem new, old, ctx;
616 struct diff_words_style diff_words_styles[] = {
617 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
618 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
619 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
622 struct diff_words_data {
623 struct diff_words_buffer minus, plus;
624 const char *current_plus;
626 struct diff_options *opt;
628 enum diff_words_type type;
629 struct diff_words_style *style;
632 static int fn_out_diff_words_write_helper(FILE *fp,
633 struct diff_words_style_elem *st_el,
635 size_t count, const char *buf,
636 const char *line_prefix)
641 char *p = memchr(buf, '\n', count);
643 fputs(line_prefix, fp);
645 if (st_el->color && fputs(st_el->color, fp) < 0)
647 if (fputs(st_el->prefix, fp) < 0 ||
648 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
649 fputs(st_el->suffix, fp) < 0)
651 if (st_el->color && *st_el->color
652 && fputs(GIT_COLOR_RESET, fp) < 0)
657 if (fputs(newline, fp) < 0)
659 count -= p + 1 - buf;
667 * '--color-words' algorithm can be described as:
669 * 1. collect a the minus/plus lines of a diff hunk, divided into
670 * minus-lines and plus-lines;
672 * 2. break both minus-lines and plus-lines into words and
673 * place them into two mmfile_t with one word for each line;
675 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
677 * And for the common parts of the both file, we output the plus side text.
678 * diff_words->current_plus is used to trace the current position of the plus file
679 * which printed. diff_words->last_minus is used to trace the last minus word
682 * For '--graph' to work with '--color-words', we need to output the graph prefix
683 * on each line of color words output. Generally, there are two conditions on
684 * which we should output the prefix.
686 * 1. diff_words->last_minus == 0 &&
687 * diff_words->current_plus == diff_words->plus.text.ptr
689 * that is: the plus text must start as a new line, and if there is no minus
690 * word printed, a graph prefix must be printed.
692 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
693 * *(diff_words->current_plus - 1) == '\n'
695 * that is: a graph prefix must be printed following a '\n'
697 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
699 if ((diff_words->last_minus == 0 &&
700 diff_words->current_plus == diff_words->plus.text.ptr) ||
701 (diff_words->current_plus > diff_words->plus.text.ptr &&
702 *(diff_words->current_plus - 1) == '\n')) {
709 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
711 struct diff_words_data *diff_words = priv;
712 struct diff_words_style *style = diff_words->style;
713 int minus_first, minus_len, plus_first, plus_len;
714 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
715 struct diff_options *opt = diff_words->opt;
716 struct strbuf *msgbuf;
717 char *line_prefix = "";
719 if (line[0] != '@' || parse_hunk_header(line, len,
720 &minus_first, &minus_len, &plus_first, &plus_len))
724 if (opt->output_prefix) {
725 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
726 line_prefix = msgbuf->buf;
729 /* POSIX requires that first be decremented by one if len == 0... */
731 minus_begin = diff_words->minus.orig[minus_first].begin;
733 diff_words->minus.orig[minus_first + minus_len - 1].end;
735 minus_begin = minus_end =
736 diff_words->minus.orig[minus_first].end;
739 plus_begin = diff_words->plus.orig[plus_first].begin;
740 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
742 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
744 if (color_words_output_graph_prefix(diff_words)) {
745 fputs(line_prefix, diff_words->opt->file);
747 if (diff_words->current_plus != plus_begin) {
748 fn_out_diff_words_write_helper(diff_words->opt->file,
749 &style->ctx, style->newline,
750 plus_begin - diff_words->current_plus,
751 diff_words->current_plus, line_prefix);
752 if (*(plus_begin - 1) == '\n')
753 fputs(line_prefix, diff_words->opt->file);
755 if (minus_begin != minus_end) {
756 fn_out_diff_words_write_helper(diff_words->opt->file,
757 &style->old, style->newline,
758 minus_end - minus_begin, minus_begin,
761 if (plus_begin != plus_end) {
762 fn_out_diff_words_write_helper(diff_words->opt->file,
763 &style->new, style->newline,
764 plus_end - plus_begin, plus_begin,
768 diff_words->current_plus = plus_end;
769 diff_words->last_minus = minus_first;
772 /* This function starts looking at *begin, and returns 0 iff a word was found. */
773 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
774 int *begin, int *end)
776 if (word_regex && *begin < buffer->size) {
778 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
779 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
780 '\n', match[0].rm_eo - match[0].rm_so);
781 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
782 *begin += match[0].rm_so;
783 return *begin >= *end;
788 /* find the next word */
789 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
791 if (*begin >= buffer->size)
794 /* find the end of the word */
796 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
803 * This function splits the words in buffer->text, stores the list with
804 * newline separator into out, and saves the offsets of the original words
807 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
816 /* fake an empty "0th" word */
817 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
818 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
821 for (i = 0; i < buffer->text.size; i++) {
822 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
825 /* store original boundaries */
826 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
828 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
829 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
833 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
834 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
835 out->ptr[out->size + j - i] = '\n';
836 out->size += j - i + 1;
842 /* this executes the word diff on the accumulated buffers */
843 static void diff_words_show(struct diff_words_data *diff_words)
847 mmfile_t minus, plus;
848 struct diff_words_style *style = diff_words->style;
850 struct diff_options *opt = diff_words->opt;
851 struct strbuf *msgbuf;
852 char *line_prefix = "";
855 if (opt->output_prefix) {
856 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
857 line_prefix = msgbuf->buf;
860 /* special case: only removal */
861 if (!diff_words->plus.text.size) {
862 fputs(line_prefix, diff_words->opt->file);
863 fn_out_diff_words_write_helper(diff_words->opt->file,
864 &style->old, style->newline,
865 diff_words->minus.text.size,
866 diff_words->minus.text.ptr, line_prefix);
867 diff_words->minus.text.size = 0;
871 diff_words->current_plus = diff_words->plus.text.ptr;
872 diff_words->last_minus = 0;
874 memset(&xpp, 0, sizeof(xpp));
875 memset(&xecfg, 0, sizeof(xecfg));
876 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
877 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
878 xpp.flags = XDF_NEED_MINIMAL;
879 /* as only the hunk header will be parsed, we need a 0-context */
881 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
885 if (diff_words->current_plus != diff_words->plus.text.ptr +
886 diff_words->plus.text.size) {
887 if (color_words_output_graph_prefix(diff_words))
888 fputs(line_prefix, diff_words->opt->file);
889 fn_out_diff_words_write_helper(diff_words->opt->file,
890 &style->ctx, style->newline,
891 diff_words->plus.text.ptr + diff_words->plus.text.size
892 - diff_words->current_plus, diff_words->current_plus,
895 diff_words->minus.text.size = diff_words->plus.text.size = 0;
898 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
899 static void diff_words_flush(struct emit_callback *ecbdata)
901 if (ecbdata->diff_words->minus.text.size ||
902 ecbdata->diff_words->plus.text.size)
903 diff_words_show(ecbdata->diff_words);
906 static void free_diff_words_data(struct emit_callback *ecbdata)
908 if (ecbdata->diff_words) {
909 diff_words_flush(ecbdata);
910 free (ecbdata->diff_words->minus.text.ptr);
911 free (ecbdata->diff_words->minus.orig);
912 free (ecbdata->diff_words->plus.text.ptr);
913 free (ecbdata->diff_words->plus.orig);
914 free(ecbdata->diff_words->word_regex);
915 free(ecbdata->diff_words);
916 ecbdata->diff_words = NULL;
920 const char *diff_get_color(int diff_use_color, enum color_diff ix)
923 return diff_colors[ix];
927 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
934 return ecb->truncate(line, len);
938 (void) utf8_width(&cp, &l);
940 break; /* truncated in the middle? */
945 static void find_lno(const char *line, struct emit_callback *ecbdata)
948 ecbdata->lno_in_preimage = 0;
949 ecbdata->lno_in_postimage = 0;
950 p = strchr(line, '-');
952 return; /* cannot happen */
953 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
956 return; /* cannot happen */
957 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
960 static void fn_out_consume(void *priv, char *line, unsigned long len)
962 struct emit_callback *ecbdata = priv;
963 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
964 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
965 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
966 struct diff_options *o = ecbdata->opt;
967 char *line_prefix = "";
968 struct strbuf *msgbuf;
970 if (o && o->output_prefix) {
971 msgbuf = o->output_prefix(o, o->output_prefix_data);
972 line_prefix = msgbuf->buf;
975 if (ecbdata->header) {
976 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
977 strbuf_reset(ecbdata->header);
978 ecbdata->header = NULL;
980 *(ecbdata->found_changesp) = 1;
982 if (ecbdata->label_path[0]) {
983 const char *name_a_tab, *name_b_tab;
985 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
986 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
988 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
989 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
990 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
991 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
992 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
995 if (diff_suppress_blank_empty
996 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1001 if (line[0] == '@') {
1002 if (ecbdata->diff_words)
1003 diff_words_flush(ecbdata);
1004 len = sane_truncate_line(ecbdata, line, len);
1005 find_lno(line, ecbdata);
1006 emit_hunk_header(ecbdata, line, len);
1007 if (line[len-1] != '\n')
1008 putc('\n', ecbdata->opt->file);
1013 emit_line(ecbdata->opt, reset, reset, line, len);
1014 if (ecbdata->diff_words
1015 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1016 fputs("~\n", ecbdata->opt->file);
1020 if (ecbdata->diff_words) {
1021 if (line[0] == '-') {
1022 diff_words_append(line, len,
1023 &ecbdata->diff_words->minus);
1025 } else if (line[0] == '+') {
1026 diff_words_append(line, len,
1027 &ecbdata->diff_words->plus);
1030 diff_words_flush(ecbdata);
1031 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1032 emit_line(ecbdata->opt, plain, reset, line, len);
1033 fputs("~\n", ecbdata->opt->file);
1035 /* don't print the prefix character */
1036 emit_line(ecbdata->opt, plain, reset, line+1, len-1);
1041 if (line[0] != '+') {
1043 diff_get_color(ecbdata->color_diff,
1044 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1045 ecbdata->lno_in_preimage++;
1047 ecbdata->lno_in_postimage++;
1048 emit_line(ecbdata->opt, color, reset, line, len);
1050 ecbdata->lno_in_postimage++;
1051 emit_add_line(reset, ecbdata, line + 1, len - 1);
1055 static char *pprint_rename(const char *a, const char *b)
1057 const char *old = a;
1058 const char *new = b;
1059 struct strbuf name = STRBUF_INIT;
1060 int pfx_length, sfx_length;
1061 int len_a = strlen(a);
1062 int len_b = strlen(b);
1063 int a_midlen, b_midlen;
1064 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1065 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1067 if (qlen_a || qlen_b) {
1068 quote_c_style(a, &name, NULL, 0);
1069 strbuf_addstr(&name, " => ");
1070 quote_c_style(b, &name, NULL, 0);
1071 return strbuf_detach(&name, NULL);
1074 /* Find common prefix */
1076 while (*old && *new && *old == *new) {
1078 pfx_length = old - a + 1;
1083 /* Find common suffix */
1087 while (a <= old && b <= new && *old == *new) {
1089 sfx_length = len_a - (old - a);
1095 * pfx{mid-a => mid-b}sfx
1096 * {pfx-a => pfx-b}sfx
1097 * pfx{sfx-a => sfx-b}
1100 a_midlen = len_a - pfx_length - sfx_length;
1101 b_midlen = len_b - pfx_length - sfx_length;
1107 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1108 if (pfx_length + sfx_length) {
1109 strbuf_add(&name, a, pfx_length);
1110 strbuf_addch(&name, '{');
1112 strbuf_add(&name, a + pfx_length, a_midlen);
1113 strbuf_addstr(&name, " => ");
1114 strbuf_add(&name, b + pfx_length, b_midlen);
1115 if (pfx_length + sfx_length) {
1116 strbuf_addch(&name, '}');
1117 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1119 return strbuf_detach(&name, NULL);
1125 struct diffstat_file {
1129 unsigned is_unmerged:1;
1130 unsigned is_binary:1;
1131 unsigned is_renamed:1;
1132 uintmax_t added, deleted;
1136 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1140 struct diffstat_file *x;
1141 x = xcalloc(sizeof (*x), 1);
1142 if (diffstat->nr == diffstat->alloc) {
1143 diffstat->alloc = alloc_nr(diffstat->alloc);
1144 diffstat->files = xrealloc(diffstat->files,
1145 diffstat->alloc * sizeof(x));
1147 diffstat->files[diffstat->nr++] = x;
1149 x->from_name = xstrdup(name_a);
1150 x->name = xstrdup(name_b);
1154 x->from_name = NULL;
1155 x->name = xstrdup(name_a);
1160 static void diffstat_consume(void *priv, char *line, unsigned long len)
1162 struct diffstat_t *diffstat = priv;
1163 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1167 else if (line[0] == '-')
1171 const char mime_boundary_leader[] = "------------";
1173 static int scale_linear(int it, int width, int max_change)
1176 * make sure that at least one '-' is printed if there were deletions,
1177 * and likewise for '+'.
1181 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1184 static void show_name(FILE *file,
1185 const char *prefix, const char *name, int len)
1187 fprintf(file, " %s%-*s |", prefix, len, name);
1190 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1194 fprintf(file, "%s", set);
1197 fprintf(file, "%s", reset);
1200 static void fill_print_name(struct diffstat_file *file)
1204 if (file->print_name)
1207 if (!file->is_renamed) {
1208 struct strbuf buf = STRBUF_INIT;
1209 if (quote_c_style(file->name, &buf, NULL, 0)) {
1210 pname = strbuf_detach(&buf, NULL);
1213 strbuf_release(&buf);
1216 pname = pprint_rename(file->from_name, file->name);
1218 file->print_name = pname;
1221 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1223 int i, len, add, del, adds = 0, dels = 0;
1224 uintmax_t max_change = 0, max_len = 0;
1225 int total_files = data->nr;
1226 int width, name_width;
1227 const char *reset, *set, *add_c, *del_c;
1228 const char *line_prefix = "";
1229 struct strbuf *msg = NULL;
1234 if (options->output_prefix) {
1235 msg = options->output_prefix(options, options->output_prefix_data);
1236 line_prefix = msg->buf;
1239 width = options->stat_width ? options->stat_width : 80;
1240 name_width = options->stat_name_width ? options->stat_name_width : 50;
1242 /* Sanity: give at least 5 columns to the graph,
1243 * but leave at least 10 columns for the name.
1247 if (name_width < 10)
1249 else if (width < name_width + 15)
1250 name_width = width - 15;
1252 /* Find the longest filename and max number of changes */
1253 reset = diff_get_color_opt(options, DIFF_RESET);
1254 set = diff_get_color_opt(options, DIFF_PLAIN);
1255 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1256 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1258 for (i = 0; i < data->nr; i++) {
1259 struct diffstat_file *file = data->files[i];
1260 uintmax_t change = file->added + file->deleted;
1261 fill_print_name(file);
1262 len = strlen(file->print_name);
1266 if (file->is_binary || file->is_unmerged)
1268 if (max_change < change)
1269 max_change = change;
1272 /* Compute the width of the graph part;
1273 * 10 is for one blank at the beginning of the line plus
1274 * " | count " between the name and the graph.
1276 * From here on, name_width is the width of the name area,
1277 * and width is the width of the graph area.
1279 name_width = (name_width < max_len) ? name_width : max_len;
1280 if (width < (name_width + 10) + max_change)
1281 width = width - (name_width + 10);
1285 for (i = 0; i < data->nr; i++) {
1286 const char *prefix = "";
1287 char *name = data->files[i]->print_name;
1288 uintmax_t added = data->files[i]->added;
1289 uintmax_t deleted = data->files[i]->deleted;
1293 * "scale" the filename
1296 name_len = strlen(name);
1297 if (name_width < name_len) {
1301 name += name_len - len;
1302 slash = strchr(name, '/');
1307 if (data->files[i]->is_binary) {
1308 fprintf(options->file, "%s", line_prefix);
1309 show_name(options->file, prefix, name, len);
1310 fprintf(options->file, " Bin ");
1311 fprintf(options->file, "%s%"PRIuMAX"%s",
1312 del_c, deleted, reset);
1313 fprintf(options->file, " -> ");
1314 fprintf(options->file, "%s%"PRIuMAX"%s",
1315 add_c, added, reset);
1316 fprintf(options->file, " bytes");
1317 fprintf(options->file, "\n");
1320 else if (data->files[i]->is_unmerged) {
1321 fprintf(options->file, "%s", line_prefix);
1322 show_name(options->file, prefix, name, len);
1323 fprintf(options->file, " Unmerged\n");
1326 else if (!data->files[i]->is_renamed &&
1327 (added + deleted == 0)) {
1333 * scale the add/delete
1340 if (width <= max_change) {
1341 add = scale_linear(add, width, max_change);
1342 del = scale_linear(del, width, max_change);
1344 fprintf(options->file, "%s", line_prefix);
1345 show_name(options->file, prefix, name, len);
1346 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1347 added + deleted ? " " : "");
1348 show_graph(options->file, '+', add, add_c, reset);
1349 show_graph(options->file, '-', del, del_c, reset);
1350 fprintf(options->file, "\n");
1352 fprintf(options->file, "%s", line_prefix);
1353 fprintf(options->file,
1354 " %d files changed, %d insertions(+), %d deletions(-)\n",
1355 total_files, adds, dels);
1358 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1360 int i, adds = 0, dels = 0, total_files = data->nr;
1365 for (i = 0; i < data->nr; i++) {
1366 if (!data->files[i]->is_binary &&
1367 !data->files[i]->is_unmerged) {
1368 int added = data->files[i]->added;
1369 int deleted= data->files[i]->deleted;
1370 if (!data->files[i]->is_renamed &&
1371 (added + deleted == 0)) {
1379 if (options->output_prefix) {
1380 struct strbuf *msg = NULL;
1381 msg = options->output_prefix(options,
1382 options->output_prefix_data);
1383 fprintf(options->file, "%s", msg->buf);
1385 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1386 total_files, adds, dels);
1389 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1396 for (i = 0; i < data->nr; i++) {
1397 struct diffstat_file *file = data->files[i];
1399 if (options->output_prefix) {
1400 struct strbuf *msg = NULL;
1401 msg = options->output_prefix(options,
1402 options->output_prefix_data);
1403 fprintf(options->file, "%s", msg->buf);
1406 if (file->is_binary)
1407 fprintf(options->file, "-\t-\t");
1409 fprintf(options->file,
1410 "%"PRIuMAX"\t%"PRIuMAX"\t",
1411 file->added, file->deleted);
1412 if (options->line_termination) {
1413 fill_print_name(file);
1414 if (!file->is_renamed)
1415 write_name_quoted(file->name, options->file,
1416 options->line_termination);
1418 fputs(file->print_name, options->file);
1419 putc(options->line_termination, options->file);
1422 if (file->is_renamed) {
1423 putc('\0', options->file);
1424 write_name_quoted(file->from_name, options->file, '\0');
1426 write_name_quoted(file->name, options->file, '\0');
1431 struct dirstat_file {
1433 unsigned long changed;
1436 struct dirstat_dir {
1437 struct dirstat_file *files;
1438 int alloc, nr, percent, cumulative;
1441 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1442 unsigned long changed, const char *base, int baselen)
1444 unsigned long this_dir = 0;
1445 unsigned int sources = 0;
1446 const char *line_prefix = "";
1447 struct strbuf *msg = NULL;
1449 if (opt->output_prefix) {
1450 msg = opt->output_prefix(opt, opt->output_prefix_data);
1451 line_prefix = msg->buf;
1455 struct dirstat_file *f = dir->files;
1456 int namelen = strlen(f->name);
1460 if (namelen < baselen)
1462 if (memcmp(f->name, base, baselen))
1464 slash = strchr(f->name + baselen, '/');
1466 int newbaselen = slash + 1 - f->name;
1467 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1479 * We don't report dirstat's for
1481 * - or cases where everything came from a single directory
1482 * under this directory (sources == 1).
1484 if (baselen && sources != 1) {
1485 int permille = this_dir * 1000 / changed;
1487 int percent = permille / 10;
1488 if (percent >= dir->percent) {
1489 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1490 percent, permille % 10, baselen, base);
1491 if (!dir->cumulative)
1499 static int dirstat_compare(const void *_a, const void *_b)
1501 const struct dirstat_file *a = _a;
1502 const struct dirstat_file *b = _b;
1503 return strcmp(a->name, b->name);
1506 static void show_dirstat(struct diff_options *options)
1509 unsigned long changed;
1510 struct dirstat_dir dir;
1511 struct diff_queue_struct *q = &diff_queued_diff;
1516 dir.percent = options->dirstat_percent;
1517 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1520 for (i = 0; i < q->nr; i++) {
1521 struct diff_filepair *p = q->queue[i];
1523 unsigned long copied, added, damage;
1525 name = p->one->path ? p->one->path : p->two->path;
1527 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1528 diff_populate_filespec(p->one, 0);
1529 diff_populate_filespec(p->two, 0);
1530 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1532 diff_free_filespec_data(p->one);
1533 diff_free_filespec_data(p->two);
1534 } else if (DIFF_FILE_VALID(p->one)) {
1535 diff_populate_filespec(p->one, 1);
1537 diff_free_filespec_data(p->one);
1538 } else if (DIFF_FILE_VALID(p->two)) {
1539 diff_populate_filespec(p->two, 1);
1541 added = p->two->size;
1542 diff_free_filespec_data(p->two);
1547 * Original minus copied is the removed material,
1548 * added is the new material. They are both damages
1549 * made to the preimage. In --dirstat-by-file mode, count
1550 * damaged files, not damaged lines. This is done by
1551 * counting only a single damaged line per file.
1553 damage = (p->one->size - copied) + added;
1554 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1557 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1558 dir.files[dir.nr].name = name;
1559 dir.files[dir.nr].changed = damage;
1564 /* This can happen even with many files, if everything was renames */
1568 /* Show all directories with more than x% of the changes */
1569 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1570 gather_dirstat(options, &dir, changed, "", 0);
1573 static void free_diffstat_info(struct diffstat_t *diffstat)
1576 for (i = 0; i < diffstat->nr; i++) {
1577 struct diffstat_file *f = diffstat->files[i];
1578 if (f->name != f->print_name)
1579 free(f->print_name);
1584 free(diffstat->files);
1587 struct checkdiff_t {
1588 const char *filename;
1590 int conflict_marker_size;
1591 struct diff_options *o;
1596 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1601 if (len < marker_size + 1)
1603 firstchar = line[0];
1604 switch (firstchar) {
1605 case '=': case '>': case '<': case '|':
1610 for (cnt = 1; cnt < marker_size; cnt++)
1611 if (line[cnt] != firstchar)
1613 /* line[1] thru line[marker_size-1] are same as firstchar */
1614 if (len < marker_size + 1 || !isspace(line[marker_size]))
1619 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1621 struct checkdiff_t *data = priv;
1622 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1623 int marker_size = data->conflict_marker_size;
1624 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1625 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1626 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1628 char *line_prefix = "";
1629 struct strbuf *msgbuf;
1632 if (data->o->output_prefix) {
1633 msgbuf = data->o->output_prefix(data->o,
1634 data->o->output_prefix_data);
1635 line_prefix = msgbuf->buf;
1638 if (line[0] == '+') {
1641 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1643 fprintf(data->o->file,
1644 "%s%s:%d: leftover conflict marker\n",
1645 line_prefix, data->filename, data->lineno);
1647 bad = ws_check(line + 1, len - 1, data->ws_rule);
1650 data->status |= bad;
1651 err = whitespace_error_string(bad);
1652 fprintf(data->o->file, "%s%s:%d: %s.\n",
1653 line_prefix, data->filename, data->lineno, err);
1655 emit_line(data->o, set, reset, line, 1);
1656 ws_check_emit(line + 1, len - 1, data->ws_rule,
1657 data->o->file, set, reset, ws);
1658 } else if (line[0] == ' ') {
1660 } else if (line[0] == '@') {
1661 char *plus = strchr(line, '+');
1663 data->lineno = strtol(plus, NULL, 10) - 1;
1665 die("invalid diff");
1669 static unsigned char *deflate_it(char *data,
1671 unsigned long *result_size)
1674 unsigned char *deflated;
1677 memset(&stream, 0, sizeof(stream));
1678 deflateInit(&stream, zlib_compression_level);
1679 bound = deflateBound(&stream, size);
1680 deflated = xmalloc(bound);
1681 stream.next_out = deflated;
1682 stream.avail_out = bound;
1684 stream.next_in = (unsigned char *)data;
1685 stream.avail_in = size;
1686 while (deflate(&stream, Z_FINISH) == Z_OK)
1688 deflateEnd(&stream);
1689 *result_size = stream.total_out;
1693 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
1699 unsigned long orig_size;
1700 unsigned long delta_size;
1701 unsigned long deflate_size;
1702 unsigned long data_size;
1704 /* We could do deflated delta, or we could do just deflated two,
1705 * whichever is smaller.
1708 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1709 if (one->size && two->size) {
1710 delta = diff_delta(one->ptr, one->size,
1711 two->ptr, two->size,
1712 &delta_size, deflate_size);
1714 void *to_free = delta;
1715 orig_size = delta_size;
1716 delta = deflate_it(delta, delta_size, &delta_size);
1721 if (delta && delta_size < deflate_size) {
1722 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
1725 data_size = delta_size;
1728 fprintf(file, "%sliteral %lu\n", prefix, two->size);
1731 data_size = deflate_size;
1734 /* emit data encoded in base85 */
1737 int bytes = (52 < data_size) ? 52 : data_size;
1741 line[0] = bytes + 'A' - 1;
1743 line[0] = bytes - 26 + 'a' - 1;
1744 encode_85(line + 1, cp, bytes);
1745 cp = (char *) cp + bytes;
1746 fprintf(file, "%s", prefix);
1750 fprintf(file, "%s\n", prefix);
1754 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
1756 fprintf(file, "%sGIT binary patch\n", prefix);
1757 emit_binary_diff_body(file, one, two, prefix);
1758 emit_binary_diff_body(file, two, one, prefix);
1761 static void diff_filespec_load_driver(struct diff_filespec *one)
1764 one->driver = userdiff_find_by_path(one->path);
1766 one->driver = userdiff_find_by_name("default");
1769 int diff_filespec_is_binary(struct diff_filespec *one)
1771 if (one->is_binary == -1) {
1772 diff_filespec_load_driver(one);
1773 if (one->driver->binary != -1)
1774 one->is_binary = one->driver->binary;
1776 if (!one->data && DIFF_FILE_VALID(one))
1777 diff_populate_filespec(one, 0);
1779 one->is_binary = buffer_is_binary(one->data,
1781 if (one->is_binary == -1)
1785 return one->is_binary;
1788 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1790 diff_filespec_load_driver(one);
1791 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1794 static const char *userdiff_word_regex(struct diff_filespec *one)
1796 diff_filespec_load_driver(one);
1797 return one->driver->word_regex;
1800 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1802 if (!options->a_prefix)
1803 options->a_prefix = a;
1804 if (!options->b_prefix)
1805 options->b_prefix = b;
1808 static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1810 if (!DIFF_FILE_VALID(one))
1812 if (!S_ISREG(one->mode))
1814 diff_filespec_load_driver(one);
1815 if (!one->driver->textconv)
1818 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1819 struct notes_cache *c = xmalloc(sizeof(*c));
1820 struct strbuf name = STRBUF_INIT;
1822 strbuf_addf(&name, "textconv/%s", one->driver->name);
1823 notes_cache_init(c, name.buf, one->driver->textconv);
1824 one->driver->textconv_cache = c;
1830 static void builtin_diff(const char *name_a,
1832 struct diff_filespec *one,
1833 struct diff_filespec *two,
1834 const char *xfrm_msg,
1835 struct diff_options *o,
1836 int complete_rewrite)
1840 char *a_one, *b_two;
1841 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1842 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1843 const char *a_prefix, *b_prefix;
1844 struct userdiff_driver *textconv_one = NULL;
1845 struct userdiff_driver *textconv_two = NULL;
1846 struct strbuf header = STRBUF_INIT;
1847 struct strbuf *msgbuf;
1848 char *line_prefix = "";
1850 if (o->output_prefix) {
1851 msgbuf = o->output_prefix(o, o->output_prefix_data);
1852 line_prefix = msgbuf->buf;
1855 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1856 (!one->mode || S_ISGITLINK(one->mode)) &&
1857 (!two->mode || S_ISGITLINK(two->mode))) {
1858 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1859 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1860 show_submodule_summary(o->file, one ? one->path : two->path,
1861 one->sha1, two->sha1, two->dirty_submodule,
1866 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1867 textconv_one = get_textconv(one);
1868 textconv_two = get_textconv(two);
1871 diff_set_mnemonic_prefix(o, "a/", "b/");
1872 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1873 a_prefix = o->b_prefix;
1874 b_prefix = o->a_prefix;
1876 a_prefix = o->a_prefix;
1877 b_prefix = o->b_prefix;
1880 /* Never use a non-valid filename anywhere if at all possible */
1881 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1882 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1884 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1885 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1886 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1887 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1888 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, set, a_one, b_two, reset);
1889 if (lbl[0][0] == '/') {
1891 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, set, two->mode, reset);
1892 if (xfrm_msg && xfrm_msg[0])
1893 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1895 else if (lbl[1][0] == '/') {
1896 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, set, one->mode, reset);
1897 if (xfrm_msg && xfrm_msg[0])
1898 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1901 if (one->mode != two->mode) {
1902 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, set, one->mode, reset);
1903 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, set, two->mode, reset);
1905 if (xfrm_msg && xfrm_msg[0])
1906 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1909 * we do not run diff between different kind
1912 if ((one->mode ^ two->mode) & S_IFMT)
1913 goto free_ab_and_return;
1914 if (complete_rewrite &&
1915 (textconv_one || !diff_filespec_is_binary(one)) &&
1916 (textconv_two || !diff_filespec_is_binary(two))) {
1917 fprintf(o->file, "%s", header.buf);
1918 strbuf_reset(&header);
1919 emit_rewrite_diff(name_a, name_b, one, two,
1920 textconv_one, textconv_two, o);
1921 o->found_changes = 1;
1922 goto free_ab_and_return;
1926 if (!DIFF_OPT_TST(o, TEXT) &&
1927 ( (!textconv_one && diff_filespec_is_binary(one)) ||
1928 (!textconv_two && diff_filespec_is_binary(two)) )) {
1929 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1930 die("unable to read files to diff");
1931 /* Quite common confusing case */
1932 if (mf1.size == mf2.size &&
1933 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1934 goto free_ab_and_return;
1935 fprintf(o->file, "%s", header.buf);
1936 strbuf_reset(&header);
1937 if (DIFF_OPT_TST(o, BINARY))
1938 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
1940 fprintf(o->file, "%sBinary files %s and %s differ\n",
1941 line_prefix, lbl[0], lbl[1]);
1942 o->found_changes = 1;
1945 /* Crazy xdl interfaces.. */
1946 const char *diffopts = getenv("GIT_DIFF_OPTS");
1949 struct emit_callback ecbdata;
1950 const struct userdiff_funcname *pe;
1952 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1953 fprintf(o->file, "%s", header.buf);
1954 strbuf_reset(&header);
1957 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1958 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1960 pe = diff_funcname_pattern(one);
1962 pe = diff_funcname_pattern(two);
1964 memset(&xpp, 0, sizeof(xpp));
1965 memset(&xecfg, 0, sizeof(xecfg));
1966 memset(&ecbdata, 0, sizeof(ecbdata));
1967 ecbdata.label_path = lbl;
1968 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1969 ecbdata.found_changesp = &o->found_changes;
1970 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1971 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1972 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1974 ecbdata.header = header.len ? &header : NULL;
1975 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1976 xecfg.ctxlen = o->context;
1977 xecfg.interhunkctxlen = o->interhunkcontext;
1978 xecfg.flags = XDL_EMIT_FUNCNAMES;
1980 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1983 else if (!prefixcmp(diffopts, "--unified="))
1984 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1985 else if (!prefixcmp(diffopts, "-u"))
1986 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1990 ecbdata.diff_words =
1991 xcalloc(1, sizeof(struct diff_words_data));
1992 ecbdata.diff_words->type = o->word_diff;
1993 ecbdata.diff_words->opt = o;
1995 o->word_regex = userdiff_word_regex(one);
1997 o->word_regex = userdiff_word_regex(two);
1999 o->word_regex = diff_word_regex_cfg;
2000 if (o->word_regex) {
2001 ecbdata.diff_words->word_regex = (regex_t *)
2002 xmalloc(sizeof(regex_t));
2003 if (regcomp(ecbdata.diff_words->word_regex,
2005 REG_EXTENDED | REG_NEWLINE))
2006 die ("Invalid regular expression: %s",
2009 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2010 if (o->word_diff == diff_words_styles[i].type) {
2011 ecbdata.diff_words->style =
2012 &diff_words_styles[i];
2016 if (DIFF_OPT_TST(o, COLOR_DIFF)) {
2017 struct diff_words_style *st = ecbdata.diff_words->style;
2018 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2019 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2020 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
2023 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2026 free_diff_words_data(&ecbdata);
2031 xdiff_clear_find_func(&xecfg);
2035 strbuf_release(&header);
2036 diff_free_filespec_data(one);
2037 diff_free_filespec_data(two);
2043 static void builtin_diffstat(const char *name_a, const char *name_b,
2044 struct diff_filespec *one,
2045 struct diff_filespec *two,
2046 struct diffstat_t *diffstat,
2047 struct diff_options *o,
2048 int complete_rewrite)
2051 struct diffstat_file *data;
2053 data = diffstat_add(diffstat, name_a, name_b);
2056 data->is_unmerged = 1;
2059 if (complete_rewrite) {
2060 diff_populate_filespec(one, 0);
2061 diff_populate_filespec(two, 0);
2062 data->deleted = count_lines(one->data, one->size);
2063 data->added = count_lines(two->data, two->size);
2064 goto free_and_return;
2066 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2067 die("unable to read files to diff");
2069 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2070 data->is_binary = 1;
2071 data->added = mf2.size;
2072 data->deleted = mf1.size;
2074 /* Crazy xdl interfaces.. */
2078 memset(&xpp, 0, sizeof(xpp));
2079 memset(&xecfg, 0, sizeof(xecfg));
2080 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
2081 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2086 diff_free_filespec_data(one);
2087 diff_free_filespec_data(two);
2090 static void builtin_checkdiff(const char *name_a, const char *name_b,
2091 const char *attr_path,
2092 struct diff_filespec *one,
2093 struct diff_filespec *two,
2094 struct diff_options *o)
2097 struct checkdiff_t data;
2102 memset(&data, 0, sizeof(data));
2103 data.filename = name_b ? name_b : name_a;
2106 data.ws_rule = whitespace_rule(attr_path);
2107 data.conflict_marker_size = ll_merge_marker_size(attr_path);
2109 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2110 die("unable to read files to diff");
2113 * All the other codepaths check both sides, but not checking
2114 * the "old" side here is deliberate. We are checking the newly
2115 * introduced changes, and as long as the "new" side is text, we
2116 * can and should check what it introduces.
2118 if (diff_filespec_is_binary(two))
2119 goto free_and_return;
2121 /* Crazy xdl interfaces.. */
2125 memset(&xpp, 0, sizeof(xpp));
2126 memset(&xecfg, 0, sizeof(xecfg));
2127 xecfg.ctxlen = 1; /* at least one context line */
2128 xpp.flags = XDF_NEED_MINIMAL;
2129 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2132 if (data.ws_rule & WS_BLANK_AT_EOF) {
2133 struct emit_callback ecbdata;
2136 ecbdata.ws_rule = data.ws_rule;
2137 check_blank_at_eof(&mf1, &mf2, &ecbdata);
2138 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
2143 err = whitespace_error_string(WS_BLANK_AT_EOF);
2144 fprintf(o->file, "%s:%d: %s.\n",
2145 data.filename, blank_at_eof, err);
2146 data.status = 1; /* report errors */
2151 diff_free_filespec_data(one);
2152 diff_free_filespec_data(two);
2154 DIFF_OPT_SET(o, CHECK_FAILED);
2157 struct diff_filespec *alloc_filespec(const char *path)
2159 int namelen = strlen(path);
2160 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2162 memset(spec, 0, sizeof(*spec));
2163 spec->path = (char *)(spec + 1);
2164 memcpy(spec->path, path, namelen+1);
2166 spec->is_binary = -1;
2170 void free_filespec(struct diff_filespec *spec)
2172 if (!--spec->count) {
2173 diff_free_filespec_data(spec);
2178 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2179 unsigned short mode)
2182 spec->mode = canon_mode(mode);
2183 hashcpy(spec->sha1, sha1);
2184 spec->sha1_valid = !is_null_sha1(sha1);
2189 * Given a name and sha1 pair, if the index tells us the file in
2190 * the work tree has that object contents, return true, so that
2191 * prepare_temp_file() does not have to inflate and extract.
2193 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2195 struct cache_entry *ce;
2200 * We do not read the cache ourselves here, because the
2201 * benchmark with my previous version that always reads cache
2202 * shows that it makes things worse for diff-tree comparing
2203 * two linux-2.6 kernel trees in an already checked out work
2204 * tree. This is because most diff-tree comparisons deal with
2205 * only a small number of files, while reading the cache is
2206 * expensive for a large project, and its cost outweighs the
2207 * savings we get by not inflating the object to a temporary
2208 * file. Practically, this code only helps when we are used
2209 * by diff-cache --cached, which does read the cache before
2215 /* We want to avoid the working directory if our caller
2216 * doesn't need the data in a normal file, this system
2217 * is rather slow with its stat/open/mmap/close syscalls,
2218 * and the object is contained in a pack file. The pack
2219 * is probably already open and will be faster to obtain
2220 * the data through than the working directory. Loose
2221 * objects however would tend to be slower as they need
2222 * to be individually opened and inflated.
2224 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2228 pos = cache_name_pos(name, len);
2231 ce = active_cache[pos];
2234 * This is not the sha1 we are looking for, or
2235 * unreusable because it is not a regular file.
2237 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2241 * If ce is marked as "assume unchanged", there is no
2242 * guarantee that work tree matches what we are looking for.
2244 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2248 * If ce matches the file in the work tree, we can reuse it.
2250 if (ce_uptodate(ce) ||
2251 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2257 static int populate_from_stdin(struct diff_filespec *s)
2259 struct strbuf buf = STRBUF_INIT;
2262 if (strbuf_read(&buf, 0, 0) < 0)
2263 return error("error while reading from stdin %s",
2266 s->should_munmap = 0;
2267 s->data = strbuf_detach(&buf, &size);
2273 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2276 char *data = xmalloc(100), *dirty = "";
2278 /* Are we looking at the work tree? */
2279 if (s->dirty_submodule)
2282 len = snprintf(data, 100,
2283 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2295 * While doing rename detection and pickaxe operation, we may need to
2296 * grab the data for the blob (or file) for our own in-core comparison.
2297 * diff_filespec has data and size fields for this purpose.
2299 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2302 if (!DIFF_FILE_VALID(s))
2303 die("internal error: asking to populate invalid file.");
2304 if (S_ISDIR(s->mode))
2310 if (size_only && 0 < s->size)
2313 if (S_ISGITLINK(s->mode))
2314 return diff_populate_gitlink(s, size_only);
2316 if (!s->sha1_valid ||
2317 reuse_worktree_file(s->path, s->sha1, 0)) {
2318 struct strbuf buf = STRBUF_INIT;
2322 if (!strcmp(s->path, "-"))
2323 return populate_from_stdin(s);
2325 if (lstat(s->path, &st) < 0) {
2326 if (errno == ENOENT) {
2330 s->data = (char *)"";
2335 s->size = xsize_t(st.st_size);
2338 if (S_ISLNK(st.st_mode)) {
2339 struct strbuf sb = STRBUF_INIT;
2341 if (strbuf_readlink(&sb, s->path, s->size))
2344 s->data = strbuf_detach(&sb, NULL);
2350 fd = open(s->path, O_RDONLY);
2353 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2355 s->should_munmap = 1;
2358 * Convert from working tree format to canonical git format
2360 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2362 munmap(s->data, s->size);
2363 s->should_munmap = 0;
2364 s->data = strbuf_detach(&buf, &size);
2370 enum object_type type;
2372 type = sha1_object_info(s->sha1, &s->size);
2374 s->data = read_sha1_file(s->sha1, &type, &s->size);
2381 void diff_free_filespec_blob(struct diff_filespec *s)
2385 else if (s->should_munmap)
2386 munmap(s->data, s->size);
2388 if (s->should_free || s->should_munmap) {
2389 s->should_free = s->should_munmap = 0;
2394 void diff_free_filespec_data(struct diff_filespec *s)
2396 diff_free_filespec_blob(s);
2401 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2404 const unsigned char *sha1,
2408 struct strbuf buf = STRBUF_INIT;
2409 struct strbuf template = STRBUF_INIT;
2410 char *path_dup = xstrdup(path);
2411 const char *base = basename(path_dup);
2413 /* Generate "XXXXXX_basename.ext" */
2414 strbuf_addstr(&template, "XXXXXX_");
2415 strbuf_addstr(&template, base);
2417 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2420 die_errno("unable to create temp-file");
2421 if (convert_to_working_tree(path,
2422 (const char *)blob, (size_t)size, &buf)) {
2426 if (write_in_full(fd, blob, size) != size)
2427 die_errno("unable to write temp-file");
2429 temp->name = temp->tmp_path;
2430 strcpy(temp->hex, sha1_to_hex(sha1));
2432 sprintf(temp->mode, "%06o", mode);
2433 strbuf_release(&buf);
2434 strbuf_release(&template);
2438 static struct diff_tempfile *prepare_temp_file(const char *name,
2439 struct diff_filespec *one)
2441 struct diff_tempfile *temp = claim_diff_tempfile();
2443 if (!DIFF_FILE_VALID(one)) {
2445 /* A '-' entry produces this for file-2, and
2446 * a '+' entry produces this for file-1.
2448 temp->name = "/dev/null";
2449 strcpy(temp->hex, ".");
2450 strcpy(temp->mode, ".");
2454 if (!remove_tempfile_installed) {
2455 atexit(remove_tempfile);
2456 sigchain_push_common(remove_tempfile_on_signal);
2457 remove_tempfile_installed = 1;
2460 if (!one->sha1_valid ||
2461 reuse_worktree_file(name, one->sha1, 1)) {
2463 if (lstat(name, &st) < 0) {
2464 if (errno == ENOENT)
2465 goto not_a_valid_file;
2466 die_errno("stat(%s)", name);
2468 if (S_ISLNK(st.st_mode)) {
2469 struct strbuf sb = STRBUF_INIT;
2470 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2471 die_errno("readlink(%s)", name);
2472 prep_temp_blob(name, temp, sb.buf, sb.len,
2474 one->sha1 : null_sha1),
2476 one->mode : S_IFLNK));
2477 strbuf_release(&sb);
2480 /* we can borrow from the file in the work tree */
2482 if (!one->sha1_valid)
2483 strcpy(temp->hex, sha1_to_hex(null_sha1));
2485 strcpy(temp->hex, sha1_to_hex(one->sha1));
2486 /* Even though we may sometimes borrow the
2487 * contents from the work tree, we always want
2488 * one->mode. mode is trustworthy even when
2489 * !(one->sha1_valid), as long as
2490 * DIFF_FILE_VALID(one).
2492 sprintf(temp->mode, "%06o", one->mode);
2497 if (diff_populate_filespec(one, 0))
2498 die("cannot read data blob for %s", one->path);
2499 prep_temp_blob(name, temp, one->data, one->size,
2500 one->sha1, one->mode);
2505 /* An external diff command takes:
2507 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2508 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2511 static void run_external_diff(const char *pgm,
2514 struct diff_filespec *one,
2515 struct diff_filespec *two,
2516 const char *xfrm_msg,
2517 int complete_rewrite)
2519 const char *spawn_arg[10];
2521 const char **arg = &spawn_arg[0];
2524 struct diff_tempfile *temp_one, *temp_two;
2525 const char *othername = (other ? other : name);
2526 temp_one = prepare_temp_file(name, one);
2527 temp_two = prepare_temp_file(othername, two);
2530 *arg++ = temp_one->name;
2531 *arg++ = temp_one->hex;
2532 *arg++ = temp_one->mode;
2533 *arg++ = temp_two->name;
2534 *arg++ = temp_two->hex;
2535 *arg++ = temp_two->mode;
2546 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2549 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2554 static int similarity_index(struct diff_filepair *p)
2556 return p->score * 100 / MAX_SCORE;
2559 static void fill_metainfo(struct strbuf *msg,
2562 struct diff_filespec *one,
2563 struct diff_filespec *two,
2564 struct diff_options *o,
2565 struct diff_filepair *p)
2567 struct strbuf *msgbuf;
2568 char *line_prefix = "";
2570 if (o->output_prefix) {
2571 msgbuf = o->output_prefix(o, o->output_prefix_data);
2572 line_prefix = msgbuf->buf;
2575 strbuf_init(msg, PATH_MAX * 2 + 300);
2576 switch (p->status) {
2577 case DIFF_STATUS_COPIED:
2578 strbuf_addf(msg, "%ssimilarity index %d%%", line_prefix, similarity_index(p));
2579 strbuf_addf(msg, "\n%scopy from ", line_prefix);
2580 quote_c_style(name, msg, NULL, 0);
2581 strbuf_addf(msg, "\n%scopy to ", line_prefix);
2582 quote_c_style(other, msg, NULL, 0);
2583 strbuf_addch(msg, '\n');
2585 case DIFF_STATUS_RENAMED:
2586 strbuf_addf(msg, "%ssimilarity index %d%%", line_prefix, similarity_index(p));
2587 strbuf_addf(msg, "\n%srename from ", line_prefix);
2588 quote_c_style(name, msg, NULL, 0);
2589 strbuf_addf(msg, "\n%srename to ", line_prefix);
2590 quote_c_style(other, msg, NULL, 0);
2591 strbuf_addch(msg, '\n');
2593 case DIFF_STATUS_MODIFIED:
2595 strbuf_addf(msg, "%sdissimilarity index %d%%\n",
2596 line_prefix, similarity_index(p));
2604 if (one && two && hashcmp(one->sha1, two->sha1)) {
2605 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2607 if (DIFF_OPT_TST(o, BINARY)) {
2609 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2610 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2613 strbuf_addf(msg, "%sindex %.*s..%.*s",
2614 line_prefix, abbrev, sha1_to_hex(one->sha1),
2615 abbrev, sha1_to_hex(two->sha1));
2616 if (one->mode == two->mode)
2617 strbuf_addf(msg, " %06o", one->mode);
2618 strbuf_addch(msg, '\n');
2621 strbuf_setlen(msg, msg->len - 1);
2624 static void run_diff_cmd(const char *pgm,
2627 const char *attr_path,
2628 struct diff_filespec *one,
2629 struct diff_filespec *two,
2631 struct diff_options *o,
2632 struct diff_filepair *p)
2634 const char *xfrm_msg = NULL;
2635 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2638 fill_metainfo(msg, name, other, one, two, o, p);
2639 xfrm_msg = msg->len ? msg->buf : NULL;
2642 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2645 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2646 if (drv && drv->external)
2647 pgm = drv->external;
2651 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2656 builtin_diff(name, other ? other : name,
2657 one, two, xfrm_msg, o, complete_rewrite);
2659 fprintf(o->file, "* Unmerged path %s\n", name);
2662 static void diff_fill_sha1_info(struct diff_filespec *one)
2664 if (DIFF_FILE_VALID(one)) {
2665 if (!one->sha1_valid) {
2667 if (!strcmp(one->path, "-")) {
2668 hashcpy(one->sha1, null_sha1);
2671 if (lstat(one->path, &st) < 0)
2672 die_errno("stat '%s'", one->path);
2673 if (index_path(one->sha1, one->path, &st, 0))
2674 die("cannot hash %s", one->path);
2681 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2683 /* Strip the prefix but do not molest /dev/null and absolute paths */
2684 if (*namep && **namep != '/')
2685 *namep += prefix_length;
2686 if (*otherp && **otherp != '/')
2687 *otherp += prefix_length;
2690 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2692 const char *pgm = external_diff();
2694 struct diff_filespec *one = p->one;
2695 struct diff_filespec *two = p->two;
2698 const char *attr_path;
2700 name = p->one->path;
2701 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2703 if (o->prefix_length)
2704 strip_prefix(o->prefix_length, &name, &other);
2706 if (DIFF_PAIR_UNMERGED(p)) {
2707 run_diff_cmd(pgm, name, NULL, attr_path,
2708 NULL, NULL, NULL, o, p);
2712 diff_fill_sha1_info(one);
2713 diff_fill_sha1_info(two);
2716 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2717 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2719 * a filepair that changes between file and symlink
2720 * needs to be split into deletion and creation.
2722 struct diff_filespec *null = alloc_filespec(two->path);
2723 run_diff_cmd(NULL, name, other, attr_path,
2724 one, null, &msg, o, p);
2726 strbuf_release(&msg);
2728 null = alloc_filespec(one->path);
2729 run_diff_cmd(NULL, name, other, attr_path,
2730 null, two, &msg, o, p);
2734 run_diff_cmd(pgm, name, other, attr_path,
2735 one, two, &msg, o, p);
2737 strbuf_release(&msg);
2740 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2741 struct diffstat_t *diffstat)
2745 int complete_rewrite = 0;
2747 if (DIFF_PAIR_UNMERGED(p)) {
2749 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2753 name = p->one->path;
2754 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2756 if (o->prefix_length)
2757 strip_prefix(o->prefix_length, &name, &other);
2759 diff_fill_sha1_info(p->one);
2760 diff_fill_sha1_info(p->two);
2762 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2763 complete_rewrite = 1;
2764 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2767 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2771 const char *attr_path;
2773 if (DIFF_PAIR_UNMERGED(p)) {
2778 name = p->one->path;
2779 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2780 attr_path = other ? other : name;
2782 if (o->prefix_length)
2783 strip_prefix(o->prefix_length, &name, &other);
2785 diff_fill_sha1_info(p->one);
2786 diff_fill_sha1_info(p->two);
2788 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2791 void diff_setup(struct diff_options *options)
2793 memset(options, 0, sizeof(*options));
2794 memset(&diff_queued_diff, 0, sizeof(diff_queued_diff));
2796 options->file = stdout;
2798 options->line_termination = '\n';
2799 options->break_opt = -1;
2800 options->rename_limit = -1;
2801 options->dirstat_percent = 3;
2802 options->context = 3;
2804 options->change = diff_change;
2805 options->add_remove = diff_addremove;
2806 if (diff_use_color_default > 0)
2807 DIFF_OPT_SET(options, COLOR_DIFF);
2808 options->detect_rename = diff_detect_rename_default;
2810 if (!diff_mnemonic_prefix) {
2811 options->a_prefix = "a/";
2812 options->b_prefix = "b/";
2816 int diff_setup_done(struct diff_options *options)
2820 if (options->output_format & DIFF_FORMAT_NAME)
2822 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2824 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2826 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2829 die("--name-only, --name-status, --check and -s are mutually exclusive");
2832 * Most of the time we can say "there are changes"
2833 * only by checking if there are changed paths, but
2834 * --ignore-whitespace* options force us to look
2838 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2839 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2840 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2841 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2843 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2845 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2846 options->detect_rename = DIFF_DETECT_COPY;
2848 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2849 options->prefix = NULL;
2850 if (options->prefix)
2851 options->prefix_length = strlen(options->prefix);
2853 options->prefix_length = 0;
2855 if (options->output_format & (DIFF_FORMAT_NAME |
2856 DIFF_FORMAT_NAME_STATUS |
2857 DIFF_FORMAT_CHECKDIFF |
2858 DIFF_FORMAT_NO_OUTPUT))
2859 options->output_format &= ~(DIFF_FORMAT_RAW |
2860 DIFF_FORMAT_NUMSTAT |
2861 DIFF_FORMAT_DIFFSTAT |
2862 DIFF_FORMAT_SHORTSTAT |
2863 DIFF_FORMAT_DIRSTAT |
2864 DIFF_FORMAT_SUMMARY |
2868 * These cases always need recursive; we do not drop caller-supplied
2869 * recursive bits for other formats here.
2871 if (options->output_format & (DIFF_FORMAT_PATCH |
2872 DIFF_FORMAT_NUMSTAT |
2873 DIFF_FORMAT_DIFFSTAT |
2874 DIFF_FORMAT_SHORTSTAT |
2875 DIFF_FORMAT_DIRSTAT |
2876 DIFF_FORMAT_SUMMARY |
2877 DIFF_FORMAT_CHECKDIFF))
2878 DIFF_OPT_SET(options, RECURSIVE);
2880 * Also pickaxe would not work very well if you do not say recursive
2882 if (options->pickaxe)
2883 DIFF_OPT_SET(options, RECURSIVE);
2885 * When patches are generated, submodules diffed against the work tree
2886 * must be checked for dirtiness too so it can be shown in the output
2888 if (options->output_format & DIFF_FORMAT_PATCH)
2889 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2891 if (options->detect_rename && options->rename_limit < 0)
2892 options->rename_limit = diff_rename_limit_default;
2893 if (options->setup & DIFF_SETUP_USE_CACHE) {
2895 /* read-cache does not die even when it fails
2896 * so it is safe for us to do this here. Also
2897 * it does not smudge active_cache or active_nr
2898 * when it fails, so we do not have to worry about
2899 * cleaning it up ourselves either.
2903 if (options->abbrev <= 0 || 40 < options->abbrev)
2904 options->abbrev = 40; /* full */
2907 * It does not make sense to show the first hit we happened
2908 * to have found. It does not make sense not to return with
2909 * exit code in such a case either.
2911 if (DIFF_OPT_TST(options, QUICK)) {
2912 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2913 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2919 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2929 if (c == arg_short) {
2933 if (val && isdigit(c)) {
2935 int n = strtoul(arg, &end, 10);
2946 eq = strchr(arg, '=');
2951 if (!len || strncmp(arg, arg_long, len))
2956 if (!isdigit(*++eq))
2958 n = strtoul(eq, &end, 10);
2966 static int diff_scoreopt_parse(const char *opt);
2968 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2970 const char *arg = av[0];
2972 /* Output format options */
2973 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
2974 options->output_format |= DIFF_FORMAT_PATCH;
2975 else if (opt_arg(arg, 'U', "unified", &options->context))
2976 options->output_format |= DIFF_FORMAT_PATCH;
2977 else if (!strcmp(arg, "--raw"))
2978 options->output_format |= DIFF_FORMAT_RAW;
2979 else if (!strcmp(arg, "--patch-with-raw"))
2980 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2981 else if (!strcmp(arg, "--numstat"))
2982 options->output_format |= DIFF_FORMAT_NUMSTAT;
2983 else if (!strcmp(arg, "--shortstat"))
2984 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2985 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2986 options->output_format |= DIFF_FORMAT_DIRSTAT;
2987 else if (!strcmp(arg, "--cumulative")) {
2988 options->output_format |= DIFF_FORMAT_DIRSTAT;
2989 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2990 } else if (opt_arg(arg, 0, "dirstat-by-file",
2991 &options->dirstat_percent)) {
2992 options->output_format |= DIFF_FORMAT_DIRSTAT;
2993 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2995 else if (!strcmp(arg, "--check"))
2996 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2997 else if (!strcmp(arg, "--summary"))
2998 options->output_format |= DIFF_FORMAT_SUMMARY;
2999 else if (!strcmp(arg, "--patch-with-stat"))
3000 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
3001 else if (!strcmp(arg, "--name-only"))
3002 options->output_format |= DIFF_FORMAT_NAME;
3003 else if (!strcmp(arg, "--name-status"))
3004 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3005 else if (!strcmp(arg, "-s"))
3006 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3007 else if (!prefixcmp(arg, "--stat")) {
3009 int width = options->stat_width;
3010 int name_width = options->stat_name_width;
3016 if (!prefixcmp(arg, "-width="))
3017 width = strtoul(arg + 7, &end, 10);
3018 else if (!prefixcmp(arg, "-name-width="))
3019 name_width = strtoul(arg + 12, &end, 10);
3022 width = strtoul(arg+1, &end, 10);
3024 name_width = strtoul(end+1, &end, 10);
3027 /* Important! This checks all the error cases! */
3030 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3031 options->stat_name_width = name_width;
3032 options->stat_width = width;
3035 /* renames options */
3036 else if (!prefixcmp(arg, "-B")) {
3037 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3040 else if (!prefixcmp(arg, "-M")) {
3041 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3043 options->detect_rename = DIFF_DETECT_RENAME;
3045 else if (!prefixcmp(arg, "-C")) {
3046 if (options->detect_rename == DIFF_DETECT_COPY)
3047 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3048 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3050 options->detect_rename = DIFF_DETECT_COPY;
3052 else if (!strcmp(arg, "--no-renames"))
3053 options->detect_rename = 0;
3054 else if (!strcmp(arg, "--relative"))
3055 DIFF_OPT_SET(options, RELATIVE_NAME);
3056 else if (!prefixcmp(arg, "--relative=")) {
3057 DIFF_OPT_SET(options, RELATIVE_NAME);
3058 options->prefix = arg + 11;
3062 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3063 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3064 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3065 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3066 else if (!strcmp(arg, "--ignore-space-at-eol"))
3067 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3068 else if (!strcmp(arg, "--patience"))
3069 DIFF_XDL_SET(options, PATIENCE_DIFF);
3072 else if (!strcmp(arg, "--binary")) {
3073 options->output_format |= DIFF_FORMAT_PATCH;
3074 DIFF_OPT_SET(options, BINARY);
3076 else if (!strcmp(arg, "--full-index"))
3077 DIFF_OPT_SET(options, FULL_INDEX);
3078 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3079 DIFF_OPT_SET(options, TEXT);
3080 else if (!strcmp(arg, "-R"))
3081 DIFF_OPT_SET(options, REVERSE_DIFF);
3082 else if (!strcmp(arg, "--find-copies-harder"))
3083 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3084 else if (!strcmp(arg, "--follow"))
3085 DIFF_OPT_SET(options, FOLLOW_RENAMES);
3086 else if (!strcmp(arg, "--color"))
3087 DIFF_OPT_SET(options, COLOR_DIFF);
3088 else if (!prefixcmp(arg, "--color=")) {
3089 int value = git_config_colorbool(NULL, arg+8, -1);
3091 DIFF_OPT_CLR(options, COLOR_DIFF);
3093 DIFF_OPT_SET(options, COLOR_DIFF);
3095 return error("option `color' expects \"always\", \"auto\", or \"never\"");
3097 else if (!strcmp(arg, "--no-color"))
3098 DIFF_OPT_CLR(options, COLOR_DIFF);
3099 else if (!strcmp(arg, "--color-words")) {
3100 DIFF_OPT_SET(options, COLOR_DIFF);
3101 options->word_diff = DIFF_WORDS_COLOR;
3103 else if (!prefixcmp(arg, "--color-words=")) {
3104 DIFF_OPT_SET(options, COLOR_DIFF);
3105 options->word_diff = DIFF_WORDS_COLOR;
3106 options->word_regex = arg + 14;
3108 else if (!strcmp(arg, "--word-diff")) {
3109 if (options->word_diff == DIFF_WORDS_NONE)
3110 options->word_diff = DIFF_WORDS_PLAIN;
3112 else if (!prefixcmp(arg, "--word-diff=")) {
3113 const char *type = arg + 12;
3114 if (!strcmp(type, "plain"))
3115 options->word_diff = DIFF_WORDS_PLAIN;
3116 else if (!strcmp(type, "color")) {
3117 DIFF_OPT_SET(options, COLOR_DIFF);
3118 options->word_diff = DIFF_WORDS_COLOR;
3120 else if (!strcmp(type, "porcelain"))
3121 options->word_diff = DIFF_WORDS_PORCELAIN;
3122 else if (!strcmp(type, "none"))
3123 options->word_diff = DIFF_WORDS_NONE;
3125 die("bad --word-diff argument: %s", type);
3127 else if (!prefixcmp(arg, "--word-diff-regex=")) {
3128 if (options->word_diff == DIFF_WORDS_NONE)
3129 options->word_diff = DIFF_WORDS_PLAIN;
3130 options->word_regex = arg + 18;
3132 else if (!strcmp(arg, "--exit-code"))
3133 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3134 else if (!strcmp(arg, "--quiet"))
3135 DIFF_OPT_SET(options, QUICK);
3136 else if (!strcmp(arg, "--ext-diff"))
3137 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3138 else if (!strcmp(arg, "--no-ext-diff"))
3139 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3140 else if (!strcmp(arg, "--textconv"))
3141 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3142 else if (!strcmp(arg, "--no-textconv"))
3143 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3144 else if (!strcmp(arg, "--ignore-submodules"))
3145 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
3146 else if (!strcmp(arg, "--submodule"))
3147 DIFF_OPT_SET(options, SUBMODULE_LOG);
3148 else if (!prefixcmp(arg, "--submodule=")) {
3149 if (!strcmp(arg + 12, "log"))
3150 DIFF_OPT_SET(options, SUBMODULE_LOG);
3154 else if (!strcmp(arg, "-z"))
3155 options->line_termination = 0;
3156 else if (!prefixcmp(arg, "-l"))
3157 options->rename_limit = strtoul(arg+2, NULL, 10);
3158 else if (!prefixcmp(arg, "-S"))
3159 options->pickaxe = arg + 2;
3160 else if (!strcmp(arg, "--pickaxe-all"))
3161 options->pickaxe_opts = DIFF_PICKAXE_ALL;
3162 else if (!strcmp(arg, "--pickaxe-regex"))
3163 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
3164 else if (!prefixcmp(arg, "-O"))
3165 options->orderfile = arg + 2;
3166 else if (!prefixcmp(arg, "--diff-filter="))
3167 options->filter = arg + 14;
3168 else if (!strcmp(arg, "--abbrev"))
3169 options->abbrev = DEFAULT_ABBREV;
3170 else if (!prefixcmp(arg, "--abbrev=")) {
3171 options->abbrev = strtoul(arg + 9, NULL, 10);
3172 if (options->abbrev < MINIMUM_ABBREV)
3173 options->abbrev = MINIMUM_ABBREV;
3174 else if (40 < options->abbrev)
3175 options->abbrev = 40;
3177 else if (!prefixcmp(arg, "--src-prefix="))
3178 options->a_prefix = arg + 13;
3179 else if (!prefixcmp(arg, "--dst-prefix="))
3180 options->b_prefix = arg + 13;
3181 else if (!strcmp(arg, "--no-prefix"))
3182 options->a_prefix = options->b_prefix = "";
3183 else if (opt_arg(arg, '\0', "inter-hunk-context",
3184 &options->interhunkcontext))
3186 else if (!prefixcmp(arg, "--output=")) {
3187 options->file = fopen(arg + strlen("--output="), "w");
3189 die_errno("Could not open '%s'", arg + strlen("--output="));
3190 options->close_file = 1;
3196 static int parse_num(const char **cp_p)
3198 unsigned long num, scale;
3200 const char *cp = *cp_p;
3207 if ( !dot && ch == '.' ) {
3210 } else if ( ch == '%' ) {
3211 scale = dot ? scale*100 : 100;
3212 cp++; /* % is always at the end */
3214 } else if ( ch >= '0' && ch <= '9' ) {
3215 if ( scale < 100000 ) {
3217 num = (num*10) + (ch-'0');
3226 /* user says num divided by scale and we say internally that
3227 * is MAX_SCORE * num / scale.
3229 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3232 static int diff_scoreopt_parse(const char *opt)
3234 int opt1, opt2, cmd;
3239 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3240 return -1; /* that is not a -M, -C nor -B option */
3242 opt1 = parse_num(&opt);
3248 else if (*opt != '/')
3249 return -1; /* we expect -B80/99 or -B80 */
3252 opt2 = parse_num(&opt);
3257 return opt1 | (opt2 << 16);
3260 struct diff_queue_struct diff_queued_diff;
3262 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3264 if (queue->alloc <= queue->nr) {
3265 queue->alloc = alloc_nr(queue->alloc);
3266 queue->queue = xrealloc(queue->queue,
3267 sizeof(dp) * queue->alloc);
3269 queue->queue[queue->nr++] = dp;
3272 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3273 struct diff_filespec *one,
3274 struct diff_filespec *two)
3276 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3284 void diff_free_filepair(struct diff_filepair *p)
3286 free_filespec(p->one);
3287 free_filespec(p->two);
3291 /* This is different from find_unique_abbrev() in that
3292 * it stuffs the result with dots for alignment.
3294 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3299 return sha1_to_hex(sha1);
3301 abbrev = find_unique_abbrev(sha1, len);
3302 abblen = strlen(abbrev);
3304 static char hex[41];
3305 if (len < abblen && abblen <= len + 2)
3306 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3308 sprintf(hex, "%s...", abbrev);
3311 return sha1_to_hex(sha1);
3314 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3316 int line_termination = opt->line_termination;
3317 int inter_name_termination = line_termination ? '\t' : '\0';
3318 if (opt->output_prefix) {
3319 struct strbuf *msg = NULL;
3320 msg = opt->output_prefix(opt, opt->output_prefix_data);
3321 fprintf(opt->file, "%s", msg->buf);
3324 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3325 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3326 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3327 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3330 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3331 inter_name_termination);
3333 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3336 if (p->status == DIFF_STATUS_COPIED ||
3337 p->status == DIFF_STATUS_RENAMED) {
3338 const char *name_a, *name_b;
3339 name_a = p->one->path;
3340 name_b = p->two->path;
3341 strip_prefix(opt->prefix_length, &name_a, &name_b);
3342 write_name_quoted(name_a, opt->file, inter_name_termination);
3343 write_name_quoted(name_b, opt->file, line_termination);
3345 const char *name_a, *name_b;
3346 name_a = p->one->mode ? p->one->path : p->two->path;
3348 strip_prefix(opt->prefix_length, &name_a, &name_b);
3349 write_name_quoted(name_a, opt->file, line_termination);
3353 int diff_unmodified_pair(struct diff_filepair *p)
3355 /* This function is written stricter than necessary to support
3356 * the currently implemented transformers, but the idea is to
3357 * let transformers to produce diff_filepairs any way they want,
3358 * and filter and clean them up here before producing the output.
3360 struct diff_filespec *one = p->one, *two = p->two;
3362 if (DIFF_PAIR_UNMERGED(p))
3363 return 0; /* unmerged is interesting */
3365 /* deletion, addition, mode or type change
3366 * and rename are all interesting.
3368 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3369 DIFF_PAIR_MODE_CHANGED(p) ||
3370 strcmp(one->path, two->path))
3373 /* both are valid and point at the same path. that is, we are
3374 * dealing with a change.
3376 if (one->sha1_valid && two->sha1_valid &&
3377 !hashcmp(one->sha1, two->sha1) &&
3378 !one->dirty_submodule && !two->dirty_submodule)
3379 return 1; /* no change */
3380 if (!one->sha1_valid && !two->sha1_valid)
3381 return 1; /* both look at the same file on the filesystem. */
3385 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3387 if (diff_unmodified_pair(p))
3390 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3391 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3392 return; /* no tree diffs in patch format */
3397 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3398 struct diffstat_t *diffstat)
3400 if (diff_unmodified_pair(p))
3403 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3404 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3405 return; /* no tree diffs in patch format */
3407 run_diffstat(p, o, diffstat);
3410 static void diff_flush_checkdiff(struct diff_filepair *p,
3411 struct diff_options *o)
3413 if (diff_unmodified_pair(p))
3416 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3417 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3418 return; /* no tree diffs in patch format */
3420 run_checkdiff(p, o);
3423 int diff_queue_is_empty(void)
3425 struct diff_queue_struct *q = &diff_queued_diff;
3427 for (i = 0; i < q->nr; i++)
3428 if (!diff_unmodified_pair(q->queue[i]))
3434 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3436 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3439 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3441 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3442 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3444 s->size, s->xfrm_flags);
3447 void diff_debug_filepair(const struct diff_filepair *p, int i)
3449 diff_debug_filespec(p->one, i, "one");
3450 diff_debug_filespec(p->two, i, "two");
3451 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3452 p->score, p->status ? p->status : '?',
3453 p->one->rename_used, p->broken_pair);
3456 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3460 fprintf(stderr, "%s\n", msg);
3461 fprintf(stderr, "q->nr = %d\n", q->nr);
3462 for (i = 0; i < q->nr; i++) {
3463 struct diff_filepair *p = q->queue[i];
3464 diff_debug_filepair(p, i);
3469 static void diff_resolve_rename_copy(void)
3472 struct diff_filepair *p;
3473 struct diff_queue_struct *q = &diff_queued_diff;
3475 diff_debug_queue("resolve-rename-copy", q);
3477 for (i = 0; i < q->nr; i++) {
3479 p->status = 0; /* undecided */
3480 if (DIFF_PAIR_UNMERGED(p))
3481 p->status = DIFF_STATUS_UNMERGED;
3482 else if (!DIFF_FILE_VALID(p->one))
3483 p->status = DIFF_STATUS_ADDED;
3484 else if (!DIFF_FILE_VALID(p->two))
3485 p->status = DIFF_STATUS_DELETED;
3486 else if (DIFF_PAIR_TYPE_CHANGED(p))
3487 p->status = DIFF_STATUS_TYPE_CHANGED;
3489 /* from this point on, we are dealing with a pair
3490 * whose both sides are valid and of the same type, i.e.
3491 * either in-place edit or rename/copy edit.
3493 else if (DIFF_PAIR_RENAME(p)) {
3495 * A rename might have re-connected a broken
3496 * pair up, causing the pathnames to be the
3497 * same again. If so, that's not a rename at
3498 * all, just a modification..
3500 * Otherwise, see if this source was used for
3501 * multiple renames, in which case we decrement
3502 * the count, and call it a copy.
3504 if (!strcmp(p->one->path, p->two->path))
3505 p->status = DIFF_STATUS_MODIFIED;
3506 else if (--p->one->rename_used > 0)
3507 p->status = DIFF_STATUS_COPIED;
3509 p->status = DIFF_STATUS_RENAMED;
3511 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3512 p->one->mode != p->two->mode ||
3513 p->one->dirty_submodule ||
3514 p->two->dirty_submodule ||
3515 is_null_sha1(p->one->sha1))
3516 p->status = DIFF_STATUS_MODIFIED;
3518 /* This is a "no-change" entry and should not
3519 * happen anymore, but prepare for broken callers.
3521 error("feeding unmodified %s to diffcore",
3523 p->status = DIFF_STATUS_UNKNOWN;
3526 diff_debug_queue("resolve-rename-copy done", q);
3529 static int check_pair_status(struct diff_filepair *p)
3531 switch (p->status) {
3532 case DIFF_STATUS_UNKNOWN:
3535 die("internal error in diff-resolve-rename-copy");
3541 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3543 int fmt = opt->output_format;
3545 if (fmt & DIFF_FORMAT_CHECKDIFF)
3546 diff_flush_checkdiff(p, opt);
3547 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3548 diff_flush_raw(p, opt);
3549 else if (fmt & DIFF_FORMAT_NAME) {
3550 const char *name_a, *name_b;
3551 name_a = p->two->path;
3553 strip_prefix(opt->prefix_length, &name_a, &name_b);
3554 write_name_quoted(name_a, opt->file, opt->line_termination);
3558 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3561 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3563 fprintf(file, " %s ", newdelete);
3564 write_name_quoted(fs->path, file, '\n');
3568 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
3569 const char *line_prefix)
3571 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3572 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
3573 p->two->mode, show_name ? ' ' : '\n');
3575 write_name_quoted(p->two->path, file, '\n');
3580 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
3581 const char *line_prefix)
3583 char *names = pprint_rename(p->one->path, p->two->path);
3585 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3587 show_mode_change(file, p, 0, line_prefix);
3590 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
3592 FILE *file = opt->file;
3593 char *line_prefix = "";
3595 if (opt->output_prefix) {
3596 struct strbuf *buf = opt->output_prefix(opt, opt->output_prefix_data);
3597 line_prefix = buf->buf;
3601 case DIFF_STATUS_DELETED:
3602 fputs(line_prefix, file);
3603 show_file_mode_name(file, "delete", p->one);
3605 case DIFF_STATUS_ADDED:
3606 fputs(line_prefix, file);
3607 show_file_mode_name(file, "create", p->two);
3609 case DIFF_STATUS_COPIED:
3610 fputs(line_prefix, file);
3611 show_rename_copy(file, "copy", p, line_prefix);
3613 case DIFF_STATUS_RENAMED:
3614 fputs(line_prefix, file);
3615 show_rename_copy(file, "rename", p, line_prefix);
3619 fprintf(file, "%s rewrite ", line_prefix);
3620 write_name_quoted(p->two->path, file, ' ');
3621 fprintf(file, "(%d%%)\n", similarity_index(p));
3623 show_mode_change(file, p, !p->score, line_prefix);
3633 static int remove_space(char *line, int len)
3639 for (i = 0; i < len; i++)
3640 if (!isspace((c = line[i])))
3646 static void patch_id_consume(void *priv, char *line, unsigned long len)
3648 struct patch_id_t *data = priv;
3651 /* Ignore line numbers when computing the SHA1 of the patch */
3652 if (!prefixcmp(line, "@@ -"))
3655 new_len = remove_space(line, len);
3657 git_SHA1_Update(data->ctx, line, new_len);
3658 data->patchlen += new_len;
3661 /* returns 0 upon success, and writes result into sha1 */
3662 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3664 struct diff_queue_struct *q = &diff_queued_diff;
3667 struct patch_id_t data;
3668 char buffer[PATH_MAX * 4 + 20];
3670 git_SHA1_Init(&ctx);
3671 memset(&data, 0, sizeof(struct patch_id_t));
3674 for (i = 0; i < q->nr; i++) {
3678 struct diff_filepair *p = q->queue[i];
3681 memset(&xpp, 0, sizeof(xpp));
3682 memset(&xecfg, 0, sizeof(xecfg));
3684 return error("internal diff status error");
3685 if (p->status == DIFF_STATUS_UNKNOWN)
3687 if (diff_unmodified_pair(p))
3689 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3690 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3692 if (DIFF_PAIR_UNMERGED(p))
3695 diff_fill_sha1_info(p->one);
3696 diff_fill_sha1_info(p->two);
3697 if (fill_mmfile(&mf1, p->one) < 0 ||
3698 fill_mmfile(&mf2, p->two) < 0)
3699 return error("unable to read files to diff");
3701 len1 = remove_space(p->one->path, strlen(p->one->path));
3702 len2 = remove_space(p->two->path, strlen(p->two->path));
3703 if (p->one->mode == 0)
3704 len1 = snprintf(buffer, sizeof(buffer),
3705 "diff--gita/%.*sb/%.*s"
3712 len2, p->two->path);
3713 else if (p->two->mode == 0)
3714 len1 = snprintf(buffer, sizeof(buffer),
3715 "diff--gita/%.*sb/%.*s"
3716 "deletedfilemode%06o"
3722 len1, p->one->path);
3724 len1 = snprintf(buffer, sizeof(buffer),
3725 "diff--gita/%.*sb/%.*s"
3731 len2, p->two->path);
3732 git_SHA1_Update(&ctx, buffer, len1);
3734 xpp.flags = XDF_NEED_MINIMAL;
3736 xecfg.flags = XDL_EMIT_FUNCNAMES;
3737 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3741 git_SHA1_Final(sha1, &ctx);
3745 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3747 struct diff_queue_struct *q = &diff_queued_diff;
3749 int result = diff_get_patch_id(options, sha1);
3751 for (i = 0; i < q->nr; i++)
3752 diff_free_filepair(q->queue[i]);
3755 DIFF_QUEUE_CLEAR(q);
3760 static int is_summary_empty(const struct diff_queue_struct *q)
3764 for (i = 0; i < q->nr; i++) {
3765 const struct diff_filepair *p = q->queue[i];
3767 switch (p->status) {
3768 case DIFF_STATUS_DELETED:
3769 case DIFF_STATUS_ADDED:
3770 case DIFF_STATUS_COPIED:
3771 case DIFF_STATUS_RENAMED:
3776 if (p->one->mode && p->two->mode &&
3777 p->one->mode != p->two->mode)
3785 void diff_flush(struct diff_options *options)
3787 struct diff_queue_struct *q = &diff_queued_diff;
3788 int i, output_format = options->output_format;
3792 * Order: raw, stat, summary, patch
3793 * or: name/name-status/checkdiff (other bits clear)
3798 if (output_format & (DIFF_FORMAT_RAW |
3800 DIFF_FORMAT_NAME_STATUS |
3801 DIFF_FORMAT_CHECKDIFF)) {
3802 for (i = 0; i < q->nr; i++) {
3803 struct diff_filepair *p = q->queue[i];
3804 if (check_pair_status(p))
3805 flush_one_pair(p, options);
3810 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3811 struct diffstat_t diffstat;
3813 memset(&diffstat, 0, sizeof(struct diffstat_t));
3814 for (i = 0; i < q->nr; i++) {
3815 struct diff_filepair *p = q->queue[i];
3816 if (check_pair_status(p))
3817 diff_flush_stat(p, options, &diffstat);
3819 if (output_format & DIFF_FORMAT_NUMSTAT)
3820 show_numstat(&diffstat, options);
3821 if (output_format & DIFF_FORMAT_DIFFSTAT)
3822 show_stats(&diffstat, options);
3823 if (output_format & DIFF_FORMAT_SHORTSTAT)
3824 show_shortstats(&diffstat, options);
3825 free_diffstat_info(&diffstat);
3828 if (output_format & DIFF_FORMAT_DIRSTAT)
3829 show_dirstat(options);
3831 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3832 for (i = 0; i < q->nr; i++) {
3833 diff_summary(options, q->queue[i]);
3838 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3839 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3840 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3842 * run diff_flush_patch for the exit status. setting
3843 * options->file to /dev/null should be safe, becaue we
3844 * aren't supposed to produce any output anyway.
3846 if (options->close_file)
3847 fclose(options->file);
3848 options->file = fopen("/dev/null", "w");
3850 die_errno("Could not open /dev/null");
3851 options->close_file = 1;
3852 for (i = 0; i < q->nr; i++) {
3853 struct diff_filepair *p = q->queue[i];
3854 if (check_pair_status(p))
3855 diff_flush_patch(p, options);
3856 if (options->found_changes)
3861 if (output_format & DIFF_FORMAT_PATCH) {
3863 putc(options->line_termination, options->file);
3864 if (options->stat_sep) {
3865 /* attach patch instead of inline */
3866 fputs(options->stat_sep, options->file);
3870 for (i = 0; i < q->nr; i++) {
3871 struct diff_filepair *p = q->queue[i];
3872 if (check_pair_status(p))
3873 diff_flush_patch(p, options);
3877 if (output_format & DIFF_FORMAT_CALLBACK)
3878 options->format_callback(q, options, options->format_callback_data);
3880 for (i = 0; i < q->nr; i++)
3881 diff_free_filepair(q->queue[i]);
3884 DIFF_QUEUE_CLEAR(q);
3885 if (options->close_file)
3886 fclose(options->file);
3889 * Report the content-level differences with HAS_CHANGES;
3890 * diff_addremove/diff_change does not set the bit when
3891 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3893 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3894 if (options->found_changes)
3895 DIFF_OPT_SET(options, HAS_CHANGES);
3897 DIFF_OPT_CLR(options, HAS_CHANGES);
3901 static void diffcore_apply_filter(const char *filter)
3904 struct diff_queue_struct *q = &diff_queued_diff;
3905 struct diff_queue_struct outq;
3906 DIFF_QUEUE_CLEAR(&outq);
3911 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3913 for (i = found = 0; !found && i < q->nr; i++) {
3914 struct diff_filepair *p = q->queue[i];
3915 if (((p->status == DIFF_STATUS_MODIFIED) &&
3917 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3919 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3920 ((p->status != DIFF_STATUS_MODIFIED) &&
3921 strchr(filter, p->status)))
3927 /* otherwise we will clear the whole queue
3928 * by copying the empty outq at the end of this
3929 * function, but first clear the current entries
3932 for (i = 0; i < q->nr; i++)
3933 diff_free_filepair(q->queue[i]);
3936 /* Only the matching ones */
3937 for (i = 0; i < q->nr; i++) {
3938 struct diff_filepair *p = q->queue[i];
3940 if (((p->status == DIFF_STATUS_MODIFIED) &&
3942 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3944 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3945 ((p->status != DIFF_STATUS_MODIFIED) &&
3946 strchr(filter, p->status)))
3949 diff_free_filepair(p);
3956 /* Check whether two filespecs with the same mode and size are identical */
3957 static int diff_filespec_is_identical(struct diff_filespec *one,
3958 struct diff_filespec *two)
3960 if (S_ISGITLINK(one->mode))
3962 if (diff_populate_filespec(one, 0))
3964 if (diff_populate_filespec(two, 0))
3966 return !memcmp(one->data, two->data, one->size);
3969 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3972 struct diff_queue_struct *q = &diff_queued_diff;
3973 struct diff_queue_struct outq;
3974 DIFF_QUEUE_CLEAR(&outq);
3976 for (i = 0; i < q->nr; i++) {
3977 struct diff_filepair *p = q->queue[i];
3980 * 1. Entries that come from stat info dirtiness
3981 * always have both sides (iow, not create/delete),
3982 * one side of the object name is unknown, with
3983 * the same mode and size. Keep the ones that
3984 * do not match these criteria. They have real
3987 * 2. At this point, the file is known to be modified,
3988 * with the same mode and size, and the object
3989 * name of one side is unknown. Need to inspect
3990 * the identical contents.
3992 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3993 !DIFF_FILE_VALID(p->two) ||
3994 (p->one->sha1_valid && p->two->sha1_valid) ||
3995 (p->one->mode != p->two->mode) ||
3996 diff_populate_filespec(p->one, 1) ||
3997 diff_populate_filespec(p->two, 1) ||
3998 (p->one->size != p->two->size) ||
3999 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4003 * The caller can subtract 1 from skip_stat_unmatch
4004 * to determine how many paths were dirty only
4005 * due to stat info mismatch.
4007 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4008 diffopt->skip_stat_unmatch++;
4009 diff_free_filepair(p);
4016 static int diffnamecmp(const void *a_, const void *b_)
4018 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4019 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4020 const char *name_a, *name_b;
4022 name_a = a->one ? a->one->path : a->two->path;
4023 name_b = b->one ? b->one->path : b->two->path;
4024 return strcmp(name_a, name_b);
4027 void diffcore_fix_diff_index(struct diff_options *options)
4029 struct diff_queue_struct *q = &diff_queued_diff;
4030 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4033 void diffcore_std(struct diff_options *options)
4035 /* We never run this function more than one time, because the
4036 * rename/copy detection logic can only run once.
4038 if (diff_queued_diff.run)
4041 if (options->skip_stat_unmatch)
4042 diffcore_skip_stat_unmatch(options);
4043 if (options->break_opt != -1)
4044 diffcore_break(options->break_opt);
4045 if (options->detect_rename)
4046 diffcore_rename(options);
4047 if (options->break_opt != -1)
4048 diffcore_merge_broken();
4049 if (options->pickaxe)
4050 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
4051 if (options->orderfile)
4052 diffcore_order(options->orderfile);
4053 diff_resolve_rename_copy();
4054 diffcore_apply_filter(options->filter);
4056 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4057 DIFF_OPT_SET(options, HAS_CHANGES);
4059 DIFF_OPT_CLR(options, HAS_CHANGES);
4061 diff_queued_diff.run = 1;
4064 int diff_result_code(struct diff_options *opt, int status)
4067 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4068 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4070 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4071 DIFF_OPT_TST(opt, HAS_CHANGES))
4073 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4074 DIFF_OPT_TST(opt, CHECK_FAILED))
4079 void diff_addremove(struct diff_options *options,
4080 int addremove, unsigned mode,
4081 const unsigned char *sha1,
4082 const char *concatpath, unsigned dirty_submodule)
4084 struct diff_filespec *one, *two;
4086 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
4089 /* This may look odd, but it is a preparation for
4090 * feeding "there are unchanged files which should
4091 * not produce diffs, but when you are doing copy
4092 * detection you would need them, so here they are"
4093 * entries to the diff-core. They will be prefixed
4094 * with something like '=' or '*' (I haven't decided
4095 * which but should not make any difference).
4096 * Feeding the same new and old to diff_change()
4097 * also has the same effect.
4098 * Before the final output happens, they are pruned after
4099 * merged into rename/copy pairs as appropriate.
4101 if (DIFF_OPT_TST(options, REVERSE_DIFF))
4102 addremove = (addremove == '+' ? '-' :
4103 addremove == '-' ? '+' : addremove);
4105 if (options->prefix &&
4106 strncmp(concatpath, options->prefix, options->prefix_length))
4109 one = alloc_filespec(concatpath);
4110 two = alloc_filespec(concatpath);
4112 if (addremove != '+')
4113 fill_filespec(one, sha1, mode);
4114 if (addremove != '-') {
4115 fill_filespec(two, sha1, mode);
4116 two->dirty_submodule = dirty_submodule;
4119 diff_queue(&diff_queued_diff, one, two);
4120 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4121 DIFF_OPT_SET(options, HAS_CHANGES);
4124 void diff_change(struct diff_options *options,
4125 unsigned old_mode, unsigned new_mode,
4126 const unsigned char *old_sha1,
4127 const unsigned char *new_sha1,
4128 const char *concatpath,
4129 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4131 struct diff_filespec *one, *two;
4133 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
4134 && S_ISGITLINK(new_mode))
4137 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4139 const unsigned char *tmp_c;
4140 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4141 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4142 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4143 new_dirty_submodule = tmp;
4146 if (options->prefix &&
4147 strncmp(concatpath, options->prefix, options->prefix_length))
4150 one = alloc_filespec(concatpath);
4151 two = alloc_filespec(concatpath);
4152 fill_filespec(one, old_sha1, old_mode);
4153 fill_filespec(two, new_sha1, new_mode);
4154 one->dirty_submodule = old_dirty_submodule;
4155 two->dirty_submodule = new_dirty_submodule;
4157 diff_queue(&diff_queued_diff, one, two);
4158 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4159 DIFF_OPT_SET(options, HAS_CHANGES);
4162 void diff_unmerge(struct diff_options *options,
4164 unsigned mode, const unsigned char *sha1)
4166 struct diff_filespec *one, *two;
4168 if (options->prefix &&
4169 strncmp(path, options->prefix, options->prefix_length))
4172 one = alloc_filespec(path);
4173 two = alloc_filespec(path);
4174 fill_filespec(one, sha1, mode);
4175 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
4178 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4181 struct diff_tempfile *temp;
4182 const char *argv[3];
4183 const char **arg = argv;
4184 struct child_process child;
4185 struct strbuf buf = STRBUF_INIT;
4188 temp = prepare_temp_file(spec->path, spec);
4190 *arg++ = temp->name;
4193 memset(&child, 0, sizeof(child));
4194 child.use_shell = 1;
4197 if (start_command(&child)) {
4202 if (strbuf_read(&buf, child.out, 0) < 0)
4203 err = error("error reading from textconv command '%s'", pgm);
4206 if (finish_command(&child) || err) {
4207 strbuf_release(&buf);
4213 return strbuf_detach(&buf, outsize);
4216 static size_t fill_textconv(struct userdiff_driver *driver,
4217 struct diff_filespec *df,
4222 if (!driver || !driver->textconv) {
4223 if (!DIFF_FILE_VALID(df)) {
4227 if (diff_populate_filespec(df, 0))
4228 die("unable to read files to diff");
4233 if (driver->textconv_cache) {
4234 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4240 *outbuf = run_textconv(driver->textconv, df, &size);
4242 die("unable to read files to diff");
4244 if (driver->textconv_cache) {
4245 /* ignore errors, as we might be in a readonly repository */
4246 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4249 * we could save up changes and flush them all at the end,
4250 * but we would need an extra call after all diffing is done.
4251 * Since generating a cache entry is the slow path anyway,
4252 * this extra overhead probably isn't a big deal.
4254 notes_cache_write(driver->textconv_cache);