core.hidedotfiles: hide '.git' dir by default
[git/dscho.git] / diff.c
blobfef9ab7aa4d1d4cd6c1b2c81f0a124bbcf63f3d7
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
15 #include "sigchain.h"
16 #include "submodule.h"
17 #include "ll-merge.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
21 #else
22 #define FAST_WORKING_DIRECTORY 1
23 #endif
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 200;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
34 static char diff_colors[][COLOR_MAXLEN] = {
35 GIT_COLOR_RESET,
36 GIT_COLOR_NORMAL, /* PLAIN */
37 GIT_COLOR_BOLD, /* METAINFO */
38 GIT_COLOR_CYAN, /* FRAGINFO */
39 GIT_COLOR_RED, /* OLD */
40 GIT_COLOR_GREEN, /* NEW */
41 GIT_COLOR_YELLOW, /* COMMIT */
42 GIT_COLOR_BG_RED, /* WHITESPACE */
43 GIT_COLOR_NORMAL, /* FUNCINFO */
46 static void diff_filespec_load_driver(struct diff_filespec *one);
47 static size_t fill_textconv(struct userdiff_driver *driver,
48 struct diff_filespec *df, char **outbuf);
50 static int parse_diff_color_slot(const char *var, int ofs)
52 if (!strcasecmp(var+ofs, "plain"))
53 return DIFF_PLAIN;
54 if (!strcasecmp(var+ofs, "meta"))
55 return DIFF_METAINFO;
56 if (!strcasecmp(var+ofs, "frag"))
57 return DIFF_FRAGINFO;
58 if (!strcasecmp(var+ofs, "old"))
59 return DIFF_FILE_OLD;
60 if (!strcasecmp(var+ofs, "new"))
61 return DIFF_FILE_NEW;
62 if (!strcasecmp(var+ofs, "commit"))
63 return DIFF_COMMIT;
64 if (!strcasecmp(var+ofs, "whitespace"))
65 return DIFF_WHITESPACE;
66 if (!strcasecmp(var+ofs, "func"))
67 return DIFF_FUNCINFO;
68 return -1;
71 static int git_config_rename(const char *var, const char *value)
73 if (!value)
74 return DIFF_DETECT_RENAME;
75 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
76 return DIFF_DETECT_COPY;
77 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
81 * These are to give UI layer defaults.
82 * The core-level commands such as git-diff-files should
83 * never be affected by the setting of diff.renames
84 * the user happens to have in the configuration file.
86 int git_diff_ui_config(const char *var, const char *value, void *cb)
88 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
89 diff_use_color_default = git_config_colorbool(var, value, -1);
90 return 0;
92 if (!strcmp(var, "diff.renames")) {
93 diff_detect_rename_default = git_config_rename(var, value);
94 return 0;
96 if (!strcmp(var, "diff.autorefreshindex")) {
97 diff_auto_refresh_index = git_config_bool(var, value);
98 return 0;
100 if (!strcmp(var, "diff.mnemonicprefix")) {
101 diff_mnemonic_prefix = git_config_bool(var, value);
102 return 0;
104 if (!strcmp(var, "diff.external"))
105 return git_config_string(&external_diff_cmd_cfg, var, value);
106 if (!strcmp(var, "diff.wordregex"))
107 return git_config_string(&diff_word_regex_cfg, var, value);
109 return git_diff_basic_config(var, value, cb);
112 int git_diff_basic_config(const char *var, const char *value, void *cb)
114 if (!strcmp(var, "diff.renamelimit")) {
115 diff_rename_limit_default = git_config_int(var, value);
116 return 0;
119 switch (userdiff_config(var, value)) {
120 case 0: break;
121 case -1: return -1;
122 default: return 0;
125 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
126 int slot = parse_diff_color_slot(var, 11);
127 if (slot < 0)
128 return 0;
129 if (!value)
130 return config_error_nonbool(var);
131 color_parse(value, var, diff_colors[slot]);
132 return 0;
135 /* like GNU diff's --suppress-blank-empty option */
136 if (!strcmp(var, "diff.suppressblankempty") ||
137 /* for backwards compatibility */
138 !strcmp(var, "diff.suppress-blank-empty")) {
139 diff_suppress_blank_empty = git_config_bool(var, value);
140 return 0;
143 return git_color_default_config(var, value, cb);
146 static char *quote_two(const char *one, const char *two)
148 int need_one = quote_c_style(one, NULL, NULL, 1);
149 int need_two = quote_c_style(two, NULL, NULL, 1);
150 struct strbuf res = STRBUF_INIT;
152 if (need_one + need_two) {
153 strbuf_addch(&res, '"');
154 quote_c_style(one, &res, NULL, 1);
155 quote_c_style(two, &res, NULL, 1);
156 strbuf_addch(&res, '"');
157 } else {
158 strbuf_addstr(&res, one);
159 strbuf_addstr(&res, two);
161 return strbuf_detach(&res, NULL);
164 static const char *external_diff(void)
166 static const char *external_diff_cmd = NULL;
167 static int done_preparing = 0;
169 if (done_preparing)
170 return external_diff_cmd;
171 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
172 if (!external_diff_cmd)
173 external_diff_cmd = external_diff_cmd_cfg;
174 done_preparing = 1;
175 return external_diff_cmd;
178 static struct diff_tempfile {
179 const char *name; /* filename external diff should read from */
180 char hex[41];
181 char mode[10];
182 char tmp_path[PATH_MAX];
183 } diff_temp[2];
185 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
187 struct emit_callback {
188 int color_diff;
189 unsigned ws_rule;
190 int blank_at_eof_in_preimage;
191 int blank_at_eof_in_postimage;
192 int lno_in_preimage;
193 int lno_in_postimage;
194 sane_truncate_fn truncate;
195 const char **label_path;
196 struct diff_words_data *diff_words;
197 int *found_changesp;
198 FILE *file;
199 struct strbuf *header;
202 static int count_lines(const char *data, int size)
204 int count, ch, completely_empty = 1, nl_just_seen = 0;
205 count = 0;
206 while (0 < size--) {
207 ch = *data++;
208 if (ch == '\n') {
209 count++;
210 nl_just_seen = 1;
211 completely_empty = 0;
213 else {
214 nl_just_seen = 0;
215 completely_empty = 0;
218 if (completely_empty)
219 return 0;
220 if (!nl_just_seen)
221 count++; /* no trailing newline */
222 return count;
225 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
227 if (!DIFF_FILE_VALID(one)) {
228 mf->ptr = (char *)""; /* does not matter */
229 mf->size = 0;
230 return 0;
232 else if (diff_populate_filespec(one, 0))
233 return -1;
235 mf->ptr = one->data;
236 mf->size = one->size;
237 return 0;
240 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
242 char *ptr = mf->ptr;
243 long size = mf->size;
244 int cnt = 0;
246 if (!size)
247 return cnt;
248 ptr += size - 1; /* pointing at the very end */
249 if (*ptr != '\n')
250 ; /* incomplete line */
251 else
252 ptr--; /* skip the last LF */
253 while (mf->ptr < ptr) {
254 char *prev_eol;
255 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
256 if (*prev_eol == '\n')
257 break;
258 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
259 break;
260 cnt++;
261 ptr = prev_eol - 1;
263 return cnt;
266 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
267 struct emit_callback *ecbdata)
269 int l1, l2, at;
270 unsigned ws_rule = ecbdata->ws_rule;
271 l1 = count_trailing_blank(mf1, ws_rule);
272 l2 = count_trailing_blank(mf2, ws_rule);
273 if (l2 <= l1) {
274 ecbdata->blank_at_eof_in_preimage = 0;
275 ecbdata->blank_at_eof_in_postimage = 0;
276 return;
278 at = count_lines(mf1->ptr, mf1->size);
279 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
281 at = count_lines(mf2->ptr, mf2->size);
282 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
285 static void emit_line_0(FILE *file, const char *set, const char *reset,
286 int first, const char *line, int len)
288 int has_trailing_newline, has_trailing_carriage_return;
289 int nofirst;
291 if (len == 0) {
292 has_trailing_newline = (first == '\n');
293 has_trailing_carriage_return = (!has_trailing_newline &&
294 (first == '\r'));
295 nofirst = has_trailing_newline || has_trailing_carriage_return;
296 } else {
297 has_trailing_newline = (len > 0 && line[len-1] == '\n');
298 if (has_trailing_newline)
299 len--;
300 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
301 if (has_trailing_carriage_return)
302 len--;
303 nofirst = 0;
306 if (len || !nofirst) {
307 fputs(set, file);
308 if (!nofirst)
309 fputc(first, file);
310 fwrite(line, len, 1, file);
311 fputs(reset, file);
313 if (has_trailing_carriage_return)
314 fputc('\r', file);
315 if (has_trailing_newline)
316 fputc('\n', file);
319 static void emit_line(FILE *file, const char *set, const char *reset,
320 const char *line, int len)
322 emit_line_0(file, set, reset, line[0], line+1, len-1);
325 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
327 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
328 ecbdata->blank_at_eof_in_preimage &&
329 ecbdata->blank_at_eof_in_postimage &&
330 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
331 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
332 return 0;
333 return ws_blank_line(line, len, ecbdata->ws_rule);
336 static void emit_add_line(const char *reset,
337 struct emit_callback *ecbdata,
338 const char *line, int len)
340 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
341 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
343 if (!*ws)
344 emit_line_0(ecbdata->file, set, reset, '+', line, len);
345 else if (new_blank_line_at_eof(ecbdata, line, len))
346 /* Blank line at EOF - paint '+' as well */
347 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
348 else {
349 /* Emit just the prefix, then the rest. */
350 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
351 ws_check_emit(line, len, ecbdata->ws_rule,
352 ecbdata->file, set, reset, ws);
356 static void emit_hunk_header(struct emit_callback *ecbdata,
357 const char *line, int len)
359 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
360 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
361 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
362 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
363 static const char atat[2] = { '@', '@' };
364 const char *cp, *ep;
367 * As a hunk header must begin with "@@ -<old>, +<new> @@",
368 * it always is at least 10 bytes long.
370 if (len < 10 ||
371 memcmp(line, atat, 2) ||
372 !(ep = memmem(line + 2, len - 2, atat, 2))) {
373 emit_line(ecbdata->file, plain, reset, line, len);
374 return;
376 ep += 2; /* skip over @@ */
378 /* The hunk header in fraginfo color */
379 emit_line(ecbdata->file, frag, reset, line, ep - line);
381 /* blank before the func header */
382 for (cp = ep; ep - line < len; ep++)
383 if (*ep != ' ' && *ep != '\t')
384 break;
385 if (ep != cp)
386 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
388 if (ep < line + len)
389 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
392 static struct diff_tempfile *claim_diff_tempfile(void) {
393 int i;
394 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
395 if (!diff_temp[i].name)
396 return diff_temp + i;
397 die("BUG: diff is failing to clean up its tempfiles");
400 static int remove_tempfile_installed;
402 static void remove_tempfile(void)
404 int i;
405 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
406 if (diff_temp[i].name == diff_temp[i].tmp_path)
407 unlink_or_warn(diff_temp[i].name);
408 diff_temp[i].name = NULL;
412 static void remove_tempfile_on_signal(int signo)
414 remove_tempfile();
415 sigchain_pop(signo);
416 raise(signo);
419 static void print_line_count(FILE *file, int count)
421 switch (count) {
422 case 0:
423 fprintf(file, "0,0");
424 break;
425 case 1:
426 fprintf(file, "1");
427 break;
428 default:
429 fprintf(file, "1,%d", count);
430 break;
434 static void emit_rewrite_lines(struct emit_callback *ecb,
435 int prefix, const char *data, int size)
437 const char *endp = NULL;
438 static const char *nneof = " No newline at end of file\n";
439 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
440 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
442 while (0 < size) {
443 int len;
445 endp = memchr(data, '\n', size);
446 len = endp ? (endp - data + 1) : size;
447 if (prefix != '+') {
448 ecb->lno_in_preimage++;
449 emit_line_0(ecb->file, old, reset, '-',
450 data, len);
451 } else {
452 ecb->lno_in_postimage++;
453 emit_add_line(reset, ecb, data, len);
455 size -= len;
456 data += len;
458 if (!endp) {
459 const char *plain = diff_get_color(ecb->color_diff,
460 DIFF_PLAIN);
461 emit_line_0(ecb->file, plain, reset, '\\',
462 nneof, strlen(nneof));
466 static void emit_rewrite_diff(const char *name_a,
467 const char *name_b,
468 struct diff_filespec *one,
469 struct diff_filespec *two,
470 struct userdiff_driver *textconv_one,
471 struct userdiff_driver *textconv_two,
472 struct diff_options *o)
474 int lc_a, lc_b;
475 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
476 const char *name_a_tab, *name_b_tab;
477 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
478 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
479 const char *reset = diff_get_color(color_diff, DIFF_RESET);
480 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
481 const char *a_prefix, *b_prefix;
482 char *data_one, *data_two;
483 size_t size_one, size_two;
484 struct emit_callback ecbdata;
486 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
487 a_prefix = o->b_prefix;
488 b_prefix = o->a_prefix;
489 } else {
490 a_prefix = o->a_prefix;
491 b_prefix = o->b_prefix;
494 name_a += (*name_a == '/');
495 name_b += (*name_b == '/');
496 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
497 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
499 strbuf_reset(&a_name);
500 strbuf_reset(&b_name);
501 quote_two_c_style(&a_name, a_prefix, name_a, 0);
502 quote_two_c_style(&b_name, b_prefix, name_b, 0);
504 size_one = fill_textconv(textconv_one, one, &data_one);
505 size_two = fill_textconv(textconv_two, two, &data_two);
507 memset(&ecbdata, 0, sizeof(ecbdata));
508 ecbdata.color_diff = color_diff;
509 ecbdata.found_changesp = &o->found_changes;
510 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
511 ecbdata.file = o->file;
512 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
513 mmfile_t mf1, mf2;
514 mf1.ptr = (char *)data_one;
515 mf2.ptr = (char *)data_two;
516 mf1.size = size_one;
517 mf2.size = size_two;
518 check_blank_at_eof(&mf1, &mf2, &ecbdata);
520 ecbdata.lno_in_preimage = 1;
521 ecbdata.lno_in_postimage = 1;
523 lc_a = count_lines(data_one, size_one);
524 lc_b = count_lines(data_two, size_two);
525 fprintf(o->file,
526 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
527 metainfo, a_name.buf, name_a_tab, reset,
528 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
529 print_line_count(o->file, lc_a);
530 fprintf(o->file, " +");
531 print_line_count(o->file, lc_b);
532 fprintf(o->file, " @@%s\n", reset);
533 if (lc_a)
534 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
535 if (lc_b)
536 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
537 if (textconv_one)
538 free((char *)data_one);
539 if (textconv_two)
540 free((char *)data_two);
543 struct diff_words_buffer {
544 mmfile_t text;
545 long alloc;
546 struct diff_words_orig {
547 const char *begin, *end;
548 } *orig;
549 int orig_nr, orig_alloc;
552 static void diff_words_append(char *line, unsigned long len,
553 struct diff_words_buffer *buffer)
555 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
556 line++;
557 len--;
558 memcpy(buffer->text.ptr + buffer->text.size, line, len);
559 buffer->text.size += len;
560 buffer->text.ptr[buffer->text.size] = '\0';
563 struct diff_words_style_elem
565 const char *prefix;
566 const char *suffix;
567 const char *color; /* NULL; filled in by the setup code if
568 * color is enabled */
571 struct diff_words_style
573 enum diff_words_type type;
574 struct diff_words_style_elem new, old, ctx;
575 const char *newline;
578 struct diff_words_style diff_words_styles[] = {
579 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
580 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
581 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
584 struct diff_words_data {
585 struct diff_words_buffer minus, plus;
586 const char *current_plus;
587 FILE *file;
588 regex_t *word_regex;
589 enum diff_words_type type;
590 struct diff_words_style *style;
593 static int fn_out_diff_words_write_helper(FILE *fp,
594 struct diff_words_style_elem *st_el,
595 const char *newline,
596 size_t count, const char *buf)
598 while (count) {
599 char *p = memchr(buf, '\n', count);
600 if (p != buf) {
601 if (st_el->color && fputs(st_el->color, fp) < 0)
602 return -1;
603 if (fputs(st_el->prefix, fp) < 0 ||
604 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
605 fputs(st_el->suffix, fp) < 0)
606 return -1;
607 if (st_el->color && *st_el->color
608 && fputs(GIT_COLOR_RESET, fp) < 0)
609 return -1;
611 if (!p)
612 return 0;
613 if (fputs(newline, fp) < 0)
614 return -1;
615 count -= p + 1 - buf;
616 buf = p + 1;
618 return 0;
621 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
623 struct diff_words_data *diff_words = priv;
624 struct diff_words_style *style = diff_words->style;
625 int minus_first, minus_len, plus_first, plus_len;
626 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
628 if (line[0] != '@' || parse_hunk_header(line, len,
629 &minus_first, &minus_len, &plus_first, &plus_len))
630 return;
632 /* POSIX requires that first be decremented by one if len == 0... */
633 if (minus_len) {
634 minus_begin = diff_words->minus.orig[minus_first].begin;
635 minus_end =
636 diff_words->minus.orig[minus_first + minus_len - 1].end;
637 } else
638 minus_begin = minus_end =
639 diff_words->minus.orig[minus_first].end;
641 if (plus_len) {
642 plus_begin = diff_words->plus.orig[plus_first].begin;
643 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
644 } else
645 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
647 if (diff_words->current_plus != plus_begin)
648 fn_out_diff_words_write_helper(diff_words->file,
649 &style->ctx, style->newline,
650 plus_begin - diff_words->current_plus,
651 diff_words->current_plus);
652 if (minus_begin != minus_end)
653 fn_out_diff_words_write_helper(diff_words->file,
654 &style->old, style->newline,
655 minus_end - minus_begin, minus_begin);
656 if (plus_begin != plus_end)
657 fn_out_diff_words_write_helper(diff_words->file,
658 &style->new, style->newline,
659 plus_end - plus_begin, plus_begin);
661 diff_words->current_plus = plus_end;
664 /* This function starts looking at *begin, and returns 0 iff a word was found. */
665 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
666 int *begin, int *end)
668 if (word_regex && *begin < buffer->size) {
669 regmatch_t match[1];
670 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
671 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
672 '\n', match[0].rm_eo - match[0].rm_so);
673 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
674 *begin += match[0].rm_so;
675 return *begin >= *end;
677 return -1;
680 /* find the next word */
681 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
682 (*begin)++;
683 if (*begin >= buffer->size)
684 return -1;
686 /* find the end of the word */
687 *end = *begin + 1;
688 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
689 (*end)++;
691 return 0;
695 * This function splits the words in buffer->text, stores the list with
696 * newline separator into out, and saves the offsets of the original words
697 * in buffer->orig.
699 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
700 regex_t *word_regex)
702 int i, j;
703 long alloc = 0;
705 out->size = 0;
706 out->ptr = NULL;
708 /* fake an empty "0th" word */
709 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
710 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
711 buffer->orig_nr = 1;
713 for (i = 0; i < buffer->text.size; i++) {
714 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
715 return;
717 /* store original boundaries */
718 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
719 buffer->orig_alloc);
720 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
721 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
722 buffer->orig_nr++;
724 /* store one word */
725 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
726 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
727 out->ptr[out->size + j - i] = '\n';
728 out->size += j - i + 1;
730 i = j - 1;
734 /* this executes the word diff on the accumulated buffers */
735 static void diff_words_show(struct diff_words_data *diff_words)
737 xpparam_t xpp;
738 xdemitconf_t xecfg;
739 xdemitcb_t ecb;
740 mmfile_t minus, plus;
741 struct diff_words_style *style = diff_words->style;
743 /* special case: only removal */
744 if (!diff_words->plus.text.size) {
745 fn_out_diff_words_write_helper(diff_words->file,
746 &style->old, style->newline,
747 diff_words->minus.text.size, diff_words->minus.text.ptr);
748 diff_words->minus.text.size = 0;
749 return;
752 diff_words->current_plus = diff_words->plus.text.ptr;
754 memset(&xpp, 0, sizeof(xpp));
755 memset(&xecfg, 0, sizeof(xecfg));
756 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
757 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
758 xpp.flags = XDF_NEED_MINIMAL;
759 /* as only the hunk header will be parsed, we need a 0-context */
760 xecfg.ctxlen = 0;
761 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
762 &xpp, &xecfg, &ecb);
763 free(minus.ptr);
764 free(plus.ptr);
765 if (diff_words->current_plus != diff_words->plus.text.ptr +
766 diff_words->plus.text.size)
767 fn_out_diff_words_write_helper(diff_words->file,
768 &style->ctx, style->newline,
769 diff_words->plus.text.ptr + diff_words->plus.text.size
770 - diff_words->current_plus, diff_words->current_plus);
771 diff_words->minus.text.size = diff_words->plus.text.size = 0;
774 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
775 static void diff_words_flush(struct emit_callback *ecbdata)
777 if (ecbdata->diff_words->minus.text.size ||
778 ecbdata->diff_words->plus.text.size)
779 diff_words_show(ecbdata->diff_words);
782 static void free_diff_words_data(struct emit_callback *ecbdata)
784 if (ecbdata->diff_words) {
785 diff_words_flush(ecbdata);
786 free (ecbdata->diff_words->minus.text.ptr);
787 free (ecbdata->diff_words->minus.orig);
788 free (ecbdata->diff_words->plus.text.ptr);
789 free (ecbdata->diff_words->plus.orig);
790 free(ecbdata->diff_words->word_regex);
791 free(ecbdata->diff_words);
792 ecbdata->diff_words = NULL;
796 const char *diff_get_color(int diff_use_color, enum color_diff ix)
798 if (diff_use_color)
799 return diff_colors[ix];
800 return "";
803 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
805 const char *cp;
806 unsigned long allot;
807 size_t l = len;
809 if (ecb->truncate)
810 return ecb->truncate(line, len);
811 cp = line;
812 allot = l;
813 while (0 < l) {
814 (void) utf8_width(&cp, &l);
815 if (!cp)
816 break; /* truncated in the middle? */
818 return allot - l;
821 static void find_lno(const char *line, struct emit_callback *ecbdata)
823 const char *p;
824 ecbdata->lno_in_preimage = 0;
825 ecbdata->lno_in_postimage = 0;
826 p = strchr(line, '-');
827 if (!p)
828 return; /* cannot happen */
829 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
830 p = strchr(p, '+');
831 if (!p)
832 return; /* cannot happen */
833 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
836 static void fn_out_consume(void *priv, char *line, unsigned long len)
838 struct emit_callback *ecbdata = priv;
839 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
840 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
841 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
843 if (ecbdata->header) {
844 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
845 strbuf_reset(ecbdata->header);
846 ecbdata->header = NULL;
848 *(ecbdata->found_changesp) = 1;
850 if (ecbdata->label_path[0]) {
851 const char *name_a_tab, *name_b_tab;
853 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
854 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
856 fprintf(ecbdata->file, "%s--- %s%s%s\n",
857 meta, ecbdata->label_path[0], reset, name_a_tab);
858 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
859 meta, ecbdata->label_path[1], reset, name_b_tab);
860 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
863 if (diff_suppress_blank_empty
864 && len == 2 && line[0] == ' ' && line[1] == '\n') {
865 line[0] = '\n';
866 len = 1;
869 if (line[0] == '@') {
870 if (ecbdata->diff_words)
871 diff_words_flush(ecbdata);
872 len = sane_truncate_line(ecbdata, line, len);
873 find_lno(line, ecbdata);
874 emit_hunk_header(ecbdata, line, len);
875 if (line[len-1] != '\n')
876 putc('\n', ecbdata->file);
877 return;
880 if (len < 1) {
881 emit_line(ecbdata->file, reset, reset, line, len);
882 if (ecbdata->diff_words
883 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
884 fputs("~\n", ecbdata->file);
885 return;
888 if (ecbdata->diff_words) {
889 if (line[0] == '-') {
890 diff_words_append(line, len,
891 &ecbdata->diff_words->minus);
892 return;
893 } else if (line[0] == '+') {
894 diff_words_append(line, len,
895 &ecbdata->diff_words->plus);
896 return;
898 diff_words_flush(ecbdata);
899 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
900 emit_line(ecbdata->file, plain, reset, line, len);
901 fputs("~\n", ecbdata->file);
902 } else {
903 /* don't print the prefix character */
904 emit_line(ecbdata->file, plain, reset, line+1, len-1);
906 return;
909 if (line[0] != '+') {
910 const char *color =
911 diff_get_color(ecbdata->color_diff,
912 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
913 ecbdata->lno_in_preimage++;
914 if (line[0] == ' ')
915 ecbdata->lno_in_postimage++;
916 emit_line(ecbdata->file, color, reset, line, len);
917 } else {
918 ecbdata->lno_in_postimage++;
919 emit_add_line(reset, ecbdata, line + 1, len - 1);
923 static char *pprint_rename(const char *a, const char *b)
925 const char *old = a;
926 const char *new = b;
927 struct strbuf name = STRBUF_INIT;
928 int pfx_length, sfx_length;
929 int len_a = strlen(a);
930 int len_b = strlen(b);
931 int a_midlen, b_midlen;
932 int qlen_a = quote_c_style(a, NULL, NULL, 0);
933 int qlen_b = quote_c_style(b, NULL, NULL, 0);
935 if (qlen_a || qlen_b) {
936 quote_c_style(a, &name, NULL, 0);
937 strbuf_addstr(&name, " => ");
938 quote_c_style(b, &name, NULL, 0);
939 return strbuf_detach(&name, NULL);
942 /* Find common prefix */
943 pfx_length = 0;
944 while (*old && *new && *old == *new) {
945 if (*old == '/')
946 pfx_length = old - a + 1;
947 old++;
948 new++;
951 /* Find common suffix */
952 old = a + len_a;
953 new = b + len_b;
954 sfx_length = 0;
955 while (a <= old && b <= new && *old == *new) {
956 if (*old == '/')
957 sfx_length = len_a - (old - a);
958 old--;
959 new--;
963 * pfx{mid-a => mid-b}sfx
964 * {pfx-a => pfx-b}sfx
965 * pfx{sfx-a => sfx-b}
966 * name-a => name-b
968 a_midlen = len_a - pfx_length - sfx_length;
969 b_midlen = len_b - pfx_length - sfx_length;
970 if (a_midlen < 0)
971 a_midlen = 0;
972 if (b_midlen < 0)
973 b_midlen = 0;
975 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
976 if (pfx_length + sfx_length) {
977 strbuf_add(&name, a, pfx_length);
978 strbuf_addch(&name, '{');
980 strbuf_add(&name, a + pfx_length, a_midlen);
981 strbuf_addstr(&name, " => ");
982 strbuf_add(&name, b + pfx_length, b_midlen);
983 if (pfx_length + sfx_length) {
984 strbuf_addch(&name, '}');
985 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
987 return strbuf_detach(&name, NULL);
990 struct diffstat_t {
991 int nr;
992 int alloc;
993 struct diffstat_file {
994 char *from_name;
995 char *name;
996 char *print_name;
997 unsigned is_unmerged:1;
998 unsigned is_binary:1;
999 unsigned is_renamed:1;
1000 uintmax_t added, deleted;
1001 } **files;
1004 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1005 const char *name_a,
1006 const char *name_b)
1008 struct diffstat_file *x;
1009 x = xcalloc(sizeof (*x), 1);
1010 if (diffstat->nr == diffstat->alloc) {
1011 diffstat->alloc = alloc_nr(diffstat->alloc);
1012 diffstat->files = xrealloc(diffstat->files,
1013 diffstat->alloc * sizeof(x));
1015 diffstat->files[diffstat->nr++] = x;
1016 if (name_b) {
1017 x->from_name = xstrdup(name_a);
1018 x->name = xstrdup(name_b);
1019 x->is_renamed = 1;
1021 else {
1022 x->from_name = NULL;
1023 x->name = xstrdup(name_a);
1025 return x;
1028 static void diffstat_consume(void *priv, char *line, unsigned long len)
1030 struct diffstat_t *diffstat = priv;
1031 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1033 if (line[0] == '+')
1034 x->added++;
1035 else if (line[0] == '-')
1036 x->deleted++;
1039 const char mime_boundary_leader[] = "------------";
1041 static int scale_linear(int it, int width, int max_change)
1044 * make sure that at least one '-' is printed if there were deletions,
1045 * and likewise for '+'.
1047 if (max_change < 2)
1048 return it;
1049 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1052 static void show_name(FILE *file,
1053 const char *prefix, const char *name, int len)
1055 fprintf(file, " %s%-*s |", prefix, len, name);
1058 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1060 if (cnt <= 0)
1061 return;
1062 fprintf(file, "%s", set);
1063 while (cnt--)
1064 putc(ch, file);
1065 fprintf(file, "%s", reset);
1068 static void fill_print_name(struct diffstat_file *file)
1070 char *pname;
1072 if (file->print_name)
1073 return;
1075 if (!file->is_renamed) {
1076 struct strbuf buf = STRBUF_INIT;
1077 if (quote_c_style(file->name, &buf, NULL, 0)) {
1078 pname = strbuf_detach(&buf, NULL);
1079 } else {
1080 pname = file->name;
1081 strbuf_release(&buf);
1083 } else {
1084 pname = pprint_rename(file->from_name, file->name);
1086 file->print_name = pname;
1089 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1091 int i, len, add, del, adds = 0, dels = 0;
1092 uintmax_t max_change = 0, max_len = 0;
1093 int total_files = data->nr;
1094 int width, name_width;
1095 const char *reset, *set, *add_c, *del_c;
1097 if (data->nr == 0)
1098 return;
1100 width = options->stat_width ? options->stat_width : 80;
1101 name_width = options->stat_name_width ? options->stat_name_width : 50;
1103 /* Sanity: give at least 5 columns to the graph,
1104 * but leave at least 10 columns for the name.
1106 if (width < 25)
1107 width = 25;
1108 if (name_width < 10)
1109 name_width = 10;
1110 else if (width < name_width + 15)
1111 name_width = width - 15;
1113 /* Find the longest filename and max number of changes */
1114 reset = diff_get_color_opt(options, DIFF_RESET);
1115 set = diff_get_color_opt(options, DIFF_PLAIN);
1116 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1117 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1119 for (i = 0; i < data->nr; i++) {
1120 struct diffstat_file *file = data->files[i];
1121 uintmax_t change = file->added + file->deleted;
1122 fill_print_name(file);
1123 len = strlen(file->print_name);
1124 if (max_len < len)
1125 max_len = len;
1127 if (file->is_binary || file->is_unmerged)
1128 continue;
1129 if (max_change < change)
1130 max_change = change;
1133 /* Compute the width of the graph part;
1134 * 10 is for one blank at the beginning of the line plus
1135 * " | count " between the name and the graph.
1137 * From here on, name_width is the width of the name area,
1138 * and width is the width of the graph area.
1140 name_width = (name_width < max_len) ? name_width : max_len;
1141 if (width < (name_width + 10) + max_change)
1142 width = width - (name_width + 10);
1143 else
1144 width = max_change;
1146 for (i = 0; i < data->nr; i++) {
1147 const char *prefix = "";
1148 char *name = data->files[i]->print_name;
1149 uintmax_t added = data->files[i]->added;
1150 uintmax_t deleted = data->files[i]->deleted;
1151 int name_len;
1154 * "scale" the filename
1156 len = name_width;
1157 name_len = strlen(name);
1158 if (name_width < name_len) {
1159 char *slash;
1160 prefix = "...";
1161 len -= 3;
1162 name += name_len - len;
1163 slash = strchr(name, '/');
1164 if (slash)
1165 name = slash;
1168 if (data->files[i]->is_binary) {
1169 show_name(options->file, prefix, name, len);
1170 fprintf(options->file, " Bin ");
1171 fprintf(options->file, "%s%"PRIuMAX"%s",
1172 del_c, deleted, reset);
1173 fprintf(options->file, " -> ");
1174 fprintf(options->file, "%s%"PRIuMAX"%s",
1175 add_c, added, reset);
1176 fprintf(options->file, " bytes");
1177 fprintf(options->file, "\n");
1178 continue;
1180 else if (data->files[i]->is_unmerged) {
1181 show_name(options->file, prefix, name, len);
1182 fprintf(options->file, " Unmerged\n");
1183 continue;
1185 else if (!data->files[i]->is_renamed &&
1186 (added + deleted == 0)) {
1187 total_files--;
1188 continue;
1192 * scale the add/delete
1194 add = added;
1195 del = deleted;
1196 adds += add;
1197 dels += del;
1199 if (width <= max_change) {
1200 add = scale_linear(add, width, max_change);
1201 del = scale_linear(del, width, max_change);
1203 show_name(options->file, prefix, name, len);
1204 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1205 added + deleted ? " " : "");
1206 show_graph(options->file, '+', add, add_c, reset);
1207 show_graph(options->file, '-', del, del_c, reset);
1208 fprintf(options->file, "\n");
1210 fprintf(options->file,
1211 " %d files changed, %d insertions(+), %d deletions(-)\n",
1212 total_files, adds, dels);
1215 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1217 int i, adds = 0, dels = 0, total_files = data->nr;
1219 if (data->nr == 0)
1220 return;
1222 for (i = 0; i < data->nr; i++) {
1223 if (!data->files[i]->is_binary &&
1224 !data->files[i]->is_unmerged) {
1225 int added = data->files[i]->added;
1226 int deleted= data->files[i]->deleted;
1227 if (!data->files[i]->is_renamed &&
1228 (added + deleted == 0)) {
1229 total_files--;
1230 } else {
1231 adds += added;
1232 dels += deleted;
1236 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1237 total_files, adds, dels);
1240 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1242 int i;
1244 if (data->nr == 0)
1245 return;
1247 for (i = 0; i < data->nr; i++) {
1248 struct diffstat_file *file = data->files[i];
1250 if (file->is_binary)
1251 fprintf(options->file, "-\t-\t");
1252 else
1253 fprintf(options->file,
1254 "%"PRIuMAX"\t%"PRIuMAX"\t",
1255 file->added, file->deleted);
1256 if (options->line_termination) {
1257 fill_print_name(file);
1258 if (!file->is_renamed)
1259 write_name_quoted(file->name, options->file,
1260 options->line_termination);
1261 else {
1262 fputs(file->print_name, options->file);
1263 putc(options->line_termination, options->file);
1265 } else {
1266 if (file->is_renamed) {
1267 putc('\0', options->file);
1268 write_name_quoted(file->from_name, options->file, '\0');
1270 write_name_quoted(file->name, options->file, '\0');
1275 struct dirstat_file {
1276 const char *name;
1277 unsigned long changed;
1280 struct dirstat_dir {
1281 struct dirstat_file *files;
1282 int alloc, nr, percent, cumulative;
1285 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1287 unsigned long this_dir = 0;
1288 unsigned int sources = 0;
1290 while (dir->nr) {
1291 struct dirstat_file *f = dir->files;
1292 int namelen = strlen(f->name);
1293 unsigned long this;
1294 char *slash;
1296 if (namelen < baselen)
1297 break;
1298 if (memcmp(f->name, base, baselen))
1299 break;
1300 slash = strchr(f->name + baselen, '/');
1301 if (slash) {
1302 int newbaselen = slash + 1 - f->name;
1303 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1304 sources++;
1305 } else {
1306 this = f->changed;
1307 dir->files++;
1308 dir->nr--;
1309 sources += 2;
1311 this_dir += this;
1315 * We don't report dirstat's for
1316 * - the top level
1317 * - or cases where everything came from a single directory
1318 * under this directory (sources == 1).
1320 if (baselen && sources != 1) {
1321 int permille = this_dir * 1000 / changed;
1322 if (permille) {
1323 int percent = permille / 10;
1324 if (percent >= dir->percent) {
1325 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1326 if (!dir->cumulative)
1327 return 0;
1331 return this_dir;
1334 static int dirstat_compare(const void *_a, const void *_b)
1336 const struct dirstat_file *a = _a;
1337 const struct dirstat_file *b = _b;
1338 return strcmp(a->name, b->name);
1341 static void show_dirstat(struct diff_options *options)
1343 int i;
1344 unsigned long changed;
1345 struct dirstat_dir dir;
1346 struct diff_queue_struct *q = &diff_queued_diff;
1348 dir.files = NULL;
1349 dir.alloc = 0;
1350 dir.nr = 0;
1351 dir.percent = options->dirstat_percent;
1352 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1354 changed = 0;
1355 for (i = 0; i < q->nr; i++) {
1356 struct diff_filepair *p = q->queue[i];
1357 const char *name;
1358 unsigned long copied, added, damage;
1360 name = p->one->path ? p->one->path : p->two->path;
1362 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1363 diff_populate_filespec(p->one, 0);
1364 diff_populate_filespec(p->two, 0);
1365 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1366 &copied, &added);
1367 diff_free_filespec_data(p->one);
1368 diff_free_filespec_data(p->two);
1369 } else if (DIFF_FILE_VALID(p->one)) {
1370 diff_populate_filespec(p->one, 1);
1371 copied = added = 0;
1372 diff_free_filespec_data(p->one);
1373 } else if (DIFF_FILE_VALID(p->two)) {
1374 diff_populate_filespec(p->two, 1);
1375 copied = 0;
1376 added = p->two->size;
1377 diff_free_filespec_data(p->two);
1378 } else
1379 continue;
1382 * Original minus copied is the removed material,
1383 * added is the new material. They are both damages
1384 * made to the preimage. In --dirstat-by-file mode, count
1385 * damaged files, not damaged lines. This is done by
1386 * counting only a single damaged line per file.
1388 damage = (p->one->size - copied) + added;
1389 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1390 damage = 1;
1392 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1393 dir.files[dir.nr].name = name;
1394 dir.files[dir.nr].changed = damage;
1395 changed += damage;
1396 dir.nr++;
1399 /* This can happen even with many files, if everything was renames */
1400 if (!changed)
1401 return;
1403 /* Show all directories with more than x% of the changes */
1404 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1405 gather_dirstat(options->file, &dir, changed, "", 0);
1408 static void free_diffstat_info(struct diffstat_t *diffstat)
1410 int i;
1411 for (i = 0; i < diffstat->nr; i++) {
1412 struct diffstat_file *f = diffstat->files[i];
1413 if (f->name != f->print_name)
1414 free(f->print_name);
1415 free(f->name);
1416 free(f->from_name);
1417 free(f);
1419 free(diffstat->files);
1422 struct checkdiff_t {
1423 const char *filename;
1424 int lineno;
1425 int conflict_marker_size;
1426 struct diff_options *o;
1427 unsigned ws_rule;
1428 unsigned status;
1431 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1433 char firstchar;
1434 int cnt;
1436 if (len < marker_size + 1)
1437 return 0;
1438 firstchar = line[0];
1439 switch (firstchar) {
1440 case '=': case '>': case '<': case '|':
1441 break;
1442 default:
1443 return 0;
1445 for (cnt = 1; cnt < marker_size; cnt++)
1446 if (line[cnt] != firstchar)
1447 return 0;
1448 /* line[1] thru line[marker_size-1] are same as firstchar */
1449 if (len < marker_size + 1 || !isspace(line[marker_size]))
1450 return 0;
1451 return 1;
1454 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1456 struct checkdiff_t *data = priv;
1457 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1458 int marker_size = data->conflict_marker_size;
1459 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1460 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1461 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1462 char *err;
1464 if (line[0] == '+') {
1465 unsigned bad;
1466 data->lineno++;
1467 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1468 data->status |= 1;
1469 fprintf(data->o->file,
1470 "%s:%d: leftover conflict marker\n",
1471 data->filename, data->lineno);
1473 bad = ws_check(line + 1, len - 1, data->ws_rule);
1474 if (!bad)
1475 return;
1476 data->status |= bad;
1477 err = whitespace_error_string(bad);
1478 fprintf(data->o->file, "%s:%d: %s.\n",
1479 data->filename, data->lineno, err);
1480 free(err);
1481 emit_line(data->o->file, set, reset, line, 1);
1482 ws_check_emit(line + 1, len - 1, data->ws_rule,
1483 data->o->file, set, reset, ws);
1484 } else if (line[0] == ' ') {
1485 data->lineno++;
1486 } else if (line[0] == '@') {
1487 char *plus = strchr(line, '+');
1488 if (plus)
1489 data->lineno = strtol(plus, NULL, 10) - 1;
1490 else
1491 die("invalid diff");
1495 static unsigned char *deflate_it(char *data,
1496 unsigned long size,
1497 unsigned long *result_size)
1499 int bound;
1500 unsigned char *deflated;
1501 z_stream stream;
1503 memset(&stream, 0, sizeof(stream));
1504 deflateInit(&stream, zlib_compression_level);
1505 bound = deflateBound(&stream, size);
1506 deflated = xmalloc(bound);
1507 stream.next_out = deflated;
1508 stream.avail_out = bound;
1510 stream.next_in = (unsigned char *)data;
1511 stream.avail_in = size;
1512 while (deflate(&stream, Z_FINISH) == Z_OK)
1513 ; /* nothing */
1514 deflateEnd(&stream);
1515 *result_size = stream.total_out;
1516 return deflated;
1519 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1521 void *cp;
1522 void *delta;
1523 void *deflated;
1524 void *data;
1525 unsigned long orig_size;
1526 unsigned long delta_size;
1527 unsigned long deflate_size;
1528 unsigned long data_size;
1530 /* We could do deflated delta, or we could do just deflated two,
1531 * whichever is smaller.
1533 delta = NULL;
1534 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1535 if (one->size && two->size) {
1536 delta = diff_delta(one->ptr, one->size,
1537 two->ptr, two->size,
1538 &delta_size, deflate_size);
1539 if (delta) {
1540 void *to_free = delta;
1541 orig_size = delta_size;
1542 delta = deflate_it(delta, delta_size, &delta_size);
1543 free(to_free);
1547 if (delta && delta_size < deflate_size) {
1548 fprintf(file, "delta %lu\n", orig_size);
1549 free(deflated);
1550 data = delta;
1551 data_size = delta_size;
1553 else {
1554 fprintf(file, "literal %lu\n", two->size);
1555 free(delta);
1556 data = deflated;
1557 data_size = deflate_size;
1560 /* emit data encoded in base85 */
1561 cp = data;
1562 while (data_size) {
1563 int bytes = (52 < data_size) ? 52 : data_size;
1564 char line[70];
1565 data_size -= bytes;
1566 if (bytes <= 26)
1567 line[0] = bytes + 'A' - 1;
1568 else
1569 line[0] = bytes - 26 + 'a' - 1;
1570 encode_85(line + 1, cp, bytes);
1571 cp = (char *) cp + bytes;
1572 fputs(line, file);
1573 fputc('\n', file);
1575 fprintf(file, "\n");
1576 free(data);
1579 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1581 fprintf(file, "GIT binary patch\n");
1582 emit_binary_diff_body(file, one, two);
1583 emit_binary_diff_body(file, two, one);
1586 static void diff_filespec_load_driver(struct diff_filespec *one)
1588 if (!one->driver)
1589 one->driver = userdiff_find_by_path(one->path);
1590 if (!one->driver)
1591 one->driver = userdiff_find_by_name("default");
1594 int diff_filespec_is_binary(struct diff_filespec *one)
1596 if (one->is_binary == -1) {
1597 diff_filespec_load_driver(one);
1598 if (one->driver->binary != -1)
1599 one->is_binary = one->driver->binary;
1600 else {
1601 if (!one->data && DIFF_FILE_VALID(one))
1602 diff_populate_filespec(one, 0);
1603 if (one->data)
1604 one->is_binary = buffer_is_binary(one->data,
1605 one->size);
1606 if (one->is_binary == -1)
1607 one->is_binary = 0;
1610 return one->is_binary;
1613 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1615 diff_filespec_load_driver(one);
1616 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1619 static const char *userdiff_word_regex(struct diff_filespec *one)
1621 diff_filespec_load_driver(one);
1622 return one->driver->word_regex;
1625 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1627 if (!options->a_prefix)
1628 options->a_prefix = a;
1629 if (!options->b_prefix)
1630 options->b_prefix = b;
1633 static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1635 if (!DIFF_FILE_VALID(one))
1636 return NULL;
1637 if (!S_ISREG(one->mode))
1638 return NULL;
1639 diff_filespec_load_driver(one);
1640 if (!one->driver->textconv)
1641 return NULL;
1643 if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1644 struct notes_cache *c = xmalloc(sizeof(*c));
1645 struct strbuf name = STRBUF_INIT;
1647 strbuf_addf(&name, "textconv/%s", one->driver->name);
1648 notes_cache_init(c, name.buf, one->driver->textconv);
1649 one->driver->textconv_cache = c;
1652 return one->driver;
1655 static void builtin_diff(const char *name_a,
1656 const char *name_b,
1657 struct diff_filespec *one,
1658 struct diff_filespec *two,
1659 const char *xfrm_msg,
1660 struct diff_options *o,
1661 int complete_rewrite)
1663 mmfile_t mf1, mf2;
1664 const char *lbl[2];
1665 char *a_one, *b_two;
1666 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1667 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1668 const char *a_prefix, *b_prefix;
1669 struct userdiff_driver *textconv_one = NULL;
1670 struct userdiff_driver *textconv_two = NULL;
1671 struct strbuf header = STRBUF_INIT;
1673 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1674 (!one->mode || S_ISGITLINK(one->mode)) &&
1675 (!two->mode || S_ISGITLINK(two->mode))) {
1676 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1677 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1678 show_submodule_summary(o->file, one ? one->path : two->path,
1679 one->sha1, two->sha1, two->dirty_submodule,
1680 del, add, reset);
1681 return;
1684 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1685 textconv_one = get_textconv(one);
1686 textconv_two = get_textconv(two);
1689 diff_set_mnemonic_prefix(o, "a/", "b/");
1690 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1691 a_prefix = o->b_prefix;
1692 b_prefix = o->a_prefix;
1693 } else {
1694 a_prefix = o->a_prefix;
1695 b_prefix = o->b_prefix;
1698 /* Never use a non-valid filename anywhere if at all possible */
1699 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1700 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1702 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1703 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1704 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1705 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1706 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1707 if (lbl[0][0] == '/') {
1708 /* /dev/null */
1709 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1710 if (xfrm_msg && xfrm_msg[0])
1711 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1713 else if (lbl[1][0] == '/') {
1714 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1715 if (xfrm_msg && xfrm_msg[0])
1716 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1718 else {
1719 if (one->mode != two->mode) {
1720 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1721 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1723 if (xfrm_msg && xfrm_msg[0])
1724 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1727 * we do not run diff between different kind
1728 * of objects.
1730 if ((one->mode ^ two->mode) & S_IFMT)
1731 goto free_ab_and_return;
1732 if (complete_rewrite &&
1733 (textconv_one || !diff_filespec_is_binary(one)) &&
1734 (textconv_two || !diff_filespec_is_binary(two))) {
1735 fprintf(o->file, "%s", header.buf);
1736 strbuf_reset(&header);
1737 emit_rewrite_diff(name_a, name_b, one, two,
1738 textconv_one, textconv_two, o);
1739 o->found_changes = 1;
1740 goto free_ab_and_return;
1744 if (!DIFF_OPT_TST(o, TEXT) &&
1745 ( (!textconv_one && diff_filespec_is_binary(one)) ||
1746 (!textconv_two && diff_filespec_is_binary(two)) )) {
1747 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1748 die("unable to read files to diff");
1749 /* Quite common confusing case */
1750 if (mf1.size == mf2.size &&
1751 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1752 goto free_ab_and_return;
1753 fprintf(o->file, "%s", header.buf);
1754 strbuf_reset(&header);
1755 if (DIFF_OPT_TST(o, BINARY))
1756 emit_binary_diff(o->file, &mf1, &mf2);
1757 else
1758 fprintf(o->file, "Binary files %s and %s differ\n",
1759 lbl[0], lbl[1]);
1760 o->found_changes = 1;
1762 else {
1763 /* Crazy xdl interfaces.. */
1764 const char *diffopts = getenv("GIT_DIFF_OPTS");
1765 xpparam_t xpp;
1766 xdemitconf_t xecfg;
1767 xdemitcb_t ecb;
1768 struct emit_callback ecbdata;
1769 const struct userdiff_funcname *pe;
1771 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1772 fprintf(o->file, "%s", header.buf);
1773 strbuf_reset(&header);
1776 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1777 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1779 pe = diff_funcname_pattern(one);
1780 if (!pe)
1781 pe = diff_funcname_pattern(two);
1783 memset(&xpp, 0, sizeof(xpp));
1784 memset(&xecfg, 0, sizeof(xecfg));
1785 memset(&ecbdata, 0, sizeof(ecbdata));
1786 ecbdata.label_path = lbl;
1787 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1788 ecbdata.found_changesp = &o->found_changes;
1789 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1790 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1791 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1792 ecbdata.file = o->file;
1793 ecbdata.header = header.len ? &header : NULL;
1794 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1795 xecfg.ctxlen = o->context;
1796 xecfg.interhunkctxlen = o->interhunkcontext;
1797 xecfg.flags = XDL_EMIT_FUNCNAMES;
1798 if (pe)
1799 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1800 if (!diffopts)
1802 else if (!prefixcmp(diffopts, "--unified="))
1803 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1804 else if (!prefixcmp(diffopts, "-u"))
1805 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1806 if (o->word_diff) {
1807 int i;
1809 ecbdata.diff_words =
1810 xcalloc(1, sizeof(struct diff_words_data));
1811 ecbdata.diff_words->file = o->file;
1812 ecbdata.diff_words->type = o->word_diff;
1813 if (!o->word_regex)
1814 o->word_regex = userdiff_word_regex(one);
1815 if (!o->word_regex)
1816 o->word_regex = userdiff_word_regex(two);
1817 if (!o->word_regex)
1818 o->word_regex = diff_word_regex_cfg;
1819 if (o->word_regex) {
1820 ecbdata.diff_words->word_regex = (regex_t *)
1821 xmalloc(sizeof(regex_t));
1822 if (regcomp(ecbdata.diff_words->word_regex,
1823 o->word_regex,
1824 REG_EXTENDED | REG_NEWLINE))
1825 die ("Invalid regular expression: %s",
1826 o->word_regex);
1828 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1829 if (o->word_diff == diff_words_styles[i].type) {
1830 ecbdata.diff_words->style =
1831 &diff_words_styles[i];
1832 break;
1835 if (DIFF_OPT_TST(o, COLOR_DIFF)) {
1836 struct diff_words_style *st = ecbdata.diff_words->style;
1837 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1838 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1839 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1842 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1843 &xpp, &xecfg, &ecb);
1844 if (o->word_diff)
1845 free_diff_words_data(&ecbdata);
1846 if (textconv_one)
1847 free(mf1.ptr);
1848 if (textconv_two)
1849 free(mf2.ptr);
1850 xdiff_clear_find_func(&xecfg);
1853 free_ab_and_return:
1854 strbuf_release(&header);
1855 diff_free_filespec_data(one);
1856 diff_free_filespec_data(two);
1857 free(a_one);
1858 free(b_two);
1859 return;
1862 static void builtin_diffstat(const char *name_a, const char *name_b,
1863 struct diff_filespec *one,
1864 struct diff_filespec *two,
1865 struct diffstat_t *diffstat,
1866 struct diff_options *o,
1867 int complete_rewrite)
1869 mmfile_t mf1, mf2;
1870 struct diffstat_file *data;
1872 data = diffstat_add(diffstat, name_a, name_b);
1874 if (!one || !two) {
1875 data->is_unmerged = 1;
1876 return;
1878 if (complete_rewrite) {
1879 diff_populate_filespec(one, 0);
1880 diff_populate_filespec(two, 0);
1881 data->deleted = count_lines(one->data, one->size);
1882 data->added = count_lines(two->data, two->size);
1883 goto free_and_return;
1885 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1886 die("unable to read files to diff");
1888 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1889 data->is_binary = 1;
1890 data->added = mf2.size;
1891 data->deleted = mf1.size;
1892 } else {
1893 /* Crazy xdl interfaces.. */
1894 xpparam_t xpp;
1895 xdemitconf_t xecfg;
1896 xdemitcb_t ecb;
1898 memset(&xpp, 0, sizeof(xpp));
1899 memset(&xecfg, 0, sizeof(xecfg));
1900 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1901 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1902 &xpp, &xecfg, &ecb);
1905 free_and_return:
1906 diff_free_filespec_data(one);
1907 diff_free_filespec_data(two);
1910 static void builtin_checkdiff(const char *name_a, const char *name_b,
1911 const char *attr_path,
1912 struct diff_filespec *one,
1913 struct diff_filespec *two,
1914 struct diff_options *o)
1916 mmfile_t mf1, mf2;
1917 struct checkdiff_t data;
1919 if (!two)
1920 return;
1922 memset(&data, 0, sizeof(data));
1923 data.filename = name_b ? name_b : name_a;
1924 data.lineno = 0;
1925 data.o = o;
1926 data.ws_rule = whitespace_rule(attr_path);
1927 data.conflict_marker_size = ll_merge_marker_size(attr_path);
1929 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1930 die("unable to read files to diff");
1933 * All the other codepaths check both sides, but not checking
1934 * the "old" side here is deliberate. We are checking the newly
1935 * introduced changes, and as long as the "new" side is text, we
1936 * can and should check what it introduces.
1938 if (diff_filespec_is_binary(two))
1939 goto free_and_return;
1940 else {
1941 /* Crazy xdl interfaces.. */
1942 xpparam_t xpp;
1943 xdemitconf_t xecfg;
1944 xdemitcb_t ecb;
1946 memset(&xpp, 0, sizeof(xpp));
1947 memset(&xecfg, 0, sizeof(xecfg));
1948 xecfg.ctxlen = 1; /* at least one context line */
1949 xpp.flags = XDF_NEED_MINIMAL;
1950 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1951 &xpp, &xecfg, &ecb);
1953 if (data.ws_rule & WS_BLANK_AT_EOF) {
1954 struct emit_callback ecbdata;
1955 int blank_at_eof;
1957 ecbdata.ws_rule = data.ws_rule;
1958 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1959 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1961 if (blank_at_eof) {
1962 static char *err;
1963 if (!err)
1964 err = whitespace_error_string(WS_BLANK_AT_EOF);
1965 fprintf(o->file, "%s:%d: %s.\n",
1966 data.filename, blank_at_eof, err);
1967 data.status = 1; /* report errors */
1971 free_and_return:
1972 diff_free_filespec_data(one);
1973 diff_free_filespec_data(two);
1974 if (data.status)
1975 DIFF_OPT_SET(o, CHECK_FAILED);
1978 struct diff_filespec *alloc_filespec(const char *path)
1980 int namelen = strlen(path);
1981 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1983 memset(spec, 0, sizeof(*spec));
1984 spec->path = (char *)(spec + 1);
1985 memcpy(spec->path, path, namelen+1);
1986 spec->count = 1;
1987 spec->is_binary = -1;
1988 return spec;
1991 void free_filespec(struct diff_filespec *spec)
1993 if (!--spec->count) {
1994 diff_free_filespec_data(spec);
1995 free(spec);
1999 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2000 unsigned short mode)
2002 if (mode) {
2003 spec->mode = canon_mode(mode);
2004 hashcpy(spec->sha1, sha1);
2005 spec->sha1_valid = !is_null_sha1(sha1);
2010 * Given a name and sha1 pair, if the index tells us the file in
2011 * the work tree has that object contents, return true, so that
2012 * prepare_temp_file() does not have to inflate and extract.
2014 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2016 struct cache_entry *ce;
2017 struct stat st;
2018 int pos, len;
2021 * We do not read the cache ourselves here, because the
2022 * benchmark with my previous version that always reads cache
2023 * shows that it makes things worse for diff-tree comparing
2024 * two linux-2.6 kernel trees in an already checked out work
2025 * tree. This is because most diff-tree comparisons deal with
2026 * only a small number of files, while reading the cache is
2027 * expensive for a large project, and its cost outweighs the
2028 * savings we get by not inflating the object to a temporary
2029 * file. Practically, this code only helps when we are used
2030 * by diff-cache --cached, which does read the cache before
2031 * calling us.
2033 if (!active_cache)
2034 return 0;
2036 /* We want to avoid the working directory if our caller
2037 * doesn't need the data in a normal file, this system
2038 * is rather slow with its stat/open/mmap/close syscalls,
2039 * and the object is contained in a pack file. The pack
2040 * is probably already open and will be faster to obtain
2041 * the data through than the working directory. Loose
2042 * objects however would tend to be slower as they need
2043 * to be individually opened and inflated.
2045 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2046 return 0;
2048 len = strlen(name);
2049 pos = cache_name_pos(name, len);
2050 if (pos < 0)
2051 return 0;
2052 ce = active_cache[pos];
2055 * This is not the sha1 we are looking for, or
2056 * unreusable because it is not a regular file.
2058 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2059 return 0;
2062 * If ce is marked as "assume unchanged", there is no
2063 * guarantee that work tree matches what we are looking for.
2065 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2066 return 0;
2069 * If ce matches the file in the work tree, we can reuse it.
2071 if (ce_uptodate(ce) ||
2072 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2073 return 1;
2075 return 0;
2078 static int populate_from_stdin(struct diff_filespec *s)
2080 struct strbuf buf = STRBUF_INIT;
2081 size_t size = 0;
2083 if (strbuf_read(&buf, 0, 0) < 0)
2084 return error("error while reading from stdin %s",
2085 strerror(errno));
2087 s->should_munmap = 0;
2088 s->data = strbuf_detach(&buf, &size);
2089 s->size = size;
2090 s->should_free = 1;
2091 return 0;
2094 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2096 int len;
2097 char *data = xmalloc(100), *dirty = "";
2099 /* Are we looking at the work tree? */
2100 if (s->dirty_submodule)
2101 dirty = "-dirty";
2103 len = snprintf(data, 100,
2104 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2105 s->data = data;
2106 s->size = len;
2107 s->should_free = 1;
2108 if (size_only) {
2109 s->data = NULL;
2110 free(data);
2112 return 0;
2116 * While doing rename detection and pickaxe operation, we may need to
2117 * grab the data for the blob (or file) for our own in-core comparison.
2118 * diff_filespec has data and size fields for this purpose.
2120 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2122 int err = 0;
2123 if (!DIFF_FILE_VALID(s))
2124 die("internal error: asking to populate invalid file.");
2125 if (S_ISDIR(s->mode))
2126 return -1;
2128 if (s->data)
2129 return 0;
2131 if (size_only && 0 < s->size)
2132 return 0;
2134 if (S_ISGITLINK(s->mode))
2135 return diff_populate_gitlink(s, size_only);
2137 if (!s->sha1_valid ||
2138 reuse_worktree_file(s->path, s->sha1, 0)) {
2139 struct strbuf buf = STRBUF_INIT;
2140 struct stat st;
2141 int fd;
2143 if (!strcmp(s->path, "-"))
2144 return populate_from_stdin(s);
2146 if (lstat(s->path, &st) < 0) {
2147 if (errno == ENOENT) {
2148 err_empty:
2149 err = -1;
2150 empty:
2151 s->data = (char *)"";
2152 s->size = 0;
2153 return err;
2156 s->size = xsize_t(st.st_size);
2157 if (!s->size)
2158 goto empty;
2159 if (S_ISLNK(st.st_mode)) {
2160 struct strbuf sb = STRBUF_INIT;
2162 if (strbuf_readlink(&sb, s->path, s->size))
2163 goto err_empty;
2164 s->size = sb.len;
2165 s->data = strbuf_detach(&sb, NULL);
2166 s->should_free = 1;
2167 return 0;
2169 if (size_only)
2170 return 0;
2171 fd = open(s->path, O_RDONLY);
2172 if (fd < 0)
2173 goto err_empty;
2174 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2175 close(fd);
2176 s->should_munmap = 1;
2179 * Convert from working tree format to canonical git format
2181 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2182 size_t size = 0;
2183 munmap(s->data, s->size);
2184 s->should_munmap = 0;
2185 s->data = strbuf_detach(&buf, &size);
2186 s->size = size;
2187 s->should_free = 1;
2190 else {
2191 enum object_type type;
2192 if (size_only)
2193 type = sha1_object_info(s->sha1, &s->size);
2194 else {
2195 s->data = read_sha1_file(s->sha1, &type, &s->size);
2196 s->should_free = 1;
2199 return 0;
2202 void diff_free_filespec_blob(struct diff_filespec *s)
2204 if (s->should_free)
2205 free(s->data);
2206 else if (s->should_munmap)
2207 munmap(s->data, s->size);
2209 if (s->should_free || s->should_munmap) {
2210 s->should_free = s->should_munmap = 0;
2211 s->data = NULL;
2215 void diff_free_filespec_data(struct diff_filespec *s)
2217 diff_free_filespec_blob(s);
2218 free(s->cnt_data);
2219 s->cnt_data = NULL;
2222 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2223 void *blob,
2224 unsigned long size,
2225 const unsigned char *sha1,
2226 int mode)
2228 int fd;
2229 struct strbuf buf = STRBUF_INIT;
2230 struct strbuf template = STRBUF_INIT;
2231 char *path_dup = xstrdup(path);
2232 const char *base = basename(path_dup);
2234 /* Generate "XXXXXX_basename.ext" */
2235 strbuf_addstr(&template, "XXXXXX_");
2236 strbuf_addstr(&template, base);
2238 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2239 strlen(base) + 1);
2240 if (fd < 0)
2241 die_errno("unable to create temp-file");
2242 if (convert_to_working_tree(path,
2243 (const char *)blob, (size_t)size, &buf)) {
2244 blob = buf.buf;
2245 size = buf.len;
2247 if (write_in_full(fd, blob, size) != size)
2248 die_errno("unable to write temp-file");
2249 close(fd);
2250 temp->name = temp->tmp_path;
2251 strcpy(temp->hex, sha1_to_hex(sha1));
2252 temp->hex[40] = 0;
2253 sprintf(temp->mode, "%06o", mode);
2254 strbuf_release(&buf);
2255 strbuf_release(&template);
2256 free(path_dup);
2259 static struct diff_tempfile *prepare_temp_file(const char *name,
2260 struct diff_filespec *one)
2262 struct diff_tempfile *temp = claim_diff_tempfile();
2264 if (!DIFF_FILE_VALID(one)) {
2265 not_a_valid_file:
2266 /* A '-' entry produces this for file-2, and
2267 * a '+' entry produces this for file-1.
2269 temp->name = "/dev/null";
2270 strcpy(temp->hex, ".");
2271 strcpy(temp->mode, ".");
2272 return temp;
2275 if (!remove_tempfile_installed) {
2276 atexit(remove_tempfile);
2277 sigchain_push_common(remove_tempfile_on_signal);
2278 remove_tempfile_installed = 1;
2281 if (!one->sha1_valid ||
2282 reuse_worktree_file(name, one->sha1, 1)) {
2283 struct stat st;
2284 if (lstat(name, &st) < 0) {
2285 if (errno == ENOENT)
2286 goto not_a_valid_file;
2287 die_errno("stat(%s)", name);
2289 if (S_ISLNK(st.st_mode)) {
2290 struct strbuf sb = STRBUF_INIT;
2291 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2292 die_errno("readlink(%s)", name);
2293 prep_temp_blob(name, temp, sb.buf, sb.len,
2294 (one->sha1_valid ?
2295 one->sha1 : null_sha1),
2296 (one->sha1_valid ?
2297 one->mode : S_IFLNK));
2298 strbuf_release(&sb);
2300 else {
2301 /* we can borrow from the file in the work tree */
2302 temp->name = name;
2303 if (!one->sha1_valid)
2304 strcpy(temp->hex, sha1_to_hex(null_sha1));
2305 else
2306 strcpy(temp->hex, sha1_to_hex(one->sha1));
2307 /* Even though we may sometimes borrow the
2308 * contents from the work tree, we always want
2309 * one->mode. mode is trustworthy even when
2310 * !(one->sha1_valid), as long as
2311 * DIFF_FILE_VALID(one).
2313 sprintf(temp->mode, "%06o", one->mode);
2315 return temp;
2317 else {
2318 if (diff_populate_filespec(one, 0))
2319 die("cannot read data blob for %s", one->path);
2320 prep_temp_blob(name, temp, one->data, one->size,
2321 one->sha1, one->mode);
2323 return temp;
2326 /* An external diff command takes:
2328 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2329 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2332 static void run_external_diff(const char *pgm,
2333 const char *name,
2334 const char *other,
2335 struct diff_filespec *one,
2336 struct diff_filespec *two,
2337 const char *xfrm_msg,
2338 int complete_rewrite)
2340 const char *spawn_arg[10];
2341 int retval;
2342 const char **arg = &spawn_arg[0];
2344 if (one && two) {
2345 struct diff_tempfile *temp_one, *temp_two;
2346 const char *othername = (other ? other : name);
2347 temp_one = prepare_temp_file(name, one);
2348 temp_two = prepare_temp_file(othername, two);
2349 *arg++ = pgm;
2350 *arg++ = name;
2351 *arg++ = temp_one->name;
2352 *arg++ = temp_one->hex;
2353 *arg++ = temp_one->mode;
2354 *arg++ = temp_two->name;
2355 *arg++ = temp_two->hex;
2356 *arg++ = temp_two->mode;
2357 if (other) {
2358 *arg++ = other;
2359 *arg++ = xfrm_msg;
2361 } else {
2362 *arg++ = pgm;
2363 *arg++ = name;
2365 *arg = NULL;
2366 fflush(NULL);
2367 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2368 remove_tempfile();
2369 if (retval) {
2370 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2371 exit(1);
2375 static int similarity_index(struct diff_filepair *p)
2377 return p->score * 100 / MAX_SCORE;
2380 static void fill_metainfo(struct strbuf *msg,
2381 const char *name,
2382 const char *other,
2383 struct diff_filespec *one,
2384 struct diff_filespec *two,
2385 struct diff_options *o,
2386 struct diff_filepair *p)
2388 strbuf_init(msg, PATH_MAX * 2 + 300);
2389 switch (p->status) {
2390 case DIFF_STATUS_COPIED:
2391 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2392 strbuf_addstr(msg, "\ncopy from ");
2393 quote_c_style(name, msg, NULL, 0);
2394 strbuf_addstr(msg, "\ncopy to ");
2395 quote_c_style(other, msg, NULL, 0);
2396 strbuf_addch(msg, '\n');
2397 break;
2398 case DIFF_STATUS_RENAMED:
2399 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2400 strbuf_addstr(msg, "\nrename from ");
2401 quote_c_style(name, msg, NULL, 0);
2402 strbuf_addstr(msg, "\nrename to ");
2403 quote_c_style(other, msg, NULL, 0);
2404 strbuf_addch(msg, '\n');
2405 break;
2406 case DIFF_STATUS_MODIFIED:
2407 if (p->score) {
2408 strbuf_addf(msg, "dissimilarity index %d%%\n",
2409 similarity_index(p));
2410 break;
2412 /* fallthru */
2413 default:
2414 /* nothing */
2417 if (one && two && hashcmp(one->sha1, two->sha1)) {
2418 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2420 if (DIFF_OPT_TST(o, BINARY)) {
2421 mmfile_t mf;
2422 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2423 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2424 abbrev = 40;
2426 strbuf_addf(msg, "index %.*s..%.*s",
2427 abbrev, sha1_to_hex(one->sha1),
2428 abbrev, sha1_to_hex(two->sha1));
2429 if (one->mode == two->mode)
2430 strbuf_addf(msg, " %06o", one->mode);
2431 strbuf_addch(msg, '\n');
2433 if (msg->len)
2434 strbuf_setlen(msg, msg->len - 1);
2437 static void run_diff_cmd(const char *pgm,
2438 const char *name,
2439 const char *other,
2440 const char *attr_path,
2441 struct diff_filespec *one,
2442 struct diff_filespec *two,
2443 struct strbuf *msg,
2444 struct diff_options *o,
2445 struct diff_filepair *p)
2447 const char *xfrm_msg = NULL;
2448 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2450 if (msg) {
2451 fill_metainfo(msg, name, other, one, two, o, p);
2452 xfrm_msg = msg->len ? msg->buf : NULL;
2455 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2456 pgm = NULL;
2457 else {
2458 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2459 if (drv && drv->external)
2460 pgm = drv->external;
2463 if (pgm) {
2464 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2465 complete_rewrite);
2466 return;
2468 if (one && two)
2469 builtin_diff(name, other ? other : name,
2470 one, two, xfrm_msg, o, complete_rewrite);
2471 else
2472 fprintf(o->file, "* Unmerged path %s\n", name);
2475 static void diff_fill_sha1_info(struct diff_filespec *one)
2477 if (DIFF_FILE_VALID(one)) {
2478 if (!one->sha1_valid) {
2479 struct stat st;
2480 if (!strcmp(one->path, "-")) {
2481 hashcpy(one->sha1, null_sha1);
2482 return;
2484 if (lstat(one->path, &st) < 0)
2485 die_errno("stat '%s'", one->path);
2486 if (index_path(one->sha1, one->path, &st, 0))
2487 die("cannot hash %s", one->path);
2490 else
2491 hashclr(one->sha1);
2494 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2496 /* Strip the prefix but do not molest /dev/null and absolute paths */
2497 if (*namep && **namep != '/')
2498 *namep += prefix_length;
2499 if (*otherp && **otherp != '/')
2500 *otherp += prefix_length;
2503 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2505 const char *pgm = external_diff();
2506 struct strbuf msg;
2507 struct diff_filespec *one = p->one;
2508 struct diff_filespec *two = p->two;
2509 const char *name;
2510 const char *other;
2511 const char *attr_path;
2513 name = p->one->path;
2514 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2515 attr_path = name;
2516 if (o->prefix_length)
2517 strip_prefix(o->prefix_length, &name, &other);
2519 if (DIFF_PAIR_UNMERGED(p)) {
2520 run_diff_cmd(pgm, name, NULL, attr_path,
2521 NULL, NULL, NULL, o, p);
2522 return;
2525 diff_fill_sha1_info(one);
2526 diff_fill_sha1_info(two);
2528 if (!pgm &&
2529 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2530 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2532 * a filepair that changes between file and symlink
2533 * needs to be split into deletion and creation.
2535 struct diff_filespec *null = alloc_filespec(two->path);
2536 run_diff_cmd(NULL, name, other, attr_path,
2537 one, null, &msg, o, p);
2538 free(null);
2539 strbuf_release(&msg);
2541 null = alloc_filespec(one->path);
2542 run_diff_cmd(NULL, name, other, attr_path,
2543 null, two, &msg, o, p);
2544 free(null);
2546 else
2547 run_diff_cmd(pgm, name, other, attr_path,
2548 one, two, &msg, o, p);
2550 strbuf_release(&msg);
2553 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2554 struct diffstat_t *diffstat)
2556 const char *name;
2557 const char *other;
2558 int complete_rewrite = 0;
2560 if (DIFF_PAIR_UNMERGED(p)) {
2561 /* unmerged */
2562 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2563 return;
2566 name = p->one->path;
2567 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2569 if (o->prefix_length)
2570 strip_prefix(o->prefix_length, &name, &other);
2572 diff_fill_sha1_info(p->one);
2573 diff_fill_sha1_info(p->two);
2575 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2576 complete_rewrite = 1;
2577 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2580 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2582 const char *name;
2583 const char *other;
2584 const char *attr_path;
2586 if (DIFF_PAIR_UNMERGED(p)) {
2587 /* unmerged */
2588 return;
2591 name = p->one->path;
2592 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2593 attr_path = other ? other : name;
2595 if (o->prefix_length)
2596 strip_prefix(o->prefix_length, &name, &other);
2598 diff_fill_sha1_info(p->one);
2599 diff_fill_sha1_info(p->two);
2601 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2604 void diff_setup(struct diff_options *options)
2606 memset(options, 0, sizeof(*options));
2608 options->file = stdout;
2610 options->line_termination = '\n';
2611 options->break_opt = -1;
2612 options->rename_limit = -1;
2613 options->dirstat_percent = 3;
2614 options->context = 3;
2616 options->change = diff_change;
2617 options->add_remove = diff_addremove;
2618 if (diff_use_color_default > 0)
2619 DIFF_OPT_SET(options, COLOR_DIFF);
2620 options->detect_rename = diff_detect_rename_default;
2622 if (!diff_mnemonic_prefix) {
2623 options->a_prefix = "a/";
2624 options->b_prefix = "b/";
2628 int diff_setup_done(struct diff_options *options)
2630 int count = 0;
2632 if (options->output_format & DIFF_FORMAT_NAME)
2633 count++;
2634 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2635 count++;
2636 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2637 count++;
2638 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2639 count++;
2640 if (count > 1)
2641 die("--name-only, --name-status, --check and -s are mutually exclusive");
2644 * Most of the time we can say "there are changes"
2645 * only by checking if there are changed paths, but
2646 * --ignore-whitespace* options force us to look
2647 * inside contents.
2650 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2651 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2652 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2653 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2654 else
2655 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2657 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2658 options->detect_rename = DIFF_DETECT_COPY;
2660 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2661 options->prefix = NULL;
2662 if (options->prefix)
2663 options->prefix_length = strlen(options->prefix);
2664 else
2665 options->prefix_length = 0;
2667 if (options->output_format & (DIFF_FORMAT_NAME |
2668 DIFF_FORMAT_NAME_STATUS |
2669 DIFF_FORMAT_CHECKDIFF |
2670 DIFF_FORMAT_NO_OUTPUT))
2671 options->output_format &= ~(DIFF_FORMAT_RAW |
2672 DIFF_FORMAT_NUMSTAT |
2673 DIFF_FORMAT_DIFFSTAT |
2674 DIFF_FORMAT_SHORTSTAT |
2675 DIFF_FORMAT_DIRSTAT |
2676 DIFF_FORMAT_SUMMARY |
2677 DIFF_FORMAT_PATCH);
2680 * These cases always need recursive; we do not drop caller-supplied
2681 * recursive bits for other formats here.
2683 if (options->output_format & (DIFF_FORMAT_PATCH |
2684 DIFF_FORMAT_NUMSTAT |
2685 DIFF_FORMAT_DIFFSTAT |
2686 DIFF_FORMAT_SHORTSTAT |
2687 DIFF_FORMAT_DIRSTAT |
2688 DIFF_FORMAT_SUMMARY |
2689 DIFF_FORMAT_CHECKDIFF))
2690 DIFF_OPT_SET(options, RECURSIVE);
2692 * Also pickaxe would not work very well if you do not say recursive
2694 if (options->pickaxe)
2695 DIFF_OPT_SET(options, RECURSIVE);
2697 * When patches are generated, submodules diffed against the work tree
2698 * must be checked for dirtiness too so it can be shown in the output
2700 if (options->output_format & DIFF_FORMAT_PATCH)
2701 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2703 if (options->detect_rename && options->rename_limit < 0)
2704 options->rename_limit = diff_rename_limit_default;
2705 if (options->setup & DIFF_SETUP_USE_CACHE) {
2706 if (!active_cache)
2707 /* read-cache does not die even when it fails
2708 * so it is safe for us to do this here. Also
2709 * it does not smudge active_cache or active_nr
2710 * when it fails, so we do not have to worry about
2711 * cleaning it up ourselves either.
2713 read_cache();
2715 if (options->abbrev <= 0 || 40 < options->abbrev)
2716 options->abbrev = 40; /* full */
2719 * It does not make sense to show the first hit we happened
2720 * to have found. It does not make sense not to return with
2721 * exit code in such a case either.
2723 if (DIFF_OPT_TST(options, QUICK)) {
2724 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2725 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2728 return 0;
2731 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2733 char c, *eq;
2734 int len;
2736 if (*arg != '-')
2737 return 0;
2738 c = *++arg;
2739 if (!c)
2740 return 0;
2741 if (c == arg_short) {
2742 c = *++arg;
2743 if (!c)
2744 return 1;
2745 if (val && isdigit(c)) {
2746 char *end;
2747 int n = strtoul(arg, &end, 10);
2748 if (*end)
2749 return 0;
2750 *val = n;
2751 return 1;
2753 return 0;
2755 if (c != '-')
2756 return 0;
2757 arg++;
2758 eq = strchr(arg, '=');
2759 if (eq)
2760 len = eq - arg;
2761 else
2762 len = strlen(arg);
2763 if (!len || strncmp(arg, arg_long, len))
2764 return 0;
2765 if (eq) {
2766 int n;
2767 char *end;
2768 if (!isdigit(*++eq))
2769 return 0;
2770 n = strtoul(eq, &end, 10);
2771 if (*end)
2772 return 0;
2773 *val = n;
2775 return 1;
2778 static int diff_scoreopt_parse(const char *opt);
2780 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2782 const char *arg = av[0];
2784 /* Output format options */
2785 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2786 options->output_format |= DIFF_FORMAT_PATCH;
2787 else if (opt_arg(arg, 'U', "unified", &options->context))
2788 options->output_format |= DIFF_FORMAT_PATCH;
2789 else if (!strcmp(arg, "--raw"))
2790 options->output_format |= DIFF_FORMAT_RAW;
2791 else if (!strcmp(arg, "--patch-with-raw"))
2792 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2793 else if (!strcmp(arg, "--numstat"))
2794 options->output_format |= DIFF_FORMAT_NUMSTAT;
2795 else if (!strcmp(arg, "--shortstat"))
2796 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2797 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2798 options->output_format |= DIFF_FORMAT_DIRSTAT;
2799 else if (!strcmp(arg, "--cumulative")) {
2800 options->output_format |= DIFF_FORMAT_DIRSTAT;
2801 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2802 } else if (opt_arg(arg, 0, "dirstat-by-file",
2803 &options->dirstat_percent)) {
2804 options->output_format |= DIFF_FORMAT_DIRSTAT;
2805 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2807 else if (!strcmp(arg, "--check"))
2808 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2809 else if (!strcmp(arg, "--summary"))
2810 options->output_format |= DIFF_FORMAT_SUMMARY;
2811 else if (!strcmp(arg, "--patch-with-stat"))
2812 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2813 else if (!strcmp(arg, "--name-only"))
2814 options->output_format |= DIFF_FORMAT_NAME;
2815 else if (!strcmp(arg, "--name-status"))
2816 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2817 else if (!strcmp(arg, "-s"))
2818 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2819 else if (!prefixcmp(arg, "--stat")) {
2820 char *end;
2821 int width = options->stat_width;
2822 int name_width = options->stat_name_width;
2823 arg += 6;
2824 end = (char *)arg;
2826 switch (*arg) {
2827 case '-':
2828 if (!prefixcmp(arg, "-width="))
2829 width = strtoul(arg + 7, &end, 10);
2830 else if (!prefixcmp(arg, "-name-width="))
2831 name_width = strtoul(arg + 12, &end, 10);
2832 break;
2833 case '=':
2834 width = strtoul(arg+1, &end, 10);
2835 if (*end == ',')
2836 name_width = strtoul(end+1, &end, 10);
2839 /* Important! This checks all the error cases! */
2840 if (*end)
2841 return 0;
2842 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2843 options->stat_name_width = name_width;
2844 options->stat_width = width;
2847 /* renames options */
2848 else if (!prefixcmp(arg, "-B")) {
2849 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2850 return -1;
2852 else if (!prefixcmp(arg, "-M")) {
2853 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2854 return -1;
2855 options->detect_rename = DIFF_DETECT_RENAME;
2857 else if (!prefixcmp(arg, "-C")) {
2858 if (options->detect_rename == DIFF_DETECT_COPY)
2859 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2860 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2861 return -1;
2862 options->detect_rename = DIFF_DETECT_COPY;
2864 else if (!strcmp(arg, "--no-renames"))
2865 options->detect_rename = 0;
2866 else if (!strcmp(arg, "--relative"))
2867 DIFF_OPT_SET(options, RELATIVE_NAME);
2868 else if (!prefixcmp(arg, "--relative=")) {
2869 DIFF_OPT_SET(options, RELATIVE_NAME);
2870 options->prefix = arg + 11;
2873 /* xdiff options */
2874 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2875 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2876 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2877 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2878 else if (!strcmp(arg, "--ignore-space-at-eol"))
2879 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2880 else if (!strcmp(arg, "--patience"))
2881 DIFF_XDL_SET(options, PATIENCE_DIFF);
2883 /* flags options */
2884 else if (!strcmp(arg, "--binary")) {
2885 options->output_format |= DIFF_FORMAT_PATCH;
2886 DIFF_OPT_SET(options, BINARY);
2888 else if (!strcmp(arg, "--full-index"))
2889 DIFF_OPT_SET(options, FULL_INDEX);
2890 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2891 DIFF_OPT_SET(options, TEXT);
2892 else if (!strcmp(arg, "-R"))
2893 DIFF_OPT_SET(options, REVERSE_DIFF);
2894 else if (!strcmp(arg, "--find-copies-harder"))
2895 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2896 else if (!strcmp(arg, "--follow"))
2897 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2898 else if (!strcmp(arg, "--color"))
2899 DIFF_OPT_SET(options, COLOR_DIFF);
2900 else if (!prefixcmp(arg, "--color=")) {
2901 int value = git_config_colorbool(NULL, arg+8, -1);
2902 if (value == 0)
2903 DIFF_OPT_CLR(options, COLOR_DIFF);
2904 else if (value > 0)
2905 DIFF_OPT_SET(options, COLOR_DIFF);
2906 else
2907 return error("option `color' expects \"always\", \"auto\", or \"never\"");
2909 else if (!strcmp(arg, "--no-color"))
2910 DIFF_OPT_CLR(options, COLOR_DIFF);
2911 else if (!strcmp(arg, "--color-words")) {
2912 DIFF_OPT_SET(options, COLOR_DIFF);
2913 options->word_diff = DIFF_WORDS_COLOR;
2915 else if (!prefixcmp(arg, "--color-words=")) {
2916 DIFF_OPT_SET(options, COLOR_DIFF);
2917 options->word_diff = DIFF_WORDS_COLOR;
2918 options->word_regex = arg + 14;
2920 else if (!strcmp(arg, "--word-diff")) {
2921 if (options->word_diff == DIFF_WORDS_NONE)
2922 options->word_diff = DIFF_WORDS_PLAIN;
2924 else if (!prefixcmp(arg, "--word-diff=")) {
2925 const char *type = arg + 12;
2926 if (!strcmp(type, "plain"))
2927 options->word_diff = DIFF_WORDS_PLAIN;
2928 else if (!strcmp(type, "color")) {
2929 DIFF_OPT_SET(options, COLOR_DIFF);
2930 options->word_diff = DIFF_WORDS_COLOR;
2932 else if (!strcmp(type, "porcelain"))
2933 options->word_diff = DIFF_WORDS_PORCELAIN;
2934 else if (!strcmp(type, "none"))
2935 options->word_diff = DIFF_WORDS_NONE;
2936 else
2937 die("bad --word-diff argument: %s", type);
2939 else if (!prefixcmp(arg, "--word-diff-regex=")) {
2940 if (options->word_diff == DIFF_WORDS_NONE)
2941 options->word_diff = DIFF_WORDS_PLAIN;
2942 options->word_regex = arg + 18;
2944 else if (!strcmp(arg, "--exit-code"))
2945 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2946 else if (!strcmp(arg, "--quiet"))
2947 DIFF_OPT_SET(options, QUICK);
2948 else if (!strcmp(arg, "--ext-diff"))
2949 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2950 else if (!strcmp(arg, "--no-ext-diff"))
2951 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2952 else if (!strcmp(arg, "--textconv"))
2953 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2954 else if (!strcmp(arg, "--no-textconv"))
2955 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2956 else if (!strcmp(arg, "--ignore-submodules"))
2957 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2958 else if (!strcmp(arg, "--submodule"))
2959 DIFF_OPT_SET(options, SUBMODULE_LOG);
2960 else if (!prefixcmp(arg, "--submodule=")) {
2961 if (!strcmp(arg + 12, "log"))
2962 DIFF_OPT_SET(options, SUBMODULE_LOG);
2965 /* misc options */
2966 else if (!strcmp(arg, "-z"))
2967 options->line_termination = 0;
2968 else if (!prefixcmp(arg, "-l"))
2969 options->rename_limit = strtoul(arg+2, NULL, 10);
2970 else if (!prefixcmp(arg, "-S"))
2971 options->pickaxe = arg + 2;
2972 else if (!strcmp(arg, "--pickaxe-all"))
2973 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2974 else if (!strcmp(arg, "--pickaxe-regex"))
2975 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2976 else if (!prefixcmp(arg, "-O"))
2977 options->orderfile = arg + 2;
2978 else if (!prefixcmp(arg, "--diff-filter="))
2979 options->filter = arg + 14;
2980 else if (!strcmp(arg, "--abbrev"))
2981 options->abbrev = DEFAULT_ABBREV;
2982 else if (!prefixcmp(arg, "--abbrev=")) {
2983 options->abbrev = strtoul(arg + 9, NULL, 10);
2984 if (options->abbrev < MINIMUM_ABBREV)
2985 options->abbrev = MINIMUM_ABBREV;
2986 else if (40 < options->abbrev)
2987 options->abbrev = 40;
2989 else if (!prefixcmp(arg, "--src-prefix="))
2990 options->a_prefix = arg + 13;
2991 else if (!prefixcmp(arg, "--dst-prefix="))
2992 options->b_prefix = arg + 13;
2993 else if (!strcmp(arg, "--no-prefix"))
2994 options->a_prefix = options->b_prefix = "";
2995 else if (opt_arg(arg, '\0', "inter-hunk-context",
2996 &options->interhunkcontext))
2998 else if (!prefixcmp(arg, "--output=")) {
2999 options->file = fopen(arg + strlen("--output="), "w");
3000 if (!options->file)
3001 die_errno("Could not open '%s'", arg + strlen("--output="));
3002 options->close_file = 1;
3003 } else
3004 return 0;
3005 return 1;
3008 static int parse_num(const char **cp_p)
3010 unsigned long num, scale;
3011 int ch, dot;
3012 const char *cp = *cp_p;
3014 num = 0;
3015 scale = 1;
3016 dot = 0;
3017 for (;;) {
3018 ch = *cp;
3019 if ( !dot && ch == '.' ) {
3020 scale = 1;
3021 dot = 1;
3022 } else if ( ch == '%' ) {
3023 scale = dot ? scale*100 : 100;
3024 cp++; /* % is always at the end */
3025 break;
3026 } else if ( ch >= '0' && ch <= '9' ) {
3027 if ( scale < 100000 ) {
3028 scale *= 10;
3029 num = (num*10) + (ch-'0');
3031 } else {
3032 break;
3034 cp++;
3036 *cp_p = cp;
3038 /* user says num divided by scale and we say internally that
3039 * is MAX_SCORE * num / scale.
3041 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3044 static int diff_scoreopt_parse(const char *opt)
3046 int opt1, opt2, cmd;
3048 if (*opt++ != '-')
3049 return -1;
3050 cmd = *opt++;
3051 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3052 return -1; /* that is not a -M, -C nor -B option */
3054 opt1 = parse_num(&opt);
3055 if (cmd != 'B')
3056 opt2 = 0;
3057 else {
3058 if (*opt == 0)
3059 opt2 = 0;
3060 else if (*opt != '/')
3061 return -1; /* we expect -B80/99 or -B80 */
3062 else {
3063 opt++;
3064 opt2 = parse_num(&opt);
3067 if (*opt != 0)
3068 return -1;
3069 return opt1 | (opt2 << 16);
3072 struct diff_queue_struct diff_queued_diff;
3074 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3076 if (queue->alloc <= queue->nr) {
3077 queue->alloc = alloc_nr(queue->alloc);
3078 queue->queue = xrealloc(queue->queue,
3079 sizeof(dp) * queue->alloc);
3081 queue->queue[queue->nr++] = dp;
3084 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3085 struct diff_filespec *one,
3086 struct diff_filespec *two)
3088 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3089 dp->one = one;
3090 dp->two = two;
3091 if (queue)
3092 diff_q(queue, dp);
3093 return dp;
3096 void diff_free_filepair(struct diff_filepair *p)
3098 free_filespec(p->one);
3099 free_filespec(p->two);
3100 free(p);
3103 /* This is different from find_unique_abbrev() in that
3104 * it stuffs the result with dots for alignment.
3106 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3108 int abblen;
3109 const char *abbrev;
3110 if (len == 40)
3111 return sha1_to_hex(sha1);
3113 abbrev = find_unique_abbrev(sha1, len);
3114 abblen = strlen(abbrev);
3115 if (abblen < 37) {
3116 static char hex[41];
3117 if (len < abblen && abblen <= len + 2)
3118 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3119 else
3120 sprintf(hex, "%s...", abbrev);
3121 return hex;
3123 return sha1_to_hex(sha1);
3126 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3128 int line_termination = opt->line_termination;
3129 int inter_name_termination = line_termination ? '\t' : '\0';
3131 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3132 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3133 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3134 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3136 if (p->score) {
3137 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3138 inter_name_termination);
3139 } else {
3140 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3143 if (p->status == DIFF_STATUS_COPIED ||
3144 p->status == DIFF_STATUS_RENAMED) {
3145 const char *name_a, *name_b;
3146 name_a = p->one->path;
3147 name_b = p->two->path;
3148 strip_prefix(opt->prefix_length, &name_a, &name_b);
3149 write_name_quoted(name_a, opt->file, inter_name_termination);
3150 write_name_quoted(name_b, opt->file, line_termination);
3151 } else {
3152 const char *name_a, *name_b;
3153 name_a = p->one->mode ? p->one->path : p->two->path;
3154 name_b = NULL;
3155 strip_prefix(opt->prefix_length, &name_a, &name_b);
3156 write_name_quoted(name_a, opt->file, line_termination);
3160 int diff_unmodified_pair(struct diff_filepair *p)
3162 /* This function is written stricter than necessary to support
3163 * the currently implemented transformers, but the idea is to
3164 * let transformers to produce diff_filepairs any way they want,
3165 * and filter and clean them up here before producing the output.
3167 struct diff_filespec *one = p->one, *two = p->two;
3169 if (DIFF_PAIR_UNMERGED(p))
3170 return 0; /* unmerged is interesting */
3172 /* deletion, addition, mode or type change
3173 * and rename are all interesting.
3175 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3176 DIFF_PAIR_MODE_CHANGED(p) ||
3177 strcmp(one->path, two->path))
3178 return 0;
3180 /* both are valid and point at the same path. that is, we are
3181 * dealing with a change.
3183 if (one->sha1_valid && two->sha1_valid &&
3184 !hashcmp(one->sha1, two->sha1) &&
3185 !one->dirty_submodule && !two->dirty_submodule)
3186 return 1; /* no change */
3187 if (!one->sha1_valid && !two->sha1_valid)
3188 return 1; /* both look at the same file on the filesystem. */
3189 return 0;
3192 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3194 if (diff_unmodified_pair(p))
3195 return;
3197 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3198 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3199 return; /* no tree diffs in patch format */
3201 run_diff(p, o);
3204 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3205 struct diffstat_t *diffstat)
3207 if (diff_unmodified_pair(p))
3208 return;
3210 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3211 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3212 return; /* no tree diffs in patch format */
3214 run_diffstat(p, o, diffstat);
3217 static void diff_flush_checkdiff(struct diff_filepair *p,
3218 struct diff_options *o)
3220 if (diff_unmodified_pair(p))
3221 return;
3223 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3224 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3225 return; /* no tree diffs in patch format */
3227 run_checkdiff(p, o);
3230 int diff_queue_is_empty(void)
3232 struct diff_queue_struct *q = &diff_queued_diff;
3233 int i;
3234 for (i = 0; i < q->nr; i++)
3235 if (!diff_unmodified_pair(q->queue[i]))
3236 return 0;
3237 return 1;
3240 #if DIFF_DEBUG
3241 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3243 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3244 x, one ? one : "",
3245 s->path,
3246 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3247 s->mode,
3248 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3249 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3250 x, one ? one : "",
3251 s->size, s->xfrm_flags);
3254 void diff_debug_filepair(const struct diff_filepair *p, int i)
3256 diff_debug_filespec(p->one, i, "one");
3257 diff_debug_filespec(p->two, i, "two");
3258 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3259 p->score, p->status ? p->status : '?',
3260 p->one->rename_used, p->broken_pair);
3263 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3265 int i;
3266 if (msg)
3267 fprintf(stderr, "%s\n", msg);
3268 fprintf(stderr, "q->nr = %d\n", q->nr);
3269 for (i = 0; i < q->nr; i++) {
3270 struct diff_filepair *p = q->queue[i];
3271 diff_debug_filepair(p, i);
3274 #endif
3276 static void diff_resolve_rename_copy(void)
3278 int i;
3279 struct diff_filepair *p;
3280 struct diff_queue_struct *q = &diff_queued_diff;
3282 diff_debug_queue("resolve-rename-copy", q);
3284 for (i = 0; i < q->nr; i++) {
3285 p = q->queue[i];
3286 p->status = 0; /* undecided */
3287 if (DIFF_PAIR_UNMERGED(p))
3288 p->status = DIFF_STATUS_UNMERGED;
3289 else if (!DIFF_FILE_VALID(p->one))
3290 p->status = DIFF_STATUS_ADDED;
3291 else if (!DIFF_FILE_VALID(p->two))
3292 p->status = DIFF_STATUS_DELETED;
3293 else if (DIFF_PAIR_TYPE_CHANGED(p))
3294 p->status = DIFF_STATUS_TYPE_CHANGED;
3296 /* from this point on, we are dealing with a pair
3297 * whose both sides are valid and of the same type, i.e.
3298 * either in-place edit or rename/copy edit.
3300 else if (DIFF_PAIR_RENAME(p)) {
3302 * A rename might have re-connected a broken
3303 * pair up, causing the pathnames to be the
3304 * same again. If so, that's not a rename at
3305 * all, just a modification..
3307 * Otherwise, see if this source was used for
3308 * multiple renames, in which case we decrement
3309 * the count, and call it a copy.
3311 if (!strcmp(p->one->path, p->two->path))
3312 p->status = DIFF_STATUS_MODIFIED;
3313 else if (--p->one->rename_used > 0)
3314 p->status = DIFF_STATUS_COPIED;
3315 else
3316 p->status = DIFF_STATUS_RENAMED;
3318 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3319 p->one->mode != p->two->mode ||
3320 p->one->dirty_submodule ||
3321 p->two->dirty_submodule ||
3322 is_null_sha1(p->one->sha1))
3323 p->status = DIFF_STATUS_MODIFIED;
3324 else {
3325 /* This is a "no-change" entry and should not
3326 * happen anymore, but prepare for broken callers.
3328 error("feeding unmodified %s to diffcore",
3329 p->one->path);
3330 p->status = DIFF_STATUS_UNKNOWN;
3333 diff_debug_queue("resolve-rename-copy done", q);
3336 static int check_pair_status(struct diff_filepair *p)
3338 switch (p->status) {
3339 case DIFF_STATUS_UNKNOWN:
3340 return 0;
3341 case 0:
3342 die("internal error in diff-resolve-rename-copy");
3343 default:
3344 return 1;
3348 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3350 int fmt = opt->output_format;
3352 if (fmt & DIFF_FORMAT_CHECKDIFF)
3353 diff_flush_checkdiff(p, opt);
3354 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3355 diff_flush_raw(p, opt);
3356 else if (fmt & DIFF_FORMAT_NAME) {
3357 const char *name_a, *name_b;
3358 name_a = p->two->path;
3359 name_b = NULL;
3360 strip_prefix(opt->prefix_length, &name_a, &name_b);
3361 write_name_quoted(name_a, opt->file, opt->line_termination);
3365 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3367 if (fs->mode)
3368 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3369 else
3370 fprintf(file, " %s ", newdelete);
3371 write_name_quoted(fs->path, file, '\n');
3375 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3377 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3378 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3379 show_name ? ' ' : '\n');
3380 if (show_name) {
3381 write_name_quoted(p->two->path, file, '\n');
3386 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3388 char *names = pprint_rename(p->one->path, p->two->path);
3390 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3391 free(names);
3392 show_mode_change(file, p, 0);
3395 static void diff_summary(FILE *file, struct diff_filepair *p)
3397 switch(p->status) {
3398 case DIFF_STATUS_DELETED:
3399 show_file_mode_name(file, "delete", p->one);
3400 break;
3401 case DIFF_STATUS_ADDED:
3402 show_file_mode_name(file, "create", p->two);
3403 break;
3404 case DIFF_STATUS_COPIED:
3405 show_rename_copy(file, "copy", p);
3406 break;
3407 case DIFF_STATUS_RENAMED:
3408 show_rename_copy(file, "rename", p);
3409 break;
3410 default:
3411 if (p->score) {
3412 fputs(" rewrite ", file);
3413 write_name_quoted(p->two->path, file, ' ');
3414 fprintf(file, "(%d%%)\n", similarity_index(p));
3416 show_mode_change(file, p, !p->score);
3417 break;
3421 struct patch_id_t {
3422 git_SHA_CTX *ctx;
3423 int patchlen;
3426 static int remove_space(char *line, int len)
3428 int i;
3429 char *dst = line;
3430 unsigned char c;
3432 for (i = 0; i < len; i++)
3433 if (!isspace((c = line[i])))
3434 *dst++ = c;
3436 return dst - line;
3439 static void patch_id_consume(void *priv, char *line, unsigned long len)
3441 struct patch_id_t *data = priv;
3442 int new_len;
3444 /* Ignore line numbers when computing the SHA1 of the patch */
3445 if (!prefixcmp(line, "@@ -"))
3446 return;
3448 new_len = remove_space(line, len);
3450 git_SHA1_Update(data->ctx, line, new_len);
3451 data->patchlen += new_len;
3454 /* returns 0 upon success, and writes result into sha1 */
3455 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3457 struct diff_queue_struct *q = &diff_queued_diff;
3458 int i;
3459 git_SHA_CTX ctx;
3460 struct patch_id_t data;
3461 char buffer[PATH_MAX * 4 + 20];
3463 git_SHA1_Init(&ctx);
3464 memset(&data, 0, sizeof(struct patch_id_t));
3465 data.ctx = &ctx;
3467 for (i = 0; i < q->nr; i++) {
3468 xpparam_t xpp;
3469 xdemitconf_t xecfg;
3470 xdemitcb_t ecb;
3471 mmfile_t mf1, mf2;
3472 struct diff_filepair *p = q->queue[i];
3473 int len1, len2;
3475 memset(&xpp, 0, sizeof(xpp));
3476 memset(&xecfg, 0, sizeof(xecfg));
3477 if (p->status == 0)
3478 return error("internal diff status error");
3479 if (p->status == DIFF_STATUS_UNKNOWN)
3480 continue;
3481 if (diff_unmodified_pair(p))
3482 continue;
3483 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3484 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3485 continue;
3486 if (DIFF_PAIR_UNMERGED(p))
3487 continue;
3489 diff_fill_sha1_info(p->one);
3490 diff_fill_sha1_info(p->two);
3491 if (fill_mmfile(&mf1, p->one) < 0 ||
3492 fill_mmfile(&mf2, p->two) < 0)
3493 return error("unable to read files to diff");
3495 len1 = remove_space(p->one->path, strlen(p->one->path));
3496 len2 = remove_space(p->two->path, strlen(p->two->path));
3497 if (p->one->mode == 0)
3498 len1 = snprintf(buffer, sizeof(buffer),
3499 "diff--gita/%.*sb/%.*s"
3500 "newfilemode%06o"
3501 "---/dev/null"
3502 "+++b/%.*s",
3503 len1, p->one->path,
3504 len2, p->two->path,
3505 p->two->mode,
3506 len2, p->two->path);
3507 else if (p->two->mode == 0)
3508 len1 = snprintf(buffer, sizeof(buffer),
3509 "diff--gita/%.*sb/%.*s"
3510 "deletedfilemode%06o"
3511 "---a/%.*s"
3512 "+++/dev/null",
3513 len1, p->one->path,
3514 len2, p->two->path,
3515 p->one->mode,
3516 len1, p->one->path);
3517 else
3518 len1 = snprintf(buffer, sizeof(buffer),
3519 "diff--gita/%.*sb/%.*s"
3520 "---a/%.*s"
3521 "+++b/%.*s",
3522 len1, p->one->path,
3523 len2, p->two->path,
3524 len1, p->one->path,
3525 len2, p->two->path);
3526 git_SHA1_Update(&ctx, buffer, len1);
3528 xpp.flags = XDF_NEED_MINIMAL;
3529 xecfg.ctxlen = 3;
3530 xecfg.flags = XDL_EMIT_FUNCNAMES;
3531 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3532 &xpp, &xecfg, &ecb);
3535 git_SHA1_Final(sha1, &ctx);
3536 return 0;
3539 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3541 struct diff_queue_struct *q = &diff_queued_diff;
3542 int i;
3543 int result = diff_get_patch_id(options, sha1);
3545 for (i = 0; i < q->nr; i++)
3546 diff_free_filepair(q->queue[i]);
3548 free(q->queue);
3549 q->queue = NULL;
3550 q->nr = q->alloc = 0;
3552 return result;
3555 static int is_summary_empty(const struct diff_queue_struct *q)
3557 int i;
3559 for (i = 0; i < q->nr; i++) {
3560 const struct diff_filepair *p = q->queue[i];
3562 switch (p->status) {
3563 case DIFF_STATUS_DELETED:
3564 case DIFF_STATUS_ADDED:
3565 case DIFF_STATUS_COPIED:
3566 case DIFF_STATUS_RENAMED:
3567 return 0;
3568 default:
3569 if (p->score)
3570 return 0;
3571 if (p->one->mode && p->two->mode &&
3572 p->one->mode != p->two->mode)
3573 return 0;
3574 break;
3577 return 1;
3580 void diff_flush(struct diff_options *options)
3582 struct diff_queue_struct *q = &diff_queued_diff;
3583 int i, output_format = options->output_format;
3584 int separator = 0;
3587 * Order: raw, stat, summary, patch
3588 * or: name/name-status/checkdiff (other bits clear)
3590 if (!q->nr)
3591 goto free_queue;
3593 if (output_format & (DIFF_FORMAT_RAW |
3594 DIFF_FORMAT_NAME |
3595 DIFF_FORMAT_NAME_STATUS |
3596 DIFF_FORMAT_CHECKDIFF)) {
3597 for (i = 0; i < q->nr; i++) {
3598 struct diff_filepair *p = q->queue[i];
3599 if (check_pair_status(p))
3600 flush_one_pair(p, options);
3602 separator++;
3605 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3606 struct diffstat_t diffstat;
3608 memset(&diffstat, 0, sizeof(struct diffstat_t));
3609 for (i = 0; i < q->nr; i++) {
3610 struct diff_filepair *p = q->queue[i];
3611 if (check_pair_status(p))
3612 diff_flush_stat(p, options, &diffstat);
3614 if (output_format & DIFF_FORMAT_NUMSTAT)
3615 show_numstat(&diffstat, options);
3616 if (output_format & DIFF_FORMAT_DIFFSTAT)
3617 show_stats(&diffstat, options);
3618 if (output_format & DIFF_FORMAT_SHORTSTAT)
3619 show_shortstats(&diffstat, options);
3620 free_diffstat_info(&diffstat);
3621 separator++;
3623 if (output_format & DIFF_FORMAT_DIRSTAT)
3624 show_dirstat(options);
3626 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3627 for (i = 0; i < q->nr; i++)
3628 diff_summary(options->file, q->queue[i]);
3629 separator++;
3632 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3633 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3634 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3636 * run diff_flush_patch for the exit status. setting
3637 * options->file to /dev/null should be safe, becaue we
3638 * aren't supposed to produce any output anyway.
3640 if (options->close_file)
3641 fclose(options->file);
3642 options->file = fopen("/dev/null", "w");
3643 if (!options->file)
3644 die_errno("Could not open /dev/null");
3645 options->close_file = 1;
3646 for (i = 0; i < q->nr; i++) {
3647 struct diff_filepair *p = q->queue[i];
3648 if (check_pair_status(p))
3649 diff_flush_patch(p, options);
3650 if (options->found_changes)
3651 break;
3655 if (output_format & DIFF_FORMAT_PATCH) {
3656 if (separator) {
3657 putc(options->line_termination, options->file);
3658 if (options->stat_sep) {
3659 /* attach patch instead of inline */
3660 fputs(options->stat_sep, options->file);
3664 for (i = 0; i < q->nr; i++) {
3665 struct diff_filepair *p = q->queue[i];
3666 if (check_pair_status(p))
3667 diff_flush_patch(p, options);
3671 if (output_format & DIFF_FORMAT_CALLBACK)
3672 options->format_callback(q, options, options->format_callback_data);
3674 for (i = 0; i < q->nr; i++)
3675 diff_free_filepair(q->queue[i]);
3676 free_queue:
3677 free(q->queue);
3678 q->queue = NULL;
3679 q->nr = q->alloc = 0;
3680 if (options->close_file)
3681 fclose(options->file);
3684 * Report the content-level differences with HAS_CHANGES;
3685 * diff_addremove/diff_change does not set the bit when
3686 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3688 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3689 if (options->found_changes)
3690 DIFF_OPT_SET(options, HAS_CHANGES);
3691 else
3692 DIFF_OPT_CLR(options, HAS_CHANGES);
3696 static void diffcore_apply_filter(const char *filter)
3698 int i;
3699 struct diff_queue_struct *q = &diff_queued_diff;
3700 struct diff_queue_struct outq;
3701 outq.queue = NULL;
3702 outq.nr = outq.alloc = 0;
3704 if (!filter)
3705 return;
3707 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3708 int found;
3709 for (i = found = 0; !found && i < q->nr; i++) {
3710 struct diff_filepair *p = q->queue[i];
3711 if (((p->status == DIFF_STATUS_MODIFIED) &&
3712 ((p->score &&
3713 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3714 (!p->score &&
3715 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3716 ((p->status != DIFF_STATUS_MODIFIED) &&
3717 strchr(filter, p->status)))
3718 found++;
3720 if (found)
3721 return;
3723 /* otherwise we will clear the whole queue
3724 * by copying the empty outq at the end of this
3725 * function, but first clear the current entries
3726 * in the queue.
3728 for (i = 0; i < q->nr; i++)
3729 diff_free_filepair(q->queue[i]);
3731 else {
3732 /* Only the matching ones */
3733 for (i = 0; i < q->nr; i++) {
3734 struct diff_filepair *p = q->queue[i];
3736 if (((p->status == DIFF_STATUS_MODIFIED) &&
3737 ((p->score &&
3738 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3739 (!p->score &&
3740 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3741 ((p->status != DIFF_STATUS_MODIFIED) &&
3742 strchr(filter, p->status)))
3743 diff_q(&outq, p);
3744 else
3745 diff_free_filepair(p);
3748 free(q->queue);
3749 *q = outq;
3752 /* Check whether two filespecs with the same mode and size are identical */
3753 static int diff_filespec_is_identical(struct diff_filespec *one,
3754 struct diff_filespec *two)
3756 if (S_ISGITLINK(one->mode))
3757 return 0;
3758 if (diff_populate_filespec(one, 0))
3759 return 0;
3760 if (diff_populate_filespec(two, 0))
3761 return 0;
3762 return !memcmp(one->data, two->data, one->size);
3765 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3767 int i;
3768 struct diff_queue_struct *q = &diff_queued_diff;
3769 struct diff_queue_struct outq;
3770 outq.queue = NULL;
3771 outq.nr = outq.alloc = 0;
3773 for (i = 0; i < q->nr; i++) {
3774 struct diff_filepair *p = q->queue[i];
3777 * 1. Entries that come from stat info dirtiness
3778 * always have both sides (iow, not create/delete),
3779 * one side of the object name is unknown, with
3780 * the same mode and size. Keep the ones that
3781 * do not match these criteria. They have real
3782 * differences.
3784 * 2. At this point, the file is known to be modified,
3785 * with the same mode and size, and the object
3786 * name of one side is unknown. Need to inspect
3787 * the identical contents.
3789 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3790 !DIFF_FILE_VALID(p->two) ||
3791 (p->one->sha1_valid && p->two->sha1_valid) ||
3792 (p->one->mode != p->two->mode) ||
3793 diff_populate_filespec(p->one, 1) ||
3794 diff_populate_filespec(p->two, 1) ||
3795 (p->one->size != p->two->size) ||
3796 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3797 diff_q(&outq, p);
3798 else {
3800 * The caller can subtract 1 from skip_stat_unmatch
3801 * to determine how many paths were dirty only
3802 * due to stat info mismatch.
3804 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3805 diffopt->skip_stat_unmatch++;
3806 diff_free_filepair(p);
3809 free(q->queue);
3810 *q = outq;
3813 static int diffnamecmp(const void *a_, const void *b_)
3815 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3816 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3817 const char *name_a, *name_b;
3819 name_a = a->one ? a->one->path : a->two->path;
3820 name_b = b->one ? b->one->path : b->two->path;
3821 return strcmp(name_a, name_b);
3824 void diffcore_fix_diff_index(struct diff_options *options)
3826 struct diff_queue_struct *q = &diff_queued_diff;
3827 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3830 void diffcore_std(struct diff_options *options)
3832 if (options->skip_stat_unmatch)
3833 diffcore_skip_stat_unmatch(options);
3834 if (options->break_opt != -1)
3835 diffcore_break(options->break_opt);
3836 if (options->detect_rename)
3837 diffcore_rename(options);
3838 if (options->break_opt != -1)
3839 diffcore_merge_broken();
3840 if (options->pickaxe)
3841 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3842 if (options->orderfile)
3843 diffcore_order(options->orderfile);
3844 diff_resolve_rename_copy();
3845 diffcore_apply_filter(options->filter);
3847 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3848 DIFF_OPT_SET(options, HAS_CHANGES);
3849 else
3850 DIFF_OPT_CLR(options, HAS_CHANGES);
3853 int diff_result_code(struct diff_options *opt, int status)
3855 int result = 0;
3856 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3857 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3858 return status;
3859 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3860 DIFF_OPT_TST(opt, HAS_CHANGES))
3861 result |= 01;
3862 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3863 DIFF_OPT_TST(opt, CHECK_FAILED))
3864 result |= 02;
3865 return result;
3868 void diff_addremove(struct diff_options *options,
3869 int addremove, unsigned mode,
3870 const unsigned char *sha1,
3871 const char *concatpath, unsigned dirty_submodule)
3873 struct diff_filespec *one, *two;
3875 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3876 return;
3878 /* This may look odd, but it is a preparation for
3879 * feeding "there are unchanged files which should
3880 * not produce diffs, but when you are doing copy
3881 * detection you would need them, so here they are"
3882 * entries to the diff-core. They will be prefixed
3883 * with something like '=' or '*' (I haven't decided
3884 * which but should not make any difference).
3885 * Feeding the same new and old to diff_change()
3886 * also has the same effect.
3887 * Before the final output happens, they are pruned after
3888 * merged into rename/copy pairs as appropriate.
3890 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3891 addremove = (addremove == '+' ? '-' :
3892 addremove == '-' ? '+' : addremove);
3894 if (options->prefix &&
3895 strncmp(concatpath, options->prefix, options->prefix_length))
3896 return;
3898 one = alloc_filespec(concatpath);
3899 two = alloc_filespec(concatpath);
3901 if (addremove != '+')
3902 fill_filespec(one, sha1, mode);
3903 if (addremove != '-') {
3904 fill_filespec(two, sha1, mode);
3905 two->dirty_submodule = dirty_submodule;
3908 diff_queue(&diff_queued_diff, one, two);
3909 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3910 DIFF_OPT_SET(options, HAS_CHANGES);
3913 void diff_change(struct diff_options *options,
3914 unsigned old_mode, unsigned new_mode,
3915 const unsigned char *old_sha1,
3916 const unsigned char *new_sha1,
3917 const char *concatpath,
3918 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3920 struct diff_filespec *one, *two;
3922 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3923 && S_ISGITLINK(new_mode))
3924 return;
3926 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3927 unsigned tmp;
3928 const unsigned char *tmp_c;
3929 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3930 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3931 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3932 new_dirty_submodule = tmp;
3935 if (options->prefix &&
3936 strncmp(concatpath, options->prefix, options->prefix_length))
3937 return;
3939 one = alloc_filespec(concatpath);
3940 two = alloc_filespec(concatpath);
3941 fill_filespec(one, old_sha1, old_mode);
3942 fill_filespec(two, new_sha1, new_mode);
3943 one->dirty_submodule = old_dirty_submodule;
3944 two->dirty_submodule = new_dirty_submodule;
3946 diff_queue(&diff_queued_diff, one, two);
3947 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3948 DIFF_OPT_SET(options, HAS_CHANGES);
3951 void diff_unmerge(struct diff_options *options,
3952 const char *path,
3953 unsigned mode, const unsigned char *sha1)
3955 struct diff_filespec *one, *two;
3957 if (options->prefix &&
3958 strncmp(path, options->prefix, options->prefix_length))
3959 return;
3961 one = alloc_filespec(path);
3962 two = alloc_filespec(path);
3963 fill_filespec(one, sha1, mode);
3964 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3967 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3968 size_t *outsize)
3970 struct diff_tempfile *temp;
3971 const char *argv[3];
3972 const char **arg = argv;
3973 struct child_process child;
3974 struct strbuf buf = STRBUF_INIT;
3975 int err = 0;
3977 temp = prepare_temp_file(spec->path, spec);
3978 *arg++ = pgm;
3979 *arg++ = temp->name;
3980 *arg = NULL;
3982 memset(&child, 0, sizeof(child));
3983 child.use_shell = 1;
3984 child.argv = argv;
3985 child.out = -1;
3986 if (start_command(&child)) {
3987 remove_tempfile();
3988 return NULL;
3991 if (strbuf_read(&buf, child.out, 0) < 0)
3992 err = error("error reading from textconv command '%s'", pgm);
3993 close(child.out);
3995 if (finish_command(&child) || err) {
3996 strbuf_release(&buf);
3997 remove_tempfile();
3998 return NULL;
4000 remove_tempfile();
4002 return strbuf_detach(&buf, outsize);
4005 static size_t fill_textconv(struct userdiff_driver *driver,
4006 struct diff_filespec *df,
4007 char **outbuf)
4009 size_t size;
4011 if (!driver || !driver->textconv) {
4012 if (!DIFF_FILE_VALID(df)) {
4013 *outbuf = "";
4014 return 0;
4016 if (diff_populate_filespec(df, 0))
4017 die("unable to read files to diff");
4018 *outbuf = df->data;
4019 return df->size;
4022 if (driver->textconv_cache) {
4023 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4024 &size);
4025 if (*outbuf)
4026 return size;
4029 *outbuf = run_textconv(driver->textconv, df, &size);
4030 if (!*outbuf)
4031 die("unable to read files to diff");
4033 if (driver->textconv_cache) {
4034 /* ignore errors, as we might be in a readonly repository */
4035 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4036 size);
4038 * we could save up changes and flush them all at the end,
4039 * but we would need an extra call after all diffing is done.
4040 * Since generating a cache entry is the slow path anyway,
4041 * this extra overhead probably isn't a big deal.
4043 notes_cache_write(driver->textconv_cache);
4046 return size;