diff: use large integers for diffstat calculations
[git/dkf.git] / diff.c
blob0182237c2dab7fa3aa7e916f2eb8bc75865c0b9a
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"
18 #ifdef NO_FAST_WORKING_DIRECTORY
19 #define FAST_WORKING_DIRECTORY 0
20 #else
21 #define FAST_WORKING_DIRECTORY 1
22 #endif
24 static int diff_detect_rename_default;
25 static int diff_rename_limit_default = 200;
26 static int diff_suppress_blank_empty;
27 int diff_use_color_default = -1;
28 static const char *diff_word_regex_cfg;
29 static const char *external_diff_cmd_cfg;
30 int diff_auto_refresh_index = 1;
31 static int diff_mnemonic_prefix;
33 static char diff_colors[][COLOR_MAXLEN] = {
34 GIT_COLOR_RESET,
35 GIT_COLOR_NORMAL, /* PLAIN */
36 GIT_COLOR_BOLD, /* METAINFO */
37 GIT_COLOR_CYAN, /* FRAGINFO */
38 GIT_COLOR_RED, /* OLD */
39 GIT_COLOR_GREEN, /* NEW */
40 GIT_COLOR_YELLOW, /* COMMIT */
41 GIT_COLOR_BG_RED, /* WHITESPACE */
42 GIT_COLOR_NORMAL, /* FUNCINFO */
45 static void diff_filespec_load_driver(struct diff_filespec *one);
46 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
48 static int parse_diff_color_slot(const char *var, int ofs)
50 if (!strcasecmp(var+ofs, "plain"))
51 return DIFF_PLAIN;
52 if (!strcasecmp(var+ofs, "meta"))
53 return DIFF_METAINFO;
54 if (!strcasecmp(var+ofs, "frag"))
55 return DIFF_FRAGINFO;
56 if (!strcasecmp(var+ofs, "old"))
57 return DIFF_FILE_OLD;
58 if (!strcasecmp(var+ofs, "new"))
59 return DIFF_FILE_NEW;
60 if (!strcasecmp(var+ofs, "commit"))
61 return DIFF_COMMIT;
62 if (!strcasecmp(var+ofs, "whitespace"))
63 return DIFF_WHITESPACE;
64 if (!strcasecmp(var+ofs, "func"))
65 return DIFF_FUNCINFO;
66 return -1;
69 static int git_config_rename(const char *var, const char *value)
71 if (!value)
72 return DIFF_DETECT_RENAME;
73 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
74 return DIFF_DETECT_COPY;
75 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
79 * These are to give UI layer defaults.
80 * The core-level commands such as git-diff-files should
81 * never be affected by the setting of diff.renames
82 * the user happens to have in the configuration file.
84 int git_diff_ui_config(const char *var, const char *value, void *cb)
86 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
87 diff_use_color_default = git_config_colorbool(var, value, -1);
88 return 0;
90 if (!strcmp(var, "diff.renames")) {
91 diff_detect_rename_default = git_config_rename(var, value);
92 return 0;
94 if (!strcmp(var, "diff.autorefreshindex")) {
95 diff_auto_refresh_index = git_config_bool(var, value);
96 return 0;
98 if (!strcmp(var, "diff.mnemonicprefix")) {
99 diff_mnemonic_prefix = git_config_bool(var, value);
100 return 0;
102 if (!strcmp(var, "diff.external"))
103 return git_config_string(&external_diff_cmd_cfg, var, value);
104 if (!strcmp(var, "diff.wordregex"))
105 return git_config_string(&diff_word_regex_cfg, var, value);
107 return git_diff_basic_config(var, value, cb);
110 int git_diff_basic_config(const char *var, const char *value, void *cb)
112 if (!strcmp(var, "diff.renamelimit")) {
113 diff_rename_limit_default = git_config_int(var, value);
114 return 0;
117 switch (userdiff_config(var, value)) {
118 case 0: break;
119 case -1: return -1;
120 default: return 0;
123 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
124 int slot = parse_diff_color_slot(var, 11);
125 if (slot < 0)
126 return 0;
127 if (!value)
128 return config_error_nonbool(var);
129 color_parse(value, var, diff_colors[slot]);
130 return 0;
133 /* like GNU diff's --suppress-blank-empty option */
134 if (!strcmp(var, "diff.suppressblankempty") ||
135 /* for backwards compatibility */
136 !strcmp(var, "diff.suppress-blank-empty")) {
137 diff_suppress_blank_empty = git_config_bool(var, value);
138 return 0;
141 return git_color_default_config(var, value, cb);
144 static char *quote_two(const char *one, const char *two)
146 int need_one = quote_c_style(one, NULL, NULL, 1);
147 int need_two = quote_c_style(two, NULL, NULL, 1);
148 struct strbuf res = STRBUF_INIT;
150 if (need_one + need_two) {
151 strbuf_addch(&res, '"');
152 quote_c_style(one, &res, NULL, 1);
153 quote_c_style(two, &res, NULL, 1);
154 strbuf_addch(&res, '"');
155 } else {
156 strbuf_addstr(&res, one);
157 strbuf_addstr(&res, two);
159 return strbuf_detach(&res, NULL);
162 static const char *external_diff(void)
164 static const char *external_diff_cmd = NULL;
165 static int done_preparing = 0;
167 if (done_preparing)
168 return external_diff_cmd;
169 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
170 if (!external_diff_cmd)
171 external_diff_cmd = external_diff_cmd_cfg;
172 done_preparing = 1;
173 return external_diff_cmd;
176 static struct diff_tempfile {
177 const char *name; /* filename external diff should read from */
178 char hex[41];
179 char mode[10];
180 char tmp_path[PATH_MAX];
181 } diff_temp[2];
183 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
185 struct emit_callback {
186 int color_diff;
187 unsigned ws_rule;
188 int blank_at_eof_in_preimage;
189 int blank_at_eof_in_postimage;
190 int lno_in_preimage;
191 int lno_in_postimage;
192 sane_truncate_fn truncate;
193 const char **label_path;
194 struct diff_words_data *diff_words;
195 int *found_changesp;
196 FILE *file;
199 static int count_lines(const char *data, int size)
201 int count, ch, completely_empty = 1, nl_just_seen = 0;
202 count = 0;
203 while (0 < size--) {
204 ch = *data++;
205 if (ch == '\n') {
206 count++;
207 nl_just_seen = 1;
208 completely_empty = 0;
210 else {
211 nl_just_seen = 0;
212 completely_empty = 0;
215 if (completely_empty)
216 return 0;
217 if (!nl_just_seen)
218 count++; /* no trailing newline */
219 return count;
222 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
224 if (!DIFF_FILE_VALID(one)) {
225 mf->ptr = (char *)""; /* does not matter */
226 mf->size = 0;
227 return 0;
229 else if (diff_populate_filespec(one, 0))
230 return -1;
232 mf->ptr = one->data;
233 mf->size = one->size;
234 return 0;
237 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
239 char *ptr = mf->ptr;
240 long size = mf->size;
241 int cnt = 0;
243 if (!size)
244 return cnt;
245 ptr += size - 1; /* pointing at the very end */
246 if (*ptr != '\n')
247 ; /* incomplete line */
248 else
249 ptr--; /* skip the last LF */
250 while (mf->ptr < ptr) {
251 char *prev_eol;
252 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
253 if (*prev_eol == '\n')
254 break;
255 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
256 break;
257 cnt++;
258 ptr = prev_eol - 1;
260 return cnt;
263 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
264 struct emit_callback *ecbdata)
266 int l1, l2, at;
267 unsigned ws_rule = ecbdata->ws_rule;
268 l1 = count_trailing_blank(mf1, ws_rule);
269 l2 = count_trailing_blank(mf2, ws_rule);
270 if (l2 <= l1) {
271 ecbdata->blank_at_eof_in_preimage = 0;
272 ecbdata->blank_at_eof_in_postimage = 0;
273 return;
275 at = count_lines(mf1->ptr, mf1->size);
276 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
278 at = count_lines(mf2->ptr, mf2->size);
279 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
282 static void emit_line_0(FILE *file, const char *set, const char *reset,
283 int first, const char *line, int len)
285 int has_trailing_newline, has_trailing_carriage_return;
286 int nofirst;
288 if (len == 0) {
289 has_trailing_newline = (first == '\n');
290 has_trailing_carriage_return = (!has_trailing_newline &&
291 (first == '\r'));
292 nofirst = has_trailing_newline || has_trailing_carriage_return;
293 } else {
294 has_trailing_newline = (len > 0 && line[len-1] == '\n');
295 if (has_trailing_newline)
296 len--;
297 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
298 if (has_trailing_carriage_return)
299 len--;
300 nofirst = 0;
303 if (len || !nofirst) {
304 fputs(set, file);
305 if (!nofirst)
306 fputc(first, file);
307 fwrite(line, len, 1, file);
308 fputs(reset, file);
310 if (has_trailing_carriage_return)
311 fputc('\r', file);
312 if (has_trailing_newline)
313 fputc('\n', file);
316 static void emit_line(FILE *file, const char *set, const char *reset,
317 const char *line, int len)
319 emit_line_0(file, set, reset, line[0], line+1, len-1);
322 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
324 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
325 ecbdata->blank_at_eof_in_preimage &&
326 ecbdata->blank_at_eof_in_postimage &&
327 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
328 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
329 return 0;
330 return ws_blank_line(line, len, ecbdata->ws_rule);
333 static void emit_add_line(const char *reset,
334 struct emit_callback *ecbdata,
335 const char *line, int len)
337 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
338 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
340 if (!*ws)
341 emit_line_0(ecbdata->file, set, reset, '+', line, len);
342 else if (new_blank_line_at_eof(ecbdata, line, len))
343 /* Blank line at EOF - paint '+' as well */
344 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
345 else {
346 /* Emit just the prefix, then the rest. */
347 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
348 ws_check_emit(line, len, ecbdata->ws_rule,
349 ecbdata->file, set, reset, ws);
353 static void emit_hunk_header(struct emit_callback *ecbdata,
354 const char *line, int len)
356 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
357 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
358 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
359 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
360 static const char atat[2] = { '@', '@' };
361 const char *cp, *ep;
364 * As a hunk header must begin with "@@ -<old>, +<new> @@",
365 * it always is at least 10 bytes long.
367 if (len < 10 ||
368 memcmp(line, atat, 2) ||
369 !(ep = memmem(line + 2, len - 2, atat, 2))) {
370 emit_line(ecbdata->file, plain, reset, line, len);
371 return;
373 ep += 2; /* skip over @@ */
375 /* The hunk header in fraginfo color */
376 emit_line(ecbdata->file, frag, reset, line, ep - line);
378 /* blank before the func header */
379 for (cp = ep; ep - line < len; ep++)
380 if (*ep != ' ' && *ep != '\t')
381 break;
382 if (ep != cp)
383 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
385 if (ep < line + len)
386 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
389 static struct diff_tempfile *claim_diff_tempfile(void) {
390 int i;
391 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
392 if (!diff_temp[i].name)
393 return diff_temp + i;
394 die("BUG: diff is failing to clean up its tempfiles");
397 static int remove_tempfile_installed;
399 static void remove_tempfile(void)
401 int i;
402 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
403 if (diff_temp[i].name == diff_temp[i].tmp_path)
404 unlink_or_warn(diff_temp[i].name);
405 diff_temp[i].name = NULL;
409 static void remove_tempfile_on_signal(int signo)
411 remove_tempfile();
412 sigchain_pop(signo);
413 raise(signo);
416 static void print_line_count(FILE *file, int count)
418 switch (count) {
419 case 0:
420 fprintf(file, "0,0");
421 break;
422 case 1:
423 fprintf(file, "1");
424 break;
425 default:
426 fprintf(file, "1,%d", count);
427 break;
431 static void emit_rewrite_lines(struct emit_callback *ecb,
432 int prefix, const char *data, int size)
434 const char *endp = NULL;
435 static const char *nneof = " No newline at end of file\n";
436 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
437 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
439 while (0 < size) {
440 int len;
442 endp = memchr(data, '\n', size);
443 len = endp ? (endp - data + 1) : size;
444 if (prefix != '+') {
445 ecb->lno_in_preimage++;
446 emit_line_0(ecb->file, old, reset, '-',
447 data, len);
448 } else {
449 ecb->lno_in_postimage++;
450 emit_add_line(reset, ecb, data, len);
452 size -= len;
453 data += len;
455 if (!endp) {
456 const char *plain = diff_get_color(ecb->color_diff,
457 DIFF_PLAIN);
458 emit_line_0(ecb->file, plain, reset, '\\',
459 nneof, strlen(nneof));
463 static void emit_rewrite_diff(const char *name_a,
464 const char *name_b,
465 struct diff_filespec *one,
466 struct diff_filespec *two,
467 const char *textconv_one,
468 const char *textconv_two,
469 struct diff_options *o)
471 int lc_a, lc_b;
472 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
473 const char *name_a_tab, *name_b_tab;
474 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
475 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
476 const char *reset = diff_get_color(color_diff, DIFF_RESET);
477 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
478 const char *a_prefix, *b_prefix;
479 const char *data_one, *data_two;
480 size_t size_one, size_two;
481 struct emit_callback ecbdata;
483 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
484 a_prefix = o->b_prefix;
485 b_prefix = o->a_prefix;
486 } else {
487 a_prefix = o->a_prefix;
488 b_prefix = o->b_prefix;
491 name_a += (*name_a == '/');
492 name_b += (*name_b == '/');
493 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
494 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
496 strbuf_reset(&a_name);
497 strbuf_reset(&b_name);
498 quote_two_c_style(&a_name, a_prefix, name_a, 0);
499 quote_two_c_style(&b_name, b_prefix, name_b, 0);
501 diff_populate_filespec(one, 0);
502 diff_populate_filespec(two, 0);
503 if (textconv_one) {
504 data_one = run_textconv(textconv_one, one, &size_one);
505 if (!data_one)
506 die("unable to read files to diff");
508 else {
509 data_one = one->data;
510 size_one = one->size;
512 if (textconv_two) {
513 data_two = run_textconv(textconv_two, two, &size_two);
514 if (!data_two)
515 die("unable to read files to diff");
517 else {
518 data_two = two->data;
519 size_two = two->size;
522 memset(&ecbdata, 0, sizeof(ecbdata));
523 ecbdata.color_diff = color_diff;
524 ecbdata.found_changesp = &o->found_changes;
525 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
526 ecbdata.file = o->file;
527 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
528 mmfile_t mf1, mf2;
529 mf1.ptr = (char *)data_one;
530 mf2.ptr = (char *)data_two;
531 mf1.size = size_one;
532 mf2.size = size_two;
533 check_blank_at_eof(&mf1, &mf2, &ecbdata);
535 ecbdata.lno_in_preimage = 1;
536 ecbdata.lno_in_postimage = 1;
538 lc_a = count_lines(data_one, size_one);
539 lc_b = count_lines(data_two, size_two);
540 fprintf(o->file,
541 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
542 metainfo, a_name.buf, name_a_tab, reset,
543 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
544 print_line_count(o->file, lc_a);
545 fprintf(o->file, " +");
546 print_line_count(o->file, lc_b);
547 fprintf(o->file, " @@%s\n", reset);
548 if (lc_a)
549 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
550 if (lc_b)
551 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
554 struct diff_words_buffer {
555 mmfile_t text;
556 long alloc;
557 struct diff_words_orig {
558 const char *begin, *end;
559 } *orig;
560 int orig_nr, orig_alloc;
563 static void diff_words_append(char *line, unsigned long len,
564 struct diff_words_buffer *buffer)
566 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
567 line++;
568 len--;
569 memcpy(buffer->text.ptr + buffer->text.size, line, len);
570 buffer->text.size += len;
571 buffer->text.ptr[buffer->text.size] = '\0';
574 struct diff_words_data {
575 struct diff_words_buffer minus, plus;
576 const char *current_plus;
577 FILE *file;
578 regex_t *word_regex;
581 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
583 struct diff_words_data *diff_words = priv;
584 int minus_first, minus_len, plus_first, plus_len;
585 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
587 if (line[0] != '@' || parse_hunk_header(line, len,
588 &minus_first, &minus_len, &plus_first, &plus_len))
589 return;
591 /* POSIX requires that first be decremented by one if len == 0... */
592 if (minus_len) {
593 minus_begin = diff_words->minus.orig[minus_first].begin;
594 minus_end =
595 diff_words->minus.orig[minus_first + minus_len - 1].end;
596 } else
597 minus_begin = minus_end =
598 diff_words->minus.orig[minus_first].end;
600 if (plus_len) {
601 plus_begin = diff_words->plus.orig[plus_first].begin;
602 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
603 } else
604 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
606 if (diff_words->current_plus != plus_begin)
607 fwrite(diff_words->current_plus,
608 plus_begin - diff_words->current_plus, 1,
609 diff_words->file);
610 if (minus_begin != minus_end)
611 color_fwrite_lines(diff_words->file,
612 diff_get_color(1, DIFF_FILE_OLD),
613 minus_end - minus_begin, minus_begin);
614 if (plus_begin != plus_end)
615 color_fwrite_lines(diff_words->file,
616 diff_get_color(1, DIFF_FILE_NEW),
617 plus_end - plus_begin, plus_begin);
619 diff_words->current_plus = plus_end;
622 /* This function starts looking at *begin, and returns 0 iff a word was found. */
623 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
624 int *begin, int *end)
626 if (word_regex && *begin < buffer->size) {
627 regmatch_t match[1];
628 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
629 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
630 '\n', match[0].rm_eo - match[0].rm_so);
631 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
632 *begin += match[0].rm_so;
633 return *begin >= *end;
635 return -1;
638 /* find the next word */
639 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
640 (*begin)++;
641 if (*begin >= buffer->size)
642 return -1;
644 /* find the end of the word */
645 *end = *begin + 1;
646 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
647 (*end)++;
649 return 0;
653 * This function splits the words in buffer->text, stores the list with
654 * newline separator into out, and saves the offsets of the original words
655 * in buffer->orig.
657 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
658 regex_t *word_regex)
660 int i, j;
661 long alloc = 0;
663 out->size = 0;
664 out->ptr = NULL;
666 /* fake an empty "0th" word */
667 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
668 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
669 buffer->orig_nr = 1;
671 for (i = 0; i < buffer->text.size; i++) {
672 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
673 return;
675 /* store original boundaries */
676 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
677 buffer->orig_alloc);
678 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
679 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
680 buffer->orig_nr++;
682 /* store one word */
683 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
684 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
685 out->ptr[out->size + j - i] = '\n';
686 out->size += j - i + 1;
688 i = j - 1;
692 /* this executes the word diff on the accumulated buffers */
693 static void diff_words_show(struct diff_words_data *diff_words)
695 xpparam_t xpp;
696 xdemitconf_t xecfg;
697 xdemitcb_t ecb;
698 mmfile_t minus, plus;
700 /* special case: only removal */
701 if (!diff_words->plus.text.size) {
702 color_fwrite_lines(diff_words->file,
703 diff_get_color(1, DIFF_FILE_OLD),
704 diff_words->minus.text.size, diff_words->minus.text.ptr);
705 diff_words->minus.text.size = 0;
706 return;
709 diff_words->current_plus = diff_words->plus.text.ptr;
711 memset(&xpp, 0, sizeof(xpp));
712 memset(&xecfg, 0, sizeof(xecfg));
713 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
714 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
715 xpp.flags = XDF_NEED_MINIMAL;
716 /* as only the hunk header will be parsed, we need a 0-context */
717 xecfg.ctxlen = 0;
718 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
719 &xpp, &xecfg, &ecb);
720 free(minus.ptr);
721 free(plus.ptr);
722 if (diff_words->current_plus != diff_words->plus.text.ptr +
723 diff_words->plus.text.size)
724 fwrite(diff_words->current_plus,
725 diff_words->plus.text.ptr + diff_words->plus.text.size
726 - diff_words->current_plus, 1,
727 diff_words->file);
728 diff_words->minus.text.size = diff_words->plus.text.size = 0;
731 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
732 static void diff_words_flush(struct emit_callback *ecbdata)
734 if (ecbdata->diff_words->minus.text.size ||
735 ecbdata->diff_words->plus.text.size)
736 diff_words_show(ecbdata->diff_words);
739 static void free_diff_words_data(struct emit_callback *ecbdata)
741 if (ecbdata->diff_words) {
742 diff_words_flush(ecbdata);
743 free (ecbdata->diff_words->minus.text.ptr);
744 free (ecbdata->diff_words->minus.orig);
745 free (ecbdata->diff_words->plus.text.ptr);
746 free (ecbdata->diff_words->plus.orig);
747 free(ecbdata->diff_words->word_regex);
748 free(ecbdata->diff_words);
749 ecbdata->diff_words = NULL;
753 const char *diff_get_color(int diff_use_color, enum color_diff ix)
755 if (diff_use_color)
756 return diff_colors[ix];
757 return "";
760 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
762 const char *cp;
763 unsigned long allot;
764 size_t l = len;
766 if (ecb->truncate)
767 return ecb->truncate(line, len);
768 cp = line;
769 allot = l;
770 while (0 < l) {
771 (void) utf8_width(&cp, &l);
772 if (!cp)
773 break; /* truncated in the middle? */
775 return allot - l;
778 static void find_lno(const char *line, struct emit_callback *ecbdata)
780 const char *p;
781 ecbdata->lno_in_preimage = 0;
782 ecbdata->lno_in_postimage = 0;
783 p = strchr(line, '-');
784 if (!p)
785 return; /* cannot happen */
786 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
787 p = strchr(p, '+');
788 if (!p)
789 return; /* cannot happen */
790 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
793 static void fn_out_consume(void *priv, char *line, unsigned long len)
795 struct emit_callback *ecbdata = priv;
796 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
797 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
798 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
800 *(ecbdata->found_changesp) = 1;
802 if (ecbdata->label_path[0]) {
803 const char *name_a_tab, *name_b_tab;
805 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
806 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
808 fprintf(ecbdata->file, "%s--- %s%s%s\n",
809 meta, ecbdata->label_path[0], reset, name_a_tab);
810 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
811 meta, ecbdata->label_path[1], reset, name_b_tab);
812 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
815 if (diff_suppress_blank_empty
816 && len == 2 && line[0] == ' ' && line[1] == '\n') {
817 line[0] = '\n';
818 len = 1;
821 if (line[0] == '@') {
822 if (ecbdata->diff_words)
823 diff_words_flush(ecbdata);
824 len = sane_truncate_line(ecbdata, line, len);
825 find_lno(line, ecbdata);
826 emit_hunk_header(ecbdata, line, len);
827 if (line[len-1] != '\n')
828 putc('\n', ecbdata->file);
829 return;
832 if (len < 1) {
833 emit_line(ecbdata->file, reset, reset, line, len);
834 return;
837 if (ecbdata->diff_words) {
838 if (line[0] == '-') {
839 diff_words_append(line, len,
840 &ecbdata->diff_words->minus);
841 return;
842 } else if (line[0] == '+') {
843 diff_words_append(line, len,
844 &ecbdata->diff_words->plus);
845 return;
847 diff_words_flush(ecbdata);
848 line++;
849 len--;
850 emit_line(ecbdata->file, plain, reset, line, len);
851 return;
854 if (line[0] != '+') {
855 const char *color =
856 diff_get_color(ecbdata->color_diff,
857 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
858 ecbdata->lno_in_preimage++;
859 if (line[0] == ' ')
860 ecbdata->lno_in_postimage++;
861 emit_line(ecbdata->file, color, reset, line, len);
862 } else {
863 ecbdata->lno_in_postimage++;
864 emit_add_line(reset, ecbdata, line + 1, len - 1);
868 static char *pprint_rename(const char *a, const char *b)
870 const char *old = a;
871 const char *new = b;
872 struct strbuf name = STRBUF_INIT;
873 int pfx_length, sfx_length;
874 int len_a = strlen(a);
875 int len_b = strlen(b);
876 int a_midlen, b_midlen;
877 int qlen_a = quote_c_style(a, NULL, NULL, 0);
878 int qlen_b = quote_c_style(b, NULL, NULL, 0);
880 if (qlen_a || qlen_b) {
881 quote_c_style(a, &name, NULL, 0);
882 strbuf_addstr(&name, " => ");
883 quote_c_style(b, &name, NULL, 0);
884 return strbuf_detach(&name, NULL);
887 /* Find common prefix */
888 pfx_length = 0;
889 while (*old && *new && *old == *new) {
890 if (*old == '/')
891 pfx_length = old - a + 1;
892 old++;
893 new++;
896 /* Find common suffix */
897 old = a + len_a;
898 new = b + len_b;
899 sfx_length = 0;
900 while (a <= old && b <= new && *old == *new) {
901 if (*old == '/')
902 sfx_length = len_a - (old - a);
903 old--;
904 new--;
908 * pfx{mid-a => mid-b}sfx
909 * {pfx-a => pfx-b}sfx
910 * pfx{sfx-a => sfx-b}
911 * name-a => name-b
913 a_midlen = len_a - pfx_length - sfx_length;
914 b_midlen = len_b - pfx_length - sfx_length;
915 if (a_midlen < 0)
916 a_midlen = 0;
917 if (b_midlen < 0)
918 b_midlen = 0;
920 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
921 if (pfx_length + sfx_length) {
922 strbuf_add(&name, a, pfx_length);
923 strbuf_addch(&name, '{');
925 strbuf_add(&name, a + pfx_length, a_midlen);
926 strbuf_addstr(&name, " => ");
927 strbuf_add(&name, b + pfx_length, b_midlen);
928 if (pfx_length + sfx_length) {
929 strbuf_addch(&name, '}');
930 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
932 return strbuf_detach(&name, NULL);
935 struct diffstat_t {
936 int nr;
937 int alloc;
938 struct diffstat_file {
939 char *from_name;
940 char *name;
941 char *print_name;
942 unsigned is_unmerged:1;
943 unsigned is_binary:1;
944 unsigned is_renamed:1;
945 uintmax_t added, deleted;
946 } **files;
949 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
950 const char *name_a,
951 const char *name_b)
953 struct diffstat_file *x;
954 x = xcalloc(sizeof (*x), 1);
955 if (diffstat->nr == diffstat->alloc) {
956 diffstat->alloc = alloc_nr(diffstat->alloc);
957 diffstat->files = xrealloc(diffstat->files,
958 diffstat->alloc * sizeof(x));
960 diffstat->files[diffstat->nr++] = x;
961 if (name_b) {
962 x->from_name = xstrdup(name_a);
963 x->name = xstrdup(name_b);
964 x->is_renamed = 1;
966 else {
967 x->from_name = NULL;
968 x->name = xstrdup(name_a);
970 return x;
973 static void diffstat_consume(void *priv, char *line, unsigned long len)
975 struct diffstat_t *diffstat = priv;
976 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
978 if (line[0] == '+')
979 x->added++;
980 else if (line[0] == '-')
981 x->deleted++;
984 const char mime_boundary_leader[] = "------------";
986 static int scale_linear(int it, int width, int max_change)
989 * make sure that at least one '-' is printed if there were deletions,
990 * and likewise for '+'.
992 if (max_change < 2)
993 return it;
994 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
997 static void show_name(FILE *file,
998 const char *prefix, const char *name, int len)
1000 fprintf(file, " %s%-*s |", prefix, len, name);
1003 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1005 if (cnt <= 0)
1006 return;
1007 fprintf(file, "%s", set);
1008 while (cnt--)
1009 putc(ch, file);
1010 fprintf(file, "%s", reset);
1013 static void fill_print_name(struct diffstat_file *file)
1015 char *pname;
1017 if (file->print_name)
1018 return;
1020 if (!file->is_renamed) {
1021 struct strbuf buf = STRBUF_INIT;
1022 if (quote_c_style(file->name, &buf, NULL, 0)) {
1023 pname = strbuf_detach(&buf, NULL);
1024 } else {
1025 pname = file->name;
1026 strbuf_release(&buf);
1028 } else {
1029 pname = pprint_rename(file->from_name, file->name);
1031 file->print_name = pname;
1034 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1036 int i, len, add, del, adds = 0, dels = 0;
1037 uintmax_t max_change = 0, max_len = 0;
1038 int total_files = data->nr;
1039 int width, name_width;
1040 const char *reset, *set, *add_c, *del_c;
1042 if (data->nr == 0)
1043 return;
1045 width = options->stat_width ? options->stat_width : 80;
1046 name_width = options->stat_name_width ? options->stat_name_width : 50;
1048 /* Sanity: give at least 5 columns to the graph,
1049 * but leave at least 10 columns for the name.
1051 if (width < 25)
1052 width = 25;
1053 if (name_width < 10)
1054 name_width = 10;
1055 else if (width < name_width + 15)
1056 name_width = width - 15;
1058 /* Find the longest filename and max number of changes */
1059 reset = diff_get_color_opt(options, DIFF_RESET);
1060 set = diff_get_color_opt(options, DIFF_PLAIN);
1061 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1062 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1064 for (i = 0; i < data->nr; i++) {
1065 struct diffstat_file *file = data->files[i];
1066 uintmax_t change = file->added + file->deleted;
1067 fill_print_name(file);
1068 len = strlen(file->print_name);
1069 if (max_len < len)
1070 max_len = len;
1072 if (file->is_binary || file->is_unmerged)
1073 continue;
1074 if (max_change < change)
1075 max_change = change;
1078 /* Compute the width of the graph part;
1079 * 10 is for one blank at the beginning of the line plus
1080 * " | count " between the name and the graph.
1082 * From here on, name_width is the width of the name area,
1083 * and width is the width of the graph area.
1085 name_width = (name_width < max_len) ? name_width : max_len;
1086 if (width < (name_width + 10) + max_change)
1087 width = width - (name_width + 10);
1088 else
1089 width = max_change;
1091 for (i = 0; i < data->nr; i++) {
1092 const char *prefix = "";
1093 char *name = data->files[i]->print_name;
1094 uintmax_t added = data->files[i]->added;
1095 uintmax_t deleted = data->files[i]->deleted;
1096 int name_len;
1099 * "scale" the filename
1101 len = name_width;
1102 name_len = strlen(name);
1103 if (name_width < name_len) {
1104 char *slash;
1105 prefix = "...";
1106 len -= 3;
1107 name += name_len - len;
1108 slash = strchr(name, '/');
1109 if (slash)
1110 name = slash;
1113 if (data->files[i]->is_binary) {
1114 show_name(options->file, prefix, name, len);
1115 fprintf(options->file, " Bin ");
1116 fprintf(options->file, "%s%"PRIuMAX"%s",
1117 del_c, deleted, reset);
1118 fprintf(options->file, " -> ");
1119 fprintf(options->file, "%s%"PRIuMAX"%s",
1120 add_c, added, reset);
1121 fprintf(options->file, " bytes");
1122 fprintf(options->file, "\n");
1123 continue;
1125 else if (data->files[i]->is_unmerged) {
1126 show_name(options->file, prefix, name, len);
1127 fprintf(options->file, " Unmerged\n");
1128 continue;
1130 else if (!data->files[i]->is_renamed &&
1131 (added + deleted == 0)) {
1132 total_files--;
1133 continue;
1137 * scale the add/delete
1139 add = added;
1140 del = deleted;
1141 adds += add;
1142 dels += del;
1144 if (width <= max_change) {
1145 add = scale_linear(add, width, max_change);
1146 del = scale_linear(del, width, max_change);
1148 show_name(options->file, prefix, name, len);
1149 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1150 added + deleted ? " " : "");
1151 show_graph(options->file, '+', add, add_c, reset);
1152 show_graph(options->file, '-', del, del_c, reset);
1153 fprintf(options->file, "\n");
1155 fprintf(options->file,
1156 " %d files changed, %d insertions(+), %d deletions(-)\n",
1157 total_files, adds, dels);
1160 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1162 int i, adds = 0, dels = 0, total_files = data->nr;
1164 if (data->nr == 0)
1165 return;
1167 for (i = 0; i < data->nr; i++) {
1168 if (!data->files[i]->is_binary &&
1169 !data->files[i]->is_unmerged) {
1170 int added = data->files[i]->added;
1171 int deleted= data->files[i]->deleted;
1172 if (!data->files[i]->is_renamed &&
1173 (added + deleted == 0)) {
1174 total_files--;
1175 } else {
1176 adds += added;
1177 dels += deleted;
1181 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1182 total_files, adds, dels);
1185 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1187 int i;
1189 if (data->nr == 0)
1190 return;
1192 for (i = 0; i < data->nr; i++) {
1193 struct diffstat_file *file = data->files[i];
1195 if (file->is_binary)
1196 fprintf(options->file, "-\t-\t");
1197 else
1198 fprintf(options->file,
1199 "%"PRIuMAX"\t%"PRIuMAX"\t",
1200 file->added, file->deleted);
1201 if (options->line_termination) {
1202 fill_print_name(file);
1203 if (!file->is_renamed)
1204 write_name_quoted(file->name, options->file,
1205 options->line_termination);
1206 else {
1207 fputs(file->print_name, options->file);
1208 putc(options->line_termination, options->file);
1210 } else {
1211 if (file->is_renamed) {
1212 putc('\0', options->file);
1213 write_name_quoted(file->from_name, options->file, '\0');
1215 write_name_quoted(file->name, options->file, '\0');
1220 struct dirstat_file {
1221 const char *name;
1222 unsigned long changed;
1225 struct dirstat_dir {
1226 struct dirstat_file *files;
1227 int alloc, nr, percent, cumulative;
1230 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1232 unsigned long this_dir = 0;
1233 unsigned int sources = 0;
1235 while (dir->nr) {
1236 struct dirstat_file *f = dir->files;
1237 int namelen = strlen(f->name);
1238 unsigned long this;
1239 char *slash;
1241 if (namelen < baselen)
1242 break;
1243 if (memcmp(f->name, base, baselen))
1244 break;
1245 slash = strchr(f->name + baselen, '/');
1246 if (slash) {
1247 int newbaselen = slash + 1 - f->name;
1248 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1249 sources++;
1250 } else {
1251 this = f->changed;
1252 dir->files++;
1253 dir->nr--;
1254 sources += 2;
1256 this_dir += this;
1260 * We don't report dirstat's for
1261 * - the top level
1262 * - or cases where everything came from a single directory
1263 * under this directory (sources == 1).
1265 if (baselen && sources != 1) {
1266 int permille = this_dir * 1000 / changed;
1267 if (permille) {
1268 int percent = permille / 10;
1269 if (percent >= dir->percent) {
1270 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1271 if (!dir->cumulative)
1272 return 0;
1276 return this_dir;
1279 static int dirstat_compare(const void *_a, const void *_b)
1281 const struct dirstat_file *a = _a;
1282 const struct dirstat_file *b = _b;
1283 return strcmp(a->name, b->name);
1286 static void show_dirstat(struct diff_options *options)
1288 int i;
1289 unsigned long changed;
1290 struct dirstat_dir dir;
1291 struct diff_queue_struct *q = &diff_queued_diff;
1293 dir.files = NULL;
1294 dir.alloc = 0;
1295 dir.nr = 0;
1296 dir.percent = options->dirstat_percent;
1297 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1299 changed = 0;
1300 for (i = 0; i < q->nr; i++) {
1301 struct diff_filepair *p = q->queue[i];
1302 const char *name;
1303 unsigned long copied, added, damage;
1305 name = p->one->path ? p->one->path : p->two->path;
1307 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1308 diff_populate_filespec(p->one, 0);
1309 diff_populate_filespec(p->two, 0);
1310 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1311 &copied, &added);
1312 diff_free_filespec_data(p->one);
1313 diff_free_filespec_data(p->two);
1314 } else if (DIFF_FILE_VALID(p->one)) {
1315 diff_populate_filespec(p->one, 1);
1316 copied = added = 0;
1317 diff_free_filespec_data(p->one);
1318 } else if (DIFF_FILE_VALID(p->two)) {
1319 diff_populate_filespec(p->two, 1);
1320 copied = 0;
1321 added = p->two->size;
1322 diff_free_filespec_data(p->two);
1323 } else
1324 continue;
1327 * Original minus copied is the removed material,
1328 * added is the new material. They are both damages
1329 * made to the preimage. In --dirstat-by-file mode, count
1330 * damaged files, not damaged lines. This is done by
1331 * counting only a single damaged line per file.
1333 damage = (p->one->size - copied) + added;
1334 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1335 damage = 1;
1337 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1338 dir.files[dir.nr].name = name;
1339 dir.files[dir.nr].changed = damage;
1340 changed += damage;
1341 dir.nr++;
1344 /* This can happen even with many files, if everything was renames */
1345 if (!changed)
1346 return;
1348 /* Show all directories with more than x% of the changes */
1349 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1350 gather_dirstat(options->file, &dir, changed, "", 0);
1353 static void free_diffstat_info(struct diffstat_t *diffstat)
1355 int i;
1356 for (i = 0; i < diffstat->nr; i++) {
1357 struct diffstat_file *f = diffstat->files[i];
1358 if (f->name != f->print_name)
1359 free(f->print_name);
1360 free(f->name);
1361 free(f->from_name);
1362 free(f);
1364 free(diffstat->files);
1367 struct checkdiff_t {
1368 const char *filename;
1369 int lineno;
1370 struct diff_options *o;
1371 unsigned ws_rule;
1372 unsigned status;
1375 static int is_conflict_marker(const char *line, unsigned long len)
1377 char firstchar;
1378 int cnt;
1380 if (len < 8)
1381 return 0;
1382 firstchar = line[0];
1383 switch (firstchar) {
1384 case '=': case '>': case '<':
1385 break;
1386 default:
1387 return 0;
1389 for (cnt = 1; cnt < 7; cnt++)
1390 if (line[cnt] != firstchar)
1391 return 0;
1392 /* line[0] thru line[6] are same as firstchar */
1393 if (firstchar == '=') {
1394 /* divider between ours and theirs? */
1395 if (len != 8 || line[7] != '\n')
1396 return 0;
1397 } else if (len < 8 || !isspace(line[7])) {
1398 /* not divider before ours nor after theirs */
1399 return 0;
1401 return 1;
1404 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1406 struct checkdiff_t *data = priv;
1407 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1408 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1409 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1410 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1411 char *err;
1413 if (line[0] == '+') {
1414 unsigned bad;
1415 data->lineno++;
1416 if (is_conflict_marker(line + 1, len - 1)) {
1417 data->status |= 1;
1418 fprintf(data->o->file,
1419 "%s:%d: leftover conflict marker\n",
1420 data->filename, data->lineno);
1422 bad = ws_check(line + 1, len - 1, data->ws_rule);
1423 if (!bad)
1424 return;
1425 data->status |= bad;
1426 err = whitespace_error_string(bad);
1427 fprintf(data->o->file, "%s:%d: %s.\n",
1428 data->filename, data->lineno, err);
1429 free(err);
1430 emit_line(data->o->file, set, reset, line, 1);
1431 ws_check_emit(line + 1, len - 1, data->ws_rule,
1432 data->o->file, set, reset, ws);
1433 } else if (line[0] == ' ') {
1434 data->lineno++;
1435 } else if (line[0] == '@') {
1436 char *plus = strchr(line, '+');
1437 if (plus)
1438 data->lineno = strtol(plus, NULL, 10) - 1;
1439 else
1440 die("invalid diff");
1444 static unsigned char *deflate_it(char *data,
1445 unsigned long size,
1446 unsigned long *result_size)
1448 int bound;
1449 unsigned char *deflated;
1450 z_stream stream;
1452 memset(&stream, 0, sizeof(stream));
1453 deflateInit(&stream, zlib_compression_level);
1454 bound = deflateBound(&stream, size);
1455 deflated = xmalloc(bound);
1456 stream.next_out = deflated;
1457 stream.avail_out = bound;
1459 stream.next_in = (unsigned char *)data;
1460 stream.avail_in = size;
1461 while (deflate(&stream, Z_FINISH) == Z_OK)
1462 ; /* nothing */
1463 deflateEnd(&stream);
1464 *result_size = stream.total_out;
1465 return deflated;
1468 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1470 void *cp;
1471 void *delta;
1472 void *deflated;
1473 void *data;
1474 unsigned long orig_size;
1475 unsigned long delta_size;
1476 unsigned long deflate_size;
1477 unsigned long data_size;
1479 /* We could do deflated delta, or we could do just deflated two,
1480 * whichever is smaller.
1482 delta = NULL;
1483 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1484 if (one->size && two->size) {
1485 delta = diff_delta(one->ptr, one->size,
1486 two->ptr, two->size,
1487 &delta_size, deflate_size);
1488 if (delta) {
1489 void *to_free = delta;
1490 orig_size = delta_size;
1491 delta = deflate_it(delta, delta_size, &delta_size);
1492 free(to_free);
1496 if (delta && delta_size < deflate_size) {
1497 fprintf(file, "delta %lu\n", orig_size);
1498 free(deflated);
1499 data = delta;
1500 data_size = delta_size;
1502 else {
1503 fprintf(file, "literal %lu\n", two->size);
1504 free(delta);
1505 data = deflated;
1506 data_size = deflate_size;
1509 /* emit data encoded in base85 */
1510 cp = data;
1511 while (data_size) {
1512 int bytes = (52 < data_size) ? 52 : data_size;
1513 char line[70];
1514 data_size -= bytes;
1515 if (bytes <= 26)
1516 line[0] = bytes + 'A' - 1;
1517 else
1518 line[0] = bytes - 26 + 'a' - 1;
1519 encode_85(line + 1, cp, bytes);
1520 cp = (char *) cp + bytes;
1521 fputs(line, file);
1522 fputc('\n', file);
1524 fprintf(file, "\n");
1525 free(data);
1528 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1530 fprintf(file, "GIT binary patch\n");
1531 emit_binary_diff_body(file, one, two);
1532 emit_binary_diff_body(file, two, one);
1535 static void diff_filespec_load_driver(struct diff_filespec *one)
1537 if (!one->driver)
1538 one->driver = userdiff_find_by_path(one->path);
1539 if (!one->driver)
1540 one->driver = userdiff_find_by_name("default");
1543 int diff_filespec_is_binary(struct diff_filespec *one)
1545 if (one->is_binary == -1) {
1546 diff_filespec_load_driver(one);
1547 if (one->driver->binary != -1)
1548 one->is_binary = one->driver->binary;
1549 else {
1550 if (!one->data && DIFF_FILE_VALID(one))
1551 diff_populate_filespec(one, 0);
1552 if (one->data)
1553 one->is_binary = buffer_is_binary(one->data,
1554 one->size);
1555 if (one->is_binary == -1)
1556 one->is_binary = 0;
1559 return one->is_binary;
1562 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1564 diff_filespec_load_driver(one);
1565 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1568 static const char *userdiff_word_regex(struct diff_filespec *one)
1570 diff_filespec_load_driver(one);
1571 return one->driver->word_regex;
1574 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1576 if (!options->a_prefix)
1577 options->a_prefix = a;
1578 if (!options->b_prefix)
1579 options->b_prefix = b;
1582 static const char *get_textconv(struct diff_filespec *one)
1584 if (!DIFF_FILE_VALID(one))
1585 return NULL;
1586 if (!S_ISREG(one->mode))
1587 return NULL;
1588 diff_filespec_load_driver(one);
1589 return one->driver->textconv;
1592 static void builtin_diff(const char *name_a,
1593 const char *name_b,
1594 struct diff_filespec *one,
1595 struct diff_filespec *two,
1596 const char *xfrm_msg,
1597 struct diff_options *o,
1598 int complete_rewrite)
1600 mmfile_t mf1, mf2;
1601 const char *lbl[2];
1602 char *a_one, *b_two;
1603 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1604 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1605 const char *a_prefix, *b_prefix;
1606 const char *textconv_one = NULL, *textconv_two = NULL;
1608 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1609 (!one->mode || S_ISGITLINK(one->mode)) &&
1610 (!two->mode || S_ISGITLINK(two->mode))) {
1611 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1612 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1613 show_submodule_summary(o->file, one ? one->path : two->path,
1614 one->sha1, two->sha1,
1615 del, add, reset);
1616 return;
1619 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1620 textconv_one = get_textconv(one);
1621 textconv_two = get_textconv(two);
1624 diff_set_mnemonic_prefix(o, "a/", "b/");
1625 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1626 a_prefix = o->b_prefix;
1627 b_prefix = o->a_prefix;
1628 } else {
1629 a_prefix = o->a_prefix;
1630 b_prefix = o->b_prefix;
1633 /* Never use a non-valid filename anywhere if at all possible */
1634 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1635 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1637 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1638 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1639 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1640 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1641 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1642 if (lbl[0][0] == '/') {
1643 /* /dev/null */
1644 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1645 if (xfrm_msg && xfrm_msg[0])
1646 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1648 else if (lbl[1][0] == '/') {
1649 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1650 if (xfrm_msg && xfrm_msg[0])
1651 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1653 else {
1654 if (one->mode != two->mode) {
1655 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1656 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1658 if (xfrm_msg && xfrm_msg[0])
1659 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1661 * we do not run diff between different kind
1662 * of objects.
1664 if ((one->mode ^ two->mode) & S_IFMT)
1665 goto free_ab_and_return;
1666 if (complete_rewrite &&
1667 (textconv_one || !diff_filespec_is_binary(one)) &&
1668 (textconv_two || !diff_filespec_is_binary(two))) {
1669 emit_rewrite_diff(name_a, name_b, one, two,
1670 textconv_one, textconv_two, o);
1671 o->found_changes = 1;
1672 goto free_ab_and_return;
1676 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1677 die("unable to read files to diff");
1679 if (!DIFF_OPT_TST(o, TEXT) &&
1680 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1681 (diff_filespec_is_binary(two) && !textconv_two) )) {
1682 /* Quite common confusing case */
1683 if (mf1.size == mf2.size &&
1684 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1685 goto free_ab_and_return;
1686 if (DIFF_OPT_TST(o, BINARY))
1687 emit_binary_diff(o->file, &mf1, &mf2);
1688 else
1689 fprintf(o->file, "Binary files %s and %s differ\n",
1690 lbl[0], lbl[1]);
1691 o->found_changes = 1;
1693 else {
1694 /* Crazy xdl interfaces.. */
1695 const char *diffopts = getenv("GIT_DIFF_OPTS");
1696 xpparam_t xpp;
1697 xdemitconf_t xecfg;
1698 xdemitcb_t ecb;
1699 struct emit_callback ecbdata;
1700 const struct userdiff_funcname *pe;
1702 if (textconv_one) {
1703 size_t size;
1704 mf1.ptr = run_textconv(textconv_one, one, &size);
1705 if (!mf1.ptr)
1706 die("unable to read files to diff");
1707 mf1.size = size;
1709 if (textconv_two) {
1710 size_t size;
1711 mf2.ptr = run_textconv(textconv_two, two, &size);
1712 if (!mf2.ptr)
1713 die("unable to read files to diff");
1714 mf2.size = size;
1717 pe = diff_funcname_pattern(one);
1718 if (!pe)
1719 pe = diff_funcname_pattern(two);
1721 memset(&xpp, 0, sizeof(xpp));
1722 memset(&xecfg, 0, sizeof(xecfg));
1723 memset(&ecbdata, 0, sizeof(ecbdata));
1724 ecbdata.label_path = lbl;
1725 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1726 ecbdata.found_changesp = &o->found_changes;
1727 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1728 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1729 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1730 ecbdata.file = o->file;
1731 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1732 xecfg.ctxlen = o->context;
1733 xecfg.interhunkctxlen = o->interhunkcontext;
1734 xecfg.flags = XDL_EMIT_FUNCNAMES;
1735 if (pe)
1736 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1737 if (!diffopts)
1739 else if (!prefixcmp(diffopts, "--unified="))
1740 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1741 else if (!prefixcmp(diffopts, "-u"))
1742 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1743 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1744 ecbdata.diff_words =
1745 xcalloc(1, sizeof(struct diff_words_data));
1746 ecbdata.diff_words->file = o->file;
1747 if (!o->word_regex)
1748 o->word_regex = userdiff_word_regex(one);
1749 if (!o->word_regex)
1750 o->word_regex = userdiff_word_regex(two);
1751 if (!o->word_regex)
1752 o->word_regex = diff_word_regex_cfg;
1753 if (o->word_regex) {
1754 ecbdata.diff_words->word_regex = (regex_t *)
1755 xmalloc(sizeof(regex_t));
1756 if (regcomp(ecbdata.diff_words->word_regex,
1757 o->word_regex,
1758 REG_EXTENDED | REG_NEWLINE))
1759 die ("Invalid regular expression: %s",
1760 o->word_regex);
1763 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1764 &xpp, &xecfg, &ecb);
1765 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1766 free_diff_words_data(&ecbdata);
1767 if (textconv_one)
1768 free(mf1.ptr);
1769 if (textconv_two)
1770 free(mf2.ptr);
1771 xdiff_clear_find_func(&xecfg);
1774 free_ab_and_return:
1775 diff_free_filespec_data(one);
1776 diff_free_filespec_data(two);
1777 free(a_one);
1778 free(b_two);
1779 return;
1782 static void builtin_diffstat(const char *name_a, const char *name_b,
1783 struct diff_filespec *one,
1784 struct diff_filespec *two,
1785 struct diffstat_t *diffstat,
1786 struct diff_options *o,
1787 int complete_rewrite)
1789 mmfile_t mf1, mf2;
1790 struct diffstat_file *data;
1792 data = diffstat_add(diffstat, name_a, name_b);
1794 if (!one || !two) {
1795 data->is_unmerged = 1;
1796 return;
1798 if (complete_rewrite) {
1799 diff_populate_filespec(one, 0);
1800 diff_populate_filespec(two, 0);
1801 data->deleted = count_lines(one->data, one->size);
1802 data->added = count_lines(two->data, two->size);
1803 goto free_and_return;
1805 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1806 die("unable to read files to diff");
1808 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1809 data->is_binary = 1;
1810 data->added = mf2.size;
1811 data->deleted = mf1.size;
1812 } else {
1813 /* Crazy xdl interfaces.. */
1814 xpparam_t xpp;
1815 xdemitconf_t xecfg;
1816 xdemitcb_t ecb;
1818 memset(&xpp, 0, sizeof(xpp));
1819 memset(&xecfg, 0, sizeof(xecfg));
1820 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1821 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1822 &xpp, &xecfg, &ecb);
1825 free_and_return:
1826 diff_free_filespec_data(one);
1827 diff_free_filespec_data(two);
1830 static void builtin_checkdiff(const char *name_a, const char *name_b,
1831 const char *attr_path,
1832 struct diff_filespec *one,
1833 struct diff_filespec *two,
1834 struct diff_options *o)
1836 mmfile_t mf1, mf2;
1837 struct checkdiff_t data;
1839 if (!two)
1840 return;
1842 memset(&data, 0, sizeof(data));
1843 data.filename = name_b ? name_b : name_a;
1844 data.lineno = 0;
1845 data.o = o;
1846 data.ws_rule = whitespace_rule(attr_path);
1848 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1849 die("unable to read files to diff");
1852 * All the other codepaths check both sides, but not checking
1853 * the "old" side here is deliberate. We are checking the newly
1854 * introduced changes, and as long as the "new" side is text, we
1855 * can and should check what it introduces.
1857 if (diff_filespec_is_binary(two))
1858 goto free_and_return;
1859 else {
1860 /* Crazy xdl interfaces.. */
1861 xpparam_t xpp;
1862 xdemitconf_t xecfg;
1863 xdemitcb_t ecb;
1865 memset(&xpp, 0, sizeof(xpp));
1866 memset(&xecfg, 0, sizeof(xecfg));
1867 xecfg.ctxlen = 1; /* at least one context line */
1868 xpp.flags = XDF_NEED_MINIMAL;
1869 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1870 &xpp, &xecfg, &ecb);
1872 if (data.ws_rule & WS_BLANK_AT_EOF) {
1873 struct emit_callback ecbdata;
1874 int blank_at_eof;
1876 ecbdata.ws_rule = data.ws_rule;
1877 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1878 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1880 if (blank_at_eof) {
1881 static char *err;
1882 if (!err)
1883 err = whitespace_error_string(WS_BLANK_AT_EOF);
1884 fprintf(o->file, "%s:%d: %s.\n",
1885 data.filename, blank_at_eof, err);
1886 data.status = 1; /* report errors */
1890 free_and_return:
1891 diff_free_filespec_data(one);
1892 diff_free_filespec_data(two);
1893 if (data.status)
1894 DIFF_OPT_SET(o, CHECK_FAILED);
1897 struct diff_filespec *alloc_filespec(const char *path)
1899 int namelen = strlen(path);
1900 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1902 memset(spec, 0, sizeof(*spec));
1903 spec->path = (char *)(spec + 1);
1904 memcpy(spec->path, path, namelen+1);
1905 spec->count = 1;
1906 spec->is_binary = -1;
1907 return spec;
1910 void free_filespec(struct diff_filespec *spec)
1912 if (!--spec->count) {
1913 diff_free_filespec_data(spec);
1914 free(spec);
1918 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1919 unsigned short mode)
1921 if (mode) {
1922 spec->mode = canon_mode(mode);
1923 hashcpy(spec->sha1, sha1);
1924 spec->sha1_valid = !is_null_sha1(sha1);
1929 * Given a name and sha1 pair, if the index tells us the file in
1930 * the work tree has that object contents, return true, so that
1931 * prepare_temp_file() does not have to inflate and extract.
1933 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1935 struct cache_entry *ce;
1936 struct stat st;
1937 int pos, len;
1940 * We do not read the cache ourselves here, because the
1941 * benchmark with my previous version that always reads cache
1942 * shows that it makes things worse for diff-tree comparing
1943 * two linux-2.6 kernel trees in an already checked out work
1944 * tree. This is because most diff-tree comparisons deal with
1945 * only a small number of files, while reading the cache is
1946 * expensive for a large project, and its cost outweighs the
1947 * savings we get by not inflating the object to a temporary
1948 * file. Practically, this code only helps when we are used
1949 * by diff-cache --cached, which does read the cache before
1950 * calling us.
1952 if (!active_cache)
1953 return 0;
1955 /* We want to avoid the working directory if our caller
1956 * doesn't need the data in a normal file, this system
1957 * is rather slow with its stat/open/mmap/close syscalls,
1958 * and the object is contained in a pack file. The pack
1959 * is probably already open and will be faster to obtain
1960 * the data through than the working directory. Loose
1961 * objects however would tend to be slower as they need
1962 * to be individually opened and inflated.
1964 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1965 return 0;
1967 len = strlen(name);
1968 pos = cache_name_pos(name, len);
1969 if (pos < 0)
1970 return 0;
1971 ce = active_cache[pos];
1974 * This is not the sha1 we are looking for, or
1975 * unreusable because it is not a regular file.
1977 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1978 return 0;
1981 * If ce is marked as "assume unchanged", there is no
1982 * guarantee that work tree matches what we are looking for.
1984 if (ce->ce_flags & CE_VALID)
1985 return 0;
1988 * If ce matches the file in the work tree, we can reuse it.
1990 if (ce_uptodate(ce) ||
1991 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1992 return 1;
1994 return 0;
1997 static int populate_from_stdin(struct diff_filespec *s)
1999 struct strbuf buf = STRBUF_INIT;
2000 size_t size = 0;
2002 if (strbuf_read(&buf, 0, 0) < 0)
2003 return error("error while reading from stdin %s",
2004 strerror(errno));
2006 s->should_munmap = 0;
2007 s->data = strbuf_detach(&buf, &size);
2008 s->size = size;
2009 s->should_free = 1;
2010 return 0;
2013 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2015 int len;
2016 char *data = xmalloc(100);
2017 len = snprintf(data, 100,
2018 "Subproject commit %s\n", sha1_to_hex(s->sha1));
2019 s->data = data;
2020 s->size = len;
2021 s->should_free = 1;
2022 if (size_only) {
2023 s->data = NULL;
2024 free(data);
2026 return 0;
2030 * While doing rename detection and pickaxe operation, we may need to
2031 * grab the data for the blob (or file) for our own in-core comparison.
2032 * diff_filespec has data and size fields for this purpose.
2034 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2036 int err = 0;
2037 if (!DIFF_FILE_VALID(s))
2038 die("internal error: asking to populate invalid file.");
2039 if (S_ISDIR(s->mode))
2040 return -1;
2042 if (s->data)
2043 return 0;
2045 if (size_only && 0 < s->size)
2046 return 0;
2048 if (S_ISGITLINK(s->mode))
2049 return diff_populate_gitlink(s, size_only);
2051 if (!s->sha1_valid ||
2052 reuse_worktree_file(s->path, s->sha1, 0)) {
2053 struct strbuf buf = STRBUF_INIT;
2054 struct stat st;
2055 int fd;
2057 if (!strcmp(s->path, "-"))
2058 return populate_from_stdin(s);
2060 if (lstat(s->path, &st) < 0) {
2061 if (errno == ENOENT) {
2062 err_empty:
2063 err = -1;
2064 empty:
2065 s->data = (char *)"";
2066 s->size = 0;
2067 return err;
2070 s->size = xsize_t(st.st_size);
2071 if (!s->size)
2072 goto empty;
2073 if (S_ISLNK(st.st_mode)) {
2074 struct strbuf sb = STRBUF_INIT;
2076 if (strbuf_readlink(&sb, s->path, s->size))
2077 goto err_empty;
2078 s->size = sb.len;
2079 s->data = strbuf_detach(&sb, NULL);
2080 s->should_free = 1;
2081 return 0;
2083 if (size_only)
2084 return 0;
2085 fd = open(s->path, O_RDONLY);
2086 if (fd < 0)
2087 goto err_empty;
2088 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2089 close(fd);
2090 s->should_munmap = 1;
2093 * Convert from working tree format to canonical git format
2095 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2096 size_t size = 0;
2097 munmap(s->data, s->size);
2098 s->should_munmap = 0;
2099 s->data = strbuf_detach(&buf, &size);
2100 s->size = size;
2101 s->should_free = 1;
2104 else {
2105 enum object_type type;
2106 if (size_only)
2107 type = sha1_object_info(s->sha1, &s->size);
2108 else {
2109 s->data = read_sha1_file(s->sha1, &type, &s->size);
2110 s->should_free = 1;
2113 return 0;
2116 void diff_free_filespec_blob(struct diff_filespec *s)
2118 if (s->should_free)
2119 free(s->data);
2120 else if (s->should_munmap)
2121 munmap(s->data, s->size);
2123 if (s->should_free || s->should_munmap) {
2124 s->should_free = s->should_munmap = 0;
2125 s->data = NULL;
2129 void diff_free_filespec_data(struct diff_filespec *s)
2131 diff_free_filespec_blob(s);
2132 free(s->cnt_data);
2133 s->cnt_data = NULL;
2136 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2137 void *blob,
2138 unsigned long size,
2139 const unsigned char *sha1,
2140 int mode)
2142 int fd;
2143 struct strbuf buf = STRBUF_INIT;
2144 struct strbuf template = STRBUF_INIT;
2145 char *path_dup = xstrdup(path);
2146 const char *base = basename(path_dup);
2148 /* Generate "XXXXXX_basename.ext" */
2149 strbuf_addstr(&template, "XXXXXX_");
2150 strbuf_addstr(&template, base);
2152 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2153 strlen(base) + 1);
2154 if (fd < 0)
2155 die_errno("unable to create temp-file");
2156 if (convert_to_working_tree(path,
2157 (const char *)blob, (size_t)size, &buf)) {
2158 blob = buf.buf;
2159 size = buf.len;
2161 if (write_in_full(fd, blob, size) != size)
2162 die_errno("unable to write temp-file");
2163 close(fd);
2164 temp->name = temp->tmp_path;
2165 strcpy(temp->hex, sha1_to_hex(sha1));
2166 temp->hex[40] = 0;
2167 sprintf(temp->mode, "%06o", mode);
2168 strbuf_release(&buf);
2169 strbuf_release(&template);
2170 free(path_dup);
2173 static struct diff_tempfile *prepare_temp_file(const char *name,
2174 struct diff_filespec *one)
2176 struct diff_tempfile *temp = claim_diff_tempfile();
2178 if (!DIFF_FILE_VALID(one)) {
2179 not_a_valid_file:
2180 /* A '-' entry produces this for file-2, and
2181 * a '+' entry produces this for file-1.
2183 temp->name = "/dev/null";
2184 strcpy(temp->hex, ".");
2185 strcpy(temp->mode, ".");
2186 return temp;
2189 if (!remove_tempfile_installed) {
2190 atexit(remove_tempfile);
2191 sigchain_push_common(remove_tempfile_on_signal);
2192 remove_tempfile_installed = 1;
2195 if (!one->sha1_valid ||
2196 reuse_worktree_file(name, one->sha1, 1)) {
2197 struct stat st;
2198 if (lstat(name, &st) < 0) {
2199 if (errno == ENOENT)
2200 goto not_a_valid_file;
2201 die_errno("stat(%s)", name);
2203 if (S_ISLNK(st.st_mode)) {
2204 struct strbuf sb = STRBUF_INIT;
2205 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2206 die_errno("readlink(%s)", name);
2207 prep_temp_blob(name, temp, sb.buf, sb.len,
2208 (one->sha1_valid ?
2209 one->sha1 : null_sha1),
2210 (one->sha1_valid ?
2211 one->mode : S_IFLNK));
2212 strbuf_release(&sb);
2214 else {
2215 /* we can borrow from the file in the work tree */
2216 temp->name = name;
2217 if (!one->sha1_valid)
2218 strcpy(temp->hex, sha1_to_hex(null_sha1));
2219 else
2220 strcpy(temp->hex, sha1_to_hex(one->sha1));
2221 /* Even though we may sometimes borrow the
2222 * contents from the work tree, we always want
2223 * one->mode. mode is trustworthy even when
2224 * !(one->sha1_valid), as long as
2225 * DIFF_FILE_VALID(one).
2227 sprintf(temp->mode, "%06o", one->mode);
2229 return temp;
2231 else {
2232 if (diff_populate_filespec(one, 0))
2233 die("cannot read data blob for %s", one->path);
2234 prep_temp_blob(name, temp, one->data, one->size,
2235 one->sha1, one->mode);
2237 return temp;
2240 /* An external diff command takes:
2242 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2243 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2246 static void run_external_diff(const char *pgm,
2247 const char *name,
2248 const char *other,
2249 struct diff_filespec *one,
2250 struct diff_filespec *two,
2251 const char *xfrm_msg,
2252 int complete_rewrite)
2254 const char *spawn_arg[10];
2255 int retval;
2256 const char **arg = &spawn_arg[0];
2258 if (one && two) {
2259 struct diff_tempfile *temp_one, *temp_two;
2260 const char *othername = (other ? other : name);
2261 temp_one = prepare_temp_file(name, one);
2262 temp_two = prepare_temp_file(othername, two);
2263 *arg++ = pgm;
2264 *arg++ = name;
2265 *arg++ = temp_one->name;
2266 *arg++ = temp_one->hex;
2267 *arg++ = temp_one->mode;
2268 *arg++ = temp_two->name;
2269 *arg++ = temp_two->hex;
2270 *arg++ = temp_two->mode;
2271 if (other) {
2272 *arg++ = other;
2273 *arg++ = xfrm_msg;
2275 } else {
2276 *arg++ = pgm;
2277 *arg++ = name;
2279 *arg = NULL;
2280 fflush(NULL);
2281 retval = run_command_v_opt(spawn_arg, 0);
2282 remove_tempfile();
2283 if (retval) {
2284 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2285 exit(1);
2289 static int similarity_index(struct diff_filepair *p)
2291 return p->score * 100 / MAX_SCORE;
2294 static void fill_metainfo(struct strbuf *msg,
2295 const char *name,
2296 const char *other,
2297 struct diff_filespec *one,
2298 struct diff_filespec *two,
2299 struct diff_options *o,
2300 struct diff_filepair *p)
2302 strbuf_init(msg, PATH_MAX * 2 + 300);
2303 switch (p->status) {
2304 case DIFF_STATUS_COPIED:
2305 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2306 strbuf_addstr(msg, "\ncopy from ");
2307 quote_c_style(name, msg, NULL, 0);
2308 strbuf_addstr(msg, "\ncopy to ");
2309 quote_c_style(other, msg, NULL, 0);
2310 strbuf_addch(msg, '\n');
2311 break;
2312 case DIFF_STATUS_RENAMED:
2313 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2314 strbuf_addstr(msg, "\nrename from ");
2315 quote_c_style(name, msg, NULL, 0);
2316 strbuf_addstr(msg, "\nrename to ");
2317 quote_c_style(other, msg, NULL, 0);
2318 strbuf_addch(msg, '\n');
2319 break;
2320 case DIFF_STATUS_MODIFIED:
2321 if (p->score) {
2322 strbuf_addf(msg, "dissimilarity index %d%%\n",
2323 similarity_index(p));
2324 break;
2326 /* fallthru */
2327 default:
2328 /* nothing */
2331 if (one && two && hashcmp(one->sha1, two->sha1)) {
2332 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2334 if (DIFF_OPT_TST(o, BINARY)) {
2335 mmfile_t mf;
2336 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2337 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2338 abbrev = 40;
2340 strbuf_addf(msg, "index %.*s..%.*s",
2341 abbrev, sha1_to_hex(one->sha1),
2342 abbrev, sha1_to_hex(two->sha1));
2343 if (one->mode == two->mode)
2344 strbuf_addf(msg, " %06o", one->mode);
2345 strbuf_addch(msg, '\n');
2347 if (msg->len)
2348 strbuf_setlen(msg, msg->len - 1);
2351 static void run_diff_cmd(const char *pgm,
2352 const char *name,
2353 const char *other,
2354 const char *attr_path,
2355 struct diff_filespec *one,
2356 struct diff_filespec *two,
2357 struct strbuf *msg,
2358 struct diff_options *o,
2359 struct diff_filepair *p)
2361 const char *xfrm_msg = NULL;
2362 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2364 if (msg) {
2365 fill_metainfo(msg, name, other, one, two, o, p);
2366 xfrm_msg = msg->len ? msg->buf : NULL;
2369 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2370 pgm = NULL;
2371 else {
2372 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2373 if (drv && drv->external)
2374 pgm = drv->external;
2377 if (pgm) {
2378 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2379 complete_rewrite);
2380 return;
2382 if (one && two)
2383 builtin_diff(name, other ? other : name,
2384 one, two, xfrm_msg, o, complete_rewrite);
2385 else
2386 fprintf(o->file, "* Unmerged path %s\n", name);
2389 static void diff_fill_sha1_info(struct diff_filespec *one)
2391 if (DIFF_FILE_VALID(one)) {
2392 if (!one->sha1_valid) {
2393 struct stat st;
2394 if (!strcmp(one->path, "-")) {
2395 hashcpy(one->sha1, null_sha1);
2396 return;
2398 if (lstat(one->path, &st) < 0)
2399 die_errno("stat '%s'", one->path);
2400 if (index_path(one->sha1, one->path, &st, 0))
2401 die("cannot hash %s", one->path);
2404 else
2405 hashclr(one->sha1);
2408 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2410 /* Strip the prefix but do not molest /dev/null and absolute paths */
2411 if (*namep && **namep != '/')
2412 *namep += prefix_length;
2413 if (*otherp && **otherp != '/')
2414 *otherp += prefix_length;
2417 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2419 const char *pgm = external_diff();
2420 struct strbuf msg;
2421 struct diff_filespec *one = p->one;
2422 struct diff_filespec *two = p->two;
2423 const char *name;
2424 const char *other;
2425 const char *attr_path;
2427 name = p->one->path;
2428 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2429 attr_path = name;
2430 if (o->prefix_length)
2431 strip_prefix(o->prefix_length, &name, &other);
2433 if (DIFF_PAIR_UNMERGED(p)) {
2434 run_diff_cmd(pgm, name, NULL, attr_path,
2435 NULL, NULL, NULL, o, p);
2436 return;
2439 diff_fill_sha1_info(one);
2440 diff_fill_sha1_info(two);
2442 if (!pgm &&
2443 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2444 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2446 * a filepair that changes between file and symlink
2447 * needs to be split into deletion and creation.
2449 struct diff_filespec *null = alloc_filespec(two->path);
2450 run_diff_cmd(NULL, name, other, attr_path,
2451 one, null, &msg, o, p);
2452 free(null);
2453 strbuf_release(&msg);
2455 null = alloc_filespec(one->path);
2456 run_diff_cmd(NULL, name, other, attr_path,
2457 null, two, &msg, o, p);
2458 free(null);
2460 else
2461 run_diff_cmd(pgm, name, other, attr_path,
2462 one, two, &msg, o, p);
2464 strbuf_release(&msg);
2467 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2468 struct diffstat_t *diffstat)
2470 const char *name;
2471 const char *other;
2472 int complete_rewrite = 0;
2474 if (DIFF_PAIR_UNMERGED(p)) {
2475 /* unmerged */
2476 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2477 return;
2480 name = p->one->path;
2481 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2483 if (o->prefix_length)
2484 strip_prefix(o->prefix_length, &name, &other);
2486 diff_fill_sha1_info(p->one);
2487 diff_fill_sha1_info(p->two);
2489 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2490 complete_rewrite = 1;
2491 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2494 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2496 const char *name;
2497 const char *other;
2498 const char *attr_path;
2500 if (DIFF_PAIR_UNMERGED(p)) {
2501 /* unmerged */
2502 return;
2505 name = p->one->path;
2506 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2507 attr_path = other ? other : name;
2509 if (o->prefix_length)
2510 strip_prefix(o->prefix_length, &name, &other);
2512 diff_fill_sha1_info(p->one);
2513 diff_fill_sha1_info(p->two);
2515 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2518 void diff_setup(struct diff_options *options)
2520 memset(options, 0, sizeof(*options));
2522 options->file = stdout;
2524 options->line_termination = '\n';
2525 options->break_opt = -1;
2526 options->rename_limit = -1;
2527 options->dirstat_percent = 3;
2528 options->context = 3;
2530 options->change = diff_change;
2531 options->add_remove = diff_addremove;
2532 if (diff_use_color_default > 0)
2533 DIFF_OPT_SET(options, COLOR_DIFF);
2534 options->detect_rename = diff_detect_rename_default;
2536 if (!diff_mnemonic_prefix) {
2537 options->a_prefix = "a/";
2538 options->b_prefix = "b/";
2542 int diff_setup_done(struct diff_options *options)
2544 int count = 0;
2546 if (options->output_format & DIFF_FORMAT_NAME)
2547 count++;
2548 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2549 count++;
2550 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2551 count++;
2552 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2553 count++;
2554 if (count > 1)
2555 die("--name-only, --name-status, --check and -s are mutually exclusive");
2557 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2558 options->detect_rename = DIFF_DETECT_COPY;
2560 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2561 options->prefix = NULL;
2562 if (options->prefix)
2563 options->prefix_length = strlen(options->prefix);
2564 else
2565 options->prefix_length = 0;
2567 if (options->output_format & (DIFF_FORMAT_NAME |
2568 DIFF_FORMAT_NAME_STATUS |
2569 DIFF_FORMAT_CHECKDIFF |
2570 DIFF_FORMAT_NO_OUTPUT))
2571 options->output_format &= ~(DIFF_FORMAT_RAW |
2572 DIFF_FORMAT_NUMSTAT |
2573 DIFF_FORMAT_DIFFSTAT |
2574 DIFF_FORMAT_SHORTSTAT |
2575 DIFF_FORMAT_DIRSTAT |
2576 DIFF_FORMAT_SUMMARY |
2577 DIFF_FORMAT_PATCH);
2580 * These cases always need recursive; we do not drop caller-supplied
2581 * recursive bits for other formats here.
2583 if (options->output_format & (DIFF_FORMAT_PATCH |
2584 DIFF_FORMAT_NUMSTAT |
2585 DIFF_FORMAT_DIFFSTAT |
2586 DIFF_FORMAT_SHORTSTAT |
2587 DIFF_FORMAT_DIRSTAT |
2588 DIFF_FORMAT_SUMMARY |
2589 DIFF_FORMAT_CHECKDIFF))
2590 DIFF_OPT_SET(options, RECURSIVE);
2592 * Also pickaxe would not work very well if you do not say recursive
2594 if (options->pickaxe)
2595 DIFF_OPT_SET(options, RECURSIVE);
2597 if (options->detect_rename && options->rename_limit < 0)
2598 options->rename_limit = diff_rename_limit_default;
2599 if (options->setup & DIFF_SETUP_USE_CACHE) {
2600 if (!active_cache)
2601 /* read-cache does not die even when it fails
2602 * so it is safe for us to do this here. Also
2603 * it does not smudge active_cache or active_nr
2604 * when it fails, so we do not have to worry about
2605 * cleaning it up ourselves either.
2607 read_cache();
2609 if (options->abbrev <= 0 || 40 < options->abbrev)
2610 options->abbrev = 40; /* full */
2613 * It does not make sense to show the first hit we happened
2614 * to have found. It does not make sense not to return with
2615 * exit code in such a case either.
2617 if (DIFF_OPT_TST(options, QUIET)) {
2618 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2619 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2622 return 0;
2625 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2627 char c, *eq;
2628 int len;
2630 if (*arg != '-')
2631 return 0;
2632 c = *++arg;
2633 if (!c)
2634 return 0;
2635 if (c == arg_short) {
2636 c = *++arg;
2637 if (!c)
2638 return 1;
2639 if (val && isdigit(c)) {
2640 char *end;
2641 int n = strtoul(arg, &end, 10);
2642 if (*end)
2643 return 0;
2644 *val = n;
2645 return 1;
2647 return 0;
2649 if (c != '-')
2650 return 0;
2651 arg++;
2652 eq = strchr(arg, '=');
2653 if (eq)
2654 len = eq - arg;
2655 else
2656 len = strlen(arg);
2657 if (!len || strncmp(arg, arg_long, len))
2658 return 0;
2659 if (eq) {
2660 int n;
2661 char *end;
2662 if (!isdigit(*++eq))
2663 return 0;
2664 n = strtoul(eq, &end, 10);
2665 if (*end)
2666 return 0;
2667 *val = n;
2669 return 1;
2672 static int diff_scoreopt_parse(const char *opt);
2674 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2676 const char *arg = av[0];
2678 /* Output format options */
2679 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2680 options->output_format |= DIFF_FORMAT_PATCH;
2681 else if (opt_arg(arg, 'U', "unified", &options->context))
2682 options->output_format |= DIFF_FORMAT_PATCH;
2683 else if (!strcmp(arg, "--raw"))
2684 options->output_format |= DIFF_FORMAT_RAW;
2685 else if (!strcmp(arg, "--patch-with-raw"))
2686 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2687 else if (!strcmp(arg, "--numstat"))
2688 options->output_format |= DIFF_FORMAT_NUMSTAT;
2689 else if (!strcmp(arg, "--shortstat"))
2690 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2691 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2692 options->output_format |= DIFF_FORMAT_DIRSTAT;
2693 else if (!strcmp(arg, "--cumulative")) {
2694 options->output_format |= DIFF_FORMAT_DIRSTAT;
2695 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2696 } else if (opt_arg(arg, 0, "dirstat-by-file",
2697 &options->dirstat_percent)) {
2698 options->output_format |= DIFF_FORMAT_DIRSTAT;
2699 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2701 else if (!strcmp(arg, "--check"))
2702 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2703 else if (!strcmp(arg, "--summary"))
2704 options->output_format |= DIFF_FORMAT_SUMMARY;
2705 else if (!strcmp(arg, "--patch-with-stat"))
2706 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2707 else if (!strcmp(arg, "--name-only"))
2708 options->output_format |= DIFF_FORMAT_NAME;
2709 else if (!strcmp(arg, "--name-status"))
2710 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2711 else if (!strcmp(arg, "-s"))
2712 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2713 else if (!prefixcmp(arg, "--stat")) {
2714 char *end;
2715 int width = options->stat_width;
2716 int name_width = options->stat_name_width;
2717 arg += 6;
2718 end = (char *)arg;
2720 switch (*arg) {
2721 case '-':
2722 if (!prefixcmp(arg, "-width="))
2723 width = strtoul(arg + 7, &end, 10);
2724 else if (!prefixcmp(arg, "-name-width="))
2725 name_width = strtoul(arg + 12, &end, 10);
2726 break;
2727 case '=':
2728 width = strtoul(arg+1, &end, 10);
2729 if (*end == ',')
2730 name_width = strtoul(end+1, &end, 10);
2733 /* Important! This checks all the error cases! */
2734 if (*end)
2735 return 0;
2736 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2737 options->stat_name_width = name_width;
2738 options->stat_width = width;
2741 /* renames options */
2742 else if (!prefixcmp(arg, "-B")) {
2743 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2744 return -1;
2746 else if (!prefixcmp(arg, "-M")) {
2747 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2748 return -1;
2749 options->detect_rename = DIFF_DETECT_RENAME;
2751 else if (!prefixcmp(arg, "-C")) {
2752 if (options->detect_rename == DIFF_DETECT_COPY)
2753 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2754 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2755 return -1;
2756 options->detect_rename = DIFF_DETECT_COPY;
2758 else if (!strcmp(arg, "--no-renames"))
2759 options->detect_rename = 0;
2760 else if (!strcmp(arg, "--relative"))
2761 DIFF_OPT_SET(options, RELATIVE_NAME);
2762 else if (!prefixcmp(arg, "--relative=")) {
2763 DIFF_OPT_SET(options, RELATIVE_NAME);
2764 options->prefix = arg + 11;
2767 /* xdiff options */
2768 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2769 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2770 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2771 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2772 else if (!strcmp(arg, "--ignore-space-at-eol"))
2773 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2774 else if (!strcmp(arg, "--patience"))
2775 DIFF_XDL_SET(options, PATIENCE_DIFF);
2777 /* flags options */
2778 else if (!strcmp(arg, "--binary")) {
2779 options->output_format |= DIFF_FORMAT_PATCH;
2780 DIFF_OPT_SET(options, BINARY);
2782 else if (!strcmp(arg, "--full-index"))
2783 DIFF_OPT_SET(options, FULL_INDEX);
2784 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2785 DIFF_OPT_SET(options, TEXT);
2786 else if (!strcmp(arg, "-R"))
2787 DIFF_OPT_SET(options, REVERSE_DIFF);
2788 else if (!strcmp(arg, "--find-copies-harder"))
2789 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2790 else if (!strcmp(arg, "--follow"))
2791 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2792 else if (!strcmp(arg, "--color"))
2793 DIFF_OPT_SET(options, COLOR_DIFF);
2794 else if (!strcmp(arg, "--no-color"))
2795 DIFF_OPT_CLR(options, COLOR_DIFF);
2796 else if (!strcmp(arg, "--color-words")) {
2797 DIFF_OPT_SET(options, COLOR_DIFF);
2798 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2800 else if (!prefixcmp(arg, "--color-words=")) {
2801 DIFF_OPT_SET(options, COLOR_DIFF);
2802 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2803 options->word_regex = arg + 14;
2805 else if (!strcmp(arg, "--exit-code"))
2806 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2807 else if (!strcmp(arg, "--quiet"))
2808 DIFF_OPT_SET(options, QUIET);
2809 else if (!strcmp(arg, "--ext-diff"))
2810 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2811 else if (!strcmp(arg, "--no-ext-diff"))
2812 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2813 else if (!strcmp(arg, "--textconv"))
2814 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2815 else if (!strcmp(arg, "--no-textconv"))
2816 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2817 else if (!strcmp(arg, "--ignore-submodules"))
2818 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2819 else if (!strcmp(arg, "--submodule"))
2820 DIFF_OPT_SET(options, SUBMODULE_LOG);
2821 else if (!prefixcmp(arg, "--submodule=")) {
2822 if (!strcmp(arg + 12, "log"))
2823 DIFF_OPT_SET(options, SUBMODULE_LOG);
2826 /* misc options */
2827 else if (!strcmp(arg, "-z"))
2828 options->line_termination = 0;
2829 else if (!prefixcmp(arg, "-l"))
2830 options->rename_limit = strtoul(arg+2, NULL, 10);
2831 else if (!prefixcmp(arg, "-S"))
2832 options->pickaxe = arg + 2;
2833 else if (!strcmp(arg, "--pickaxe-all"))
2834 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2835 else if (!strcmp(arg, "--pickaxe-regex"))
2836 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2837 else if (!prefixcmp(arg, "-O"))
2838 options->orderfile = arg + 2;
2839 else if (!prefixcmp(arg, "--diff-filter="))
2840 options->filter = arg + 14;
2841 else if (!strcmp(arg, "--abbrev"))
2842 options->abbrev = DEFAULT_ABBREV;
2843 else if (!prefixcmp(arg, "--abbrev=")) {
2844 options->abbrev = strtoul(arg + 9, NULL, 10);
2845 if (options->abbrev < MINIMUM_ABBREV)
2846 options->abbrev = MINIMUM_ABBREV;
2847 else if (40 < options->abbrev)
2848 options->abbrev = 40;
2850 else if (!prefixcmp(arg, "--src-prefix="))
2851 options->a_prefix = arg + 13;
2852 else if (!prefixcmp(arg, "--dst-prefix="))
2853 options->b_prefix = arg + 13;
2854 else if (!strcmp(arg, "--no-prefix"))
2855 options->a_prefix = options->b_prefix = "";
2856 else if (opt_arg(arg, '\0', "inter-hunk-context",
2857 &options->interhunkcontext))
2859 else if (!prefixcmp(arg, "--output=")) {
2860 options->file = fopen(arg + strlen("--output="), "w");
2861 options->close_file = 1;
2862 } else
2863 return 0;
2864 return 1;
2867 static int parse_num(const char **cp_p)
2869 unsigned long num, scale;
2870 int ch, dot;
2871 const char *cp = *cp_p;
2873 num = 0;
2874 scale = 1;
2875 dot = 0;
2876 for (;;) {
2877 ch = *cp;
2878 if ( !dot && ch == '.' ) {
2879 scale = 1;
2880 dot = 1;
2881 } else if ( ch == '%' ) {
2882 scale = dot ? scale*100 : 100;
2883 cp++; /* % is always at the end */
2884 break;
2885 } else if ( ch >= '0' && ch <= '9' ) {
2886 if ( scale < 100000 ) {
2887 scale *= 10;
2888 num = (num*10) + (ch-'0');
2890 } else {
2891 break;
2893 cp++;
2895 *cp_p = cp;
2897 /* user says num divided by scale and we say internally that
2898 * is MAX_SCORE * num / scale.
2900 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2903 static int diff_scoreopt_parse(const char *opt)
2905 int opt1, opt2, cmd;
2907 if (*opt++ != '-')
2908 return -1;
2909 cmd = *opt++;
2910 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2911 return -1; /* that is not a -M, -C nor -B option */
2913 opt1 = parse_num(&opt);
2914 if (cmd != 'B')
2915 opt2 = 0;
2916 else {
2917 if (*opt == 0)
2918 opt2 = 0;
2919 else if (*opt != '/')
2920 return -1; /* we expect -B80/99 or -B80 */
2921 else {
2922 opt++;
2923 opt2 = parse_num(&opt);
2926 if (*opt != 0)
2927 return -1;
2928 return opt1 | (opt2 << 16);
2931 struct diff_queue_struct diff_queued_diff;
2933 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2935 if (queue->alloc <= queue->nr) {
2936 queue->alloc = alloc_nr(queue->alloc);
2937 queue->queue = xrealloc(queue->queue,
2938 sizeof(dp) * queue->alloc);
2940 queue->queue[queue->nr++] = dp;
2943 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2944 struct diff_filespec *one,
2945 struct diff_filespec *two)
2947 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2948 dp->one = one;
2949 dp->two = two;
2950 if (queue)
2951 diff_q(queue, dp);
2952 return dp;
2955 void diff_free_filepair(struct diff_filepair *p)
2957 free_filespec(p->one);
2958 free_filespec(p->two);
2959 free(p);
2962 /* This is different from find_unique_abbrev() in that
2963 * it stuffs the result with dots for alignment.
2965 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2967 int abblen;
2968 const char *abbrev;
2969 if (len == 40)
2970 return sha1_to_hex(sha1);
2972 abbrev = find_unique_abbrev(sha1, len);
2973 abblen = strlen(abbrev);
2974 if (abblen < 37) {
2975 static char hex[41];
2976 if (len < abblen && abblen <= len + 2)
2977 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2978 else
2979 sprintf(hex, "%s...", abbrev);
2980 return hex;
2982 return sha1_to_hex(sha1);
2985 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2987 int line_termination = opt->line_termination;
2988 int inter_name_termination = line_termination ? '\t' : '\0';
2990 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2991 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2992 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2993 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2995 if (p->score) {
2996 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2997 inter_name_termination);
2998 } else {
2999 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3002 if (p->status == DIFF_STATUS_COPIED ||
3003 p->status == DIFF_STATUS_RENAMED) {
3004 const char *name_a, *name_b;
3005 name_a = p->one->path;
3006 name_b = p->two->path;
3007 strip_prefix(opt->prefix_length, &name_a, &name_b);
3008 write_name_quoted(name_a, opt->file, inter_name_termination);
3009 write_name_quoted(name_b, opt->file, line_termination);
3010 } else {
3011 const char *name_a, *name_b;
3012 name_a = p->one->mode ? p->one->path : p->two->path;
3013 name_b = NULL;
3014 strip_prefix(opt->prefix_length, &name_a, &name_b);
3015 write_name_quoted(name_a, opt->file, line_termination);
3019 int diff_unmodified_pair(struct diff_filepair *p)
3021 /* This function is written stricter than necessary to support
3022 * the currently implemented transformers, but the idea is to
3023 * let transformers to produce diff_filepairs any way they want,
3024 * and filter and clean them up here before producing the output.
3026 struct diff_filespec *one = p->one, *two = p->two;
3028 if (DIFF_PAIR_UNMERGED(p))
3029 return 0; /* unmerged is interesting */
3031 /* deletion, addition, mode or type change
3032 * and rename are all interesting.
3034 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3035 DIFF_PAIR_MODE_CHANGED(p) ||
3036 strcmp(one->path, two->path))
3037 return 0;
3039 /* both are valid and point at the same path. that is, we are
3040 * dealing with a change.
3042 if (one->sha1_valid && two->sha1_valid &&
3043 !hashcmp(one->sha1, two->sha1))
3044 return 1; /* no change */
3045 if (!one->sha1_valid && !two->sha1_valid)
3046 return 1; /* both look at the same file on the filesystem. */
3047 return 0;
3050 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3052 if (diff_unmodified_pair(p))
3053 return;
3055 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3056 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3057 return; /* no tree diffs in patch format */
3059 run_diff(p, o);
3062 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3063 struct diffstat_t *diffstat)
3065 if (diff_unmodified_pair(p))
3066 return;
3068 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3069 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3070 return; /* no tree diffs in patch format */
3072 run_diffstat(p, o, diffstat);
3075 static void diff_flush_checkdiff(struct diff_filepair *p,
3076 struct diff_options *o)
3078 if (diff_unmodified_pair(p))
3079 return;
3081 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3082 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3083 return; /* no tree diffs in patch format */
3085 run_checkdiff(p, o);
3088 int diff_queue_is_empty(void)
3090 struct diff_queue_struct *q = &diff_queued_diff;
3091 int i;
3092 for (i = 0; i < q->nr; i++)
3093 if (!diff_unmodified_pair(q->queue[i]))
3094 return 0;
3095 return 1;
3098 #if DIFF_DEBUG
3099 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3101 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3102 x, one ? one : "",
3103 s->path,
3104 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3105 s->mode,
3106 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3107 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3108 x, one ? one : "",
3109 s->size, s->xfrm_flags);
3112 void diff_debug_filepair(const struct diff_filepair *p, int i)
3114 diff_debug_filespec(p->one, i, "one");
3115 diff_debug_filespec(p->two, i, "two");
3116 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3117 p->score, p->status ? p->status : '?',
3118 p->one->rename_used, p->broken_pair);
3121 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3123 int i;
3124 if (msg)
3125 fprintf(stderr, "%s\n", msg);
3126 fprintf(stderr, "q->nr = %d\n", q->nr);
3127 for (i = 0; i < q->nr; i++) {
3128 struct diff_filepair *p = q->queue[i];
3129 diff_debug_filepair(p, i);
3132 #endif
3134 static void diff_resolve_rename_copy(void)
3136 int i;
3137 struct diff_filepair *p;
3138 struct diff_queue_struct *q = &diff_queued_diff;
3140 diff_debug_queue("resolve-rename-copy", q);
3142 for (i = 0; i < q->nr; i++) {
3143 p = q->queue[i];
3144 p->status = 0; /* undecided */
3145 if (DIFF_PAIR_UNMERGED(p))
3146 p->status = DIFF_STATUS_UNMERGED;
3147 else if (!DIFF_FILE_VALID(p->one))
3148 p->status = DIFF_STATUS_ADDED;
3149 else if (!DIFF_FILE_VALID(p->two))
3150 p->status = DIFF_STATUS_DELETED;
3151 else if (DIFF_PAIR_TYPE_CHANGED(p))
3152 p->status = DIFF_STATUS_TYPE_CHANGED;
3154 /* from this point on, we are dealing with a pair
3155 * whose both sides are valid and of the same type, i.e.
3156 * either in-place edit or rename/copy edit.
3158 else if (DIFF_PAIR_RENAME(p)) {
3160 * A rename might have re-connected a broken
3161 * pair up, causing the pathnames to be the
3162 * same again. If so, that's not a rename at
3163 * all, just a modification..
3165 * Otherwise, see if this source was used for
3166 * multiple renames, in which case we decrement
3167 * the count, and call it a copy.
3169 if (!strcmp(p->one->path, p->two->path))
3170 p->status = DIFF_STATUS_MODIFIED;
3171 else if (--p->one->rename_used > 0)
3172 p->status = DIFF_STATUS_COPIED;
3173 else
3174 p->status = DIFF_STATUS_RENAMED;
3176 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3177 p->one->mode != p->two->mode ||
3178 is_null_sha1(p->one->sha1))
3179 p->status = DIFF_STATUS_MODIFIED;
3180 else {
3181 /* This is a "no-change" entry and should not
3182 * happen anymore, but prepare for broken callers.
3184 error("feeding unmodified %s to diffcore",
3185 p->one->path);
3186 p->status = DIFF_STATUS_UNKNOWN;
3189 diff_debug_queue("resolve-rename-copy done", q);
3192 static int check_pair_status(struct diff_filepair *p)
3194 switch (p->status) {
3195 case DIFF_STATUS_UNKNOWN:
3196 return 0;
3197 case 0:
3198 die("internal error in diff-resolve-rename-copy");
3199 default:
3200 return 1;
3204 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3206 int fmt = opt->output_format;
3208 if (fmt & DIFF_FORMAT_CHECKDIFF)
3209 diff_flush_checkdiff(p, opt);
3210 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3211 diff_flush_raw(p, opt);
3212 else if (fmt & DIFF_FORMAT_NAME) {
3213 const char *name_a, *name_b;
3214 name_a = p->two->path;
3215 name_b = NULL;
3216 strip_prefix(opt->prefix_length, &name_a, &name_b);
3217 write_name_quoted(name_a, opt->file, opt->line_termination);
3221 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3223 if (fs->mode)
3224 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3225 else
3226 fprintf(file, " %s ", newdelete);
3227 write_name_quoted(fs->path, file, '\n');
3231 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3233 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3234 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3235 show_name ? ' ' : '\n');
3236 if (show_name) {
3237 write_name_quoted(p->two->path, file, '\n');
3242 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3244 char *names = pprint_rename(p->one->path, p->two->path);
3246 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3247 free(names);
3248 show_mode_change(file, p, 0);
3251 static void diff_summary(FILE *file, struct diff_filepair *p)
3253 switch(p->status) {
3254 case DIFF_STATUS_DELETED:
3255 show_file_mode_name(file, "delete", p->one);
3256 break;
3257 case DIFF_STATUS_ADDED:
3258 show_file_mode_name(file, "create", p->two);
3259 break;
3260 case DIFF_STATUS_COPIED:
3261 show_rename_copy(file, "copy", p);
3262 break;
3263 case DIFF_STATUS_RENAMED:
3264 show_rename_copy(file, "rename", p);
3265 break;
3266 default:
3267 if (p->score) {
3268 fputs(" rewrite ", file);
3269 write_name_quoted(p->two->path, file, ' ');
3270 fprintf(file, "(%d%%)\n", similarity_index(p));
3272 show_mode_change(file, p, !p->score);
3273 break;
3277 struct patch_id_t {
3278 git_SHA_CTX *ctx;
3279 int patchlen;
3282 static int remove_space(char *line, int len)
3284 int i;
3285 char *dst = line;
3286 unsigned char c;
3288 for (i = 0; i < len; i++)
3289 if (!isspace((c = line[i])))
3290 *dst++ = c;
3292 return dst - line;
3295 static void patch_id_consume(void *priv, char *line, unsigned long len)
3297 struct patch_id_t *data = priv;
3298 int new_len;
3300 /* Ignore line numbers when computing the SHA1 of the patch */
3301 if (!prefixcmp(line, "@@ -"))
3302 return;
3304 new_len = remove_space(line, len);
3306 git_SHA1_Update(data->ctx, line, new_len);
3307 data->patchlen += new_len;
3310 /* returns 0 upon success, and writes result into sha1 */
3311 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3313 struct diff_queue_struct *q = &diff_queued_diff;
3314 int i;
3315 git_SHA_CTX ctx;
3316 struct patch_id_t data;
3317 char buffer[PATH_MAX * 4 + 20];
3319 git_SHA1_Init(&ctx);
3320 memset(&data, 0, sizeof(struct patch_id_t));
3321 data.ctx = &ctx;
3323 for (i = 0; i < q->nr; i++) {
3324 xpparam_t xpp;
3325 xdemitconf_t xecfg;
3326 xdemitcb_t ecb;
3327 mmfile_t mf1, mf2;
3328 struct diff_filepair *p = q->queue[i];
3329 int len1, len2;
3331 memset(&xpp, 0, sizeof(xpp));
3332 memset(&xecfg, 0, sizeof(xecfg));
3333 if (p->status == 0)
3334 return error("internal diff status error");
3335 if (p->status == DIFF_STATUS_UNKNOWN)
3336 continue;
3337 if (diff_unmodified_pair(p))
3338 continue;
3339 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3340 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3341 continue;
3342 if (DIFF_PAIR_UNMERGED(p))
3343 continue;
3345 diff_fill_sha1_info(p->one);
3346 diff_fill_sha1_info(p->two);
3347 if (fill_mmfile(&mf1, p->one) < 0 ||
3348 fill_mmfile(&mf2, p->two) < 0)
3349 return error("unable to read files to diff");
3351 len1 = remove_space(p->one->path, strlen(p->one->path));
3352 len2 = remove_space(p->two->path, strlen(p->two->path));
3353 if (p->one->mode == 0)
3354 len1 = snprintf(buffer, sizeof(buffer),
3355 "diff--gita/%.*sb/%.*s"
3356 "newfilemode%06o"
3357 "---/dev/null"
3358 "+++b/%.*s",
3359 len1, p->one->path,
3360 len2, p->two->path,
3361 p->two->mode,
3362 len2, p->two->path);
3363 else if (p->two->mode == 0)
3364 len1 = snprintf(buffer, sizeof(buffer),
3365 "diff--gita/%.*sb/%.*s"
3366 "deletedfilemode%06o"
3367 "---a/%.*s"
3368 "+++/dev/null",
3369 len1, p->one->path,
3370 len2, p->two->path,
3371 p->one->mode,
3372 len1, p->one->path);
3373 else
3374 len1 = snprintf(buffer, sizeof(buffer),
3375 "diff--gita/%.*sb/%.*s"
3376 "---a/%.*s"
3377 "+++b/%.*s",
3378 len1, p->one->path,
3379 len2, p->two->path,
3380 len1, p->one->path,
3381 len2, p->two->path);
3382 git_SHA1_Update(&ctx, buffer, len1);
3384 xpp.flags = XDF_NEED_MINIMAL;
3385 xecfg.ctxlen = 3;
3386 xecfg.flags = XDL_EMIT_FUNCNAMES;
3387 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3388 &xpp, &xecfg, &ecb);
3391 git_SHA1_Final(sha1, &ctx);
3392 return 0;
3395 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3397 struct diff_queue_struct *q = &diff_queued_diff;
3398 int i;
3399 int result = diff_get_patch_id(options, sha1);
3401 for (i = 0; i < q->nr; i++)
3402 diff_free_filepair(q->queue[i]);
3404 free(q->queue);
3405 q->queue = NULL;
3406 q->nr = q->alloc = 0;
3408 return result;
3411 static int is_summary_empty(const struct diff_queue_struct *q)
3413 int i;
3415 for (i = 0; i < q->nr; i++) {
3416 const struct diff_filepair *p = q->queue[i];
3418 switch (p->status) {
3419 case DIFF_STATUS_DELETED:
3420 case DIFF_STATUS_ADDED:
3421 case DIFF_STATUS_COPIED:
3422 case DIFF_STATUS_RENAMED:
3423 return 0;
3424 default:
3425 if (p->score)
3426 return 0;
3427 if (p->one->mode && p->two->mode &&
3428 p->one->mode != p->two->mode)
3429 return 0;
3430 break;
3433 return 1;
3436 void diff_flush(struct diff_options *options)
3438 struct diff_queue_struct *q = &diff_queued_diff;
3439 int i, output_format = options->output_format;
3440 int separator = 0;
3443 * Order: raw, stat, summary, patch
3444 * or: name/name-status/checkdiff (other bits clear)
3446 if (!q->nr)
3447 goto free_queue;
3449 if (output_format & (DIFF_FORMAT_RAW |
3450 DIFF_FORMAT_NAME |
3451 DIFF_FORMAT_NAME_STATUS |
3452 DIFF_FORMAT_CHECKDIFF)) {
3453 for (i = 0; i < q->nr; i++) {
3454 struct diff_filepair *p = q->queue[i];
3455 if (check_pair_status(p))
3456 flush_one_pair(p, options);
3458 separator++;
3461 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3462 struct diffstat_t diffstat;
3464 memset(&diffstat, 0, sizeof(struct diffstat_t));
3465 for (i = 0; i < q->nr; i++) {
3466 struct diff_filepair *p = q->queue[i];
3467 if (check_pair_status(p))
3468 diff_flush_stat(p, options, &diffstat);
3470 if (output_format & DIFF_FORMAT_NUMSTAT)
3471 show_numstat(&diffstat, options);
3472 if (output_format & DIFF_FORMAT_DIFFSTAT)
3473 show_stats(&diffstat, options);
3474 if (output_format & DIFF_FORMAT_SHORTSTAT)
3475 show_shortstats(&diffstat, options);
3476 free_diffstat_info(&diffstat);
3477 separator++;
3479 if (output_format & DIFF_FORMAT_DIRSTAT)
3480 show_dirstat(options);
3482 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3483 for (i = 0; i < q->nr; i++)
3484 diff_summary(options->file, q->queue[i]);
3485 separator++;
3488 if (output_format & DIFF_FORMAT_PATCH) {
3489 if (separator) {
3490 putc(options->line_termination, options->file);
3491 if (options->stat_sep) {
3492 /* attach patch instead of inline */
3493 fputs(options->stat_sep, options->file);
3497 for (i = 0; i < q->nr; i++) {
3498 struct diff_filepair *p = q->queue[i];
3499 if (check_pair_status(p))
3500 diff_flush_patch(p, options);
3504 if (output_format & DIFF_FORMAT_CALLBACK)
3505 options->format_callback(q, options, options->format_callback_data);
3507 for (i = 0; i < q->nr; i++)
3508 diff_free_filepair(q->queue[i]);
3509 free_queue:
3510 free(q->queue);
3511 q->queue = NULL;
3512 q->nr = q->alloc = 0;
3513 if (options->close_file)
3514 fclose(options->file);
3517 static void diffcore_apply_filter(const char *filter)
3519 int i;
3520 struct diff_queue_struct *q = &diff_queued_diff;
3521 struct diff_queue_struct outq;
3522 outq.queue = NULL;
3523 outq.nr = outq.alloc = 0;
3525 if (!filter)
3526 return;
3528 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3529 int found;
3530 for (i = found = 0; !found && i < q->nr; i++) {
3531 struct diff_filepair *p = q->queue[i];
3532 if (((p->status == DIFF_STATUS_MODIFIED) &&
3533 ((p->score &&
3534 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3535 (!p->score &&
3536 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3537 ((p->status != DIFF_STATUS_MODIFIED) &&
3538 strchr(filter, p->status)))
3539 found++;
3541 if (found)
3542 return;
3544 /* otherwise we will clear the whole queue
3545 * by copying the empty outq at the end of this
3546 * function, but first clear the current entries
3547 * in the queue.
3549 for (i = 0; i < q->nr; i++)
3550 diff_free_filepair(q->queue[i]);
3552 else {
3553 /* Only the matching ones */
3554 for (i = 0; i < q->nr; i++) {
3555 struct diff_filepair *p = q->queue[i];
3557 if (((p->status == DIFF_STATUS_MODIFIED) &&
3558 ((p->score &&
3559 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3560 (!p->score &&
3561 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3562 ((p->status != DIFF_STATUS_MODIFIED) &&
3563 strchr(filter, p->status)))
3564 diff_q(&outq, p);
3565 else
3566 diff_free_filepair(p);
3569 free(q->queue);
3570 *q = outq;
3573 /* Check whether two filespecs with the same mode and size are identical */
3574 static int diff_filespec_is_identical(struct diff_filespec *one,
3575 struct diff_filespec *two)
3577 if (S_ISGITLINK(one->mode))
3578 return 0;
3579 if (diff_populate_filespec(one, 0))
3580 return 0;
3581 if (diff_populate_filespec(two, 0))
3582 return 0;
3583 return !memcmp(one->data, two->data, one->size);
3586 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3588 int i;
3589 struct diff_queue_struct *q = &diff_queued_diff;
3590 struct diff_queue_struct outq;
3591 outq.queue = NULL;
3592 outq.nr = outq.alloc = 0;
3594 for (i = 0; i < q->nr; i++) {
3595 struct diff_filepair *p = q->queue[i];
3598 * 1. Entries that come from stat info dirtyness
3599 * always have both sides (iow, not create/delete),
3600 * one side of the object name is unknown, with
3601 * the same mode and size. Keep the ones that
3602 * do not match these criteria. They have real
3603 * differences.
3605 * 2. At this point, the file is known to be modified,
3606 * with the same mode and size, and the object
3607 * name of one side is unknown. Need to inspect
3608 * the identical contents.
3610 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3611 !DIFF_FILE_VALID(p->two) ||
3612 (p->one->sha1_valid && p->two->sha1_valid) ||
3613 (p->one->mode != p->two->mode) ||
3614 diff_populate_filespec(p->one, 1) ||
3615 diff_populate_filespec(p->two, 1) ||
3616 (p->one->size != p->two->size) ||
3617 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3618 diff_q(&outq, p);
3619 else {
3621 * The caller can subtract 1 from skip_stat_unmatch
3622 * to determine how many paths were dirty only
3623 * due to stat info mismatch.
3625 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3626 diffopt->skip_stat_unmatch++;
3627 diff_free_filepair(p);
3630 free(q->queue);
3631 *q = outq;
3634 void diffcore_std(struct diff_options *options)
3636 if (options->skip_stat_unmatch)
3637 diffcore_skip_stat_unmatch(options);
3638 if (options->break_opt != -1)
3639 diffcore_break(options->break_opt);
3640 if (options->detect_rename)
3641 diffcore_rename(options);
3642 if (options->break_opt != -1)
3643 diffcore_merge_broken();
3644 if (options->pickaxe)
3645 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3646 if (options->orderfile)
3647 diffcore_order(options->orderfile);
3648 diff_resolve_rename_copy();
3649 diffcore_apply_filter(options->filter);
3651 if (diff_queued_diff.nr)
3652 DIFF_OPT_SET(options, HAS_CHANGES);
3653 else
3654 DIFF_OPT_CLR(options, HAS_CHANGES);
3657 int diff_result_code(struct diff_options *opt, int status)
3659 int result = 0;
3660 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3661 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3662 return status;
3663 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3664 DIFF_OPT_TST(opt, HAS_CHANGES))
3665 result |= 01;
3666 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3667 DIFF_OPT_TST(opt, CHECK_FAILED))
3668 result |= 02;
3669 return result;
3672 void diff_addremove(struct diff_options *options,
3673 int addremove, unsigned mode,
3674 const unsigned char *sha1,
3675 const char *concatpath)
3677 struct diff_filespec *one, *two;
3679 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3680 return;
3682 /* This may look odd, but it is a preparation for
3683 * feeding "there are unchanged files which should
3684 * not produce diffs, but when you are doing copy
3685 * detection you would need them, so here they are"
3686 * entries to the diff-core. They will be prefixed
3687 * with something like '=' or '*' (I haven't decided
3688 * which but should not make any difference).
3689 * Feeding the same new and old to diff_change()
3690 * also has the same effect.
3691 * Before the final output happens, they are pruned after
3692 * merged into rename/copy pairs as appropriate.
3694 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3695 addremove = (addremove == '+' ? '-' :
3696 addremove == '-' ? '+' : addremove);
3698 if (options->prefix &&
3699 strncmp(concatpath, options->prefix, options->prefix_length))
3700 return;
3702 one = alloc_filespec(concatpath);
3703 two = alloc_filespec(concatpath);
3705 if (addremove != '+')
3706 fill_filespec(one, sha1, mode);
3707 if (addremove != '-')
3708 fill_filespec(two, sha1, mode);
3710 diff_queue(&diff_queued_diff, one, two);
3711 DIFF_OPT_SET(options, HAS_CHANGES);
3714 void diff_change(struct diff_options *options,
3715 unsigned old_mode, unsigned new_mode,
3716 const unsigned char *old_sha1,
3717 const unsigned char *new_sha1,
3718 const char *concatpath)
3720 struct diff_filespec *one, *two;
3722 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3723 && S_ISGITLINK(new_mode))
3724 return;
3726 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3727 unsigned tmp;
3728 const unsigned char *tmp_c;
3729 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3730 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3733 if (options->prefix &&
3734 strncmp(concatpath, options->prefix, options->prefix_length))
3735 return;
3737 one = alloc_filespec(concatpath);
3738 two = alloc_filespec(concatpath);
3739 fill_filespec(one, old_sha1, old_mode);
3740 fill_filespec(two, new_sha1, new_mode);
3742 diff_queue(&diff_queued_diff, one, two);
3743 DIFF_OPT_SET(options, HAS_CHANGES);
3746 void diff_unmerge(struct diff_options *options,
3747 const char *path,
3748 unsigned mode, const unsigned char *sha1)
3750 struct diff_filespec *one, *two;
3752 if (options->prefix &&
3753 strncmp(path, options->prefix, options->prefix_length))
3754 return;
3756 one = alloc_filespec(path);
3757 two = alloc_filespec(path);
3758 fill_filespec(one, sha1, mode);
3759 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3762 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3763 size_t *outsize)
3765 struct diff_tempfile *temp;
3766 const char *argv[3];
3767 const char **arg = argv;
3768 struct child_process child;
3769 struct strbuf buf = STRBUF_INIT;
3771 temp = prepare_temp_file(spec->path, spec);
3772 *arg++ = pgm;
3773 *arg++ = temp->name;
3774 *arg = NULL;
3776 memset(&child, 0, sizeof(child));
3777 child.argv = argv;
3778 child.out = -1;
3779 if (start_command(&child) != 0 ||
3780 strbuf_read(&buf, child.out, 0) < 0 ||
3781 finish_command(&child) != 0) {
3782 strbuf_release(&buf);
3783 remove_tempfile();
3784 error("error running textconv command '%s'", pgm);
3785 return NULL;
3787 remove_tempfile();
3789 return strbuf_detach(&buf, outsize);