status: fix bug with missing --ignore files
[alt-git.git] / diff.c
bloba1bf1e9cb37104cda8168c5118769ce5bbcfcbb2
1 /*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12 #include "run-command.h"
13 #include "utf8.h"
14 #include "userdiff.h"
15 #include "sigchain.h"
16 #include "submodule.h"
17 #include "ll-merge.h"
19 #ifdef NO_FAST_WORKING_DIRECTORY
20 #define FAST_WORKING_DIRECTORY 0
21 #else
22 #define FAST_WORKING_DIRECTORY 1
23 #endif
25 static int diff_detect_rename_default;
26 static int diff_rename_limit_default = 200;
27 static int diff_suppress_blank_empty;
28 int diff_use_color_default = -1;
29 static const char *diff_word_regex_cfg;
30 static const char *external_diff_cmd_cfg;
31 int diff_auto_refresh_index = 1;
32 static int diff_mnemonic_prefix;
34 static char diff_colors[][COLOR_MAXLEN] = {
35 GIT_COLOR_RESET,
36 GIT_COLOR_NORMAL, /* PLAIN */
37 GIT_COLOR_BOLD, /* METAINFO */
38 GIT_COLOR_CYAN, /* FRAGINFO */
39 GIT_COLOR_RED, /* OLD */
40 GIT_COLOR_GREEN, /* NEW */
41 GIT_COLOR_YELLOW, /* COMMIT */
42 GIT_COLOR_BG_RED, /* WHITESPACE */
43 GIT_COLOR_NORMAL, /* FUNCINFO */
46 static void diff_filespec_load_driver(struct diff_filespec *one);
47 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
49 static int parse_diff_color_slot(const char *var, int ofs)
51 if (!strcasecmp(var+ofs, "plain"))
52 return DIFF_PLAIN;
53 if (!strcasecmp(var+ofs, "meta"))
54 return DIFF_METAINFO;
55 if (!strcasecmp(var+ofs, "frag"))
56 return DIFF_FRAGINFO;
57 if (!strcasecmp(var+ofs, "old"))
58 return DIFF_FILE_OLD;
59 if (!strcasecmp(var+ofs, "new"))
60 return DIFF_FILE_NEW;
61 if (!strcasecmp(var+ofs, "commit"))
62 return DIFF_COMMIT;
63 if (!strcasecmp(var+ofs, "whitespace"))
64 return DIFF_WHITESPACE;
65 if (!strcasecmp(var+ofs, "func"))
66 return DIFF_FUNCINFO;
67 return -1;
70 static int git_config_rename(const char *var, const char *value)
72 if (!value)
73 return DIFF_DETECT_RENAME;
74 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
75 return DIFF_DETECT_COPY;
76 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
80 * These are to give UI layer defaults.
81 * The core-level commands such as git-diff-files should
82 * never be affected by the setting of diff.renames
83 * the user happens to have in the configuration file.
85 int git_diff_ui_config(const char *var, const char *value, void *cb)
87 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
88 diff_use_color_default = git_config_colorbool(var, value, -1);
89 return 0;
91 if (!strcmp(var, "diff.renames")) {
92 diff_detect_rename_default = git_config_rename(var, value);
93 return 0;
95 if (!strcmp(var, "diff.autorefreshindex")) {
96 diff_auto_refresh_index = git_config_bool(var, value);
97 return 0;
99 if (!strcmp(var, "diff.mnemonicprefix")) {
100 diff_mnemonic_prefix = git_config_bool(var, value);
101 return 0;
103 if (!strcmp(var, "diff.external"))
104 return git_config_string(&external_diff_cmd_cfg, var, value);
105 if (!strcmp(var, "diff.wordregex"))
106 return git_config_string(&diff_word_regex_cfg, var, value);
108 return git_diff_basic_config(var, value, cb);
111 int git_diff_basic_config(const char *var, const char *value, void *cb)
113 if (!strcmp(var, "diff.renamelimit")) {
114 diff_rename_limit_default = git_config_int(var, value);
115 return 0;
118 switch (userdiff_config(var, value)) {
119 case 0: break;
120 case -1: return -1;
121 default: return 0;
124 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
125 int slot = parse_diff_color_slot(var, 11);
126 if (slot < 0)
127 return 0;
128 if (!value)
129 return config_error_nonbool(var);
130 color_parse(value, var, diff_colors[slot]);
131 return 0;
134 /* like GNU diff's --suppress-blank-empty option */
135 if (!strcmp(var, "diff.suppressblankempty") ||
136 /* for backwards compatibility */
137 !strcmp(var, "diff.suppress-blank-empty")) {
138 diff_suppress_blank_empty = git_config_bool(var, value);
139 return 0;
142 return git_color_default_config(var, value, cb);
145 static char *quote_two(const char *one, const char *two)
147 int need_one = quote_c_style(one, NULL, NULL, 1);
148 int need_two = quote_c_style(two, NULL, NULL, 1);
149 struct strbuf res = STRBUF_INIT;
151 if (need_one + need_two) {
152 strbuf_addch(&res, '"');
153 quote_c_style(one, &res, NULL, 1);
154 quote_c_style(two, &res, NULL, 1);
155 strbuf_addch(&res, '"');
156 } else {
157 strbuf_addstr(&res, one);
158 strbuf_addstr(&res, two);
160 return strbuf_detach(&res, NULL);
163 static const char *external_diff(void)
165 static const char *external_diff_cmd = NULL;
166 static int done_preparing = 0;
168 if (done_preparing)
169 return external_diff_cmd;
170 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
171 if (!external_diff_cmd)
172 external_diff_cmd = external_diff_cmd_cfg;
173 done_preparing = 1;
174 return external_diff_cmd;
177 static struct diff_tempfile {
178 const char *name; /* filename external diff should read from */
179 char hex[41];
180 char mode[10];
181 char tmp_path[PATH_MAX];
182 } diff_temp[2];
184 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
186 struct emit_callback {
187 int color_diff;
188 unsigned ws_rule;
189 int blank_at_eof_in_preimage;
190 int blank_at_eof_in_postimage;
191 int lno_in_preimage;
192 int lno_in_postimage;
193 sane_truncate_fn truncate;
194 const char **label_path;
195 struct diff_words_data *diff_words;
196 int *found_changesp;
197 FILE *file;
198 struct strbuf *header;
201 static int count_lines(const char *data, int size)
203 int count, ch, completely_empty = 1, nl_just_seen = 0;
204 count = 0;
205 while (0 < size--) {
206 ch = *data++;
207 if (ch == '\n') {
208 count++;
209 nl_just_seen = 1;
210 completely_empty = 0;
212 else {
213 nl_just_seen = 0;
214 completely_empty = 0;
217 if (completely_empty)
218 return 0;
219 if (!nl_just_seen)
220 count++; /* no trailing newline */
221 return count;
224 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
226 if (!DIFF_FILE_VALID(one)) {
227 mf->ptr = (char *)""; /* does not matter */
228 mf->size = 0;
229 return 0;
231 else if (diff_populate_filespec(one, 0))
232 return -1;
234 mf->ptr = one->data;
235 mf->size = one->size;
236 return 0;
239 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
241 char *ptr = mf->ptr;
242 long size = mf->size;
243 int cnt = 0;
245 if (!size)
246 return cnt;
247 ptr += size - 1; /* pointing at the very end */
248 if (*ptr != '\n')
249 ; /* incomplete line */
250 else
251 ptr--; /* skip the last LF */
252 while (mf->ptr < ptr) {
253 char *prev_eol;
254 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
255 if (*prev_eol == '\n')
256 break;
257 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
258 break;
259 cnt++;
260 ptr = prev_eol - 1;
262 return cnt;
265 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
266 struct emit_callback *ecbdata)
268 int l1, l2, at;
269 unsigned ws_rule = ecbdata->ws_rule;
270 l1 = count_trailing_blank(mf1, ws_rule);
271 l2 = count_trailing_blank(mf2, ws_rule);
272 if (l2 <= l1) {
273 ecbdata->blank_at_eof_in_preimage = 0;
274 ecbdata->blank_at_eof_in_postimage = 0;
275 return;
277 at = count_lines(mf1->ptr, mf1->size);
278 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
280 at = count_lines(mf2->ptr, mf2->size);
281 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
284 static void emit_line_0(FILE *file, const char *set, const char *reset,
285 int first, const char *line, int len)
287 int has_trailing_newline, has_trailing_carriage_return;
288 int nofirst;
290 if (len == 0) {
291 has_trailing_newline = (first == '\n');
292 has_trailing_carriage_return = (!has_trailing_newline &&
293 (first == '\r'));
294 nofirst = has_trailing_newline || has_trailing_carriage_return;
295 } else {
296 has_trailing_newline = (len > 0 && line[len-1] == '\n');
297 if (has_trailing_newline)
298 len--;
299 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
300 if (has_trailing_carriage_return)
301 len--;
302 nofirst = 0;
305 if (len || !nofirst) {
306 fputs(set, file);
307 if (!nofirst)
308 fputc(first, file);
309 fwrite(line, len, 1, file);
310 fputs(reset, file);
312 if (has_trailing_carriage_return)
313 fputc('\r', file);
314 if (has_trailing_newline)
315 fputc('\n', file);
318 static void emit_line(FILE *file, const char *set, const char *reset,
319 const char *line, int len)
321 emit_line_0(file, set, reset, line[0], line+1, len-1);
324 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
326 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
327 ecbdata->blank_at_eof_in_preimage &&
328 ecbdata->blank_at_eof_in_postimage &&
329 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
330 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
331 return 0;
332 return ws_blank_line(line, len, ecbdata->ws_rule);
335 static void emit_add_line(const char *reset,
336 struct emit_callback *ecbdata,
337 const char *line, int len)
339 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
340 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
342 if (!*ws)
343 emit_line_0(ecbdata->file, set, reset, '+', line, len);
344 else if (new_blank_line_at_eof(ecbdata, line, len))
345 /* Blank line at EOF - paint '+' as well */
346 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
347 else {
348 /* Emit just the prefix, then the rest. */
349 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
350 ws_check_emit(line, len, ecbdata->ws_rule,
351 ecbdata->file, set, reset, ws);
355 static void emit_hunk_header(struct emit_callback *ecbdata,
356 const char *line, int len)
358 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
359 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
360 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
361 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
362 static const char atat[2] = { '@', '@' };
363 const char *cp, *ep;
366 * As a hunk header must begin with "@@ -<old>, +<new> @@",
367 * it always is at least 10 bytes long.
369 if (len < 10 ||
370 memcmp(line, atat, 2) ||
371 !(ep = memmem(line + 2, len - 2, atat, 2))) {
372 emit_line(ecbdata->file, plain, reset, line, len);
373 return;
375 ep += 2; /* skip over @@ */
377 /* The hunk header in fraginfo color */
378 emit_line(ecbdata->file, frag, reset, line, ep - line);
380 /* blank before the func header */
381 for (cp = ep; ep - line < len; ep++)
382 if (*ep != ' ' && *ep != '\t')
383 break;
384 if (ep != cp)
385 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
387 if (ep < line + len)
388 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
391 static struct diff_tempfile *claim_diff_tempfile(void) {
392 int i;
393 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
394 if (!diff_temp[i].name)
395 return diff_temp + i;
396 die("BUG: diff is failing to clean up its tempfiles");
399 static int remove_tempfile_installed;
401 static void remove_tempfile(void)
403 int i;
404 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
405 if (diff_temp[i].name == diff_temp[i].tmp_path)
406 unlink_or_warn(diff_temp[i].name);
407 diff_temp[i].name = NULL;
411 static void remove_tempfile_on_signal(int signo)
413 remove_tempfile();
414 sigchain_pop(signo);
415 raise(signo);
418 static void print_line_count(FILE *file, int count)
420 switch (count) {
421 case 0:
422 fprintf(file, "0,0");
423 break;
424 case 1:
425 fprintf(file, "1");
426 break;
427 default:
428 fprintf(file, "1,%d", count);
429 break;
433 static void emit_rewrite_lines(struct emit_callback *ecb,
434 int prefix, const char *data, int size)
436 const char *endp = NULL;
437 static const char *nneof = " No newline at end of file\n";
438 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
439 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
441 while (0 < size) {
442 int len;
444 endp = memchr(data, '\n', size);
445 len = endp ? (endp - data + 1) : size;
446 if (prefix != '+') {
447 ecb->lno_in_preimage++;
448 emit_line_0(ecb->file, old, reset, '-',
449 data, len);
450 } else {
451 ecb->lno_in_postimage++;
452 emit_add_line(reset, ecb, data, len);
454 size -= len;
455 data += len;
457 if (!endp) {
458 const char *plain = diff_get_color(ecb->color_diff,
459 DIFF_PLAIN);
460 emit_line_0(ecb->file, plain, reset, '\\',
461 nneof, strlen(nneof));
465 static void emit_rewrite_diff(const char *name_a,
466 const char *name_b,
467 struct diff_filespec *one,
468 struct diff_filespec *two,
469 const char *textconv_one,
470 const char *textconv_two,
471 struct diff_options *o)
473 int lc_a, lc_b;
474 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
475 const char *name_a_tab, *name_b_tab;
476 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
477 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
478 const char *reset = diff_get_color(color_diff, DIFF_RESET);
479 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
480 const char *a_prefix, *b_prefix;
481 const char *data_one, *data_two;
482 size_t size_one, size_two;
483 struct emit_callback ecbdata;
485 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
486 a_prefix = o->b_prefix;
487 b_prefix = o->a_prefix;
488 } else {
489 a_prefix = o->a_prefix;
490 b_prefix = o->b_prefix;
493 name_a += (*name_a == '/');
494 name_b += (*name_b == '/');
495 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
496 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
498 strbuf_reset(&a_name);
499 strbuf_reset(&b_name);
500 quote_two_c_style(&a_name, a_prefix, name_a, 0);
501 quote_two_c_style(&b_name, b_prefix, name_b, 0);
503 diff_populate_filespec(one, 0);
504 diff_populate_filespec(two, 0);
505 if (textconv_one) {
506 data_one = run_textconv(textconv_one, one, &size_one);
507 if (!data_one)
508 die("unable to read files to diff");
510 else {
511 data_one = one->data;
512 size_one = one->size;
514 if (textconv_two) {
515 data_two = run_textconv(textconv_two, two, &size_two);
516 if (!data_two)
517 die("unable to read files to diff");
519 else {
520 data_two = two->data;
521 size_two = two->size;
524 memset(&ecbdata, 0, sizeof(ecbdata));
525 ecbdata.color_diff = color_diff;
526 ecbdata.found_changesp = &o->found_changes;
527 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
528 ecbdata.file = o->file;
529 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
530 mmfile_t mf1, mf2;
531 mf1.ptr = (char *)data_one;
532 mf2.ptr = (char *)data_two;
533 mf1.size = size_one;
534 mf2.size = size_two;
535 check_blank_at_eof(&mf1, &mf2, &ecbdata);
537 ecbdata.lno_in_preimage = 1;
538 ecbdata.lno_in_postimage = 1;
540 lc_a = count_lines(data_one, size_one);
541 lc_b = count_lines(data_two, size_two);
542 fprintf(o->file,
543 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
544 metainfo, a_name.buf, name_a_tab, reset,
545 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
546 print_line_count(o->file, lc_a);
547 fprintf(o->file, " +");
548 print_line_count(o->file, lc_b);
549 fprintf(o->file, " @@%s\n", reset);
550 if (lc_a)
551 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
552 if (lc_b)
553 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
554 if (textconv_one)
555 free((char *)data_one);
556 if (textconv_two)
557 free((char *)data_two);
560 struct diff_words_buffer {
561 mmfile_t text;
562 long alloc;
563 struct diff_words_orig {
564 const char *begin, *end;
565 } *orig;
566 int orig_nr, orig_alloc;
569 static void diff_words_append(char *line, unsigned long len,
570 struct diff_words_buffer *buffer)
572 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
573 line++;
574 len--;
575 memcpy(buffer->text.ptr + buffer->text.size, line, len);
576 buffer->text.size += len;
577 buffer->text.ptr[buffer->text.size] = '\0';
580 struct diff_words_data {
581 struct diff_words_buffer minus, plus;
582 const char *current_plus;
583 FILE *file;
584 regex_t *word_regex;
587 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
589 struct diff_words_data *diff_words = priv;
590 int minus_first, minus_len, plus_first, plus_len;
591 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
593 if (line[0] != '@' || parse_hunk_header(line, len,
594 &minus_first, &minus_len, &plus_first, &plus_len))
595 return;
597 /* POSIX requires that first be decremented by one if len == 0... */
598 if (minus_len) {
599 minus_begin = diff_words->minus.orig[minus_first].begin;
600 minus_end =
601 diff_words->minus.orig[minus_first + minus_len - 1].end;
602 } else
603 minus_begin = minus_end =
604 diff_words->minus.orig[minus_first].end;
606 if (plus_len) {
607 plus_begin = diff_words->plus.orig[plus_first].begin;
608 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
609 } else
610 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
612 if (diff_words->current_plus != plus_begin)
613 fwrite(diff_words->current_plus,
614 plus_begin - diff_words->current_plus, 1,
615 diff_words->file);
616 if (minus_begin != minus_end)
617 color_fwrite_lines(diff_words->file,
618 diff_get_color(1, DIFF_FILE_OLD),
619 minus_end - minus_begin, minus_begin);
620 if (plus_begin != plus_end)
621 color_fwrite_lines(diff_words->file,
622 diff_get_color(1, DIFF_FILE_NEW),
623 plus_end - plus_begin, plus_begin);
625 diff_words->current_plus = plus_end;
628 /* This function starts looking at *begin, and returns 0 iff a word was found. */
629 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
630 int *begin, int *end)
632 if (word_regex && *begin < buffer->size) {
633 regmatch_t match[1];
634 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
635 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
636 '\n', match[0].rm_eo - match[0].rm_so);
637 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
638 *begin += match[0].rm_so;
639 return *begin >= *end;
641 return -1;
644 /* find the next word */
645 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
646 (*begin)++;
647 if (*begin >= buffer->size)
648 return -1;
650 /* find the end of the word */
651 *end = *begin + 1;
652 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
653 (*end)++;
655 return 0;
659 * This function splits the words in buffer->text, stores the list with
660 * newline separator into out, and saves the offsets of the original words
661 * in buffer->orig.
663 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
664 regex_t *word_regex)
666 int i, j;
667 long alloc = 0;
669 out->size = 0;
670 out->ptr = NULL;
672 /* fake an empty "0th" word */
673 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
674 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
675 buffer->orig_nr = 1;
677 for (i = 0; i < buffer->text.size; i++) {
678 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
679 return;
681 /* store original boundaries */
682 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
683 buffer->orig_alloc);
684 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
685 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
686 buffer->orig_nr++;
688 /* store one word */
689 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
690 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
691 out->ptr[out->size + j - i] = '\n';
692 out->size += j - i + 1;
694 i = j - 1;
698 /* this executes the word diff on the accumulated buffers */
699 static void diff_words_show(struct diff_words_data *diff_words)
701 xpparam_t xpp;
702 xdemitconf_t xecfg;
703 xdemitcb_t ecb;
704 mmfile_t minus, plus;
706 /* special case: only removal */
707 if (!diff_words->plus.text.size) {
708 color_fwrite_lines(diff_words->file,
709 diff_get_color(1, DIFF_FILE_OLD),
710 diff_words->minus.text.size, diff_words->minus.text.ptr);
711 diff_words->minus.text.size = 0;
712 return;
715 diff_words->current_plus = diff_words->plus.text.ptr;
717 memset(&xpp, 0, sizeof(xpp));
718 memset(&xecfg, 0, sizeof(xecfg));
719 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
720 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
721 xpp.flags = XDF_NEED_MINIMAL;
722 /* as only the hunk header will be parsed, we need a 0-context */
723 xecfg.ctxlen = 0;
724 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
725 &xpp, &xecfg, &ecb);
726 free(minus.ptr);
727 free(plus.ptr);
728 if (diff_words->current_plus != diff_words->plus.text.ptr +
729 diff_words->plus.text.size)
730 fwrite(diff_words->current_plus,
731 diff_words->plus.text.ptr + diff_words->plus.text.size
732 - diff_words->current_plus, 1,
733 diff_words->file);
734 diff_words->minus.text.size = diff_words->plus.text.size = 0;
737 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
738 static void diff_words_flush(struct emit_callback *ecbdata)
740 if (ecbdata->diff_words->minus.text.size ||
741 ecbdata->diff_words->plus.text.size)
742 diff_words_show(ecbdata->diff_words);
745 static void free_diff_words_data(struct emit_callback *ecbdata)
747 if (ecbdata->diff_words) {
748 diff_words_flush(ecbdata);
749 free (ecbdata->diff_words->minus.text.ptr);
750 free (ecbdata->diff_words->minus.orig);
751 free (ecbdata->diff_words->plus.text.ptr);
752 free (ecbdata->diff_words->plus.orig);
753 free(ecbdata->diff_words->word_regex);
754 free(ecbdata->diff_words);
755 ecbdata->diff_words = NULL;
759 const char *diff_get_color(int diff_use_color, enum color_diff ix)
761 if (diff_use_color)
762 return diff_colors[ix];
763 return "";
766 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
768 const char *cp;
769 unsigned long allot;
770 size_t l = len;
772 if (ecb->truncate)
773 return ecb->truncate(line, len);
774 cp = line;
775 allot = l;
776 while (0 < l) {
777 (void) utf8_width(&cp, &l);
778 if (!cp)
779 break; /* truncated in the middle? */
781 return allot - l;
784 static void find_lno(const char *line, struct emit_callback *ecbdata)
786 const char *p;
787 ecbdata->lno_in_preimage = 0;
788 ecbdata->lno_in_postimage = 0;
789 p = strchr(line, '-');
790 if (!p)
791 return; /* cannot happen */
792 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
793 p = strchr(p, '+');
794 if (!p)
795 return; /* cannot happen */
796 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
799 static void fn_out_consume(void *priv, char *line, unsigned long len)
801 struct emit_callback *ecbdata = priv;
802 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
803 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
804 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
806 if (ecbdata->header) {
807 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
808 strbuf_reset(ecbdata->header);
809 ecbdata->header = NULL;
811 *(ecbdata->found_changesp) = 1;
813 if (ecbdata->label_path[0]) {
814 const char *name_a_tab, *name_b_tab;
816 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
817 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
819 fprintf(ecbdata->file, "%s--- %s%s%s\n",
820 meta, ecbdata->label_path[0], reset, name_a_tab);
821 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
822 meta, ecbdata->label_path[1], reset, name_b_tab);
823 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
826 if (diff_suppress_blank_empty
827 && len == 2 && line[0] == ' ' && line[1] == '\n') {
828 line[0] = '\n';
829 len = 1;
832 if (line[0] == '@') {
833 if (ecbdata->diff_words)
834 diff_words_flush(ecbdata);
835 len = sane_truncate_line(ecbdata, line, len);
836 find_lno(line, ecbdata);
837 emit_hunk_header(ecbdata, line, len);
838 if (line[len-1] != '\n')
839 putc('\n', ecbdata->file);
840 return;
843 if (len < 1) {
844 emit_line(ecbdata->file, reset, reset, line, len);
845 return;
848 if (ecbdata->diff_words) {
849 if (line[0] == '-') {
850 diff_words_append(line, len,
851 &ecbdata->diff_words->minus);
852 return;
853 } else if (line[0] == '+') {
854 diff_words_append(line, len,
855 &ecbdata->diff_words->plus);
856 return;
858 diff_words_flush(ecbdata);
859 line++;
860 len--;
861 emit_line(ecbdata->file, plain, reset, line, len);
862 return;
865 if (line[0] != '+') {
866 const char *color =
867 diff_get_color(ecbdata->color_diff,
868 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
869 ecbdata->lno_in_preimage++;
870 if (line[0] == ' ')
871 ecbdata->lno_in_postimage++;
872 emit_line(ecbdata->file, color, reset, line, len);
873 } else {
874 ecbdata->lno_in_postimage++;
875 emit_add_line(reset, ecbdata, line + 1, len - 1);
879 static char *pprint_rename(const char *a, const char *b)
881 const char *old = a;
882 const char *new = b;
883 struct strbuf name = STRBUF_INIT;
884 int pfx_length, sfx_length;
885 int len_a = strlen(a);
886 int len_b = strlen(b);
887 int a_midlen, b_midlen;
888 int qlen_a = quote_c_style(a, NULL, NULL, 0);
889 int qlen_b = quote_c_style(b, NULL, NULL, 0);
891 if (qlen_a || qlen_b) {
892 quote_c_style(a, &name, NULL, 0);
893 strbuf_addstr(&name, " => ");
894 quote_c_style(b, &name, NULL, 0);
895 return strbuf_detach(&name, NULL);
898 /* Find common prefix */
899 pfx_length = 0;
900 while (*old && *new && *old == *new) {
901 if (*old == '/')
902 pfx_length = old - a + 1;
903 old++;
904 new++;
907 /* Find common suffix */
908 old = a + len_a;
909 new = b + len_b;
910 sfx_length = 0;
911 while (a <= old && b <= new && *old == *new) {
912 if (*old == '/')
913 sfx_length = len_a - (old - a);
914 old--;
915 new--;
919 * pfx{mid-a => mid-b}sfx
920 * {pfx-a => pfx-b}sfx
921 * pfx{sfx-a => sfx-b}
922 * name-a => name-b
924 a_midlen = len_a - pfx_length - sfx_length;
925 b_midlen = len_b - pfx_length - sfx_length;
926 if (a_midlen < 0)
927 a_midlen = 0;
928 if (b_midlen < 0)
929 b_midlen = 0;
931 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
932 if (pfx_length + sfx_length) {
933 strbuf_add(&name, a, pfx_length);
934 strbuf_addch(&name, '{');
936 strbuf_add(&name, a + pfx_length, a_midlen);
937 strbuf_addstr(&name, " => ");
938 strbuf_add(&name, b + pfx_length, b_midlen);
939 if (pfx_length + sfx_length) {
940 strbuf_addch(&name, '}');
941 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
943 return strbuf_detach(&name, NULL);
946 struct diffstat_t {
947 int nr;
948 int alloc;
949 struct diffstat_file {
950 char *from_name;
951 char *name;
952 char *print_name;
953 unsigned is_unmerged:1;
954 unsigned is_binary:1;
955 unsigned is_renamed:1;
956 unsigned int added, deleted;
957 } **files;
960 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
961 const char *name_a,
962 const char *name_b)
964 struct diffstat_file *x;
965 x = xcalloc(sizeof (*x), 1);
966 if (diffstat->nr == diffstat->alloc) {
967 diffstat->alloc = alloc_nr(diffstat->alloc);
968 diffstat->files = xrealloc(diffstat->files,
969 diffstat->alloc * sizeof(x));
971 diffstat->files[diffstat->nr++] = x;
972 if (name_b) {
973 x->from_name = xstrdup(name_a);
974 x->name = xstrdup(name_b);
975 x->is_renamed = 1;
977 else {
978 x->from_name = NULL;
979 x->name = xstrdup(name_a);
981 return x;
984 static void diffstat_consume(void *priv, char *line, unsigned long len)
986 struct diffstat_t *diffstat = priv;
987 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
989 if (line[0] == '+')
990 x->added++;
991 else if (line[0] == '-')
992 x->deleted++;
995 const char mime_boundary_leader[] = "------------";
997 static int scale_linear(int it, int width, int max_change)
1000 * make sure that at least one '-' is printed if there were deletions,
1001 * and likewise for '+'.
1003 if (max_change < 2)
1004 return it;
1005 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1008 static void show_name(FILE *file,
1009 const char *prefix, const char *name, int len)
1011 fprintf(file, " %s%-*s |", prefix, len, name);
1014 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1016 if (cnt <= 0)
1017 return;
1018 fprintf(file, "%s", set);
1019 while (cnt--)
1020 putc(ch, file);
1021 fprintf(file, "%s", reset);
1024 static void fill_print_name(struct diffstat_file *file)
1026 char *pname;
1028 if (file->print_name)
1029 return;
1031 if (!file->is_renamed) {
1032 struct strbuf buf = STRBUF_INIT;
1033 if (quote_c_style(file->name, &buf, NULL, 0)) {
1034 pname = strbuf_detach(&buf, NULL);
1035 } else {
1036 pname = file->name;
1037 strbuf_release(&buf);
1039 } else {
1040 pname = pprint_rename(file->from_name, file->name);
1042 file->print_name = pname;
1045 static void show_stats(struct diffstat_t *data, struct diff_options *options)
1047 int i, len, add, del, adds = 0, dels = 0;
1048 int max_change = 0, max_len = 0;
1049 int total_files = data->nr;
1050 int width, name_width;
1051 const char *reset, *set, *add_c, *del_c;
1053 if (data->nr == 0)
1054 return;
1056 width = options->stat_width ? options->stat_width : 80;
1057 name_width = options->stat_name_width ? options->stat_name_width : 50;
1059 /* Sanity: give at least 5 columns to the graph,
1060 * but leave at least 10 columns for the name.
1062 if (width < 25)
1063 width = 25;
1064 if (name_width < 10)
1065 name_width = 10;
1066 else if (width < name_width + 15)
1067 name_width = width - 15;
1069 /* Find the longest filename and max number of changes */
1070 reset = diff_get_color_opt(options, DIFF_RESET);
1071 set = diff_get_color_opt(options, DIFF_PLAIN);
1072 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1073 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1075 for (i = 0; i < data->nr; i++) {
1076 struct diffstat_file *file = data->files[i];
1077 int change = file->added + file->deleted;
1078 fill_print_name(file);
1079 len = strlen(file->print_name);
1080 if (max_len < len)
1081 max_len = len;
1083 if (file->is_binary || file->is_unmerged)
1084 continue;
1085 if (max_change < change)
1086 max_change = change;
1089 /* Compute the width of the graph part;
1090 * 10 is for one blank at the beginning of the line plus
1091 * " | count " between the name and the graph.
1093 * From here on, name_width is the width of the name area,
1094 * and width is the width of the graph area.
1096 name_width = (name_width < max_len) ? name_width : max_len;
1097 if (width < (name_width + 10) + max_change)
1098 width = width - (name_width + 10);
1099 else
1100 width = max_change;
1102 for (i = 0; i < data->nr; i++) {
1103 const char *prefix = "";
1104 char *name = data->files[i]->print_name;
1105 int added = data->files[i]->added;
1106 int deleted = data->files[i]->deleted;
1107 int name_len;
1110 * "scale" the filename
1112 len = name_width;
1113 name_len = strlen(name);
1114 if (name_width < name_len) {
1115 char *slash;
1116 prefix = "...";
1117 len -= 3;
1118 name += name_len - len;
1119 slash = strchr(name, '/');
1120 if (slash)
1121 name = slash;
1124 if (data->files[i]->is_binary) {
1125 show_name(options->file, prefix, name, len);
1126 fprintf(options->file, " Bin ");
1127 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
1128 fprintf(options->file, " -> ");
1129 fprintf(options->file, "%s%d%s", add_c, added, reset);
1130 fprintf(options->file, " bytes");
1131 fprintf(options->file, "\n");
1132 continue;
1134 else if (data->files[i]->is_unmerged) {
1135 show_name(options->file, prefix, name, len);
1136 fprintf(options->file, " Unmerged\n");
1137 continue;
1139 else if (!data->files[i]->is_renamed &&
1140 (added + deleted == 0)) {
1141 total_files--;
1142 continue;
1146 * scale the add/delete
1148 add = added;
1149 del = deleted;
1150 adds += add;
1151 dels += del;
1153 if (width <= max_change) {
1154 add = scale_linear(add, width, max_change);
1155 del = scale_linear(del, width, max_change);
1157 show_name(options->file, prefix, name, len);
1158 fprintf(options->file, "%5d%s", added + deleted,
1159 added + deleted ? " " : "");
1160 show_graph(options->file, '+', add, add_c, reset);
1161 show_graph(options->file, '-', del, del_c, reset);
1162 fprintf(options->file, "\n");
1164 fprintf(options->file,
1165 " %d files changed, %d insertions(+), %d deletions(-)\n",
1166 total_files, adds, dels);
1169 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1171 int i, adds = 0, dels = 0, total_files = data->nr;
1173 if (data->nr == 0)
1174 return;
1176 for (i = 0; i < data->nr; i++) {
1177 if (!data->files[i]->is_binary &&
1178 !data->files[i]->is_unmerged) {
1179 int added = data->files[i]->added;
1180 int deleted= data->files[i]->deleted;
1181 if (!data->files[i]->is_renamed &&
1182 (added + deleted == 0)) {
1183 total_files--;
1184 } else {
1185 adds += added;
1186 dels += deleted;
1190 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1191 total_files, adds, dels);
1194 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1196 int i;
1198 if (data->nr == 0)
1199 return;
1201 for (i = 0; i < data->nr; i++) {
1202 struct diffstat_file *file = data->files[i];
1204 if (file->is_binary)
1205 fprintf(options->file, "-\t-\t");
1206 else
1207 fprintf(options->file,
1208 "%d\t%d\t", file->added, file->deleted);
1209 if (options->line_termination) {
1210 fill_print_name(file);
1211 if (!file->is_renamed)
1212 write_name_quoted(file->name, options->file,
1213 options->line_termination);
1214 else {
1215 fputs(file->print_name, options->file);
1216 putc(options->line_termination, options->file);
1218 } else {
1219 if (file->is_renamed) {
1220 putc('\0', options->file);
1221 write_name_quoted(file->from_name, options->file, '\0');
1223 write_name_quoted(file->name, options->file, '\0');
1228 struct dirstat_file {
1229 const char *name;
1230 unsigned long changed;
1233 struct dirstat_dir {
1234 struct dirstat_file *files;
1235 int alloc, nr, percent, cumulative;
1238 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1240 unsigned long this_dir = 0;
1241 unsigned int sources = 0;
1243 while (dir->nr) {
1244 struct dirstat_file *f = dir->files;
1245 int namelen = strlen(f->name);
1246 unsigned long this;
1247 char *slash;
1249 if (namelen < baselen)
1250 break;
1251 if (memcmp(f->name, base, baselen))
1252 break;
1253 slash = strchr(f->name + baselen, '/');
1254 if (slash) {
1255 int newbaselen = slash + 1 - f->name;
1256 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1257 sources++;
1258 } else {
1259 this = f->changed;
1260 dir->files++;
1261 dir->nr--;
1262 sources += 2;
1264 this_dir += this;
1268 * We don't report dirstat's for
1269 * - the top level
1270 * - or cases where everything came from a single directory
1271 * under this directory (sources == 1).
1273 if (baselen && sources != 1) {
1274 int permille = this_dir * 1000 / changed;
1275 if (permille) {
1276 int percent = permille / 10;
1277 if (percent >= dir->percent) {
1278 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1279 if (!dir->cumulative)
1280 return 0;
1284 return this_dir;
1287 static int dirstat_compare(const void *_a, const void *_b)
1289 const struct dirstat_file *a = _a;
1290 const struct dirstat_file *b = _b;
1291 return strcmp(a->name, b->name);
1294 static void show_dirstat(struct diff_options *options)
1296 int i;
1297 unsigned long changed;
1298 struct dirstat_dir dir;
1299 struct diff_queue_struct *q = &diff_queued_diff;
1301 dir.files = NULL;
1302 dir.alloc = 0;
1303 dir.nr = 0;
1304 dir.percent = options->dirstat_percent;
1305 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1307 changed = 0;
1308 for (i = 0; i < q->nr; i++) {
1309 struct diff_filepair *p = q->queue[i];
1310 const char *name;
1311 unsigned long copied, added, damage;
1313 name = p->one->path ? p->one->path : p->two->path;
1315 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1316 diff_populate_filespec(p->one, 0);
1317 diff_populate_filespec(p->two, 0);
1318 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1319 &copied, &added);
1320 diff_free_filespec_data(p->one);
1321 diff_free_filespec_data(p->two);
1322 } else if (DIFF_FILE_VALID(p->one)) {
1323 diff_populate_filespec(p->one, 1);
1324 copied = added = 0;
1325 diff_free_filespec_data(p->one);
1326 } else if (DIFF_FILE_VALID(p->two)) {
1327 diff_populate_filespec(p->two, 1);
1328 copied = 0;
1329 added = p->two->size;
1330 diff_free_filespec_data(p->two);
1331 } else
1332 continue;
1335 * Original minus copied is the removed material,
1336 * added is the new material. They are both damages
1337 * made to the preimage. In --dirstat-by-file mode, count
1338 * damaged files, not damaged lines. This is done by
1339 * counting only a single damaged line per file.
1341 damage = (p->one->size - copied) + added;
1342 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1343 damage = 1;
1345 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1346 dir.files[dir.nr].name = name;
1347 dir.files[dir.nr].changed = damage;
1348 changed += damage;
1349 dir.nr++;
1352 /* This can happen even with many files, if everything was renames */
1353 if (!changed)
1354 return;
1356 /* Show all directories with more than x% of the changes */
1357 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1358 gather_dirstat(options->file, &dir, changed, "", 0);
1361 static void free_diffstat_info(struct diffstat_t *diffstat)
1363 int i;
1364 for (i = 0; i < diffstat->nr; i++) {
1365 struct diffstat_file *f = diffstat->files[i];
1366 if (f->name != f->print_name)
1367 free(f->print_name);
1368 free(f->name);
1369 free(f->from_name);
1370 free(f);
1372 free(diffstat->files);
1375 struct checkdiff_t {
1376 const char *filename;
1377 int lineno;
1378 int conflict_marker_size;
1379 struct diff_options *o;
1380 unsigned ws_rule;
1381 unsigned status;
1384 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1386 char firstchar;
1387 int cnt;
1389 if (len < marker_size + 1)
1390 return 0;
1391 firstchar = line[0];
1392 switch (firstchar) {
1393 case '=': case '>': case '<': case '|':
1394 break;
1395 default:
1396 return 0;
1398 for (cnt = 1; cnt < marker_size; cnt++)
1399 if (line[cnt] != firstchar)
1400 return 0;
1401 /* line[1] thru line[marker_size-1] are same as firstchar */
1402 if (len < marker_size + 1 || !isspace(line[marker_size]))
1403 return 0;
1404 return 1;
1407 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1409 struct checkdiff_t *data = priv;
1410 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1411 int marker_size = data->conflict_marker_size;
1412 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1413 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1414 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1415 char *err;
1417 if (line[0] == '+') {
1418 unsigned bad;
1419 data->lineno++;
1420 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1421 data->status |= 1;
1422 fprintf(data->o->file,
1423 "%s:%d: leftover conflict marker\n",
1424 data->filename, data->lineno);
1426 bad = ws_check(line + 1, len - 1, data->ws_rule);
1427 if (!bad)
1428 return;
1429 data->status |= bad;
1430 err = whitespace_error_string(bad);
1431 fprintf(data->o->file, "%s:%d: %s.\n",
1432 data->filename, data->lineno, err);
1433 free(err);
1434 emit_line(data->o->file, set, reset, line, 1);
1435 ws_check_emit(line + 1, len - 1, data->ws_rule,
1436 data->o->file, set, reset, ws);
1437 } else if (line[0] == ' ') {
1438 data->lineno++;
1439 } else if (line[0] == '@') {
1440 char *plus = strchr(line, '+');
1441 if (plus)
1442 data->lineno = strtol(plus, NULL, 10) - 1;
1443 else
1444 die("invalid diff");
1448 static unsigned char *deflate_it(char *data,
1449 unsigned long size,
1450 unsigned long *result_size)
1452 int bound;
1453 unsigned char *deflated;
1454 z_stream stream;
1456 memset(&stream, 0, sizeof(stream));
1457 deflateInit(&stream, zlib_compression_level);
1458 bound = deflateBound(&stream, size);
1459 deflated = xmalloc(bound);
1460 stream.next_out = deflated;
1461 stream.avail_out = bound;
1463 stream.next_in = (unsigned char *)data;
1464 stream.avail_in = size;
1465 while (deflate(&stream, Z_FINISH) == Z_OK)
1466 ; /* nothing */
1467 deflateEnd(&stream);
1468 *result_size = stream.total_out;
1469 return deflated;
1472 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1474 void *cp;
1475 void *delta;
1476 void *deflated;
1477 void *data;
1478 unsigned long orig_size;
1479 unsigned long delta_size;
1480 unsigned long deflate_size;
1481 unsigned long data_size;
1483 /* We could do deflated delta, or we could do just deflated two,
1484 * whichever is smaller.
1486 delta = NULL;
1487 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1488 if (one->size && two->size) {
1489 delta = diff_delta(one->ptr, one->size,
1490 two->ptr, two->size,
1491 &delta_size, deflate_size);
1492 if (delta) {
1493 void *to_free = delta;
1494 orig_size = delta_size;
1495 delta = deflate_it(delta, delta_size, &delta_size);
1496 free(to_free);
1500 if (delta && delta_size < deflate_size) {
1501 fprintf(file, "delta %lu\n", orig_size);
1502 free(deflated);
1503 data = delta;
1504 data_size = delta_size;
1506 else {
1507 fprintf(file, "literal %lu\n", two->size);
1508 free(delta);
1509 data = deflated;
1510 data_size = deflate_size;
1513 /* emit data encoded in base85 */
1514 cp = data;
1515 while (data_size) {
1516 int bytes = (52 < data_size) ? 52 : data_size;
1517 char line[70];
1518 data_size -= bytes;
1519 if (bytes <= 26)
1520 line[0] = bytes + 'A' - 1;
1521 else
1522 line[0] = bytes - 26 + 'a' - 1;
1523 encode_85(line + 1, cp, bytes);
1524 cp = (char *) cp + bytes;
1525 fputs(line, file);
1526 fputc('\n', file);
1528 fprintf(file, "\n");
1529 free(data);
1532 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1534 fprintf(file, "GIT binary patch\n");
1535 emit_binary_diff_body(file, one, two);
1536 emit_binary_diff_body(file, two, one);
1539 static void diff_filespec_load_driver(struct diff_filespec *one)
1541 if (!one->driver)
1542 one->driver = userdiff_find_by_path(one->path);
1543 if (!one->driver)
1544 one->driver = userdiff_find_by_name("default");
1547 int diff_filespec_is_binary(struct diff_filespec *one)
1549 if (one->is_binary == -1) {
1550 diff_filespec_load_driver(one);
1551 if (one->driver->binary != -1)
1552 one->is_binary = one->driver->binary;
1553 else {
1554 if (!one->data && DIFF_FILE_VALID(one))
1555 diff_populate_filespec(one, 0);
1556 if (one->data)
1557 one->is_binary = buffer_is_binary(one->data,
1558 one->size);
1559 if (one->is_binary == -1)
1560 one->is_binary = 0;
1563 return one->is_binary;
1566 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1568 diff_filespec_load_driver(one);
1569 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1572 static const char *userdiff_word_regex(struct diff_filespec *one)
1574 diff_filespec_load_driver(one);
1575 return one->driver->word_regex;
1578 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1580 if (!options->a_prefix)
1581 options->a_prefix = a;
1582 if (!options->b_prefix)
1583 options->b_prefix = b;
1586 static const char *get_textconv(struct diff_filespec *one)
1588 if (!DIFF_FILE_VALID(one))
1589 return NULL;
1590 if (!S_ISREG(one->mode))
1591 return NULL;
1592 diff_filespec_load_driver(one);
1593 return one->driver->textconv;
1596 static void builtin_diff(const char *name_a,
1597 const char *name_b,
1598 struct diff_filespec *one,
1599 struct diff_filespec *two,
1600 const char *xfrm_msg,
1601 struct diff_options *o,
1602 int complete_rewrite)
1604 mmfile_t mf1, mf2;
1605 const char *lbl[2];
1606 char *a_one, *b_two;
1607 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1608 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1609 const char *a_prefix, *b_prefix;
1610 const char *textconv_one = NULL, *textconv_two = NULL;
1611 struct strbuf header = STRBUF_INIT;
1613 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1614 (!one->mode || S_ISGITLINK(one->mode)) &&
1615 (!two->mode || S_ISGITLINK(two->mode))) {
1616 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1617 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1618 show_submodule_summary(o->file, one ? one->path : two->path,
1619 one->sha1, two->sha1, two->dirty_submodule,
1620 del, add, reset);
1621 return;
1624 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1625 textconv_one = get_textconv(one);
1626 textconv_two = get_textconv(two);
1629 diff_set_mnemonic_prefix(o, "a/", "b/");
1630 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1631 a_prefix = o->b_prefix;
1632 b_prefix = o->a_prefix;
1633 } else {
1634 a_prefix = o->a_prefix;
1635 b_prefix = o->b_prefix;
1638 /* Never use a non-valid filename anywhere if at all possible */
1639 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1640 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1642 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1643 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1644 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1645 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1646 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1647 if (lbl[0][0] == '/') {
1648 /* /dev/null */
1649 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1650 if (xfrm_msg && xfrm_msg[0])
1651 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1653 else if (lbl[1][0] == '/') {
1654 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1655 if (xfrm_msg && xfrm_msg[0])
1656 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1658 else {
1659 if (one->mode != two->mode) {
1660 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1661 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1663 if (xfrm_msg && xfrm_msg[0])
1664 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1667 * we do not run diff between different kind
1668 * of objects.
1670 if ((one->mode ^ two->mode) & S_IFMT)
1671 goto free_ab_and_return;
1672 if (complete_rewrite &&
1673 (textconv_one || !diff_filespec_is_binary(one)) &&
1674 (textconv_two || !diff_filespec_is_binary(two))) {
1675 fprintf(o->file, "%s", header.buf);
1676 strbuf_reset(&header);
1677 emit_rewrite_diff(name_a, name_b, one, two,
1678 textconv_one, textconv_two, o);
1679 o->found_changes = 1;
1680 goto free_ab_and_return;
1684 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1685 die("unable to read files to diff");
1687 if (!DIFF_OPT_TST(o, TEXT) &&
1688 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1689 (diff_filespec_is_binary(two) && !textconv_two) )) {
1690 /* Quite common confusing case */
1691 if (mf1.size == mf2.size &&
1692 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1693 goto free_ab_and_return;
1694 fprintf(o->file, "%s", header.buf);
1695 strbuf_reset(&header);
1696 if (DIFF_OPT_TST(o, BINARY))
1697 emit_binary_diff(o->file, &mf1, &mf2);
1698 else
1699 fprintf(o->file, "Binary files %s and %s differ\n",
1700 lbl[0], lbl[1]);
1701 o->found_changes = 1;
1703 else {
1704 /* Crazy xdl interfaces.. */
1705 const char *diffopts = getenv("GIT_DIFF_OPTS");
1706 xpparam_t xpp;
1707 xdemitconf_t xecfg;
1708 xdemitcb_t ecb;
1709 struct emit_callback ecbdata;
1710 const struct userdiff_funcname *pe;
1712 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1713 fprintf(o->file, "%s", header.buf);
1714 strbuf_reset(&header);
1717 if (textconv_one) {
1718 size_t size;
1719 mf1.ptr = run_textconv(textconv_one, one, &size);
1720 if (!mf1.ptr)
1721 die("unable to read files to diff");
1722 mf1.size = size;
1724 if (textconv_two) {
1725 size_t size;
1726 mf2.ptr = run_textconv(textconv_two, two, &size);
1727 if (!mf2.ptr)
1728 die("unable to read files to diff");
1729 mf2.size = size;
1732 pe = diff_funcname_pattern(one);
1733 if (!pe)
1734 pe = diff_funcname_pattern(two);
1736 memset(&xpp, 0, sizeof(xpp));
1737 memset(&xecfg, 0, sizeof(xecfg));
1738 memset(&ecbdata, 0, sizeof(ecbdata));
1739 ecbdata.label_path = lbl;
1740 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1741 ecbdata.found_changesp = &o->found_changes;
1742 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1743 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1744 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1745 ecbdata.file = o->file;
1746 ecbdata.header = header.len ? &header : NULL;
1747 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1748 xecfg.ctxlen = o->context;
1749 xecfg.interhunkctxlen = o->interhunkcontext;
1750 xecfg.flags = XDL_EMIT_FUNCNAMES;
1751 if (pe)
1752 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1753 if (!diffopts)
1755 else if (!prefixcmp(diffopts, "--unified="))
1756 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1757 else if (!prefixcmp(diffopts, "-u"))
1758 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1759 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1760 ecbdata.diff_words =
1761 xcalloc(1, sizeof(struct diff_words_data));
1762 ecbdata.diff_words->file = o->file;
1763 if (!o->word_regex)
1764 o->word_regex = userdiff_word_regex(one);
1765 if (!o->word_regex)
1766 o->word_regex = userdiff_word_regex(two);
1767 if (!o->word_regex)
1768 o->word_regex = diff_word_regex_cfg;
1769 if (o->word_regex) {
1770 ecbdata.diff_words->word_regex = (regex_t *)
1771 xmalloc(sizeof(regex_t));
1772 if (regcomp(ecbdata.diff_words->word_regex,
1773 o->word_regex,
1774 REG_EXTENDED | REG_NEWLINE))
1775 die ("Invalid regular expression: %s",
1776 o->word_regex);
1779 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1780 &xpp, &xecfg, &ecb);
1781 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1782 free_diff_words_data(&ecbdata);
1783 if (textconv_one)
1784 free(mf1.ptr);
1785 if (textconv_two)
1786 free(mf2.ptr);
1787 xdiff_clear_find_func(&xecfg);
1790 free_ab_and_return:
1791 strbuf_release(&header);
1792 diff_free_filespec_data(one);
1793 diff_free_filespec_data(two);
1794 free(a_one);
1795 free(b_two);
1796 return;
1799 static void builtin_diffstat(const char *name_a, const char *name_b,
1800 struct diff_filespec *one,
1801 struct diff_filespec *two,
1802 struct diffstat_t *diffstat,
1803 struct diff_options *o,
1804 int complete_rewrite)
1806 mmfile_t mf1, mf2;
1807 struct diffstat_file *data;
1809 data = diffstat_add(diffstat, name_a, name_b);
1811 if (!one || !two) {
1812 data->is_unmerged = 1;
1813 return;
1815 if (complete_rewrite) {
1816 diff_populate_filespec(one, 0);
1817 diff_populate_filespec(two, 0);
1818 data->deleted = count_lines(one->data, one->size);
1819 data->added = count_lines(two->data, two->size);
1820 goto free_and_return;
1822 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1823 die("unable to read files to diff");
1825 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1826 data->is_binary = 1;
1827 data->added = mf2.size;
1828 data->deleted = mf1.size;
1829 } else {
1830 /* Crazy xdl interfaces.. */
1831 xpparam_t xpp;
1832 xdemitconf_t xecfg;
1833 xdemitcb_t ecb;
1835 memset(&xpp, 0, sizeof(xpp));
1836 memset(&xecfg, 0, sizeof(xecfg));
1837 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1838 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1839 &xpp, &xecfg, &ecb);
1842 free_and_return:
1843 diff_free_filespec_data(one);
1844 diff_free_filespec_data(two);
1847 static void builtin_checkdiff(const char *name_a, const char *name_b,
1848 const char *attr_path,
1849 struct diff_filespec *one,
1850 struct diff_filespec *two,
1851 struct diff_options *o)
1853 mmfile_t mf1, mf2;
1854 struct checkdiff_t data;
1856 if (!two)
1857 return;
1859 memset(&data, 0, sizeof(data));
1860 data.filename = name_b ? name_b : name_a;
1861 data.lineno = 0;
1862 data.o = o;
1863 data.ws_rule = whitespace_rule(attr_path);
1864 data.conflict_marker_size = ll_merge_marker_size(attr_path);
1866 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1867 die("unable to read files to diff");
1870 * All the other codepaths check both sides, but not checking
1871 * the "old" side here is deliberate. We are checking the newly
1872 * introduced changes, and as long as the "new" side is text, we
1873 * can and should check what it introduces.
1875 if (diff_filespec_is_binary(two))
1876 goto free_and_return;
1877 else {
1878 /* Crazy xdl interfaces.. */
1879 xpparam_t xpp;
1880 xdemitconf_t xecfg;
1881 xdemitcb_t ecb;
1883 memset(&xpp, 0, sizeof(xpp));
1884 memset(&xecfg, 0, sizeof(xecfg));
1885 xecfg.ctxlen = 1; /* at least one context line */
1886 xpp.flags = XDF_NEED_MINIMAL;
1887 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1888 &xpp, &xecfg, &ecb);
1890 if (data.ws_rule & WS_BLANK_AT_EOF) {
1891 struct emit_callback ecbdata;
1892 int blank_at_eof;
1894 ecbdata.ws_rule = data.ws_rule;
1895 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1896 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1898 if (blank_at_eof) {
1899 static char *err;
1900 if (!err)
1901 err = whitespace_error_string(WS_BLANK_AT_EOF);
1902 fprintf(o->file, "%s:%d: %s.\n",
1903 data.filename, blank_at_eof, err);
1904 data.status = 1; /* report errors */
1908 free_and_return:
1909 diff_free_filespec_data(one);
1910 diff_free_filespec_data(two);
1911 if (data.status)
1912 DIFF_OPT_SET(o, CHECK_FAILED);
1915 struct diff_filespec *alloc_filespec(const char *path)
1917 int namelen = strlen(path);
1918 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1920 memset(spec, 0, sizeof(*spec));
1921 spec->path = (char *)(spec + 1);
1922 memcpy(spec->path, path, namelen+1);
1923 spec->count = 1;
1924 spec->is_binary = -1;
1925 return spec;
1928 void free_filespec(struct diff_filespec *spec)
1930 if (!--spec->count) {
1931 diff_free_filespec_data(spec);
1932 free(spec);
1936 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1937 unsigned short mode)
1939 if (mode) {
1940 spec->mode = canon_mode(mode);
1941 hashcpy(spec->sha1, sha1);
1942 spec->sha1_valid = !is_null_sha1(sha1);
1947 * Given a name and sha1 pair, if the index tells us the file in
1948 * the work tree has that object contents, return true, so that
1949 * prepare_temp_file() does not have to inflate and extract.
1951 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1953 struct cache_entry *ce;
1954 struct stat st;
1955 int pos, len;
1958 * We do not read the cache ourselves here, because the
1959 * benchmark with my previous version that always reads cache
1960 * shows that it makes things worse for diff-tree comparing
1961 * two linux-2.6 kernel trees in an already checked out work
1962 * tree. This is because most diff-tree comparisons deal with
1963 * only a small number of files, while reading the cache is
1964 * expensive for a large project, and its cost outweighs the
1965 * savings we get by not inflating the object to a temporary
1966 * file. Practically, this code only helps when we are used
1967 * by diff-cache --cached, which does read the cache before
1968 * calling us.
1970 if (!active_cache)
1971 return 0;
1973 /* We want to avoid the working directory if our caller
1974 * doesn't need the data in a normal file, this system
1975 * is rather slow with its stat/open/mmap/close syscalls,
1976 * and the object is contained in a pack file. The pack
1977 * is probably already open and will be faster to obtain
1978 * the data through than the working directory. Loose
1979 * objects however would tend to be slower as they need
1980 * to be individually opened and inflated.
1982 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1983 return 0;
1985 len = strlen(name);
1986 pos = cache_name_pos(name, len);
1987 if (pos < 0)
1988 return 0;
1989 ce = active_cache[pos];
1992 * This is not the sha1 we are looking for, or
1993 * unreusable because it is not a regular file.
1995 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1996 return 0;
1999 * If ce is marked as "assume unchanged", there is no
2000 * guarantee that work tree matches what we are looking for.
2002 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2003 return 0;
2006 * If ce matches the file in the work tree, we can reuse it.
2008 if (ce_uptodate(ce) ||
2009 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2010 return 1;
2012 return 0;
2015 static int populate_from_stdin(struct diff_filespec *s)
2017 struct strbuf buf = STRBUF_INIT;
2018 size_t size = 0;
2020 if (strbuf_read(&buf, 0, 0) < 0)
2021 return error("error while reading from stdin %s",
2022 strerror(errno));
2024 s->should_munmap = 0;
2025 s->data = strbuf_detach(&buf, &size);
2026 s->size = size;
2027 s->should_free = 1;
2028 return 0;
2031 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2033 int len;
2034 char *data = xmalloc(100), *dirty = "";
2036 /* Are we looking at the work tree? */
2037 if (s->dirty_submodule)
2038 dirty = "-dirty";
2040 len = snprintf(data, 100,
2041 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2042 s->data = data;
2043 s->size = len;
2044 s->should_free = 1;
2045 if (size_only) {
2046 s->data = NULL;
2047 free(data);
2049 return 0;
2053 * While doing rename detection and pickaxe operation, we may need to
2054 * grab the data for the blob (or file) for our own in-core comparison.
2055 * diff_filespec has data and size fields for this purpose.
2057 int diff_populate_filespec(struct diff_filespec *s, int size_only)
2059 int err = 0;
2060 if (!DIFF_FILE_VALID(s))
2061 die("internal error: asking to populate invalid file.");
2062 if (S_ISDIR(s->mode))
2063 return -1;
2065 if (s->data)
2066 return 0;
2068 if (size_only && 0 < s->size)
2069 return 0;
2071 if (S_ISGITLINK(s->mode))
2072 return diff_populate_gitlink(s, size_only);
2074 if (!s->sha1_valid ||
2075 reuse_worktree_file(s->path, s->sha1, 0)) {
2076 struct strbuf buf = STRBUF_INIT;
2077 struct stat st;
2078 int fd;
2080 if (!strcmp(s->path, "-"))
2081 return populate_from_stdin(s);
2083 if (lstat(s->path, &st) < 0) {
2084 if (errno == ENOENT) {
2085 err_empty:
2086 err = -1;
2087 empty:
2088 s->data = (char *)"";
2089 s->size = 0;
2090 return err;
2093 s->size = xsize_t(st.st_size);
2094 if (!s->size)
2095 goto empty;
2096 if (S_ISLNK(st.st_mode)) {
2097 struct strbuf sb = STRBUF_INIT;
2099 if (strbuf_readlink(&sb, s->path, s->size))
2100 goto err_empty;
2101 s->size = sb.len;
2102 s->data = strbuf_detach(&sb, NULL);
2103 s->should_free = 1;
2104 return 0;
2106 if (size_only)
2107 return 0;
2108 fd = open(s->path, O_RDONLY);
2109 if (fd < 0)
2110 goto err_empty;
2111 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2112 close(fd);
2113 s->should_munmap = 1;
2116 * Convert from working tree format to canonical git format
2118 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2119 size_t size = 0;
2120 munmap(s->data, s->size);
2121 s->should_munmap = 0;
2122 s->data = strbuf_detach(&buf, &size);
2123 s->size = size;
2124 s->should_free = 1;
2127 else {
2128 enum object_type type;
2129 if (size_only)
2130 type = sha1_object_info(s->sha1, &s->size);
2131 else {
2132 s->data = read_sha1_file(s->sha1, &type, &s->size);
2133 s->should_free = 1;
2136 return 0;
2139 void diff_free_filespec_blob(struct diff_filespec *s)
2141 if (s->should_free)
2142 free(s->data);
2143 else if (s->should_munmap)
2144 munmap(s->data, s->size);
2146 if (s->should_free || s->should_munmap) {
2147 s->should_free = s->should_munmap = 0;
2148 s->data = NULL;
2152 void diff_free_filespec_data(struct diff_filespec *s)
2154 diff_free_filespec_blob(s);
2155 free(s->cnt_data);
2156 s->cnt_data = NULL;
2159 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2160 void *blob,
2161 unsigned long size,
2162 const unsigned char *sha1,
2163 int mode)
2165 int fd;
2166 struct strbuf buf = STRBUF_INIT;
2167 struct strbuf template = STRBUF_INIT;
2168 char *path_dup = xstrdup(path);
2169 const char *base = basename(path_dup);
2171 /* Generate "XXXXXX_basename.ext" */
2172 strbuf_addstr(&template, "XXXXXX_");
2173 strbuf_addstr(&template, base);
2175 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2176 strlen(base) + 1);
2177 if (fd < 0)
2178 die_errno("unable to create temp-file");
2179 if (convert_to_working_tree(path,
2180 (const char *)blob, (size_t)size, &buf)) {
2181 blob = buf.buf;
2182 size = buf.len;
2184 if (write_in_full(fd, blob, size) != size)
2185 die_errno("unable to write temp-file");
2186 close(fd);
2187 temp->name = temp->tmp_path;
2188 strcpy(temp->hex, sha1_to_hex(sha1));
2189 temp->hex[40] = 0;
2190 sprintf(temp->mode, "%06o", mode);
2191 strbuf_release(&buf);
2192 strbuf_release(&template);
2193 free(path_dup);
2196 static struct diff_tempfile *prepare_temp_file(const char *name,
2197 struct diff_filespec *one)
2199 struct diff_tempfile *temp = claim_diff_tempfile();
2201 if (!DIFF_FILE_VALID(one)) {
2202 not_a_valid_file:
2203 /* A '-' entry produces this for file-2, and
2204 * a '+' entry produces this for file-1.
2206 temp->name = "/dev/null";
2207 strcpy(temp->hex, ".");
2208 strcpy(temp->mode, ".");
2209 return temp;
2212 if (!remove_tempfile_installed) {
2213 atexit(remove_tempfile);
2214 sigchain_push_common(remove_tempfile_on_signal);
2215 remove_tempfile_installed = 1;
2218 if (!one->sha1_valid ||
2219 reuse_worktree_file(name, one->sha1, 1)) {
2220 struct stat st;
2221 if (lstat(name, &st) < 0) {
2222 if (errno == ENOENT)
2223 goto not_a_valid_file;
2224 die_errno("stat(%s)", name);
2226 if (S_ISLNK(st.st_mode)) {
2227 struct strbuf sb = STRBUF_INIT;
2228 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2229 die_errno("readlink(%s)", name);
2230 prep_temp_blob(name, temp, sb.buf, sb.len,
2231 (one->sha1_valid ?
2232 one->sha1 : null_sha1),
2233 (one->sha1_valid ?
2234 one->mode : S_IFLNK));
2235 strbuf_release(&sb);
2237 else {
2238 /* we can borrow from the file in the work tree */
2239 temp->name = name;
2240 if (!one->sha1_valid)
2241 strcpy(temp->hex, sha1_to_hex(null_sha1));
2242 else
2243 strcpy(temp->hex, sha1_to_hex(one->sha1));
2244 /* Even though we may sometimes borrow the
2245 * contents from the work tree, we always want
2246 * one->mode. mode is trustworthy even when
2247 * !(one->sha1_valid), as long as
2248 * DIFF_FILE_VALID(one).
2250 sprintf(temp->mode, "%06o", one->mode);
2252 return temp;
2254 else {
2255 if (diff_populate_filespec(one, 0))
2256 die("cannot read data blob for %s", one->path);
2257 prep_temp_blob(name, temp, one->data, one->size,
2258 one->sha1, one->mode);
2260 return temp;
2263 /* An external diff command takes:
2265 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2266 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2269 static void run_external_diff(const char *pgm,
2270 const char *name,
2271 const char *other,
2272 struct diff_filespec *one,
2273 struct diff_filespec *two,
2274 const char *xfrm_msg,
2275 int complete_rewrite)
2277 const char *spawn_arg[10];
2278 int retval;
2279 const char **arg = &spawn_arg[0];
2281 if (one && two) {
2282 struct diff_tempfile *temp_one, *temp_two;
2283 const char *othername = (other ? other : name);
2284 temp_one = prepare_temp_file(name, one);
2285 temp_two = prepare_temp_file(othername, two);
2286 *arg++ = pgm;
2287 *arg++ = name;
2288 *arg++ = temp_one->name;
2289 *arg++ = temp_one->hex;
2290 *arg++ = temp_one->mode;
2291 *arg++ = temp_two->name;
2292 *arg++ = temp_two->hex;
2293 *arg++ = temp_two->mode;
2294 if (other) {
2295 *arg++ = other;
2296 *arg++ = xfrm_msg;
2298 } else {
2299 *arg++ = pgm;
2300 *arg++ = name;
2302 *arg = NULL;
2303 fflush(NULL);
2304 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2305 remove_tempfile();
2306 if (retval) {
2307 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2308 exit(1);
2312 static int similarity_index(struct diff_filepair *p)
2314 return p->score * 100 / MAX_SCORE;
2317 static void fill_metainfo(struct strbuf *msg,
2318 const char *name,
2319 const char *other,
2320 struct diff_filespec *one,
2321 struct diff_filespec *two,
2322 struct diff_options *o,
2323 struct diff_filepair *p)
2325 strbuf_init(msg, PATH_MAX * 2 + 300);
2326 switch (p->status) {
2327 case DIFF_STATUS_COPIED:
2328 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2329 strbuf_addstr(msg, "\ncopy from ");
2330 quote_c_style(name, msg, NULL, 0);
2331 strbuf_addstr(msg, "\ncopy to ");
2332 quote_c_style(other, msg, NULL, 0);
2333 strbuf_addch(msg, '\n');
2334 break;
2335 case DIFF_STATUS_RENAMED:
2336 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2337 strbuf_addstr(msg, "\nrename from ");
2338 quote_c_style(name, msg, NULL, 0);
2339 strbuf_addstr(msg, "\nrename to ");
2340 quote_c_style(other, msg, NULL, 0);
2341 strbuf_addch(msg, '\n');
2342 break;
2343 case DIFF_STATUS_MODIFIED:
2344 if (p->score) {
2345 strbuf_addf(msg, "dissimilarity index %d%%\n",
2346 similarity_index(p));
2347 break;
2349 /* fallthru */
2350 default:
2351 /* nothing */
2354 if (one && two && hashcmp(one->sha1, two->sha1)) {
2355 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2357 if (DIFF_OPT_TST(o, BINARY)) {
2358 mmfile_t mf;
2359 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2360 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2361 abbrev = 40;
2363 strbuf_addf(msg, "index %.*s..%.*s",
2364 abbrev, sha1_to_hex(one->sha1),
2365 abbrev, sha1_to_hex(two->sha1));
2366 if (one->mode == two->mode)
2367 strbuf_addf(msg, " %06o", one->mode);
2368 strbuf_addch(msg, '\n');
2370 if (msg->len)
2371 strbuf_setlen(msg, msg->len - 1);
2374 static void run_diff_cmd(const char *pgm,
2375 const char *name,
2376 const char *other,
2377 const char *attr_path,
2378 struct diff_filespec *one,
2379 struct diff_filespec *two,
2380 struct strbuf *msg,
2381 struct diff_options *o,
2382 struct diff_filepair *p)
2384 const char *xfrm_msg = NULL;
2385 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2387 if (msg) {
2388 fill_metainfo(msg, name, other, one, two, o, p);
2389 xfrm_msg = msg->len ? msg->buf : NULL;
2392 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2393 pgm = NULL;
2394 else {
2395 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2396 if (drv && drv->external)
2397 pgm = drv->external;
2400 if (pgm) {
2401 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2402 complete_rewrite);
2403 return;
2405 if (one && two)
2406 builtin_diff(name, other ? other : name,
2407 one, two, xfrm_msg, o, complete_rewrite);
2408 else
2409 fprintf(o->file, "* Unmerged path %s\n", name);
2412 static void diff_fill_sha1_info(struct diff_filespec *one)
2414 if (DIFF_FILE_VALID(one)) {
2415 if (!one->sha1_valid) {
2416 struct stat st;
2417 if (!strcmp(one->path, "-")) {
2418 hashcpy(one->sha1, null_sha1);
2419 return;
2421 if (lstat(one->path, &st) < 0)
2422 die_errno("stat '%s'", one->path);
2423 if (index_path(one->sha1, one->path, &st, 0))
2424 die("cannot hash %s", one->path);
2427 else
2428 hashclr(one->sha1);
2431 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2433 /* Strip the prefix but do not molest /dev/null and absolute paths */
2434 if (*namep && **namep != '/')
2435 *namep += prefix_length;
2436 if (*otherp && **otherp != '/')
2437 *otherp += prefix_length;
2440 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2442 const char *pgm = external_diff();
2443 struct strbuf msg;
2444 struct diff_filespec *one = p->one;
2445 struct diff_filespec *two = p->two;
2446 const char *name;
2447 const char *other;
2448 const char *attr_path;
2450 name = p->one->path;
2451 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2452 attr_path = name;
2453 if (o->prefix_length)
2454 strip_prefix(o->prefix_length, &name, &other);
2456 if (DIFF_PAIR_UNMERGED(p)) {
2457 run_diff_cmd(pgm, name, NULL, attr_path,
2458 NULL, NULL, NULL, o, p);
2459 return;
2462 diff_fill_sha1_info(one);
2463 diff_fill_sha1_info(two);
2465 if (!pgm &&
2466 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2467 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2469 * a filepair that changes between file and symlink
2470 * needs to be split into deletion and creation.
2472 struct diff_filespec *null = alloc_filespec(two->path);
2473 run_diff_cmd(NULL, name, other, attr_path,
2474 one, null, &msg, o, p);
2475 free(null);
2476 strbuf_release(&msg);
2478 null = alloc_filespec(one->path);
2479 run_diff_cmd(NULL, name, other, attr_path,
2480 null, two, &msg, o, p);
2481 free(null);
2483 else
2484 run_diff_cmd(pgm, name, other, attr_path,
2485 one, two, &msg, o, p);
2487 strbuf_release(&msg);
2490 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2491 struct diffstat_t *diffstat)
2493 const char *name;
2494 const char *other;
2495 int complete_rewrite = 0;
2497 if (DIFF_PAIR_UNMERGED(p)) {
2498 /* unmerged */
2499 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2500 return;
2503 name = p->one->path;
2504 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2506 if (o->prefix_length)
2507 strip_prefix(o->prefix_length, &name, &other);
2509 diff_fill_sha1_info(p->one);
2510 diff_fill_sha1_info(p->two);
2512 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2513 complete_rewrite = 1;
2514 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2517 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2519 const char *name;
2520 const char *other;
2521 const char *attr_path;
2523 if (DIFF_PAIR_UNMERGED(p)) {
2524 /* unmerged */
2525 return;
2528 name = p->one->path;
2529 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2530 attr_path = other ? other : name;
2532 if (o->prefix_length)
2533 strip_prefix(o->prefix_length, &name, &other);
2535 diff_fill_sha1_info(p->one);
2536 diff_fill_sha1_info(p->two);
2538 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2541 void diff_setup(struct diff_options *options)
2543 memset(options, 0, sizeof(*options));
2545 options->file = stdout;
2547 options->line_termination = '\n';
2548 options->break_opt = -1;
2549 options->rename_limit = -1;
2550 options->dirstat_percent = 3;
2551 options->context = 3;
2553 options->change = diff_change;
2554 options->add_remove = diff_addremove;
2555 if (diff_use_color_default > 0)
2556 DIFF_OPT_SET(options, COLOR_DIFF);
2557 options->detect_rename = diff_detect_rename_default;
2559 if (!diff_mnemonic_prefix) {
2560 options->a_prefix = "a/";
2561 options->b_prefix = "b/";
2565 int diff_setup_done(struct diff_options *options)
2567 int count = 0;
2569 if (options->output_format & DIFF_FORMAT_NAME)
2570 count++;
2571 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2572 count++;
2573 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2574 count++;
2575 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2576 count++;
2577 if (count > 1)
2578 die("--name-only, --name-status, --check and -s are mutually exclusive");
2581 * Most of the time we can say "there are changes"
2582 * only by checking if there are changed paths, but
2583 * --ignore-whitespace* options force us to look
2584 * inside contents.
2587 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2588 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2589 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2590 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2591 else
2592 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2594 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2595 options->detect_rename = DIFF_DETECT_COPY;
2597 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2598 options->prefix = NULL;
2599 if (options->prefix)
2600 options->prefix_length = strlen(options->prefix);
2601 else
2602 options->prefix_length = 0;
2604 if (options->output_format & (DIFF_FORMAT_NAME |
2605 DIFF_FORMAT_NAME_STATUS |
2606 DIFF_FORMAT_CHECKDIFF |
2607 DIFF_FORMAT_NO_OUTPUT))
2608 options->output_format &= ~(DIFF_FORMAT_RAW |
2609 DIFF_FORMAT_NUMSTAT |
2610 DIFF_FORMAT_DIFFSTAT |
2611 DIFF_FORMAT_SHORTSTAT |
2612 DIFF_FORMAT_DIRSTAT |
2613 DIFF_FORMAT_SUMMARY |
2614 DIFF_FORMAT_PATCH);
2617 * These cases always need recursive; we do not drop caller-supplied
2618 * recursive bits for other formats here.
2620 if (options->output_format & (DIFF_FORMAT_PATCH |
2621 DIFF_FORMAT_NUMSTAT |
2622 DIFF_FORMAT_DIFFSTAT |
2623 DIFF_FORMAT_SHORTSTAT |
2624 DIFF_FORMAT_DIRSTAT |
2625 DIFF_FORMAT_SUMMARY |
2626 DIFF_FORMAT_CHECKDIFF))
2627 DIFF_OPT_SET(options, RECURSIVE);
2629 * Also pickaxe would not work very well if you do not say recursive
2631 if (options->pickaxe)
2632 DIFF_OPT_SET(options, RECURSIVE);
2634 * When patches are generated, submodules diffed against the work tree
2635 * must be checked for dirtiness too so it can be shown in the output
2637 if (options->output_format & DIFF_FORMAT_PATCH)
2638 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2640 if (options->detect_rename && options->rename_limit < 0)
2641 options->rename_limit = diff_rename_limit_default;
2642 if (options->setup & DIFF_SETUP_USE_CACHE) {
2643 if (!active_cache)
2644 /* read-cache does not die even when it fails
2645 * so it is safe for us to do this here. Also
2646 * it does not smudge active_cache or active_nr
2647 * when it fails, so we do not have to worry about
2648 * cleaning it up ourselves either.
2650 read_cache();
2652 if (options->abbrev <= 0 || 40 < options->abbrev)
2653 options->abbrev = 40; /* full */
2656 * It does not make sense to show the first hit we happened
2657 * to have found. It does not make sense not to return with
2658 * exit code in such a case either.
2660 if (DIFF_OPT_TST(options, QUICK)) {
2661 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2662 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2665 return 0;
2668 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2670 char c, *eq;
2671 int len;
2673 if (*arg != '-')
2674 return 0;
2675 c = *++arg;
2676 if (!c)
2677 return 0;
2678 if (c == arg_short) {
2679 c = *++arg;
2680 if (!c)
2681 return 1;
2682 if (val && isdigit(c)) {
2683 char *end;
2684 int n = strtoul(arg, &end, 10);
2685 if (*end)
2686 return 0;
2687 *val = n;
2688 return 1;
2690 return 0;
2692 if (c != '-')
2693 return 0;
2694 arg++;
2695 eq = strchr(arg, '=');
2696 if (eq)
2697 len = eq - arg;
2698 else
2699 len = strlen(arg);
2700 if (!len || strncmp(arg, arg_long, len))
2701 return 0;
2702 if (eq) {
2703 int n;
2704 char *end;
2705 if (!isdigit(*++eq))
2706 return 0;
2707 n = strtoul(eq, &end, 10);
2708 if (*end)
2709 return 0;
2710 *val = n;
2712 return 1;
2715 static int diff_scoreopt_parse(const char *opt);
2717 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2719 const char *arg = av[0];
2721 /* Output format options */
2722 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2723 options->output_format |= DIFF_FORMAT_PATCH;
2724 else if (opt_arg(arg, 'U', "unified", &options->context))
2725 options->output_format |= DIFF_FORMAT_PATCH;
2726 else if (!strcmp(arg, "--raw"))
2727 options->output_format |= DIFF_FORMAT_RAW;
2728 else if (!strcmp(arg, "--patch-with-raw"))
2729 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2730 else if (!strcmp(arg, "--numstat"))
2731 options->output_format |= DIFF_FORMAT_NUMSTAT;
2732 else if (!strcmp(arg, "--shortstat"))
2733 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2734 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2735 options->output_format |= DIFF_FORMAT_DIRSTAT;
2736 else if (!strcmp(arg, "--cumulative")) {
2737 options->output_format |= DIFF_FORMAT_DIRSTAT;
2738 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2739 } else if (opt_arg(arg, 0, "dirstat-by-file",
2740 &options->dirstat_percent)) {
2741 options->output_format |= DIFF_FORMAT_DIRSTAT;
2742 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2744 else if (!strcmp(arg, "--check"))
2745 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2746 else if (!strcmp(arg, "--summary"))
2747 options->output_format |= DIFF_FORMAT_SUMMARY;
2748 else if (!strcmp(arg, "--patch-with-stat"))
2749 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2750 else if (!strcmp(arg, "--name-only"))
2751 options->output_format |= DIFF_FORMAT_NAME;
2752 else if (!strcmp(arg, "--name-status"))
2753 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2754 else if (!strcmp(arg, "-s"))
2755 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2756 else if (!prefixcmp(arg, "--stat")) {
2757 char *end;
2758 int width = options->stat_width;
2759 int name_width = options->stat_name_width;
2760 arg += 6;
2761 end = (char *)arg;
2763 switch (*arg) {
2764 case '-':
2765 if (!prefixcmp(arg, "-width="))
2766 width = strtoul(arg + 7, &end, 10);
2767 else if (!prefixcmp(arg, "-name-width="))
2768 name_width = strtoul(arg + 12, &end, 10);
2769 break;
2770 case '=':
2771 width = strtoul(arg+1, &end, 10);
2772 if (*end == ',')
2773 name_width = strtoul(end+1, &end, 10);
2776 /* Important! This checks all the error cases! */
2777 if (*end)
2778 return 0;
2779 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2780 options->stat_name_width = name_width;
2781 options->stat_width = width;
2784 /* renames options */
2785 else if (!prefixcmp(arg, "-B")) {
2786 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2787 return -1;
2789 else if (!prefixcmp(arg, "-M")) {
2790 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2791 return -1;
2792 options->detect_rename = DIFF_DETECT_RENAME;
2794 else if (!prefixcmp(arg, "-C")) {
2795 if (options->detect_rename == DIFF_DETECT_COPY)
2796 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2797 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2798 return -1;
2799 options->detect_rename = DIFF_DETECT_COPY;
2801 else if (!strcmp(arg, "--no-renames"))
2802 options->detect_rename = 0;
2803 else if (!strcmp(arg, "--relative"))
2804 DIFF_OPT_SET(options, RELATIVE_NAME);
2805 else if (!prefixcmp(arg, "--relative=")) {
2806 DIFF_OPT_SET(options, RELATIVE_NAME);
2807 options->prefix = arg + 11;
2810 /* xdiff options */
2811 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2812 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2813 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2814 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2815 else if (!strcmp(arg, "--ignore-space-at-eol"))
2816 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2817 else if (!strcmp(arg, "--patience"))
2818 DIFF_XDL_SET(options, PATIENCE_DIFF);
2820 /* flags options */
2821 else if (!strcmp(arg, "--binary")) {
2822 options->output_format |= DIFF_FORMAT_PATCH;
2823 DIFF_OPT_SET(options, BINARY);
2825 else if (!strcmp(arg, "--full-index"))
2826 DIFF_OPT_SET(options, FULL_INDEX);
2827 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2828 DIFF_OPT_SET(options, TEXT);
2829 else if (!strcmp(arg, "-R"))
2830 DIFF_OPT_SET(options, REVERSE_DIFF);
2831 else if (!strcmp(arg, "--find-copies-harder"))
2832 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2833 else if (!strcmp(arg, "--follow"))
2834 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2835 else if (!strcmp(arg, "--color"))
2836 DIFF_OPT_SET(options, COLOR_DIFF);
2837 else if (!prefixcmp(arg, "--color=")) {
2838 int value = git_config_colorbool(NULL, arg+8, -1);
2839 if (value == 0)
2840 DIFF_OPT_CLR(options, COLOR_DIFF);
2841 else if (value > 0)
2842 DIFF_OPT_SET(options, COLOR_DIFF);
2843 else
2844 return error("option `color' expects \"always\", \"auto\", or \"never\"");
2846 else if (!strcmp(arg, "--no-color"))
2847 DIFF_OPT_CLR(options, COLOR_DIFF);
2848 else if (!strcmp(arg, "--color-words")) {
2849 DIFF_OPT_SET(options, COLOR_DIFF);
2850 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2852 else if (!prefixcmp(arg, "--color-words=")) {
2853 DIFF_OPT_SET(options, COLOR_DIFF);
2854 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2855 options->word_regex = arg + 14;
2857 else if (!strcmp(arg, "--exit-code"))
2858 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2859 else if (!strcmp(arg, "--quiet"))
2860 DIFF_OPT_SET(options, QUICK);
2861 else if (!strcmp(arg, "--ext-diff"))
2862 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2863 else if (!strcmp(arg, "--no-ext-diff"))
2864 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2865 else if (!strcmp(arg, "--textconv"))
2866 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2867 else if (!strcmp(arg, "--no-textconv"))
2868 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2869 else if (!strcmp(arg, "--ignore-submodules"))
2870 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2871 else if (!strcmp(arg, "--submodule"))
2872 DIFF_OPT_SET(options, SUBMODULE_LOG);
2873 else if (!prefixcmp(arg, "--submodule=")) {
2874 if (!strcmp(arg + 12, "log"))
2875 DIFF_OPT_SET(options, SUBMODULE_LOG);
2878 /* misc options */
2879 else if (!strcmp(arg, "-z"))
2880 options->line_termination = 0;
2881 else if (!prefixcmp(arg, "-l"))
2882 options->rename_limit = strtoul(arg+2, NULL, 10);
2883 else if (!prefixcmp(arg, "-S"))
2884 options->pickaxe = arg + 2;
2885 else if (!strcmp(arg, "--pickaxe-all"))
2886 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2887 else if (!strcmp(arg, "--pickaxe-regex"))
2888 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2889 else if (!prefixcmp(arg, "-O"))
2890 options->orderfile = arg + 2;
2891 else if (!prefixcmp(arg, "--diff-filter="))
2892 options->filter = arg + 14;
2893 else if (!strcmp(arg, "--abbrev"))
2894 options->abbrev = DEFAULT_ABBREV;
2895 else if (!prefixcmp(arg, "--abbrev=")) {
2896 options->abbrev = strtoul(arg + 9, NULL, 10);
2897 if (options->abbrev < MINIMUM_ABBREV)
2898 options->abbrev = MINIMUM_ABBREV;
2899 else if (40 < options->abbrev)
2900 options->abbrev = 40;
2902 else if (!prefixcmp(arg, "--src-prefix="))
2903 options->a_prefix = arg + 13;
2904 else if (!prefixcmp(arg, "--dst-prefix="))
2905 options->b_prefix = arg + 13;
2906 else if (!strcmp(arg, "--no-prefix"))
2907 options->a_prefix = options->b_prefix = "";
2908 else if (opt_arg(arg, '\0', "inter-hunk-context",
2909 &options->interhunkcontext))
2911 else if (!prefixcmp(arg, "--output=")) {
2912 options->file = fopen(arg + strlen("--output="), "w");
2913 if (!options->file)
2914 die_errno("Could not open '%s'", arg + strlen("--output="));
2915 options->close_file = 1;
2916 } else
2917 return 0;
2918 return 1;
2921 static int parse_num(const char **cp_p)
2923 unsigned long num, scale;
2924 int ch, dot;
2925 const char *cp = *cp_p;
2927 num = 0;
2928 scale = 1;
2929 dot = 0;
2930 for (;;) {
2931 ch = *cp;
2932 if ( !dot && ch == '.' ) {
2933 scale = 1;
2934 dot = 1;
2935 } else if ( ch == '%' ) {
2936 scale = dot ? scale*100 : 100;
2937 cp++; /* % is always at the end */
2938 break;
2939 } else if ( ch >= '0' && ch <= '9' ) {
2940 if ( scale < 100000 ) {
2941 scale *= 10;
2942 num = (num*10) + (ch-'0');
2944 } else {
2945 break;
2947 cp++;
2949 *cp_p = cp;
2951 /* user says num divided by scale and we say internally that
2952 * is MAX_SCORE * num / scale.
2954 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2957 static int diff_scoreopt_parse(const char *opt)
2959 int opt1, opt2, cmd;
2961 if (*opt++ != '-')
2962 return -1;
2963 cmd = *opt++;
2964 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2965 return -1; /* that is not a -M, -C nor -B option */
2967 opt1 = parse_num(&opt);
2968 if (cmd != 'B')
2969 opt2 = 0;
2970 else {
2971 if (*opt == 0)
2972 opt2 = 0;
2973 else if (*opt != '/')
2974 return -1; /* we expect -B80/99 or -B80 */
2975 else {
2976 opt++;
2977 opt2 = parse_num(&opt);
2980 if (*opt != 0)
2981 return -1;
2982 return opt1 | (opt2 << 16);
2985 struct diff_queue_struct diff_queued_diff;
2987 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2989 if (queue->alloc <= queue->nr) {
2990 queue->alloc = alloc_nr(queue->alloc);
2991 queue->queue = xrealloc(queue->queue,
2992 sizeof(dp) * queue->alloc);
2994 queue->queue[queue->nr++] = dp;
2997 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2998 struct diff_filespec *one,
2999 struct diff_filespec *two)
3001 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3002 dp->one = one;
3003 dp->two = two;
3004 if (queue)
3005 diff_q(queue, dp);
3006 return dp;
3009 void diff_free_filepair(struct diff_filepair *p)
3011 free_filespec(p->one);
3012 free_filespec(p->two);
3013 free(p);
3016 /* This is different from find_unique_abbrev() in that
3017 * it stuffs the result with dots for alignment.
3019 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3021 int abblen;
3022 const char *abbrev;
3023 if (len == 40)
3024 return sha1_to_hex(sha1);
3026 abbrev = find_unique_abbrev(sha1, len);
3027 abblen = strlen(abbrev);
3028 if (abblen < 37) {
3029 static char hex[41];
3030 if (len < abblen && abblen <= len + 2)
3031 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3032 else
3033 sprintf(hex, "%s...", abbrev);
3034 return hex;
3036 return sha1_to_hex(sha1);
3039 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3041 int line_termination = opt->line_termination;
3042 int inter_name_termination = line_termination ? '\t' : '\0';
3044 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3045 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3046 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3047 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3049 if (p->score) {
3050 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3051 inter_name_termination);
3052 } else {
3053 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3056 if (p->status == DIFF_STATUS_COPIED ||
3057 p->status == DIFF_STATUS_RENAMED) {
3058 const char *name_a, *name_b;
3059 name_a = p->one->path;
3060 name_b = p->two->path;
3061 strip_prefix(opt->prefix_length, &name_a, &name_b);
3062 write_name_quoted(name_a, opt->file, inter_name_termination);
3063 write_name_quoted(name_b, opt->file, line_termination);
3064 } else {
3065 const char *name_a, *name_b;
3066 name_a = p->one->mode ? p->one->path : p->two->path;
3067 name_b = NULL;
3068 strip_prefix(opt->prefix_length, &name_a, &name_b);
3069 write_name_quoted(name_a, opt->file, line_termination);
3073 int diff_unmodified_pair(struct diff_filepair *p)
3075 /* This function is written stricter than necessary to support
3076 * the currently implemented transformers, but the idea is to
3077 * let transformers to produce diff_filepairs any way they want,
3078 * and filter and clean them up here before producing the output.
3080 struct diff_filespec *one = p->one, *two = p->two;
3082 if (DIFF_PAIR_UNMERGED(p))
3083 return 0; /* unmerged is interesting */
3085 /* deletion, addition, mode or type change
3086 * and rename are all interesting.
3088 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3089 DIFF_PAIR_MODE_CHANGED(p) ||
3090 strcmp(one->path, two->path))
3091 return 0;
3093 /* both are valid and point at the same path. that is, we are
3094 * dealing with a change.
3096 if (one->sha1_valid && two->sha1_valid &&
3097 !hashcmp(one->sha1, two->sha1) &&
3098 !one->dirty_submodule && !two->dirty_submodule)
3099 return 1; /* no change */
3100 if (!one->sha1_valid && !two->sha1_valid)
3101 return 1; /* both look at the same file on the filesystem. */
3102 return 0;
3105 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3107 if (diff_unmodified_pair(p))
3108 return;
3110 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3111 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3112 return; /* no tree diffs in patch format */
3114 run_diff(p, o);
3117 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3118 struct diffstat_t *diffstat)
3120 if (diff_unmodified_pair(p))
3121 return;
3123 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3124 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3125 return; /* no tree diffs in patch format */
3127 run_diffstat(p, o, diffstat);
3130 static void diff_flush_checkdiff(struct diff_filepair *p,
3131 struct diff_options *o)
3133 if (diff_unmodified_pair(p))
3134 return;
3136 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3137 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3138 return; /* no tree diffs in patch format */
3140 run_checkdiff(p, o);
3143 int diff_queue_is_empty(void)
3145 struct diff_queue_struct *q = &diff_queued_diff;
3146 int i;
3147 for (i = 0; i < q->nr; i++)
3148 if (!diff_unmodified_pair(q->queue[i]))
3149 return 0;
3150 return 1;
3153 #if DIFF_DEBUG
3154 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3156 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3157 x, one ? one : "",
3158 s->path,
3159 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3160 s->mode,
3161 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3162 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3163 x, one ? one : "",
3164 s->size, s->xfrm_flags);
3167 void diff_debug_filepair(const struct diff_filepair *p, int i)
3169 diff_debug_filespec(p->one, i, "one");
3170 diff_debug_filespec(p->two, i, "two");
3171 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3172 p->score, p->status ? p->status : '?',
3173 p->one->rename_used, p->broken_pair);
3176 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3178 int i;
3179 if (msg)
3180 fprintf(stderr, "%s\n", msg);
3181 fprintf(stderr, "q->nr = %d\n", q->nr);
3182 for (i = 0; i < q->nr; i++) {
3183 struct diff_filepair *p = q->queue[i];
3184 diff_debug_filepair(p, i);
3187 #endif
3189 static void diff_resolve_rename_copy(void)
3191 int i;
3192 struct diff_filepair *p;
3193 struct diff_queue_struct *q = &diff_queued_diff;
3195 diff_debug_queue("resolve-rename-copy", q);
3197 for (i = 0; i < q->nr; i++) {
3198 p = q->queue[i];
3199 p->status = 0; /* undecided */
3200 if (DIFF_PAIR_UNMERGED(p))
3201 p->status = DIFF_STATUS_UNMERGED;
3202 else if (!DIFF_FILE_VALID(p->one))
3203 p->status = DIFF_STATUS_ADDED;
3204 else if (!DIFF_FILE_VALID(p->two))
3205 p->status = DIFF_STATUS_DELETED;
3206 else if (DIFF_PAIR_TYPE_CHANGED(p))
3207 p->status = DIFF_STATUS_TYPE_CHANGED;
3209 /* from this point on, we are dealing with a pair
3210 * whose both sides are valid and of the same type, i.e.
3211 * either in-place edit or rename/copy edit.
3213 else if (DIFF_PAIR_RENAME(p)) {
3215 * A rename might have re-connected a broken
3216 * pair up, causing the pathnames to be the
3217 * same again. If so, that's not a rename at
3218 * all, just a modification..
3220 * Otherwise, see if this source was used for
3221 * multiple renames, in which case we decrement
3222 * the count, and call it a copy.
3224 if (!strcmp(p->one->path, p->two->path))
3225 p->status = DIFF_STATUS_MODIFIED;
3226 else if (--p->one->rename_used > 0)
3227 p->status = DIFF_STATUS_COPIED;
3228 else
3229 p->status = DIFF_STATUS_RENAMED;
3231 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3232 p->one->mode != p->two->mode ||
3233 p->one->dirty_submodule ||
3234 p->two->dirty_submodule ||
3235 is_null_sha1(p->one->sha1))
3236 p->status = DIFF_STATUS_MODIFIED;
3237 else {
3238 /* This is a "no-change" entry and should not
3239 * happen anymore, but prepare for broken callers.
3241 error("feeding unmodified %s to diffcore",
3242 p->one->path);
3243 p->status = DIFF_STATUS_UNKNOWN;
3246 diff_debug_queue("resolve-rename-copy done", q);
3249 static int check_pair_status(struct diff_filepair *p)
3251 switch (p->status) {
3252 case DIFF_STATUS_UNKNOWN:
3253 return 0;
3254 case 0:
3255 die("internal error in diff-resolve-rename-copy");
3256 default:
3257 return 1;
3261 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3263 int fmt = opt->output_format;
3265 if (fmt & DIFF_FORMAT_CHECKDIFF)
3266 diff_flush_checkdiff(p, opt);
3267 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3268 diff_flush_raw(p, opt);
3269 else if (fmt & DIFF_FORMAT_NAME) {
3270 const char *name_a, *name_b;
3271 name_a = p->two->path;
3272 name_b = NULL;
3273 strip_prefix(opt->prefix_length, &name_a, &name_b);
3274 write_name_quoted(name_a, opt->file, opt->line_termination);
3278 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3280 if (fs->mode)
3281 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3282 else
3283 fprintf(file, " %s ", newdelete);
3284 write_name_quoted(fs->path, file, '\n');
3288 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3290 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3291 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3292 show_name ? ' ' : '\n');
3293 if (show_name) {
3294 write_name_quoted(p->two->path, file, '\n');
3299 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3301 char *names = pprint_rename(p->one->path, p->two->path);
3303 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3304 free(names);
3305 show_mode_change(file, p, 0);
3308 static void diff_summary(FILE *file, struct diff_filepair *p)
3310 switch(p->status) {
3311 case DIFF_STATUS_DELETED:
3312 show_file_mode_name(file, "delete", p->one);
3313 break;
3314 case DIFF_STATUS_ADDED:
3315 show_file_mode_name(file, "create", p->two);
3316 break;
3317 case DIFF_STATUS_COPIED:
3318 show_rename_copy(file, "copy", p);
3319 break;
3320 case DIFF_STATUS_RENAMED:
3321 show_rename_copy(file, "rename", p);
3322 break;
3323 default:
3324 if (p->score) {
3325 fputs(" rewrite ", file);
3326 write_name_quoted(p->two->path, file, ' ');
3327 fprintf(file, "(%d%%)\n", similarity_index(p));
3329 show_mode_change(file, p, !p->score);
3330 break;
3334 struct patch_id_t {
3335 git_SHA_CTX *ctx;
3336 int patchlen;
3339 static int remove_space(char *line, int len)
3341 int i;
3342 char *dst = line;
3343 unsigned char c;
3345 for (i = 0; i < len; i++)
3346 if (!isspace((c = line[i])))
3347 *dst++ = c;
3349 return dst - line;
3352 static void patch_id_consume(void *priv, char *line, unsigned long len)
3354 struct patch_id_t *data = priv;
3355 int new_len;
3357 /* Ignore line numbers when computing the SHA1 of the patch */
3358 if (!prefixcmp(line, "@@ -"))
3359 return;
3361 new_len = remove_space(line, len);
3363 git_SHA1_Update(data->ctx, line, new_len);
3364 data->patchlen += new_len;
3367 /* returns 0 upon success, and writes result into sha1 */
3368 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3370 struct diff_queue_struct *q = &diff_queued_diff;
3371 int i;
3372 git_SHA_CTX ctx;
3373 struct patch_id_t data;
3374 char buffer[PATH_MAX * 4 + 20];
3376 git_SHA1_Init(&ctx);
3377 memset(&data, 0, sizeof(struct patch_id_t));
3378 data.ctx = &ctx;
3380 for (i = 0; i < q->nr; i++) {
3381 xpparam_t xpp;
3382 xdemitconf_t xecfg;
3383 xdemitcb_t ecb;
3384 mmfile_t mf1, mf2;
3385 struct diff_filepair *p = q->queue[i];
3386 int len1, len2;
3388 memset(&xpp, 0, sizeof(xpp));
3389 memset(&xecfg, 0, sizeof(xecfg));
3390 if (p->status == 0)
3391 return error("internal diff status error");
3392 if (p->status == DIFF_STATUS_UNKNOWN)
3393 continue;
3394 if (diff_unmodified_pair(p))
3395 continue;
3396 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3397 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3398 continue;
3399 if (DIFF_PAIR_UNMERGED(p))
3400 continue;
3402 diff_fill_sha1_info(p->one);
3403 diff_fill_sha1_info(p->two);
3404 if (fill_mmfile(&mf1, p->one) < 0 ||
3405 fill_mmfile(&mf2, p->two) < 0)
3406 return error("unable to read files to diff");
3408 len1 = remove_space(p->one->path, strlen(p->one->path));
3409 len2 = remove_space(p->two->path, strlen(p->two->path));
3410 if (p->one->mode == 0)
3411 len1 = snprintf(buffer, sizeof(buffer),
3412 "diff--gita/%.*sb/%.*s"
3413 "newfilemode%06o"
3414 "---/dev/null"
3415 "+++b/%.*s",
3416 len1, p->one->path,
3417 len2, p->two->path,
3418 p->two->mode,
3419 len2, p->two->path);
3420 else if (p->two->mode == 0)
3421 len1 = snprintf(buffer, sizeof(buffer),
3422 "diff--gita/%.*sb/%.*s"
3423 "deletedfilemode%06o"
3424 "---a/%.*s"
3425 "+++/dev/null",
3426 len1, p->one->path,
3427 len2, p->two->path,
3428 p->one->mode,
3429 len1, p->one->path);
3430 else
3431 len1 = snprintf(buffer, sizeof(buffer),
3432 "diff--gita/%.*sb/%.*s"
3433 "---a/%.*s"
3434 "+++b/%.*s",
3435 len1, p->one->path,
3436 len2, p->two->path,
3437 len1, p->one->path,
3438 len2, p->two->path);
3439 git_SHA1_Update(&ctx, buffer, len1);
3441 xpp.flags = XDF_NEED_MINIMAL;
3442 xecfg.ctxlen = 3;
3443 xecfg.flags = XDL_EMIT_FUNCNAMES;
3444 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3445 &xpp, &xecfg, &ecb);
3448 git_SHA1_Final(sha1, &ctx);
3449 return 0;
3452 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3454 struct diff_queue_struct *q = &diff_queued_diff;
3455 int i;
3456 int result = diff_get_patch_id(options, sha1);
3458 for (i = 0; i < q->nr; i++)
3459 diff_free_filepair(q->queue[i]);
3461 free(q->queue);
3462 q->queue = NULL;
3463 q->nr = q->alloc = 0;
3465 return result;
3468 static int is_summary_empty(const struct diff_queue_struct *q)
3470 int i;
3472 for (i = 0; i < q->nr; i++) {
3473 const struct diff_filepair *p = q->queue[i];
3475 switch (p->status) {
3476 case DIFF_STATUS_DELETED:
3477 case DIFF_STATUS_ADDED:
3478 case DIFF_STATUS_COPIED:
3479 case DIFF_STATUS_RENAMED:
3480 return 0;
3481 default:
3482 if (p->score)
3483 return 0;
3484 if (p->one->mode && p->two->mode &&
3485 p->one->mode != p->two->mode)
3486 return 0;
3487 break;
3490 return 1;
3493 void diff_flush(struct diff_options *options)
3495 struct diff_queue_struct *q = &diff_queued_diff;
3496 int i, output_format = options->output_format;
3497 int separator = 0;
3500 * Order: raw, stat, summary, patch
3501 * or: name/name-status/checkdiff (other bits clear)
3503 if (!q->nr)
3504 goto free_queue;
3506 if (output_format & (DIFF_FORMAT_RAW |
3507 DIFF_FORMAT_NAME |
3508 DIFF_FORMAT_NAME_STATUS |
3509 DIFF_FORMAT_CHECKDIFF)) {
3510 for (i = 0; i < q->nr; i++) {
3511 struct diff_filepair *p = q->queue[i];
3512 if (check_pair_status(p))
3513 flush_one_pair(p, options);
3515 separator++;
3518 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3519 struct diffstat_t diffstat;
3521 memset(&diffstat, 0, sizeof(struct diffstat_t));
3522 for (i = 0; i < q->nr; i++) {
3523 struct diff_filepair *p = q->queue[i];
3524 if (check_pair_status(p))
3525 diff_flush_stat(p, options, &diffstat);
3527 if (output_format & DIFF_FORMAT_NUMSTAT)
3528 show_numstat(&diffstat, options);
3529 if (output_format & DIFF_FORMAT_DIFFSTAT)
3530 show_stats(&diffstat, options);
3531 if (output_format & DIFF_FORMAT_SHORTSTAT)
3532 show_shortstats(&diffstat, options);
3533 free_diffstat_info(&diffstat);
3534 separator++;
3536 if (output_format & DIFF_FORMAT_DIRSTAT)
3537 show_dirstat(options);
3539 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3540 for (i = 0; i < q->nr; i++)
3541 diff_summary(options->file, q->queue[i]);
3542 separator++;
3545 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3546 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3547 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3549 * run diff_flush_patch for the exit status. setting
3550 * options->file to /dev/null should be safe, becaue we
3551 * aren't supposed to produce any output anyway.
3553 if (options->close_file)
3554 fclose(options->file);
3555 options->file = fopen("/dev/null", "w");
3556 if (!options->file)
3557 die_errno("Could not open /dev/null");
3558 options->close_file = 1;
3559 for (i = 0; i < q->nr; i++) {
3560 struct diff_filepair *p = q->queue[i];
3561 if (check_pair_status(p))
3562 diff_flush_patch(p, options);
3563 if (options->found_changes)
3564 break;
3568 if (output_format & DIFF_FORMAT_PATCH) {
3569 if (separator) {
3570 putc(options->line_termination, options->file);
3571 if (options->stat_sep) {
3572 /* attach patch instead of inline */
3573 fputs(options->stat_sep, options->file);
3577 for (i = 0; i < q->nr; i++) {
3578 struct diff_filepair *p = q->queue[i];
3579 if (check_pair_status(p))
3580 diff_flush_patch(p, options);
3584 if (output_format & DIFF_FORMAT_CALLBACK)
3585 options->format_callback(q, options, options->format_callback_data);
3587 for (i = 0; i < q->nr; i++)
3588 diff_free_filepair(q->queue[i]);
3589 free_queue:
3590 free(q->queue);
3591 q->queue = NULL;
3592 q->nr = q->alloc = 0;
3593 if (options->close_file)
3594 fclose(options->file);
3597 * Report the content-level differences with HAS_CHANGES;
3598 * diff_addremove/diff_change does not set the bit when
3599 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3601 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3602 if (options->found_changes)
3603 DIFF_OPT_SET(options, HAS_CHANGES);
3604 else
3605 DIFF_OPT_CLR(options, HAS_CHANGES);
3609 static void diffcore_apply_filter(const char *filter)
3611 int i;
3612 struct diff_queue_struct *q = &diff_queued_diff;
3613 struct diff_queue_struct outq;
3614 outq.queue = NULL;
3615 outq.nr = outq.alloc = 0;
3617 if (!filter)
3618 return;
3620 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3621 int found;
3622 for (i = found = 0; !found && i < q->nr; i++) {
3623 struct diff_filepair *p = q->queue[i];
3624 if (((p->status == DIFF_STATUS_MODIFIED) &&
3625 ((p->score &&
3626 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3627 (!p->score &&
3628 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3629 ((p->status != DIFF_STATUS_MODIFIED) &&
3630 strchr(filter, p->status)))
3631 found++;
3633 if (found)
3634 return;
3636 /* otherwise we will clear the whole queue
3637 * by copying the empty outq at the end of this
3638 * function, but first clear the current entries
3639 * in the queue.
3641 for (i = 0; i < q->nr; i++)
3642 diff_free_filepair(q->queue[i]);
3644 else {
3645 /* Only the matching ones */
3646 for (i = 0; i < q->nr; i++) {
3647 struct diff_filepair *p = q->queue[i];
3649 if (((p->status == DIFF_STATUS_MODIFIED) &&
3650 ((p->score &&
3651 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3652 (!p->score &&
3653 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3654 ((p->status != DIFF_STATUS_MODIFIED) &&
3655 strchr(filter, p->status)))
3656 diff_q(&outq, p);
3657 else
3658 diff_free_filepair(p);
3661 free(q->queue);
3662 *q = outq;
3665 /* Check whether two filespecs with the same mode and size are identical */
3666 static int diff_filespec_is_identical(struct diff_filespec *one,
3667 struct diff_filespec *two)
3669 if (S_ISGITLINK(one->mode))
3670 return 0;
3671 if (diff_populate_filespec(one, 0))
3672 return 0;
3673 if (diff_populate_filespec(two, 0))
3674 return 0;
3675 return !memcmp(one->data, two->data, one->size);
3678 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3680 int i;
3681 struct diff_queue_struct *q = &diff_queued_diff;
3682 struct diff_queue_struct outq;
3683 outq.queue = NULL;
3684 outq.nr = outq.alloc = 0;
3686 for (i = 0; i < q->nr; i++) {
3687 struct diff_filepair *p = q->queue[i];
3690 * 1. Entries that come from stat info dirtiness
3691 * always have both sides (iow, not create/delete),
3692 * one side of the object name is unknown, with
3693 * the same mode and size. Keep the ones that
3694 * do not match these criteria. They have real
3695 * differences.
3697 * 2. At this point, the file is known to be modified,
3698 * with the same mode and size, and the object
3699 * name of one side is unknown. Need to inspect
3700 * the identical contents.
3702 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3703 !DIFF_FILE_VALID(p->two) ||
3704 (p->one->sha1_valid && p->two->sha1_valid) ||
3705 (p->one->mode != p->two->mode) ||
3706 diff_populate_filespec(p->one, 1) ||
3707 diff_populate_filespec(p->two, 1) ||
3708 (p->one->size != p->two->size) ||
3709 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3710 diff_q(&outq, p);
3711 else {
3713 * The caller can subtract 1 from skip_stat_unmatch
3714 * to determine how many paths were dirty only
3715 * due to stat info mismatch.
3717 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3718 diffopt->skip_stat_unmatch++;
3719 diff_free_filepair(p);
3722 free(q->queue);
3723 *q = outq;
3726 static int diffnamecmp(const void *a_, const void *b_)
3728 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3729 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3730 const char *name_a, *name_b;
3732 name_a = a->one ? a->one->path : a->two->path;
3733 name_b = b->one ? b->one->path : b->two->path;
3734 return strcmp(name_a, name_b);
3737 void diffcore_fix_diff_index(struct diff_options *options)
3739 struct diff_queue_struct *q = &diff_queued_diff;
3740 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3743 void diffcore_std(struct diff_options *options)
3745 if (options->skip_stat_unmatch)
3746 diffcore_skip_stat_unmatch(options);
3747 if (options->break_opt != -1)
3748 diffcore_break(options->break_opt);
3749 if (options->detect_rename)
3750 diffcore_rename(options);
3751 if (options->break_opt != -1)
3752 diffcore_merge_broken();
3753 if (options->pickaxe)
3754 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3755 if (options->orderfile)
3756 diffcore_order(options->orderfile);
3757 diff_resolve_rename_copy();
3758 diffcore_apply_filter(options->filter);
3760 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3761 DIFF_OPT_SET(options, HAS_CHANGES);
3762 else
3763 DIFF_OPT_CLR(options, HAS_CHANGES);
3766 int diff_result_code(struct diff_options *opt, int status)
3768 int result = 0;
3769 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3770 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3771 return status;
3772 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3773 DIFF_OPT_TST(opt, HAS_CHANGES))
3774 result |= 01;
3775 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3776 DIFF_OPT_TST(opt, CHECK_FAILED))
3777 result |= 02;
3778 return result;
3781 void diff_addremove(struct diff_options *options,
3782 int addremove, unsigned mode,
3783 const unsigned char *sha1,
3784 const char *concatpath, unsigned dirty_submodule)
3786 struct diff_filespec *one, *two;
3788 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3789 return;
3791 /* This may look odd, but it is a preparation for
3792 * feeding "there are unchanged files which should
3793 * not produce diffs, but when you are doing copy
3794 * detection you would need them, so here they are"
3795 * entries to the diff-core. They will be prefixed
3796 * with something like '=' or '*' (I haven't decided
3797 * which but should not make any difference).
3798 * Feeding the same new and old to diff_change()
3799 * also has the same effect.
3800 * Before the final output happens, they are pruned after
3801 * merged into rename/copy pairs as appropriate.
3803 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3804 addremove = (addremove == '+' ? '-' :
3805 addremove == '-' ? '+' : addremove);
3807 if (options->prefix &&
3808 strncmp(concatpath, options->prefix, options->prefix_length))
3809 return;
3811 one = alloc_filespec(concatpath);
3812 two = alloc_filespec(concatpath);
3814 if (addremove != '+')
3815 fill_filespec(one, sha1, mode);
3816 if (addremove != '-') {
3817 fill_filespec(two, sha1, mode);
3818 two->dirty_submodule = dirty_submodule;
3821 diff_queue(&diff_queued_diff, one, two);
3822 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3823 DIFF_OPT_SET(options, HAS_CHANGES);
3826 void diff_change(struct diff_options *options,
3827 unsigned old_mode, unsigned new_mode,
3828 const unsigned char *old_sha1,
3829 const unsigned char *new_sha1,
3830 const char *concatpath,
3831 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3833 struct diff_filespec *one, *two;
3835 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3836 && S_ISGITLINK(new_mode))
3837 return;
3839 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3840 unsigned tmp;
3841 const unsigned char *tmp_c;
3842 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3843 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3844 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3845 new_dirty_submodule = tmp;
3848 if (options->prefix &&
3849 strncmp(concatpath, options->prefix, options->prefix_length))
3850 return;
3852 one = alloc_filespec(concatpath);
3853 two = alloc_filespec(concatpath);
3854 fill_filespec(one, old_sha1, old_mode);
3855 fill_filespec(two, new_sha1, new_mode);
3856 one->dirty_submodule = old_dirty_submodule;
3857 two->dirty_submodule = new_dirty_submodule;
3859 diff_queue(&diff_queued_diff, one, two);
3860 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3861 DIFF_OPT_SET(options, HAS_CHANGES);
3864 void diff_unmerge(struct diff_options *options,
3865 const char *path,
3866 unsigned mode, const unsigned char *sha1)
3868 struct diff_filespec *one, *two;
3870 if (options->prefix &&
3871 strncmp(path, options->prefix, options->prefix_length))
3872 return;
3874 one = alloc_filespec(path);
3875 two = alloc_filespec(path);
3876 fill_filespec(one, sha1, mode);
3877 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3880 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3881 size_t *outsize)
3883 struct diff_tempfile *temp;
3884 const char *argv[3];
3885 const char **arg = argv;
3886 struct child_process child;
3887 struct strbuf buf = STRBUF_INIT;
3888 int err = 0;
3890 temp = prepare_temp_file(spec->path, spec);
3891 *arg++ = pgm;
3892 *arg++ = temp->name;
3893 *arg = NULL;
3895 memset(&child, 0, sizeof(child));
3896 child.use_shell = 1;
3897 child.argv = argv;
3898 child.out = -1;
3899 if (start_command(&child)) {
3900 remove_tempfile();
3901 return NULL;
3904 if (strbuf_read(&buf, child.out, 0) < 0)
3905 err = error("error reading from textconv command '%s'", pgm);
3906 close(child.out);
3908 if (finish_command(&child) || err) {
3909 strbuf_release(&buf);
3910 remove_tempfile();
3911 return NULL;
3913 remove_tempfile();
3915 return strbuf_detach(&buf, outsize);