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;
33 static int diff_no_prefix;
35 static char diff_colors[][COLOR_MAXLEN] = {
37 GIT_COLOR_NORMAL, /* PLAIN */
38 GIT_COLOR_BOLD, /* METAINFO */
39 GIT_COLOR_CYAN, /* FRAGINFO */
40 GIT_COLOR_RED, /* OLD */
41 GIT_COLOR_GREEN, /* NEW */
42 GIT_COLOR_YELLOW, /* COMMIT */
43 GIT_COLOR_BG_RED, /* WHITESPACE */
44 GIT_COLOR_NORMAL, /* FUNCINFO */
47 static void diff_filespec_load_driver(struct diff_filespec *one);
48 static size_t fill_textconv(struct userdiff_driver *driver,
49 struct diff_filespec *df, char **outbuf);
51 static int parse_diff_color_slot(const char *var, int ofs)
53 if (!strcasecmp(var+ofs, "plain"))
55 if (!strcasecmp(var+ofs, "meta"))
57 if (!strcasecmp(var+ofs, "frag"))
59 if (!strcasecmp(var+ofs, "old"))
61 if (!strcasecmp(var+ofs, "new"))
63 if (!strcasecmp(var+ofs, "commit"))
65 if (!strcasecmp(var+ofs, "whitespace"))
66 return DIFF_WHITESPACE;
67 if (!strcasecmp(var+ofs, "func"))
72 static int git_config_rename(const char *var, const char *value)
75 return DIFF_DETECT_RENAME;
76 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
77 return DIFF_DETECT_COPY;
78 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
82 * These are to give UI layer defaults.
83 * The core-level commands such as git-diff-files should
84 * never be affected by the setting of diff.renames
85 * the user happens to have in the configuration file.
87 int git_diff_ui_config(const char *var, const char *value, void *cb)
89 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
90 diff_use_color_default = git_config_colorbool(var, value, -1);
93 if (!strcmp(var, "diff.renames")) {
94 diff_detect_rename_default = git_config_rename(var, value);
97 if (!strcmp(var, "diff.autorefreshindex")) {
98 diff_auto_refresh_index = git_config_bool(var, value);
101 if (!strcmp(var, "diff.mnemonicprefix")) {
102 diff_mnemonic_prefix = git_config_bool(var, value);
105 if (!strcmp(var, "diff.noprefix")) {
106 diff_no_prefix = git_config_bool(var, value);
109 if (!strcmp(var, "diff.external"))
110 return git_config_string(&external_diff_cmd_cfg, var, value);
111 if (!strcmp(var, "diff.wordregex"))
112 return git_config_string(&diff_word_regex_cfg, var, value);
114 return git_diff_basic_config(var, value, cb);
117 int git_diff_basic_config(const char *var, const char *value, void *cb)
119 if (!strcmp(var, "diff.renamelimit")) {
120 diff_rename_limit_default = git_config_int(var, value);
124 switch (userdiff_config(var, value)) {
130 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
131 int slot = parse_diff_color_slot(var, 11);
135 return config_error_nonbool(var);
136 color_parse(value, var, diff_colors[slot]);
140 /* like GNU diff's --suppress-blank-empty option */
141 if (!strcmp(var, "diff.suppressblankempty") ||
142 /* for backwards compatibility */
143 !strcmp(var, "diff.suppress-blank-empty")) {
144 diff_suppress_blank_empty = git_config_bool(var, value);
148 return git_color_default_config(var, value, cb);
151 static char *quote_two(const char *one, const char *two)
153 int need_one = quote_c_style(one, NULL, NULL, 1);
154 int need_two = quote_c_style(two, NULL, NULL, 1);
155 struct strbuf res = STRBUF_INIT;
157 if (need_one + need_two) {
158 strbuf_addch(&res, '"');
159 quote_c_style(one, &res, NULL, 1);
160 quote_c_style(two, &res, NULL, 1);
161 strbuf_addch(&res, '"');
163 strbuf_addstr(&res, one);
164 strbuf_addstr(&res, two);
166 return strbuf_detach(&res, NULL);
169 static const char *external_diff(void)
171 static const char *external_diff_cmd = NULL;
172 static int done_preparing = 0;
175 return external_diff_cmd;
176 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
177 if (!external_diff_cmd)
178 external_diff_cmd = external_diff_cmd_cfg;
180 return external_diff_cmd;
183 static struct diff_tempfile {
184 const char *name; /* filename external diff should read from */
187 char tmp_path[PATH_MAX];
190 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
192 struct emit_callback {
195 int blank_at_eof_in_preimage;
196 int blank_at_eof_in_postimage;
198 int lno_in_postimage;
199 sane_truncate_fn truncate;
200 const char **label_path;
201 struct diff_words_data *diff_words;
204 struct strbuf *header;
207 static int count_lines(const char *data, int size)
209 int count, ch, completely_empty = 1, nl_just_seen = 0;
216 completely_empty = 0;
220 completely_empty = 0;
223 if (completely_empty)
226 count++; /* no trailing newline */
230 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
232 if (!DIFF_FILE_VALID(one)) {
233 mf->ptr = (char *)""; /* does not matter */
237 else if (diff_populate_filespec(one, 0))
241 mf->size = one->size;
245 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
248 long size = mf->size;
253 ptr += size - 1; /* pointing at the very end */
255 ; /* incomplete line */
257 ptr--; /* skip the last LF */
258 while (mf->ptr < ptr) {
260 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
261 if (*prev_eol == '\n')
263 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
271 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
272 struct emit_callback *ecbdata)
275 unsigned ws_rule = ecbdata->ws_rule;
276 l1 = count_trailing_blank(mf1, ws_rule);
277 l2 = count_trailing_blank(mf2, ws_rule);
279 ecbdata->blank_at_eof_in_preimage = 0;
280 ecbdata->blank_at_eof_in_postimage = 0;
283 at = count_lines(mf1->ptr, mf1->size);
284 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
286 at = count_lines(mf2->ptr, mf2->size);
287 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
290 static void emit_line_0(FILE *file, const char *set, const char *reset,
291 int first, const char *line, int len)
293 int has_trailing_newline, has_trailing_carriage_return;
297 has_trailing_newline = (first == '\n');
298 has_trailing_carriage_return = (!has_trailing_newline &&
300 nofirst = has_trailing_newline || has_trailing_carriage_return;
302 has_trailing_newline = (len > 0 && line[len-1] == '\n');
303 if (has_trailing_newline)
305 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
306 if (has_trailing_carriage_return)
311 if (len || !nofirst) {
315 fwrite(line, len, 1, file);
318 if (has_trailing_carriage_return)
320 if (has_trailing_newline)
324 static void emit_line(FILE *file, const char *set, const char *reset,
325 const char *line, int len)
327 emit_line_0(file, set, reset, line[0], line+1, len-1);
330 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
332 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
333 ecbdata->blank_at_eof_in_preimage &&
334 ecbdata->blank_at_eof_in_postimage &&
335 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
336 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
338 return ws_blank_line(line, len, ecbdata->ws_rule);
341 static void emit_add_line(const char *reset,
342 struct emit_callback *ecbdata,
343 const char *line, int len)
345 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
346 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
349 emit_line_0(ecbdata->file, set, reset, '+', line, len);
350 else if (new_blank_line_at_eof(ecbdata, line, len))
351 /* Blank line at EOF - paint '+' as well */
352 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
354 /* Emit just the prefix, then the rest. */
355 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
356 ws_check_emit(line, len, ecbdata->ws_rule,
357 ecbdata->file, set, reset, ws);
361 static void emit_hunk_header(struct emit_callback *ecbdata,
362 const char *line, int len)
364 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
365 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
366 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
367 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
368 static const char atat[2] = { '@', '@' };
372 * As a hunk header must begin with "@@ -<old>, +<new> @@",
373 * it always is at least 10 bytes long.
376 memcmp(line, atat, 2) ||
377 !(ep = memmem(line + 2, len - 2, atat, 2))) {
378 emit_line(ecbdata->file, plain, reset, line, len);
381 ep += 2; /* skip over @@ */
383 /* The hunk header in fraginfo color */
384 emit_line(ecbdata->file, frag, reset, line, ep - line);
386 /* blank before the func header */
387 for (cp = ep; ep - line < len; ep++)
388 if (*ep != ' ' && *ep != '\t')
391 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
394 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
397 static struct diff_tempfile *claim_diff_tempfile(void) {
399 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
400 if (!diff_temp[i].name)
401 return diff_temp + i;
402 die("BUG: diff is failing to clean up its tempfiles");
405 static int remove_tempfile_installed;
407 static void remove_tempfile(void)
410 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
411 if (diff_temp[i].name == diff_temp[i].tmp_path)
412 unlink_or_warn(diff_temp[i].name);
413 diff_temp[i].name = NULL;
417 static void remove_tempfile_on_signal(int signo)
424 static void print_line_count(FILE *file, int count)
428 fprintf(file, "0,0");
434 fprintf(file, "1,%d", count);
439 static void emit_rewrite_lines(struct emit_callback *ecb,
440 int prefix, const char *data, int size)
442 const char *endp = NULL;
443 static const char *nneof = " No newline at end of file\n";
444 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
445 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
450 endp = memchr(data, '\n', size);
451 len = endp ? (endp - data + 1) : size;
453 ecb->lno_in_preimage++;
454 emit_line_0(ecb->file, old, reset, '-',
457 ecb->lno_in_postimage++;
458 emit_add_line(reset, ecb, data, len);
464 const char *plain = diff_get_color(ecb->color_diff,
466 emit_line_0(ecb->file, plain, reset, '\\',
467 nneof, strlen(nneof));
471 static void emit_rewrite_diff(const char *name_a,
473 struct diff_filespec *one,
474 struct diff_filespec *two,
475 struct userdiff_driver *textconv_one,
476 struct userdiff_driver *textconv_two,
477 struct diff_options *o)
480 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
481 const char *name_a_tab, *name_b_tab;
482 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
483 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
484 const char *reset = diff_get_color(color_diff, DIFF_RESET);
485 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
486 const char *a_prefix, *b_prefix;
487 char *data_one, *data_two;
488 size_t size_one, size_two;
489 struct emit_callback ecbdata;
491 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
492 a_prefix = o->b_prefix;
493 b_prefix = o->a_prefix;
495 a_prefix = o->a_prefix;
496 b_prefix = o->b_prefix;
499 name_a += (*name_a == '/');
500 name_b += (*name_b == '/');
501 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
502 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
504 strbuf_reset(&a_name);
505 strbuf_reset(&b_name);
506 quote_two_c_style(&a_name, a_prefix, name_a, 0);
507 quote_two_c_style(&b_name, b_prefix, name_b, 0);
509 size_one = fill_textconv(textconv_one, one, &data_one);
510 size_two = fill_textconv(textconv_two, two, &data_two);
512 memset(&ecbdata, 0, sizeof(ecbdata));
513 ecbdata.color_diff = color_diff;
514 ecbdata.found_changesp = &o->found_changes;
515 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
516 ecbdata.file = o->file;
517 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
519 mf1.ptr = (char *)data_one;
520 mf2.ptr = (char *)data_two;
523 check_blank_at_eof(&mf1, &mf2, &ecbdata);
525 ecbdata.lno_in_preimage = 1;
526 ecbdata.lno_in_postimage = 1;
528 lc_a = count_lines(data_one, size_one);
529 lc_b = count_lines(data_two, size_two);
531 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
532 metainfo, a_name.buf, name_a_tab, reset,
533 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
534 print_line_count(o->file, lc_a);
535 fprintf(o->file, " +");
536 print_line_count(o->file, lc_b);
537 fprintf(o->file, " @@%s\n", reset);
539 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
541 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
543 free((char *)data_one);
545 free((char *)data_two);
548 struct diff_words_buffer {
551 struct diff_words_orig {
552 const char *begin, *end;
554 int orig_nr, orig_alloc;
557 static void diff_words_append(char *line, unsigned long len,
558 struct diff_words_buffer *buffer)
560 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
563 memcpy(buffer->text.ptr + buffer->text.size, line, len);
564 buffer->text.size += len;
565 buffer->text.ptr[buffer->text.size] = '\0';
568 struct diff_words_data {
569 struct diff_words_buffer minus, plus;
570 const char *current_plus;
575 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
577 struct diff_words_data *diff_words = priv;
578 int minus_first, minus_len, plus_first, plus_len;
579 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
581 if (line[0] != '@' || parse_hunk_header(line, len,
582 &minus_first, &minus_len, &plus_first, &plus_len))
585 /* POSIX requires that first be decremented by one if len == 0... */
587 minus_begin = diff_words->minus.orig[minus_first].begin;
589 diff_words->minus.orig[minus_first + minus_len - 1].end;
591 minus_begin = minus_end =
592 diff_words->minus.orig[minus_first].end;
595 plus_begin = diff_words->plus.orig[plus_first].begin;
596 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
598 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
600 if (diff_words->current_plus != plus_begin)
601 fwrite(diff_words->current_plus,
602 plus_begin - diff_words->current_plus, 1,
604 if (minus_begin != minus_end)
605 color_fwrite_lines(diff_words->file,
606 diff_get_color(1, DIFF_FILE_OLD),
607 minus_end - minus_begin, minus_begin);
608 if (plus_begin != plus_end)
609 color_fwrite_lines(diff_words->file,
610 diff_get_color(1, DIFF_FILE_NEW),
611 plus_end - plus_begin, plus_begin);
613 diff_words->current_plus = plus_end;
616 /* This function starts looking at *begin, and returns 0 iff a word was found. */
617 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
618 int *begin, int *end)
620 if (word_regex && *begin < buffer->size) {
622 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
623 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
624 '\n', match[0].rm_eo - match[0].rm_so);
625 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
626 *begin += match[0].rm_so;
627 return *begin >= *end;
632 /* find the next word */
633 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
635 if (*begin >= buffer->size)
638 /* find the end of the word */
640 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
647 * This function splits the words in buffer->text, stores the list with
648 * newline separator into out, and saves the offsets of the original words
651 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
660 /* fake an empty "0th" word */
661 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
662 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
665 for (i = 0; i < buffer->text.size; i++) {
666 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
669 /* store original boundaries */
670 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
672 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
673 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
677 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
678 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
679 out->ptr[out->size + j - i] = '\n';
680 out->size += j - i + 1;
686 /* this executes the word diff on the accumulated buffers */
687 static void diff_words_show(struct diff_words_data *diff_words)
691 mmfile_t minus, plus;
693 /* special case: only removal */
694 if (!diff_words->plus.text.size) {
695 color_fwrite_lines(diff_words->file,
696 diff_get_color(1, DIFF_FILE_OLD),
697 diff_words->minus.text.size, diff_words->minus.text.ptr);
698 diff_words->minus.text.size = 0;
702 diff_words->current_plus = diff_words->plus.text.ptr;
704 memset(&xpp, 0, sizeof(xpp));
705 memset(&xecfg, 0, sizeof(xecfg));
706 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
707 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
708 xpp.flags = XDF_NEED_MINIMAL;
709 /* as only the hunk header will be parsed, we need a 0-context */
711 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
715 if (diff_words->current_plus != diff_words->plus.text.ptr +
716 diff_words->plus.text.size)
717 fwrite(diff_words->current_plus,
718 diff_words->plus.text.ptr + diff_words->plus.text.size
719 - diff_words->current_plus, 1,
721 diff_words->minus.text.size = diff_words->plus.text.size = 0;
724 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
725 static void diff_words_flush(struct emit_callback *ecbdata)
727 if (ecbdata->diff_words->minus.text.size ||
728 ecbdata->diff_words->plus.text.size)
729 diff_words_show(ecbdata->diff_words);
732 static void free_diff_words_data(struct emit_callback *ecbdata)
734 if (ecbdata->diff_words) {
735 diff_words_flush(ecbdata);
736 free (ecbdata->diff_words->minus.text.ptr);
737 free (ecbdata->diff_words->minus.orig);
738 free (ecbdata->diff_words->plus.text.ptr);
739 free (ecbdata->diff_words->plus.orig);
740 free(ecbdata->diff_words->word_regex);
741 free(ecbdata->diff_words);
742 ecbdata->diff_words = NULL;
746 const char *diff_get_color(int diff_use_color, enum color_diff ix)
749 return diff_colors[ix];
753 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
760 return ecb->truncate(line, len);
764 (void) utf8_width(&cp, &l);
766 break; /* truncated in the middle? */
771 static void find_lno(const char *line, struct emit_callback *ecbdata)
774 ecbdata->lno_in_preimage = 0;
775 ecbdata->lno_in_postimage = 0;
776 p = strchr(line, '-');
778 return; /* cannot happen */
779 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
782 return; /* cannot happen */
783 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
786 static void fn_out_consume(void *priv, char *line, unsigned long len)
788 struct emit_callback *ecbdata = priv;
789 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
790 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
791 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
793 if (ecbdata->header) {
794 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
795 strbuf_reset(ecbdata->header);
796 ecbdata->header = NULL;
798 *(ecbdata->found_changesp) = 1;
800 if (ecbdata->label_path[0]) {
801 const char *name_a_tab, *name_b_tab;
803 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
804 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
806 fprintf(ecbdata->file, "%s--- %s%s%s\n",
807 meta, ecbdata->label_path[0], reset, name_a_tab);
808 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
809 meta, ecbdata->label_path[1], reset, name_b_tab);
810 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
813 if (diff_suppress_blank_empty
814 && len == 2 && line[0] == ' ' && line[1] == '\n') {
819 if (line[0] == '@') {
820 if (ecbdata->diff_words)
821 diff_words_flush(ecbdata);
822 len = sane_truncate_line(ecbdata, line, len);
823 find_lno(line, ecbdata);
824 emit_hunk_header(ecbdata, line, len);
825 if (line[len-1] != '\n')
826 putc('\n', ecbdata->file);
831 emit_line(ecbdata->file, reset, reset, line, len);
835 if (ecbdata->diff_words) {
836 if (line[0] == '-') {
837 diff_words_append(line, len,
838 &ecbdata->diff_words->minus);
840 } else if (line[0] == '+') {
841 diff_words_append(line, len,
842 &ecbdata->diff_words->plus);
845 diff_words_flush(ecbdata);
848 emit_line(ecbdata->file, plain, reset, line, len);
852 if (line[0] != '+') {
854 diff_get_color(ecbdata->color_diff,
855 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
856 ecbdata->lno_in_preimage++;
858 ecbdata->lno_in_postimage++;
859 emit_line(ecbdata->file, color, reset, line, len);
861 ecbdata->lno_in_postimage++;
862 emit_add_line(reset, ecbdata, line + 1, len - 1);
866 static char *pprint_rename(const char *a, const char *b)
870 struct strbuf name = STRBUF_INIT;
871 int pfx_length, sfx_length;
872 int len_a = strlen(a);
873 int len_b = strlen(b);
874 int a_midlen, b_midlen;
875 int qlen_a = quote_c_style(a, NULL, NULL, 0);
876 int qlen_b = quote_c_style(b, NULL, NULL, 0);
878 if (qlen_a || qlen_b) {
879 quote_c_style(a, &name, NULL, 0);
880 strbuf_addstr(&name, " => ");
881 quote_c_style(b, &name, NULL, 0);
882 return strbuf_detach(&name, NULL);
885 /* Find common prefix */
887 while (*old && *new && *old == *new) {
889 pfx_length = old - a + 1;
894 /* Find common suffix */
898 while (a <= old && b <= new && *old == *new) {
900 sfx_length = len_a - (old - a);
906 * pfx{mid-a => mid-b}sfx
907 * {pfx-a => pfx-b}sfx
908 * pfx{sfx-a => sfx-b}
911 a_midlen = len_a - pfx_length - sfx_length;
912 b_midlen = len_b - pfx_length - sfx_length;
918 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
919 if (pfx_length + sfx_length) {
920 strbuf_add(&name, a, pfx_length);
921 strbuf_addch(&name, '{');
923 strbuf_add(&name, a + pfx_length, a_midlen);
924 strbuf_addstr(&name, " => ");
925 strbuf_add(&name, b + pfx_length, b_midlen);
926 if (pfx_length + sfx_length) {
927 strbuf_addch(&name, '}');
928 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
930 return strbuf_detach(&name, NULL);
936 struct diffstat_file {
940 unsigned is_unmerged:1;
941 unsigned is_binary:1;
942 unsigned is_renamed:1;
943 uintmax_t added, deleted;
947 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
951 struct diffstat_file *x;
952 x = xcalloc(sizeof (*x), 1);
953 if (diffstat->nr == diffstat->alloc) {
954 diffstat->alloc = alloc_nr(diffstat->alloc);
955 diffstat->files = xrealloc(diffstat->files,
956 diffstat->alloc * sizeof(x));
958 diffstat->files[diffstat->nr++] = x;
960 x->from_name = xstrdup(name_a);
961 x->name = xstrdup(name_b);
966 x->name = xstrdup(name_a);
971 static void diffstat_consume(void *priv, char *line, unsigned long len)
973 struct diffstat_t *diffstat = priv;
974 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
978 else if (line[0] == '-')
982 const char mime_boundary_leader[] = "------------";
984 static int scale_linear(int it, int width, int max_change)
987 * make sure that at least one '-' is printed if there were deletions,
988 * and likewise for '+'.
992 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
995 static void show_name(FILE *file,
996 const char *prefix, const char *name, int len)
998 fprintf(file, " %s%-*s |", prefix, len, name);
1001 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1005 fprintf(file, "%s", set);
1008 fprintf(file, "%s", reset);
1011 static void fill_print_name(struct diffstat_file *file)
1015 if (file->print_name)
1018 if (!file->is_renamed) {
1019 struct strbuf buf = STRBUF_INIT;
1020 if (quote_c_style(file->name, &buf, NULL, 0)) {
1021 pname = strbuf_detach(&buf, NULL);
1024 strbuf_release(&buf);
1027 pname = pprint_rename(file->from_name, file->name);
1029 file->print_name = pname;
1032 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1034 int i, len, add, del, adds = 0, dels = 0;
1035 uintmax_t max_change = 0, max_len = 0;
1036 int total_files = data->nr;
1037 int width, name_width;
1038 const char *reset, *set, *add_c, *del_c;
1043 width = options->stat_width ? options->stat_width : 80;
1044 name_width = options->stat_name_width ? options->stat_name_width : 50;
1046 /* Sanity: give at least 5 columns to the graph,
1047 * but leave at least 10 columns for the name.
1051 if (name_width < 10)
1053 else if (width < name_width + 15)
1054 name_width = width - 15;
1056 /* Find the longest filename and max number of changes */
1057 reset = diff_get_color_opt(options, DIFF_RESET);
1058 set = diff_get_color_opt(options, DIFF_PLAIN);
1059 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1060 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1062 for (i = 0; i < data->nr; i++) {
1063 struct diffstat_file *file = data->files[i];
1064 uintmax_t change = file->added + file->deleted;
1065 fill_print_name(file);
1066 len = strlen(file->print_name);
1070 if (file->is_binary || file->is_unmerged)
1072 if (max_change < change)
1073 max_change = change;
1076 /* Compute the width of the graph part;
1077 * 10 is for one blank at the beginning of the line plus
1078 * " | count " between the name and the graph.
1080 * From here on, name_width is the width of the name area,
1081 * and width is the width of the graph area.
1083 name_width = (name_width < max_len) ? name_width : max_len;
1084 if (width < (name_width + 10) + max_change)
1085 width = width - (name_width + 10);
1089 for (i = 0; i < data->nr; i++) {
1090 const char *prefix = "";
1091 char *name = data->files[i]->print_name;
1092 uintmax_t added = data->files[i]->added;
1093 uintmax_t deleted = data->files[i]->deleted;
1097 * "scale" the filename
1100 name_len = strlen(name);
1101 if (name_width < name_len) {
1105 name += name_len - len;
1106 slash = strchr(name, '/');
1111 if (data->files[i]->is_binary) {
1112 show_name(options->file, prefix, name, len);
1113 fprintf(options->file, " Bin ");
1114 fprintf(options->file, "%s%"PRIuMAX"%s",
1115 del_c, deleted, reset);
1116 fprintf(options->file, " -> ");
1117 fprintf(options->file, "%s%"PRIuMAX"%s",
1118 add_c, added, reset);
1119 fprintf(options->file, " bytes");
1120 fprintf(options->file, "\n");
1123 else if (data->files[i]->is_unmerged) {
1124 show_name(options->file, prefix, name, len);
1125 fprintf(options->file, " Unmerged\n");
1128 else if (!data->files[i]->is_renamed &&
1129 (added + deleted == 0)) {
1135 * scale the add/delete
1142 if (width <= max_change) {
1143 add = scale_linear(add, width, max_change);
1144 del = scale_linear(del, width, max_change);
1146 show_name(options->file, prefix, name, len);
1147 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1148 added + deleted ? " " : "");
1149 show_graph(options->file, '+', add, add_c, reset);
1150 show_graph(options->file, '-', del, del_c, reset);
1151 fprintf(options->file, "\n");
1153 fprintf(options->file,
1154 " %d files changed, %d insertions(+), %d deletions(-)\n",
1155 total_files, adds, dels);
1158 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1160 int i, adds = 0, dels = 0, total_files = data->nr;
1165 for (i = 0; i < data->nr; i++) {
1166 if (!data->files[i]->is_binary &&
1167 !data->files[i]->is_unmerged) {
1168 int added = data->files[i]->added;
1169 int deleted= data->files[i]->deleted;
1170 if (!data->files[i]->is_renamed &&
1171 (added + deleted == 0)) {
1179 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1180 total_files, adds, dels);
1183 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1190 for (i = 0; i < data->nr; i++) {
1191 struct diffstat_file *file = data->files[i];
1193 if (file->is_binary)
1194 fprintf(options->file, "-\t-\t");
1196 fprintf(options->file,
1197 "%"PRIuMAX"\t%"PRIuMAX"\t",
1198 file->added, file->deleted);
1199 if (options->line_termination) {
1200 fill_print_name(file);
1201 if (!file->is_renamed)
1202 write_name_quoted(file->name, options->file,
1203 options->line_termination);
1205 fputs(file->print_name, options->file);
1206 putc(options->line_termination, options->file);
1209 if (file->is_renamed) {
1210 putc('\0', options->file);
1211 write_name_quoted(file->from_name, options->file, '\0');
1213 write_name_quoted(file->name, options->file, '\0');
1218 struct dirstat_file {
1220 unsigned long changed;
1223 struct dirstat_dir {
1224 struct dirstat_file *files;
1225 int alloc, nr, percent, cumulative;
1228 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1230 unsigned long this_dir = 0;
1231 unsigned int sources = 0;
1234 struct dirstat_file *f = dir->files;
1235 int namelen = strlen(f->name);
1239 if (namelen < baselen)
1241 if (memcmp(f->name, base, baselen))
1243 slash = strchr(f->name + baselen, '/');
1245 int newbaselen = slash + 1 - f->name;
1246 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1258 * We don't report dirstat's for
1260 * - or cases where everything came from a single directory
1261 * under this directory (sources == 1).
1263 if (baselen && sources != 1) {
1264 int permille = this_dir * 1000 / changed;
1266 int percent = permille / 10;
1267 if (percent >= dir->percent) {
1268 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1269 if (!dir->cumulative)
1277 static int dirstat_compare(const void *_a, const void *_b)
1279 const struct dirstat_file *a = _a;
1280 const struct dirstat_file *b = _b;
1281 return strcmp(a->name, b->name);
1284 static void show_dirstat(struct diff_options *options)
1287 unsigned long changed;
1288 struct dirstat_dir dir;
1289 struct diff_queue_struct *q = &diff_queued_diff;
1294 dir.percent = options->dirstat_percent;
1295 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1298 for (i = 0; i < q->nr; i++) {
1299 struct diff_filepair *p = q->queue[i];
1301 unsigned long copied, added, damage;
1303 name = p->one->path ? p->one->path : p->two->path;
1305 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1306 diff_populate_filespec(p->one, 0);
1307 diff_populate_filespec(p->two, 0);
1308 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1310 diff_free_filespec_data(p->one);
1311 diff_free_filespec_data(p->two);
1312 } else if (DIFF_FILE_VALID(p->one)) {
1313 diff_populate_filespec(p->one, 1);
1315 diff_free_filespec_data(p->one);
1316 } else if (DIFF_FILE_VALID(p->two)) {
1317 diff_populate_filespec(p->two, 1);
1319 added = p->two->size;
1320 diff_free_filespec_data(p->two);
1325 * Original minus copied is the removed material,
1326 * added is the new material. They are both damages
1327 * made to the preimage. In --dirstat-by-file mode, count
1328 * damaged files, not damaged lines. This is done by
1329 * counting only a single damaged line per file.
1331 damage = (p->one->size - copied) + added;
1332 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1335 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1336 dir.files[dir.nr].name = name;
1337 dir.files[dir.nr].changed = damage;
1342 /* This can happen even with many files, if everything was renames */
1346 /* Show all directories with more than x% of the changes */
1347 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1348 gather_dirstat(options->file, &dir, changed, "", 0);
1351 static void free_diffstat_info(struct diffstat_t *diffstat)
1354 for (i = 0; i < diffstat->nr; i++) {
1355 struct diffstat_file *f = diffstat->files[i];
1356 if (f->name != f->print_name)
1357 free(f->print_name);
1362 free(diffstat->files);
1365 struct checkdiff_t {
1366 const char *filename;
1368 int conflict_marker_size;
1369 struct diff_options *o;
1374 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1379 if (len < marker_size + 1)
1381 firstchar = line[0];
1382 switch (firstchar) {
1383 case '=': case '>': case '<': case '|':
1388 for (cnt = 1; cnt < marker_size; cnt++)
1389 if (line[cnt] != firstchar)
1391 /* line[1] thru line[marker_size-1] are same as firstchar */
1392 if (len < marker_size + 1 || !isspace(line[marker_size]))
1397 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1399 struct checkdiff_t *data = priv;
1400 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1401 int marker_size = data->conflict_marker_size;
1402 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1403 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1404 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1407 if (line[0] == '+') {
1410 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1412 fprintf(data->o->file,
1413 "%s:%d: leftover conflict marker\n",
1414 data->filename, data->lineno);
1416 bad = ws_check(line + 1, len - 1, data->ws_rule);
1419 data->status |= bad;
1420 err = whitespace_error_string(bad);
1421 fprintf(data->o->file, "%s:%d: %s.\n",
1422 data->filename, data->lineno, err);
1424 emit_line(data->o->file, set, reset, line, 1);
1425 ws_check_emit(line + 1, len - 1, data->ws_rule,
1426 data->o->file, set, reset, ws);
1427 } else if (line[0] == ' ') {
1429 } else if (line[0] == '@') {
1430 char *plus = strchr(line, '+');
1432 data->lineno = strtol(plus, NULL, 10) - 1;
1434 die("invalid diff");
1438 static unsigned char *deflate_it(char *data,
1440 unsigned long *result_size)
1443 unsigned char *deflated;
1446 memset(&stream, 0, sizeof(stream));
1447 deflateInit(&stream, zlib_compression_level);
1448 bound = deflateBound(&stream, size);
1449 deflated = xmalloc(bound);
1450 stream.next_out = deflated;
1451 stream.avail_out = bound;
1453 stream.next_in = (unsigned char *)data;
1454 stream.avail_in = size;
1455 while (deflate(&stream, Z_FINISH) == Z_OK)
1457 deflateEnd(&stream);
1458 *result_size = stream.total_out;
1462 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1468 unsigned long orig_size;
1469 unsigned long delta_size;
1470 unsigned long deflate_size;
1471 unsigned long data_size;
1473 /* We could do deflated delta, or we could do just deflated two,
1474 * whichever is smaller.
1477 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1478 if (one->size && two->size) {
1479 delta = diff_delta(one->ptr, one->size,
1480 two->ptr, two->size,
1481 &delta_size, deflate_size);
1483 void *to_free = delta;
1484 orig_size = delta_size;
1485 delta = deflate_it(delta, delta_size, &delta_size);
1490 if (delta && delta_size < deflate_size) {
1491 fprintf(file, "delta %lu\n", orig_size);
1494 data_size = delta_size;
1497 fprintf(file, "literal %lu\n", two->size);
1500 data_size = deflate_size;
1503 /* emit data encoded in base85 */
1506 int bytes = (52 < data_size) ? 52 : data_size;
1510 line[0] = bytes + 'A' - 1;
1512 line[0] = bytes - 26 + 'a' - 1;
1513 encode_85(line + 1, cp, bytes);
1514 cp = (char *) cp + bytes;
1518 fprintf(file, "\n");
1522 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1524 fprintf(file, "GIT binary patch\n");
1525 emit_binary_diff_body(file, one, two);
1526 emit_binary_diff_body(file, two, one);
1529 static void diff_filespec_load_driver(struct diff_filespec *one)
1532 one->driver = userdiff_find_by_path(one->path);
1534 one->driver = userdiff_find_by_name("default");
1537 int diff_filespec_is_binary(struct diff_filespec *one)
1539 if (one->is_binary == -1) {
1540 diff_filespec_load_driver(one);
1541 if (one->driver->binary != -1)
1542 one->is_binary = one->driver->binary;
1544 if (!one->data && DIFF_FILE_VALID(one))
1545 diff_populate_filespec(one, 0);
1547 one->is_binary = buffer_is_binary(one->data,
1549 if (one->is_binary == -1)
1553 return one->is_binary;
1556 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1558 diff_filespec_load_driver(one);
1559 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1562 static const char *userdiff_word_regex(struct diff_filespec *one)
1564 diff_filespec_load_driver(one);
1565 return one->driver->word_regex;
1568 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1570 if (!options->a_prefix)
1571 options->a_prefix = a;
1572 if (!options->b_prefix)
1573 options->b_prefix = b;
1576 static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1578 if (!DIFF_FILE_VALID(one))
1580 if (!S_ISREG(one->mode))
1582 diff_filespec_load_driver(one);
1583 if (!one->driver->textconv)
1586 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1587 struct notes_cache *c = xmalloc(sizeof(*c));
1588 struct strbuf name = STRBUF_INIT;
1590 strbuf_addf(&name, "textconv/%s", one->driver->name);
1591 notes_cache_init(c, name.buf, one->driver->textconv);
1592 one->driver->textconv_cache = c;
1598 static void builtin_diff(const char *name_a,
1600 struct diff_filespec *one,
1601 struct diff_filespec *two,
1602 const char *xfrm_msg,
1603 struct diff_options *o,
1604 int complete_rewrite)
1608 char *a_one, *b_two;
1609 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1610 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1611 const char *a_prefix, *b_prefix;
1612 struct userdiff_driver *textconv_one = NULL;
1613 struct userdiff_driver *textconv_two = NULL;
1614 struct strbuf header = STRBUF_INIT;
1616 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1617 (!one->mode || S_ISGITLINK(one->mode)) &&
1618 (!two->mode || S_ISGITLINK(two->mode))) {
1619 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1620 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1621 show_submodule_summary(o->file, one ? one->path : two->path,
1622 one->sha1, two->sha1, two->dirty_submodule,
1627 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1628 textconv_one = get_textconv(one);
1629 textconv_two = get_textconv(two);
1632 diff_set_mnemonic_prefix(o, "a/", "b/");
1633 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1634 a_prefix = o->b_prefix;
1635 b_prefix = o->a_prefix;
1637 a_prefix = o->a_prefix;
1638 b_prefix = o->b_prefix;
1641 /* Never use a non-valid filename anywhere if at all possible */
1642 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1643 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1645 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1646 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1647 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1648 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1649 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1650 if (lbl[0][0] == '/') {
1652 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1653 if (xfrm_msg && xfrm_msg[0])
1654 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1656 else if (lbl[1][0] == '/') {
1657 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1658 if (xfrm_msg && xfrm_msg[0])
1659 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1662 if (one->mode != two->mode) {
1663 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1664 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1666 if (xfrm_msg && xfrm_msg[0])
1667 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1670 * we do not run diff between different kind
1673 if ((one->mode ^ two->mode) & S_IFMT)
1674 goto free_ab_and_return;
1675 if (complete_rewrite &&
1676 (textconv_one || !diff_filespec_is_binary(one)) &&
1677 (textconv_two || !diff_filespec_is_binary(two))) {
1678 fprintf(o->file, "%s", header.buf);
1679 strbuf_reset(&header);
1680 emit_rewrite_diff(name_a, name_b, one, two,
1681 textconv_one, textconv_two, o);
1682 o->found_changes = 1;
1683 goto free_ab_and_return;
1687 if (!DIFF_OPT_TST(o, TEXT) &&
1688 ( (!textconv_one && diff_filespec_is_binary(one)) ||
1689 (!textconv_two && diff_filespec_is_binary(two)) )) {
1690 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1691 die("unable to read files to diff");
1692 /* Quite common confusing case */
1693 if (mf1.size == mf2.size &&
1694 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1695 goto free_ab_and_return;
1696 fprintf(o->file, "%s", header.buf);
1697 strbuf_reset(&header);
1698 if (DIFF_OPT_TST(o, BINARY))
1699 emit_binary_diff(o->file, &mf1, &mf2);
1701 fprintf(o->file, "Binary files %s and %s differ\n",
1703 o->found_changes = 1;
1706 /* Crazy xdl interfaces.. */
1707 const char *diffopts = getenv("GIT_DIFF_OPTS");
1710 struct emit_callback ecbdata;
1711 const struct userdiff_funcname *pe;
1713 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1714 fprintf(o->file, "%s", header.buf);
1715 strbuf_reset(&header);
1718 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1719 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1721 pe = diff_funcname_pattern(one);
1723 pe = diff_funcname_pattern(two);
1725 memset(&xpp, 0, sizeof(xpp));
1726 memset(&xecfg, 0, sizeof(xecfg));
1727 memset(&ecbdata, 0, sizeof(ecbdata));
1728 ecbdata.label_path = lbl;
1729 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1730 ecbdata.found_changesp = &o->found_changes;
1731 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1732 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1733 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1734 ecbdata.file = o->file;
1735 ecbdata.header = header.len ? &header : NULL;
1736 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1737 xecfg.ctxlen = o->context;
1738 xecfg.interhunkctxlen = o->interhunkcontext;
1739 xecfg.flags = XDL_EMIT_FUNCNAMES;
1741 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1744 else if (!prefixcmp(diffopts, "--unified="))
1745 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1746 else if (!prefixcmp(diffopts, "-u"))
1747 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1748 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1749 ecbdata.diff_words =
1750 xcalloc(1, sizeof(struct diff_words_data));
1751 ecbdata.diff_words->file = o->file;
1753 o->word_regex = userdiff_word_regex(one);
1755 o->word_regex = userdiff_word_regex(two);
1757 o->word_regex = diff_word_regex_cfg;
1758 if (o->word_regex) {
1759 ecbdata.diff_words->word_regex = (regex_t *)
1760 xmalloc(sizeof(regex_t));
1761 if (regcomp(ecbdata.diff_words->word_regex,
1763 REG_EXTENDED | REG_NEWLINE))
1764 die ("Invalid regular expression: %s",
1768 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1770 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1771 free_diff_words_data(&ecbdata);
1776 xdiff_clear_find_func(&xecfg);
1780 strbuf_release(&header);
1781 diff_free_filespec_data(one);
1782 diff_free_filespec_data(two);
1788 static void builtin_diffstat(const char *name_a, const char *name_b,
1789 struct diff_filespec *one,
1790 struct diff_filespec *two,
1791 struct diffstat_t *diffstat,
1792 struct diff_options *o,
1793 int complete_rewrite)
1796 struct diffstat_file *data;
1798 data = diffstat_add(diffstat, name_a, name_b);
1801 data->is_unmerged = 1;
1804 if (complete_rewrite) {
1805 diff_populate_filespec(one, 0);
1806 diff_populate_filespec(two, 0);
1807 data->deleted = count_lines(one->data, one->size);
1808 data->added = count_lines(two->data, two->size);
1809 goto free_and_return;
1811 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1812 die("unable to read files to diff");
1814 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1815 data->is_binary = 1;
1816 data->added = mf2.size;
1817 data->deleted = mf1.size;
1819 /* Crazy xdl interfaces.. */
1823 memset(&xpp, 0, sizeof(xpp));
1824 memset(&xecfg, 0, sizeof(xecfg));
1825 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1826 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1831 diff_free_filespec_data(one);
1832 diff_free_filespec_data(two);
1835 static void builtin_checkdiff(const char *name_a, const char *name_b,
1836 const char *attr_path,
1837 struct diff_filespec *one,
1838 struct diff_filespec *two,
1839 struct diff_options *o)
1842 struct checkdiff_t data;
1847 memset(&data, 0, sizeof(data));
1848 data.filename = name_b ? name_b : name_a;
1851 data.ws_rule = whitespace_rule(attr_path);
1852 data.conflict_marker_size = ll_merge_marker_size(attr_path);
1854 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1855 die("unable to read files to diff");
1858 * All the other codepaths check both sides, but not checking
1859 * the "old" side here is deliberate. We are checking the newly
1860 * introduced changes, and as long as the "new" side is text, we
1861 * can and should check what it introduces.
1863 if (diff_filespec_is_binary(two))
1864 goto free_and_return;
1866 /* Crazy xdl interfaces.. */
1870 memset(&xpp, 0, sizeof(xpp));
1871 memset(&xecfg, 0, sizeof(xecfg));
1872 xecfg.ctxlen = 1; /* at least one context line */
1873 xpp.flags = XDF_NEED_MINIMAL;
1874 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1877 if (data.ws_rule & WS_BLANK_AT_EOF) {
1878 struct emit_callback ecbdata;
1881 ecbdata.ws_rule = data.ws_rule;
1882 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1883 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1888 err = whitespace_error_string(WS_BLANK_AT_EOF);
1889 fprintf(o->file, "%s:%d: %s.\n",
1890 data.filename, blank_at_eof, err);
1891 data.status = 1; /* report errors */
1896 diff_free_filespec_data(one);
1897 diff_free_filespec_data(two);
1899 DIFF_OPT_SET(o, CHECK_FAILED);
1902 struct diff_filespec *alloc_filespec(const char *path)
1904 int namelen = strlen(path);
1905 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1907 memset(spec, 0, sizeof(*spec));
1908 spec->path = (char *)(spec + 1);
1909 memcpy(spec->path, path, namelen+1);
1911 spec->is_binary = -1;
1915 void free_filespec(struct diff_filespec *spec)
1917 if (!--spec->count) {
1918 diff_free_filespec_data(spec);
1923 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1924 unsigned short mode)
1927 spec->mode = canon_mode(mode);
1928 hashcpy(spec->sha1, sha1);
1929 spec->sha1_valid = !is_null_sha1(sha1);
1934 * Given a name and sha1 pair, if the index tells us the file in
1935 * the work tree has that object contents, return true, so that
1936 * prepare_temp_file() does not have to inflate and extract.
1938 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1940 struct cache_entry *ce;
1945 * We do not read the cache ourselves here, because the
1946 * benchmark with my previous version that always reads cache
1947 * shows that it makes things worse for diff-tree comparing
1948 * two linux-2.6 kernel trees in an already checked out work
1949 * tree. This is because most diff-tree comparisons deal with
1950 * only a small number of files, while reading the cache is
1951 * expensive for a large project, and its cost outweighs the
1952 * savings we get by not inflating the object to a temporary
1953 * file. Practically, this code only helps when we are used
1954 * by diff-cache --cached, which does read the cache before
1960 /* We want to avoid the working directory if our caller
1961 * doesn't need the data in a normal file, this system
1962 * is rather slow with its stat/open/mmap/close syscalls,
1963 * and the object is contained in a pack file. The pack
1964 * is probably already open and will be faster to obtain
1965 * the data through than the working directory. Loose
1966 * objects however would tend to be slower as they need
1967 * to be individually opened and inflated.
1969 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1973 pos = cache_name_pos(name, len);
1976 ce = active_cache[pos];
1979 * This is not the sha1 we are looking for, or
1980 * unreusable because it is not a regular file.
1982 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1986 * If ce is marked as "assume unchanged", there is no
1987 * guarantee that work tree matches what we are looking for.
1989 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
1993 * If ce matches the file in the work tree, we can reuse it.
1995 if (ce_uptodate(ce) ||
1996 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2002 static int populate_from_stdin(struct diff_filespec *s)
2004 struct strbuf buf = STRBUF_INIT;
2007 if (strbuf_read(&buf, 0, 0) < 0)
2008 return error("error while reading from stdin %s",
2011 s->should_munmap = 0;
2012 s->data = strbuf_detach(&buf, &size);
2018 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2021 char *data = xmalloc(100), *dirty = "";
2023 /* Are we looking at the work tree? */
2024 if (s->dirty_submodule)
2027 len = snprintf(data, 100,
2028 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2040 * While doing rename detection and pickaxe operation, we may need to
2041 * grab the data for the blob (or file) for our own in-core comparison.
2042 * diff_filespec has data and size fields for this purpose.
2044 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2047 if (!DIFF_FILE_VALID(s))
2048 die("internal error: asking to populate invalid file.");
2049 if (S_ISDIR(s->mode))
2055 if (size_only && 0 < s->size)
2058 if (S_ISGITLINK(s->mode))
2059 return diff_populate_gitlink(s, size_only);
2061 if (!s->sha1_valid ||
2062 reuse_worktree_file(s->path, s->sha1, 0)) {
2063 struct strbuf buf = STRBUF_INIT;
2067 if (!strcmp(s->path, "-"))
2068 return populate_from_stdin(s);
2070 if (lstat(s->path, &st) < 0) {
2071 if (errno == ENOENT) {
2075 s->data = (char *)"";
2080 s->size = xsize_t(st.st_size);
2083 if (S_ISLNK(st.st_mode)) {
2084 struct strbuf sb = STRBUF_INIT;
2086 if (strbuf_readlink(&sb, s->path, s->size))
2089 s->data = strbuf_detach(&sb, NULL);
2095 fd = open(s->path, O_RDONLY);
2098 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2100 s->should_munmap = 1;
2103 * Convert from working tree format to canonical git format
2105 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2107 munmap(s->data, s->size);
2108 s->should_munmap = 0;
2109 s->data = strbuf_detach(&buf, &size);
2115 enum object_type type;
2117 type = sha1_object_info(s->sha1, &s->size);
2119 s->data = read_sha1_file(s->sha1, &type, &s->size);
2126 void diff_free_filespec_blob(struct diff_filespec *s)
2130 else if (s->should_munmap)
2131 munmap(s->data, s->size);
2133 if (s->should_free || s->should_munmap) {
2134 s->should_free = s->should_munmap = 0;
2139 void diff_free_filespec_data(struct diff_filespec *s)
2141 diff_free_filespec_blob(s);
2146 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2149 const unsigned char *sha1,
2153 struct strbuf buf = STRBUF_INIT;
2154 struct strbuf template = STRBUF_INIT;
2155 char *path_dup = xstrdup(path);
2156 const char *base = basename(path_dup);
2158 /* Generate "XXXXXX_basename.ext" */
2159 strbuf_addstr(&template, "XXXXXX_");
2160 strbuf_addstr(&template, base);
2162 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2165 die_errno("unable to create temp-file");
2166 if (convert_to_working_tree(path,
2167 (const char *)blob, (size_t)size, &buf)) {
2171 if (write_in_full(fd, blob, size) != size)
2172 die_errno("unable to write temp-file");
2174 temp->name = temp->tmp_path;
2175 strcpy(temp->hex, sha1_to_hex(sha1));
2177 sprintf(temp->mode, "%06o", mode);
2178 strbuf_release(&buf);
2179 strbuf_release(&template);
2183 static struct diff_tempfile *prepare_temp_file(const char *name,
2184 struct diff_filespec *one)
2186 struct diff_tempfile *temp = claim_diff_tempfile();
2188 if (!DIFF_FILE_VALID(one)) {
2190 /* A '-' entry produces this for file-2, and
2191 * a '+' entry produces this for file-1.
2193 temp->name = "/dev/null";
2194 strcpy(temp->hex, ".");
2195 strcpy(temp->mode, ".");
2199 if (!remove_tempfile_installed) {
2200 atexit(remove_tempfile);
2201 sigchain_push_common(remove_tempfile_on_signal);
2202 remove_tempfile_installed = 1;
2205 if (!one->sha1_valid ||
2206 reuse_worktree_file(name, one->sha1, 1)) {
2208 if (lstat(name, &st) < 0) {
2209 if (errno == ENOENT)
2210 goto not_a_valid_file;
2211 die_errno("stat(%s)", name);
2213 if (S_ISLNK(st.st_mode)) {
2214 struct strbuf sb = STRBUF_INIT;
2215 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2216 die_errno("readlink(%s)", name);
2217 prep_temp_blob(name, temp, sb.buf, sb.len,
2219 one->sha1 : null_sha1),
2221 one->mode : S_IFLNK));
2222 strbuf_release(&sb);
2225 /* we can borrow from the file in the work tree */
2227 if (!one->sha1_valid)
2228 strcpy(temp->hex, sha1_to_hex(null_sha1));
2230 strcpy(temp->hex, sha1_to_hex(one->sha1));
2231 /* Even though we may sometimes borrow the
2232 * contents from the work tree, we always want
2233 * one->mode. mode is trustworthy even when
2234 * !(one->sha1_valid), as long as
2235 * DIFF_FILE_VALID(one).
2237 sprintf(temp->mode, "%06o", one->mode);
2242 if (diff_populate_filespec(one, 0))
2243 die("cannot read data blob for %s", one->path);
2244 prep_temp_blob(name, temp, one->data, one->size,
2245 one->sha1, one->mode);
2250 /* An external diff command takes:
2252 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2253 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2256 static void run_external_diff(const char *pgm,
2259 struct diff_filespec *one,
2260 struct diff_filespec *two,
2261 const char *xfrm_msg,
2262 int complete_rewrite)
2264 const char *spawn_arg[10];
2266 const char **arg = &spawn_arg[0];
2269 struct diff_tempfile *temp_one, *temp_two;
2270 const char *othername = (other ? other : name);
2271 temp_one = prepare_temp_file(name, one);
2272 temp_two = prepare_temp_file(othername, two);
2275 *arg++ = temp_one->name;
2276 *arg++ = temp_one->hex;
2277 *arg++ = temp_one->mode;
2278 *arg++ = temp_two->name;
2279 *arg++ = temp_two->hex;
2280 *arg++ = temp_two->mode;
2291 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2294 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2299 static int similarity_index(struct diff_filepair *p)
2301 return p->score * 100 / MAX_SCORE;
2304 static void fill_metainfo(struct strbuf *msg,
2307 struct diff_filespec *one,
2308 struct diff_filespec *two,
2309 struct diff_options *o,
2310 struct diff_filepair *p)
2312 strbuf_init(msg, PATH_MAX * 2 + 300);
2313 switch (p->status) {
2314 case DIFF_STATUS_COPIED:
2315 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2316 strbuf_addstr(msg, "\ncopy from ");
2317 quote_c_style(name, msg, NULL, 0);
2318 strbuf_addstr(msg, "\ncopy to ");
2319 quote_c_style(other, msg, NULL, 0);
2320 strbuf_addch(msg, '\n');
2322 case DIFF_STATUS_RENAMED:
2323 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2324 strbuf_addstr(msg, "\nrename from ");
2325 quote_c_style(name, msg, NULL, 0);
2326 strbuf_addstr(msg, "\nrename to ");
2327 quote_c_style(other, msg, NULL, 0);
2328 strbuf_addch(msg, '\n');
2330 case DIFF_STATUS_MODIFIED:
2332 strbuf_addf(msg, "dissimilarity index %d%%\n",
2333 similarity_index(p));
2341 if (one && two && hashcmp(one->sha1, two->sha1)) {
2342 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2344 if (DIFF_OPT_TST(o, BINARY)) {
2346 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2347 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2350 strbuf_addf(msg, "index %.*s..%.*s",
2351 abbrev, sha1_to_hex(one->sha1),
2352 abbrev, sha1_to_hex(two->sha1));
2353 if (one->mode == two->mode)
2354 strbuf_addf(msg, " %06o", one->mode);
2355 strbuf_addch(msg, '\n');
2358 strbuf_setlen(msg, msg->len - 1);
2361 static void run_diff_cmd(const char *pgm,
2364 const char *attr_path,
2365 struct diff_filespec *one,
2366 struct diff_filespec *two,
2368 struct diff_options *o,
2369 struct diff_filepair *p)
2371 const char *xfrm_msg = NULL;
2372 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2375 fill_metainfo(msg, name, other, one, two, o, p);
2376 xfrm_msg = msg->len ? msg->buf : NULL;
2379 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2382 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2383 if (drv && drv->external)
2384 pgm = drv->external;
2388 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2393 builtin_diff(name, other ? other : name,
2394 one, two, xfrm_msg, o, complete_rewrite);
2396 fprintf(o->file, "* Unmerged path %s\n", name);
2399 static void diff_fill_sha1_info(struct diff_filespec *one)
2401 if (DIFF_FILE_VALID(one)) {
2402 if (!one->sha1_valid) {
2404 if (!strcmp(one->path, "-")) {
2405 hashcpy(one->sha1, null_sha1);
2408 if (lstat(one->path, &st) < 0)
2409 die_errno("stat '%s'", one->path);
2410 if (index_path(one->sha1, one->path, &st, 0))
2411 die("cannot hash %s", one->path);
2418 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2420 /* Strip the prefix but do not molest /dev/null and absolute paths */
2421 if (*namep && **namep != '/')
2422 *namep += prefix_length;
2423 if (*otherp && **otherp != '/')
2424 *otherp += prefix_length;
2427 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2429 const char *pgm = external_diff();
2431 struct diff_filespec *one = p->one;
2432 struct diff_filespec *two = p->two;
2435 const char *attr_path;
2437 name = p->one->path;
2438 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2440 if (o->prefix_length)
2441 strip_prefix(o->prefix_length, &name, &other);
2443 if (DIFF_PAIR_UNMERGED(p)) {
2444 run_diff_cmd(pgm, name, NULL, attr_path,
2445 NULL, NULL, NULL, o, p);
2449 diff_fill_sha1_info(one);
2450 diff_fill_sha1_info(two);
2453 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2454 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2456 * a filepair that changes between file and symlink
2457 * needs to be split into deletion and creation.
2459 struct diff_filespec *null = alloc_filespec(two->path);
2460 run_diff_cmd(NULL, name, other, attr_path,
2461 one, null, &msg, o, p);
2463 strbuf_release(&msg);
2465 null = alloc_filespec(one->path);
2466 run_diff_cmd(NULL, name, other, attr_path,
2467 null, two, &msg, o, p);
2471 run_diff_cmd(pgm, name, other, attr_path,
2472 one, two, &msg, o, p);
2474 strbuf_release(&msg);
2477 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2478 struct diffstat_t *diffstat)
2482 int complete_rewrite = 0;
2484 if (DIFF_PAIR_UNMERGED(p)) {
2486 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2490 name = p->one->path;
2491 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2493 if (o->prefix_length)
2494 strip_prefix(o->prefix_length, &name, &other);
2496 diff_fill_sha1_info(p->one);
2497 diff_fill_sha1_info(p->two);
2499 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2500 complete_rewrite = 1;
2501 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2504 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2508 const char *attr_path;
2510 if (DIFF_PAIR_UNMERGED(p)) {
2515 name = p->one->path;
2516 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2517 attr_path = other ? other : name;
2519 if (o->prefix_length)
2520 strip_prefix(o->prefix_length, &name, &other);
2522 diff_fill_sha1_info(p->one);
2523 diff_fill_sha1_info(p->two);
2525 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2528 void diff_setup(struct diff_options *options)
2530 memset(options, 0, sizeof(*options));
2532 options->file = stdout;
2534 options->line_termination = '\n';
2535 options->break_opt = -1;
2536 options->rename_limit = -1;
2537 options->dirstat_percent = 3;
2538 options->context = 3;
2540 options->change = diff_change;
2541 options->add_remove = diff_addremove;
2542 if (diff_use_color_default > 0)
2543 DIFF_OPT_SET(options, COLOR_DIFF);
2544 options->detect_rename = diff_detect_rename_default;
2546 if (diff_no_prefix) {
2547 options->a_prefix = options->b_prefix = "";
2548 } else if (!diff_mnemonic_prefix) {
2549 options->a_prefix = "a/";
2550 options->b_prefix = "b/";
2554 int diff_setup_done(struct diff_options *options)
2558 if (options->output_format & DIFF_FORMAT_NAME)
2560 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2562 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2564 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2567 die("--name-only, --name-status, --check and -s are mutually exclusive");
2570 * Most of the time we can say "there are changes"
2571 * only by checking if there are changed paths, but
2572 * --ignore-whitespace* options force us to look
2576 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2577 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2578 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2579 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2581 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2583 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2584 options->detect_rename = DIFF_DETECT_COPY;
2586 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2587 options->prefix = NULL;
2588 if (options->prefix)
2589 options->prefix_length = strlen(options->prefix);
2591 options->prefix_length = 0;
2593 if (options->output_format & (DIFF_FORMAT_NAME |
2594 DIFF_FORMAT_NAME_STATUS |
2595 DIFF_FORMAT_CHECKDIFF |
2596 DIFF_FORMAT_NO_OUTPUT))
2597 options->output_format &= ~(DIFF_FORMAT_RAW |
2598 DIFF_FORMAT_NUMSTAT |
2599 DIFF_FORMAT_DIFFSTAT |
2600 DIFF_FORMAT_SHORTSTAT |
2601 DIFF_FORMAT_DIRSTAT |
2602 DIFF_FORMAT_SUMMARY |
2606 * These cases always need recursive; we do not drop caller-supplied
2607 * recursive bits for other formats here.
2609 if (options->output_format & (DIFF_FORMAT_PATCH |
2610 DIFF_FORMAT_NUMSTAT |
2611 DIFF_FORMAT_DIFFSTAT |
2612 DIFF_FORMAT_SHORTSTAT |
2613 DIFF_FORMAT_DIRSTAT |
2614 DIFF_FORMAT_SUMMARY |
2615 DIFF_FORMAT_CHECKDIFF))
2616 DIFF_OPT_SET(options, RECURSIVE);
2618 * Also pickaxe would not work very well if you do not say recursive
2620 if (options->pickaxe)
2621 DIFF_OPT_SET(options, RECURSIVE);
2623 * When patches are generated, submodules diffed against the work tree
2624 * must be checked for dirtiness too so it can be shown in the output
2626 if (options->output_format & DIFF_FORMAT_PATCH)
2627 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2629 if (options->detect_rename && options->rename_limit < 0)
2630 options->rename_limit = diff_rename_limit_default;
2631 if (options->setup & DIFF_SETUP_USE_CACHE) {
2633 /* read-cache does not die even when it fails
2634 * so it is safe for us to do this here. Also
2635 * it does not smudge active_cache or active_nr
2636 * when it fails, so we do not have to worry about
2637 * cleaning it up ourselves either.
2641 if (options->abbrev <= 0 || 40 < options->abbrev)
2642 options->abbrev = 40; /* full */
2645 * It does not make sense to show the first hit we happened
2646 * to have found. It does not make sense not to return with
2647 * exit code in such a case either.
2649 if (DIFF_OPT_TST(options, QUICK)) {
2650 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2651 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2657 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2667 if (c == arg_short) {
2671 if (val && isdigit(c)) {
2673 int n = strtoul(arg, &end, 10);
2684 eq = strchr(arg, '=');
2689 if (!len || strncmp(arg, arg_long, len))
2694 if (!isdigit(*++eq))
2696 n = strtoul(eq, &end, 10);
2704 static int diff_scoreopt_parse(const char *opt);
2706 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2708 const char *arg = av[0];
2710 /* Output format options */
2711 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2712 options->output_format |= DIFF_FORMAT_PATCH;
2713 else if (opt_arg(arg, 'U', "unified", &options->context))
2714 options->output_format |= DIFF_FORMAT_PATCH;
2715 else if (!strcmp(arg, "--raw"))
2716 options->output_format |= DIFF_FORMAT_RAW;
2717 else if (!strcmp(arg, "--patch-with-raw"))
2718 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2719 else if (!strcmp(arg, "--numstat"))
2720 options->output_format |= DIFF_FORMAT_NUMSTAT;
2721 else if (!strcmp(arg, "--shortstat"))
2722 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2723 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2724 options->output_format |= DIFF_FORMAT_DIRSTAT;
2725 else if (!strcmp(arg, "--cumulative")) {
2726 options->output_format |= DIFF_FORMAT_DIRSTAT;
2727 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2728 } else if (opt_arg(arg, 0, "dirstat-by-file",
2729 &options->dirstat_percent)) {
2730 options->output_format |= DIFF_FORMAT_DIRSTAT;
2731 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2733 else if (!strcmp(arg, "--check"))
2734 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2735 else if (!strcmp(arg, "--summary"))
2736 options->output_format |= DIFF_FORMAT_SUMMARY;
2737 else if (!strcmp(arg, "--patch-with-stat"))
2738 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2739 else if (!strcmp(arg, "--name-only"))
2740 options->output_format |= DIFF_FORMAT_NAME;
2741 else if (!strcmp(arg, "--name-status"))
2742 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2743 else if (!strcmp(arg, "-s"))
2744 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2745 else if (!prefixcmp(arg, "--stat")) {
2747 int width = options->stat_width;
2748 int name_width = options->stat_name_width;
2754 if (!prefixcmp(arg, "-width="))
2755 width = strtoul(arg + 7, &end, 10);
2756 else if (!prefixcmp(arg, "-name-width="))
2757 name_width = strtoul(arg + 12, &end, 10);
2760 width = strtoul(arg+1, &end, 10);
2762 name_width = strtoul(end+1, &end, 10);
2765 /* Important! This checks all the error cases! */
2768 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2769 options->stat_name_width = name_width;
2770 options->stat_width = width;
2773 /* renames options */
2774 else if (!prefixcmp(arg, "-B")) {
2775 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2778 else if (!prefixcmp(arg, "-M")) {
2779 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2781 options->detect_rename = DIFF_DETECT_RENAME;
2783 else if (!prefixcmp(arg, "-C")) {
2784 if (options->detect_rename == DIFF_DETECT_COPY)
2785 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2786 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2788 options->detect_rename = DIFF_DETECT_COPY;
2790 else if (!strcmp(arg, "--no-renames"))
2791 options->detect_rename = 0;
2792 else if (!strcmp(arg, "--relative"))
2793 DIFF_OPT_SET(options, RELATIVE_NAME);
2794 else if (!prefixcmp(arg, "--relative=")) {
2795 DIFF_OPT_SET(options, RELATIVE_NAME);
2796 options->prefix = arg + 11;
2800 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2801 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2802 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2803 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2804 else if (!strcmp(arg, "--ignore-space-at-eol"))
2805 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2806 else if (!strcmp(arg, "--patience"))
2807 DIFF_XDL_SET(options, PATIENCE_DIFF);
2810 else if (!strcmp(arg, "--binary")) {
2811 options->output_format |= DIFF_FORMAT_PATCH;
2812 DIFF_OPT_SET(options, BINARY);
2814 else if (!strcmp(arg, "--full-index"))
2815 DIFF_OPT_SET(options, FULL_INDEX);
2816 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2817 DIFF_OPT_SET(options, TEXT);
2818 else if (!strcmp(arg, "-R"))
2819 DIFF_OPT_SET(options, REVERSE_DIFF);
2820 else if (!strcmp(arg, "--find-copies-harder"))
2821 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2822 else if (!strcmp(arg, "--follow"))
2823 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2824 else if (!strcmp(arg, "--color"))
2825 DIFF_OPT_SET(options, COLOR_DIFF);
2826 else if (!prefixcmp(arg, "--color=")) {
2827 int value = git_config_colorbool(NULL, arg+8, -1);
2829 DIFF_OPT_CLR(options, COLOR_DIFF);
2831 DIFF_OPT_SET(options, COLOR_DIFF);
2833 return error("option `color' expects \"always\", \"auto\", or \"never\"");
2835 else if (!strcmp(arg, "--no-color"))
2836 DIFF_OPT_CLR(options, COLOR_DIFF);
2837 else if (!strcmp(arg, "--color-words")) {
2838 DIFF_OPT_SET(options, COLOR_DIFF);
2839 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2841 else if (!prefixcmp(arg, "--color-words=")) {
2842 DIFF_OPT_SET(options, COLOR_DIFF);
2843 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2844 options->word_regex = arg + 14;
2846 else if (!strcmp(arg, "--exit-code"))
2847 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2848 else if (!strcmp(arg, "--quiet"))
2849 DIFF_OPT_SET(options, QUICK);
2850 else if (!strcmp(arg, "--ext-diff"))
2851 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2852 else if (!strcmp(arg, "--no-ext-diff"))
2853 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2854 else if (!strcmp(arg, "--textconv"))
2855 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2856 else if (!strcmp(arg, "--no-textconv"))
2857 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2858 else if (!strcmp(arg, "--ignore-submodules"))
2859 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2860 else if (!strcmp(arg, "--submodule"))
2861 DIFF_OPT_SET(options, SUBMODULE_LOG);
2862 else if (!prefixcmp(arg, "--submodule=")) {
2863 if (!strcmp(arg + 12, "log"))
2864 DIFF_OPT_SET(options, SUBMODULE_LOG);
2868 else if (!strcmp(arg, "-z"))
2869 options->line_termination = 0;
2870 else if (!prefixcmp(arg, "-l"))
2871 options->rename_limit = strtoul(arg+2, NULL, 10);
2872 else if (!prefixcmp(arg, "-S"))
2873 options->pickaxe = arg + 2;
2874 else if (!strcmp(arg, "--pickaxe-all"))
2875 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2876 else if (!strcmp(arg, "--pickaxe-regex"))
2877 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2878 else if (!prefixcmp(arg, "-O"))
2879 options->orderfile = arg + 2;
2880 else if (!prefixcmp(arg, "--diff-filter="))
2881 options->filter = arg + 14;
2882 else if (!strcmp(arg, "--abbrev"))
2883 options->abbrev = DEFAULT_ABBREV;
2884 else if (!prefixcmp(arg, "--abbrev=")) {
2885 options->abbrev = strtoul(arg + 9, NULL, 10);
2886 if (options->abbrev < MINIMUM_ABBREV)
2887 options->abbrev = MINIMUM_ABBREV;
2888 else if (40 < options->abbrev)
2889 options->abbrev = 40;
2891 else if (!prefixcmp(arg, "--src-prefix="))
2892 options->a_prefix = arg + 13;
2893 else if (!prefixcmp(arg, "--dst-prefix="))
2894 options->b_prefix = arg + 13;
2895 else if (!strcmp(arg, "--no-prefix"))
2896 options->a_prefix = options->b_prefix = "";
2897 else if (opt_arg(arg, '\0', "inter-hunk-context",
2898 &options->interhunkcontext))
2900 else if (!prefixcmp(arg, "--output=")) {
2901 options->file = fopen(arg + strlen("--output="), "w");
2903 die_errno("Could not open '%s'", arg + strlen("--output="));
2904 options->close_file = 1;
2910 static int parse_num(const char **cp_p)
2912 unsigned long num, scale;
2914 const char *cp = *cp_p;
2921 if ( !dot && ch == '.' ) {
2924 } else if ( ch == '%' ) {
2925 scale = dot ? scale*100 : 100;
2926 cp++; /* % is always at the end */
2928 } else if ( ch >= '0' && ch <= '9' ) {
2929 if ( scale < 100000 ) {
2931 num = (num*10) + (ch-'0');
2940 /* user says num divided by scale and we say internally that
2941 * is MAX_SCORE * num / scale.
2943 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2946 static int diff_scoreopt_parse(const char *opt)
2948 int opt1, opt2, cmd;
2953 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2954 return -1; /* that is not a -M, -C nor -B option */
2956 opt1 = parse_num(&opt);
2962 else if (*opt != '/')
2963 return -1; /* we expect -B80/99 or -B80 */
2966 opt2 = parse_num(&opt);
2971 return opt1 | (opt2 << 16);
2974 struct diff_queue_struct diff_queued_diff;
2976 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2978 if (queue->alloc <= queue->nr) {
2979 queue->alloc = alloc_nr(queue->alloc);
2980 queue->queue = xrealloc(queue->queue,
2981 sizeof(dp) * queue->alloc);
2983 queue->queue[queue->nr++] = dp;
2986 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2987 struct diff_filespec *one,
2988 struct diff_filespec *two)
2990 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2998 void diff_free_filepair(struct diff_filepair *p)
3000 free_filespec(p->one);
3001 free_filespec(p->two);
3005 /* This is different from find_unique_abbrev() in that
3006 * it stuffs the result with dots for alignment.
3008 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3013 return sha1_to_hex(sha1);
3015 abbrev = find_unique_abbrev(sha1, len);
3016 abblen = strlen(abbrev);
3018 static char hex[41];
3019 if (len < abblen && abblen <= len + 2)
3020 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3022 sprintf(hex, "%s...", abbrev);
3025 return sha1_to_hex(sha1);
3028 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3030 int line_termination = opt->line_termination;
3031 int inter_name_termination = line_termination ? '\t' : '\0';
3033 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3034 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3035 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3036 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3039 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3040 inter_name_termination);
3042 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3045 if (p->status == DIFF_STATUS_COPIED ||
3046 p->status == DIFF_STATUS_RENAMED) {
3047 const char *name_a, *name_b;
3048 name_a = p->one->path;
3049 name_b = p->two->path;
3050 strip_prefix(opt->prefix_length, &name_a, &name_b);
3051 write_name_quoted(name_a, opt->file, inter_name_termination);
3052 write_name_quoted(name_b, opt->file, line_termination);
3054 const char *name_a, *name_b;
3055 name_a = p->one->mode ? p->one->path : p->two->path;
3057 strip_prefix(opt->prefix_length, &name_a, &name_b);
3058 write_name_quoted(name_a, opt->file, line_termination);
3062 int diff_unmodified_pair(struct diff_filepair *p)
3064 /* This function is written stricter than necessary to support
3065 * the currently implemented transformers, but the idea is to
3066 * let transformers to produce diff_filepairs any way they want,
3067 * and filter and clean them up here before producing the output.
3069 struct diff_filespec *one = p->one, *two = p->two;
3071 if (DIFF_PAIR_UNMERGED(p))
3072 return 0; /* unmerged is interesting */
3074 /* deletion, addition, mode or type change
3075 * and rename are all interesting.
3077 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3078 DIFF_PAIR_MODE_CHANGED(p) ||
3079 strcmp(one->path, two->path))
3082 /* both are valid and point at the same path. that is, we are
3083 * dealing with a change.
3085 if (one->sha1_valid && two->sha1_valid &&
3086 !hashcmp(one->sha1, two->sha1) &&
3087 !one->dirty_submodule && !two->dirty_submodule)
3088 return 1; /* no change */
3089 if (!one->sha1_valid && !two->sha1_valid)
3090 return 1; /* both look at the same file on the filesystem. */
3094 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3096 if (diff_unmodified_pair(p))
3099 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3100 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3101 return; /* no tree diffs in patch format */
3106 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3107 struct diffstat_t *diffstat)
3109 if (diff_unmodified_pair(p))
3112 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3113 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3114 return; /* no tree diffs in patch format */
3116 run_diffstat(p, o, diffstat);
3119 static void diff_flush_checkdiff(struct diff_filepair *p,
3120 struct diff_options *o)
3122 if (diff_unmodified_pair(p))
3125 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3126 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3127 return; /* no tree diffs in patch format */
3129 run_checkdiff(p, o);
3132 int diff_queue_is_empty(void)
3134 struct diff_queue_struct *q = &diff_queued_diff;
3136 for (i = 0; i < q->nr; i++)
3137 if (!diff_unmodified_pair(q->queue[i]))
3143 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3145 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3148 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3150 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3151 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3153 s->size, s->xfrm_flags);
3156 void diff_debug_filepair(const struct diff_filepair *p, int i)
3158 diff_debug_filespec(p->one, i, "one");
3159 diff_debug_filespec(p->two, i, "two");
3160 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3161 p->score, p->status ? p->status : '?',
3162 p->one->rename_used, p->broken_pair);
3165 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3169 fprintf(stderr, "%s\n", msg);
3170 fprintf(stderr, "q->nr = %d\n", q->nr);
3171 for (i = 0; i < q->nr; i++) {
3172 struct diff_filepair *p = q->queue[i];
3173 diff_debug_filepair(p, i);
3178 static void diff_resolve_rename_copy(void)
3181 struct diff_filepair *p;
3182 struct diff_queue_struct *q = &diff_queued_diff;
3184 diff_debug_queue("resolve-rename-copy", q);
3186 for (i = 0; i < q->nr; i++) {
3188 p->status = 0; /* undecided */
3189 if (DIFF_PAIR_UNMERGED(p))
3190 p->status = DIFF_STATUS_UNMERGED;
3191 else if (!DIFF_FILE_VALID(p->one))
3192 p->status = DIFF_STATUS_ADDED;
3193 else if (!DIFF_FILE_VALID(p->two))
3194 p->status = DIFF_STATUS_DELETED;
3195 else if (DIFF_PAIR_TYPE_CHANGED(p))
3196 p->status = DIFF_STATUS_TYPE_CHANGED;
3198 /* from this point on, we are dealing with a pair
3199 * whose both sides are valid and of the same type, i.e.
3200 * either in-place edit or rename/copy edit.
3202 else if (DIFF_PAIR_RENAME(p)) {
3204 * A rename might have re-connected a broken
3205 * pair up, causing the pathnames to be the
3206 * same again. If so, that's not a rename at
3207 * all, just a modification..
3209 * Otherwise, see if this source was used for
3210 * multiple renames, in which case we decrement
3211 * the count, and call it a copy.
3213 if (!strcmp(p->one->path, p->two->path))
3214 p->status = DIFF_STATUS_MODIFIED;
3215 else if (--p->one->rename_used > 0)
3216 p->status = DIFF_STATUS_COPIED;
3218 p->status = DIFF_STATUS_RENAMED;
3220 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3221 p->one->mode != p->two->mode ||
3222 p->one->dirty_submodule ||
3223 p->two->dirty_submodule ||
3224 is_null_sha1(p->one->sha1))
3225 p->status = DIFF_STATUS_MODIFIED;
3227 /* This is a "no-change" entry and should not
3228 * happen anymore, but prepare for broken callers.
3230 error("feeding unmodified %s to diffcore",
3232 p->status = DIFF_STATUS_UNKNOWN;
3235 diff_debug_queue("resolve-rename-copy done", q);
3238 static int check_pair_status(struct diff_filepair *p)
3240 switch (p->status) {
3241 case DIFF_STATUS_UNKNOWN:
3244 die("internal error in diff-resolve-rename-copy");
3250 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3252 int fmt = opt->output_format;
3254 if (fmt & DIFF_FORMAT_CHECKDIFF)
3255 diff_flush_checkdiff(p, opt);
3256 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3257 diff_flush_raw(p, opt);
3258 else if (fmt & DIFF_FORMAT_NAME) {
3259 const char *name_a, *name_b;
3260 name_a = p->two->path;
3262 strip_prefix(opt->prefix_length, &name_a, &name_b);
3263 write_name_quoted(name_a, opt->file, opt->line_termination);
3267 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3270 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3272 fprintf(file, " %s ", newdelete);
3273 write_name_quoted(fs->path, file, '\n');
3277 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3279 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3280 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3281 show_name ? ' ' : '\n');
3283 write_name_quoted(p->two->path, file, '\n');
3288 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3290 char *names = pprint_rename(p->one->path, p->two->path);
3292 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3294 show_mode_change(file, p, 0);
3297 static void diff_summary(FILE *file, struct diff_filepair *p)
3300 case DIFF_STATUS_DELETED:
3301 show_file_mode_name(file, "delete", p->one);
3303 case DIFF_STATUS_ADDED:
3304 show_file_mode_name(file, "create", p->two);
3306 case DIFF_STATUS_COPIED:
3307 show_rename_copy(file, "copy", p);
3309 case DIFF_STATUS_RENAMED:
3310 show_rename_copy(file, "rename", p);
3314 fputs(" rewrite ", file);
3315 write_name_quoted(p->two->path, file, ' ');
3316 fprintf(file, "(%d%%)\n", similarity_index(p));
3318 show_mode_change(file, p, !p->score);
3328 static int remove_space(char *line, int len)
3334 for (i = 0; i < len; i++)
3335 if (!isspace((c = line[i])))
3341 static void patch_id_consume(void *priv, char *line, unsigned long len)
3343 struct patch_id_t *data = priv;
3346 /* Ignore line numbers when computing the SHA1 of the patch */
3347 if (!prefixcmp(line, "@@ -"))
3350 new_len = remove_space(line, len);
3352 git_SHA1_Update(data->ctx, line, new_len);
3353 data->patchlen += new_len;
3356 /* returns 0 upon success, and writes result into sha1 */
3357 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3359 struct diff_queue_struct *q = &diff_queued_diff;
3362 struct patch_id_t data;
3363 char buffer[PATH_MAX * 4 + 20];
3365 git_SHA1_Init(&ctx);
3366 memset(&data, 0, sizeof(struct patch_id_t));
3369 for (i = 0; i < q->nr; i++) {
3373 struct diff_filepair *p = q->queue[i];
3376 memset(&xpp, 0, sizeof(xpp));
3377 memset(&xecfg, 0, sizeof(xecfg));
3379 return error("internal diff status error");
3380 if (p->status == DIFF_STATUS_UNKNOWN)
3382 if (diff_unmodified_pair(p))
3384 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3385 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3387 if (DIFF_PAIR_UNMERGED(p))
3390 diff_fill_sha1_info(p->one);
3391 diff_fill_sha1_info(p->two);
3392 if (fill_mmfile(&mf1, p->one) < 0 ||
3393 fill_mmfile(&mf2, p->two) < 0)
3394 return error("unable to read files to diff");
3396 len1 = remove_space(p->one->path, strlen(p->one->path));
3397 len2 = remove_space(p->two->path, strlen(p->two->path));
3398 if (p->one->mode == 0)
3399 len1 = snprintf(buffer, sizeof(buffer),
3400 "diff--gita/%.*sb/%.*s"
3407 len2, p->two->path);
3408 else if (p->two->mode == 0)
3409 len1 = snprintf(buffer, sizeof(buffer),
3410 "diff--gita/%.*sb/%.*s"
3411 "deletedfilemode%06o"
3417 len1, p->one->path);
3419 len1 = snprintf(buffer, sizeof(buffer),
3420 "diff--gita/%.*sb/%.*s"
3426 len2, p->two->path);
3427 git_SHA1_Update(&ctx, buffer, len1);
3429 xpp.flags = XDF_NEED_MINIMAL;
3431 xecfg.flags = XDL_EMIT_FUNCNAMES;
3432 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3436 git_SHA1_Final(sha1, &ctx);
3440 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3442 struct diff_queue_struct *q = &diff_queued_diff;
3444 int result = diff_get_patch_id(options, sha1);
3446 for (i = 0; i < q->nr; i++)
3447 diff_free_filepair(q->queue[i]);
3451 q->nr = q->alloc = 0;
3456 static int is_summary_empty(const struct diff_queue_struct *q)
3460 for (i = 0; i < q->nr; i++) {
3461 const struct diff_filepair *p = q->queue[i];
3463 switch (p->status) {
3464 case DIFF_STATUS_DELETED:
3465 case DIFF_STATUS_ADDED:
3466 case DIFF_STATUS_COPIED:
3467 case DIFF_STATUS_RENAMED:
3472 if (p->one->mode && p->two->mode &&
3473 p->one->mode != p->two->mode)
3481 void diff_flush(struct diff_options *options)
3483 struct diff_queue_struct *q = &diff_queued_diff;
3484 int i, output_format = options->output_format;
3488 * Order: raw, stat, summary, patch
3489 * or: name/name-status/checkdiff (other bits clear)
3494 if (output_format & (DIFF_FORMAT_RAW |
3496 DIFF_FORMAT_NAME_STATUS |
3497 DIFF_FORMAT_CHECKDIFF)) {
3498 for (i = 0; i < q->nr; i++) {
3499 struct diff_filepair *p = q->queue[i];
3500 if (check_pair_status(p))
3501 flush_one_pair(p, options);
3506 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3507 struct diffstat_t diffstat;
3509 memset(&diffstat, 0, sizeof(struct diffstat_t));
3510 for (i = 0; i < q->nr; i++) {
3511 struct diff_filepair *p = q->queue[i];
3512 if (check_pair_status(p))
3513 diff_flush_stat(p, options, &diffstat);
3515 if (output_format & DIFF_FORMAT_NUMSTAT)
3516 show_numstat(&diffstat, options);
3517 if (output_format & DIFF_FORMAT_DIFFSTAT)
3518 show_stats(&diffstat, options);
3519 if (output_format & DIFF_FORMAT_SHORTSTAT)
3520 show_shortstats(&diffstat, options);
3521 free_diffstat_info(&diffstat);
3524 if (output_format & DIFF_FORMAT_DIRSTAT)
3525 show_dirstat(options);
3527 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3528 for (i = 0; i < q->nr; i++)
3529 diff_summary(options->file, q->queue[i]);
3533 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3534 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3535 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3537 * run diff_flush_patch for the exit status. setting
3538 * options->file to /dev/null should be safe, becaue we
3539 * aren't supposed to produce any output anyway.
3541 if (options->close_file)
3542 fclose(options->file);
3543 options->file = fopen("/dev/null", "w");
3545 die_errno("Could not open /dev/null");
3546 options->close_file = 1;
3547 for (i = 0; i < q->nr; i++) {
3548 struct diff_filepair *p = q->queue[i];
3549 if (check_pair_status(p))
3550 diff_flush_patch(p, options);
3551 if (options->found_changes)
3556 if (output_format & DIFF_FORMAT_PATCH) {
3558 putc(options->line_termination, options->file);
3559 if (options->stat_sep) {
3560 /* attach patch instead of inline */
3561 fputs(options->stat_sep, options->file);
3565 for (i = 0; i < q->nr; i++) {
3566 struct diff_filepair *p = q->queue[i];
3567 if (check_pair_status(p))
3568 diff_flush_patch(p, options);
3572 if (output_format & DIFF_FORMAT_CALLBACK)
3573 options->format_callback(q, options, options->format_callback_data);
3575 for (i = 0; i < q->nr; i++)
3576 diff_free_filepair(q->queue[i]);
3580 q->nr = q->alloc = 0;
3581 if (options->close_file)
3582 fclose(options->file);
3585 * Report the content-level differences with HAS_CHANGES;
3586 * diff_addremove/diff_change does not set the bit when
3587 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3589 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3590 if (options->found_changes)
3591 DIFF_OPT_SET(options, HAS_CHANGES);
3593 DIFF_OPT_CLR(options, HAS_CHANGES);
3597 static void diffcore_apply_filter(const char *filter)
3600 struct diff_queue_struct *q = &diff_queued_diff;
3601 struct diff_queue_struct outq;
3603 outq.nr = outq.alloc = 0;
3608 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3610 for (i = found = 0; !found && i < q->nr; i++) {
3611 struct diff_filepair *p = q->queue[i];
3612 if (((p->status == DIFF_STATUS_MODIFIED) &&
3614 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3616 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3617 ((p->status != DIFF_STATUS_MODIFIED) &&
3618 strchr(filter, p->status)))
3624 /* otherwise we will clear the whole queue
3625 * by copying the empty outq at the end of this
3626 * function, but first clear the current entries
3629 for (i = 0; i < q->nr; i++)
3630 diff_free_filepair(q->queue[i]);
3633 /* Only the matching ones */
3634 for (i = 0; i < q->nr; i++) {
3635 struct diff_filepair *p = q->queue[i];
3637 if (((p->status == DIFF_STATUS_MODIFIED) &&
3639 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3641 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3642 ((p->status != DIFF_STATUS_MODIFIED) &&
3643 strchr(filter, p->status)))
3646 diff_free_filepair(p);
3653 /* Check whether two filespecs with the same mode and size are identical */
3654 static int diff_filespec_is_identical(struct diff_filespec *one,
3655 struct diff_filespec *two)
3657 if (S_ISGITLINK(one->mode))
3659 if (diff_populate_filespec(one, 0))
3661 if (diff_populate_filespec(two, 0))
3663 return !memcmp(one->data, two->data, one->size);
3666 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3669 struct diff_queue_struct *q = &diff_queued_diff;
3670 struct diff_queue_struct outq;
3672 outq.nr = outq.alloc = 0;
3674 for (i = 0; i < q->nr; i++) {
3675 struct diff_filepair *p = q->queue[i];
3678 * 1. Entries that come from stat info dirtiness
3679 * always have both sides (iow, not create/delete),
3680 * one side of the object name is unknown, with
3681 * the same mode and size. Keep the ones that
3682 * do not match these criteria. They have real
3685 * 2. At this point, the file is known to be modified,
3686 * with the same mode and size, and the object
3687 * name of one side is unknown. Need to inspect
3688 * the identical contents.
3690 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3691 !DIFF_FILE_VALID(p->two) ||
3692 (p->one->sha1_valid && p->two->sha1_valid) ||
3693 (p->one->mode != p->two->mode) ||
3694 diff_populate_filespec(p->one, 1) ||
3695 diff_populate_filespec(p->two, 1) ||
3696 (p->one->size != p->two->size) ||
3697 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3701 * The caller can subtract 1 from skip_stat_unmatch
3702 * to determine how many paths were dirty only
3703 * due to stat info mismatch.
3705 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3706 diffopt->skip_stat_unmatch++;
3707 diff_free_filepair(p);
3714 static int diffnamecmp(const void *a_, const void *b_)
3716 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3717 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3718 const char *name_a, *name_b;
3720 name_a = a->one ? a->one->path : a->two->path;
3721 name_b = b->one ? b->one->path : b->two->path;
3722 return strcmp(name_a, name_b);
3725 void diffcore_fix_diff_index(struct diff_options *options)
3727 struct diff_queue_struct *q = &diff_queued_diff;
3728 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3731 void diffcore_std(struct diff_options *options)
3733 if (options->skip_stat_unmatch)
3734 diffcore_skip_stat_unmatch(options);
3735 if (options->break_opt != -1)
3736 diffcore_break(options->break_opt);
3737 if (options->detect_rename)
3738 diffcore_rename(options);
3739 if (options->break_opt != -1)
3740 diffcore_merge_broken();
3741 if (options->pickaxe)
3742 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3743 if (options->orderfile)
3744 diffcore_order(options->orderfile);
3745 diff_resolve_rename_copy();
3746 diffcore_apply_filter(options->filter);
3748 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3749 DIFF_OPT_SET(options, HAS_CHANGES);
3751 DIFF_OPT_CLR(options, HAS_CHANGES);
3754 int diff_result_code(struct diff_options *opt, int status)
3757 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3758 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3760 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3761 DIFF_OPT_TST(opt, HAS_CHANGES))
3763 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3764 DIFF_OPT_TST(opt, CHECK_FAILED))
3769 void diff_addremove(struct diff_options *options,
3770 int addremove, unsigned mode,
3771 const unsigned char *sha1,
3772 const char *concatpath, unsigned dirty_submodule)
3774 struct diff_filespec *one, *two;
3776 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3779 /* This may look odd, but it is a preparation for
3780 * feeding "there are unchanged files which should
3781 * not produce diffs, but when you are doing copy
3782 * detection you would need them, so here they are"
3783 * entries to the diff-core. They will be prefixed
3784 * with something like '=' or '*' (I haven't decided
3785 * which but should not make any difference).
3786 * Feeding the same new and old to diff_change()
3787 * also has the same effect.
3788 * Before the final output happens, they are pruned after
3789 * merged into rename/copy pairs as appropriate.
3791 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3792 addremove = (addremove == '+' ? '-' :
3793 addremove == '-' ? '+' : addremove);
3795 if (options->prefix &&
3796 strncmp(concatpath, options->prefix, options->prefix_length))
3799 one = alloc_filespec(concatpath);
3800 two = alloc_filespec(concatpath);
3802 if (addremove != '+')
3803 fill_filespec(one, sha1, mode);
3804 if (addremove != '-') {
3805 fill_filespec(two, sha1, mode);
3806 two->dirty_submodule = dirty_submodule;
3809 diff_queue(&diff_queued_diff, one, two);
3810 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3811 DIFF_OPT_SET(options, HAS_CHANGES);
3814 void diff_change(struct diff_options *options,
3815 unsigned old_mode, unsigned new_mode,
3816 const unsigned char *old_sha1,
3817 const unsigned char *new_sha1,
3818 const char *concatpath,
3819 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3821 struct diff_filespec *one, *two;
3823 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3824 && S_ISGITLINK(new_mode))
3827 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3829 const unsigned char *tmp_c;
3830 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3831 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3832 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3833 new_dirty_submodule = tmp;
3836 if (options->prefix &&
3837 strncmp(concatpath, options->prefix, options->prefix_length))
3840 one = alloc_filespec(concatpath);
3841 two = alloc_filespec(concatpath);
3842 fill_filespec(one, old_sha1, old_mode);
3843 fill_filespec(two, new_sha1, new_mode);
3844 one->dirty_submodule = old_dirty_submodule;
3845 two->dirty_submodule = new_dirty_submodule;
3847 diff_queue(&diff_queued_diff, one, two);
3848 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3849 DIFF_OPT_SET(options, HAS_CHANGES);
3852 void diff_unmerge(struct diff_options *options,
3854 unsigned mode, const unsigned char *sha1)
3856 struct diff_filespec *one, *two;
3858 if (options->prefix &&
3859 strncmp(path, options->prefix, options->prefix_length))
3862 one = alloc_filespec(path);
3863 two = alloc_filespec(path);
3864 fill_filespec(one, sha1, mode);
3865 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3868 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3871 struct diff_tempfile *temp;
3872 const char *argv[3];
3873 const char **arg = argv;
3874 struct child_process child;
3875 struct strbuf buf = STRBUF_INIT;
3878 temp = prepare_temp_file(spec->path, spec);
3880 *arg++ = temp->name;
3883 memset(&child, 0, sizeof(child));
3884 child.use_shell = 1;
3887 if (start_command(&child)) {
3892 if (strbuf_read(&buf, child.out, 0) < 0)
3893 err = error("error reading from textconv command '%s'", pgm);
3896 if (finish_command(&child) || err) {
3897 strbuf_release(&buf);
3903 return strbuf_detach(&buf, outsize);
3906 static size_t fill_textconv(struct userdiff_driver *driver,
3907 struct diff_filespec *df,
3912 if (!driver || !driver->textconv) {
3913 if (!DIFF_FILE_VALID(df)) {
3917 if (diff_populate_filespec(df, 0))
3918 die("unable to read files to diff");
3923 if (driver->textconv_cache) {
3924 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
3930 *outbuf = run_textconv(driver->textconv, df, &size);
3932 die("unable to read files to diff");
3934 if (driver->textconv_cache) {
3935 /* ignore errors, as we might be in a readonly repository */
3936 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
3939 * we could save up changes and flush them all at the end,
3940 * but we would need an extra call after all diffing is done.
3941 * Since generating a cache entry is the slow path anyway,
3942 * this extra overhead probably isn't a big deal.
3944 notes_cache_write(driver->textconv_cache);